diff --git a/local-test-curl-delta-01/afc-curl/CHANGES.md b/local-test-curl-delta-01/afc-curl/CHANGES.md new file mode 100644 index 0000000000000000000000000000000000000000..6e2f7c6bcc4b23df966c4e531c347ae62e0c9f07 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/CHANGES.md @@ -0,0 +1,12 @@ + + +In a release tarball, check the RELEASES-NOTES file for what was done in the +most recent release. In a git check-out, that file mentions changes that have +been done since the previous release. + +See the online [changelog](https://curl.se/changes.html) for the edited and +human readable version of what has changed in different curl releases. diff --git a/local-test-curl-delta-01/afc-curl/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0cba6f626b8b512eed4f82f37ae4452cbcd4cdc6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/CMakeLists.txt @@ -0,0 +1,2355 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# by Tetetest and Sukender (Benoit Neil) + +# Note: By default this CMake build script detects the version of some +# dependencies using `check_symbol_exists`. Those checks do not work in +# the case that both CURL and its dependency are included as sub-projects +# in a larger build using `FetchContent`. To support that case, additional +# variables may be defined by the parent project, ideally in the "extra" +# find package redirect file: +# https://cmake.org/cmake/help/latest/module/FetchContent.html#integrating-with-find-package +# +# The following variables are available: +# HAVE_SSL_SET0_WBIO: `SSL_set0_wbio` present in OpenSSL/wolfSSL +# HAVE_OPENSSL_SRP: `SSL_CTX_set_srp_username` present in OpenSSL/wolfSSL +# HAVE_GNUTLS_SRP: `gnutls_srp_verifier` present in GnuTLS +# HAVE_SSL_CTX_SET_QUIC_METHOD: `SSL_CTX_set_quic_method` present in OpenSSL/wolfSSL +# HAVE_QUICHE_CONN_SET_QLOG_FD: `quiche_conn_set_qlog_fd` present in quiche +# HAVE_ECH: ECH API checks for OpenSSL, BoringSSL or wolfSSL +# +# For each of the above variables, if the variable is DEFINED (either +# to ON or OFF), the symbol detection is skipped. If the variable is +# NOT DEFINED, the symbol detection is performed. + +cmake_minimum_required(VERSION 3.7...3.16 FATAL_ERROR) +message(STATUS "Using CMake version ${CMAKE_VERSION}") + +# Collect command-line arguments for buildinfo.txt. +# Must reside at the top of the script to work as expected. +set(_cmake_args "") +if(NOT "$ENV{CURL_BUILDINFO}$ENV{CURL_CI}$ENV{CI}" STREQUAL "") + get_cmake_property(_cache_vars CACHE_VARIABLES) + foreach(_cache_var IN ITEMS ${_cache_vars}) + get_property(_cache_var_helpstring CACHE ${_cache_var} PROPERTY HELPSTRING) + if(_cache_var_helpstring STREQUAL "No help, variable specified on the command line.") + get_property(_cache_var_type CACHE ${_cache_var} PROPERTY TYPE) + get_property(_cache_var_value CACHE ${_cache_var} PROPERTY VALUE) + if(_cache_var_type STREQUAL "UNINITIALIZED") + set(_cache_var_type) + else() + set(_cache_var_type ":${_cache_var_type}") + endif() + set(_cmake_args "${_cmake_args} -D${_cache_var}${_cache_var_type}=\"${_cache_var_value}\"") + endif() + endforeach() +endif() + +function(curl_dumpvars) # Dump all defined variables with their values + message("::group::CMake Variable Dump") + get_cmake_property(_vars VARIABLES) + foreach(_var ${_vars}) + message("${_var} = ${${_var}}") + endforeach() + message("::endgroup::") +endfunction() + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}") +include(Utilities) +include(Macros) +include(CMakeDependentOption) +include(CheckCCompilerFlag) + +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/curl/curlver.h" _curl_version_h_contents REGEX "#define LIBCURL_VERSION( |_NUM )") +string(REGEX MATCH "#define LIBCURL_VERSION \"[^\"]*" _curl_version ${_curl_version_h_contents}) +string(REGEX REPLACE "[^\"]+\"" "" _curl_version ${_curl_version}) +string(REGEX MATCH "#define LIBCURL_VERSION_NUM 0x[0-9a-fA-F]+" _curl_version_num ${_curl_version_h_contents}) +string(REGEX REPLACE "[^0]+0x" "" _curl_version_num ${_curl_version_num}) +unset(_curl_version_h_contents) + +message(STATUS "curl version=[${_curl_version}]") + +string(REGEX REPLACE "([0-9]+\.[0-9]+\.[0-9]+).+" "\\1" _curl_version_sem "${_curl_version}") +project(CURL + VERSION "${_curl_version_sem}" + LANGUAGES C) + +unset(_target_flags) +if(APPLE) + set(_target_flags "${_target_flags} APPLE") +endif() +if(UNIX) + set(_target_flags "${_target_flags} UNIX") +endif() +if(BSD) + set(_target_flags "${_target_flags} BSD") +endif() +if(WIN32) + set(_target_flags "${_target_flags} WIN32") +endif() +if(WINDOWS_STORE) + set(_target_flags "${_target_flags} UWP") +endif() +if(CYGWIN) + set(_target_flags "${_target_flags} CYGWIN") +endif() +if(MSYS) + set(_target_flags "${_target_flags} MSYS") +endif() +if(CMAKE_COMPILER_IS_GNUCC) + set(_target_flags "${_target_flags} GCC") +endif() +if(MINGW) + set(_target_flags "${_target_flags} MINGW") +endif() +if(MSVC) + set(_target_flags "${_target_flags} MSVC") +endif() +if(VCPKG_TOOLCHAIN) + set(_target_flags "${_target_flags} VCPKG") +endif() +if(CMAKE_CROSSCOMPILING) + set(_target_flags "${_target_flags} CROSS") +endif() +message(STATUS "CMake platform flags:${_target_flags}") + +if(CMAKE_CROSSCOMPILING) + message(STATUS "Cross-compiling: " + "${CMAKE_HOST_SYSTEM_NAME}/${CMAKE_HOST_SYSTEM_PROCESSOR} -> " + "${CMAKE_SYSTEM_NAME}/${CMAKE_SYSTEM_PROCESSOR}") +endif() + +if(CMAKE_C_COMPILER_TARGET) + set(CURL_OS "\"${CMAKE_C_COMPILER_TARGET}\"") +else() + set(CURL_OS "\"${CMAKE_SYSTEM_NAME}\"") +endif() + +include_directories("${PROJECT_SOURCE_DIR}/include") + +if(NOT DEFINED CMAKE_UNITY_BUILD_BATCH_SIZE) + set(CMAKE_UNITY_BUILD_BATCH_SIZE 0) +endif() + +# Having CMAKE_TRY_COMPILE_TARGET_TYPE set to STATIC_LIBRARY breaks certain +# 'check_function_exists()' detections (possibly more), by detecting +# non-existing features. This happens by default when using 'ios.toolchain.cmake'. +# Work it around by setting this value to `EXECUTABLE`. +if(CMAKE_TRY_COMPILE_TARGET_TYPE STREQUAL "STATIC_LIBRARY") + message(STATUS "CMAKE_TRY_COMPILE_TARGET_TYPE was found set to STATIC_LIBRARY. " + "Overriding with EXECUTABLE for feature detections to work.") + set(_cmake_try_compile_target_type_save ${CMAKE_TRY_COMPILE_TARGET_TYPE}) + set(CMAKE_TRY_COMPILE_TARGET_TYPE "EXECUTABLE") +endif() + +option(CURL_WERROR "Turn compiler warnings into errors" OFF) +option(PICKY_COMPILER "Enable picky compiler options" ON) +option(BUILD_CURL_EXE "Build curl executable" ON) +option(BUILD_SHARED_LIBS "Build shared libraries" ON) +option(BUILD_STATIC_LIBS "Build static libraries" OFF) +option(BUILD_STATIC_CURL "Build curl executable with static libcurl" OFF) +option(ENABLE_ARES "Enable c-ares support" OFF) +option(CURL_DISABLE_INSTALL "Disable installation targets" OFF) + +if(WIN32) + option(CURL_STATIC_CRT "Build libcurl with static CRT with MSVC (/MT)" OFF) + if(CURL_STATIC_CRT AND MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT") + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd") + endif() + + option(ENABLE_UNICODE "Use the Unicode version of the Windows API functions" OFF) + if(WINDOWS_STORE) + set(ENABLE_UNICODE ON) + endif() + if(ENABLE_UNICODE) + add_definitions("-DUNICODE" "-D_UNICODE") + if(MINGW) + add_compile_options("-municode") + endif() + endif() + + list(APPEND CMAKE_REQUIRED_DEFINITIONS "-DWIN32_LEAN_AND_MEAN") # Apply to all feature checks + + set(CURL_TARGET_WINDOWS_VERSION "" CACHE STRING "Minimum target Windows version as hex string") + if(CURL_TARGET_WINDOWS_VERSION) + add_definitions("-D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}") + list(APPEND CMAKE_REQUIRED_DEFINITIONS "-D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}") # Apply to all feature checks + endif() + + # Detect actual value of _WIN32_WINNT and store as HAVE_WIN32_WINNT + curl_internal_test(HAVE_WIN32_WINNT) + if(HAVE_WIN32_WINNT) + string(REGEX MATCH ".*_WIN32_WINNT=0x[0-9a-fA-F]+" CURL_TEST_OUTPUT "${CURL_TEST_OUTPUT}") + string(REGEX REPLACE ".*_WIN32_WINNT=" "" CURL_TEST_OUTPUT "${CURL_TEST_OUTPUT}") + string(REGEX REPLACE "0x([0-9a-f][0-9a-f][0-9a-f])$" "0x0\\1" CURL_TEST_OUTPUT "${CURL_TEST_OUTPUT}") # pad to 4 digits + string(TOLOWER "${CURL_TEST_OUTPUT}" HAVE_WIN32_WINNT) + message(STATUS "Found _WIN32_WINNT=${HAVE_WIN32_WINNT}") + endif() + # Avoid storing HAVE_WIN32_WINNT in CMake cache + unset(HAVE_WIN32_WINNT CACHE) +endif() +option(CURL_LTO "Enable compiler Link Time Optimizations" OFF) + +cmake_dependent_option(ENABLE_THREADED_RESOLVER "Enable threaded DNS lookup" + ON "NOT ENABLE_ARES" + OFF) + +include(PickyWarnings) + +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") # Required for sendmmsg() +endif() + +option(ENABLE_DEBUG "Enable curl debug features (for developing curl itself)" OFF) +if(ENABLE_DEBUG) + message(WARNING "This curl build is Debug-enabled, do not use in production.") +endif() +option(ENABLE_CURLDEBUG "Enable TrackMemory debug feature" ${ENABLE_DEBUG}) + +if(MSVC) + set(ENABLE_CURLDEBUG OFF) # FIXME: TrackMemory + MSVC fails test 558 and 1330. Tested with static build, Debug mode. +endif() + +if(ENABLE_DEBUG) + set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS "DEBUGBUILD") +endif() + +if(ENABLE_CURLDEBUG) + set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS "CURLDEBUG") +endif() + +# For debug libs and exes, add "-d" postfix +if(NOT DEFINED CMAKE_DEBUG_POSTFIX) + set(CMAKE_DEBUG_POSTFIX "-d") +endif() + +set(LIB_STATIC "libcurl_static") +set(LIB_SHARED "libcurl_shared") + +if(NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) + set(BUILD_STATIC_LIBS ON) +endif() +if(NOT BUILD_STATIC_CURL AND NOT BUILD_SHARED_LIBS) + set(BUILD_STATIC_CURL ON) +elseif(BUILD_STATIC_CURL AND NOT BUILD_STATIC_LIBS) + set(BUILD_STATIC_CURL OFF) +endif() + +# Lib flavour selected for curl tool +if(BUILD_STATIC_CURL) + set(LIB_SELECTED_FOR_EXE ${LIB_STATIC}) +else() + set(LIB_SELECTED_FOR_EXE ${LIB_SHARED}) +endif() + +# Lib flavour selected for example and test programs. +if(BUILD_SHARED_LIBS) + set(LIB_SELECTED ${LIB_SHARED}) +else() + set(LIB_SELECTED ${LIB_STATIC}) +endif() + +# Override to force-disable or force-enable the use of pkg-config. +if(UNIX OR VCPKG_TOOLCHAIN OR (MINGW AND NOT CMAKE_CROSSCOMPILING)) # Keep in sync with CMake/curl-config.cmake.in + set(_curl_use_pkgconfig_default ON) +else() + set(_curl_use_pkgconfig_default OFF) +endif() +option(CURL_USE_PKGCONFIG "Enable pkg-config to detect dependencies" ${_curl_use_pkgconfig_default}) + +# Initialize variables collecting dependency libs, paths, pkg-config names. +set(CURL_LIBS "") +set(CURL_LIBDIRS "") +set(LIBCURL_PC_REQUIRES_PRIVATE "") + +if(ENABLE_ARES) + set(USE_ARES 1) + find_package(Cares REQUIRED) + list(APPEND CURL_LIBS ${CARES_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libcares") + add_definitions("-DCARES_NO_DEPRECATED") # Ignore c-ares deprecation warnings +endif() + +include(CurlSymbolHiding) + +option(CURL_ENABLE_EXPORT_TARGET "Enable CMake export target" ON) +mark_as_advanced(CURL_ENABLE_EXPORT_TARGET) + +option(CURL_DISABLE_ALTSVC "Disable alt-svc support" OFF) +mark_as_advanced(CURL_DISABLE_ALTSVC) +option(CURL_DISABLE_SRP "Disable TLS-SRP support" OFF) +mark_as_advanced(CURL_DISABLE_SRP) +option(CURL_DISABLE_COOKIES "Disable cookies support" OFF) +mark_as_advanced(CURL_DISABLE_COOKIES) +option(CURL_DISABLE_BASIC_AUTH "Disable Basic authentication" OFF) +mark_as_advanced(CURL_DISABLE_BASIC_AUTH) +option(CURL_DISABLE_BEARER_AUTH "Disable Bearer authentication" OFF) +mark_as_advanced(CURL_DISABLE_BEARER_AUTH) +option(CURL_DISABLE_DIGEST_AUTH "Disable Digest authentication" OFF) +mark_as_advanced(CURL_DISABLE_DIGEST_AUTH) +option(CURL_DISABLE_KERBEROS_AUTH "Disable Kerberos authentication" OFF) +mark_as_advanced(CURL_DISABLE_KERBEROS_AUTH) +option(CURL_DISABLE_NEGOTIATE_AUTH "Disable negotiate authentication" OFF) +mark_as_advanced(CURL_DISABLE_NEGOTIATE_AUTH) +option(CURL_DISABLE_AWS "Disable aws-sigv4" OFF) +mark_as_advanced(CURL_DISABLE_AWS) +option(CURL_DISABLE_DICT "Disable DICT" OFF) +mark_as_advanced(CURL_DISABLE_DICT) +option(CURL_DISABLE_DOH "Disable DNS-over-HTTPS" OFF) +mark_as_advanced(CURL_DISABLE_DOH) +option(CURL_DISABLE_FILE "Disable FILE" OFF) +mark_as_advanced(CURL_DISABLE_FILE) +option(CURL_DISABLE_FTP "Disable FTP" OFF) +mark_as_advanced(CURL_DISABLE_FTP) +option(CURL_DISABLE_GETOPTIONS "Disable curl_easy_options API for existing options to curl_easy_setopt" OFF) +mark_as_advanced(CURL_DISABLE_GETOPTIONS) +option(CURL_DISABLE_GOPHER "Disable Gopher" OFF) +mark_as_advanced(CURL_DISABLE_GOPHER) +option(CURL_DISABLE_HEADERS_API "Disable headers-api support" OFF) +mark_as_advanced(CURL_DISABLE_HEADERS_API) +option(CURL_DISABLE_HSTS "Disable HSTS support" OFF) +mark_as_advanced(CURL_DISABLE_HSTS) +option(CURL_DISABLE_HTTP "Disable HTTP" OFF) +mark_as_advanced(CURL_DISABLE_HTTP) +option(CURL_DISABLE_HTTP_AUTH "Disable all HTTP authentication methods" OFF) +mark_as_advanced(CURL_DISABLE_HTTP_AUTH) +option(CURL_DISABLE_IMAP "Disable IMAP" OFF) +mark_as_advanced(CURL_DISABLE_IMAP) +option(CURL_DISABLE_LDAP "Disable LDAP" OFF) +mark_as_advanced(CURL_DISABLE_LDAP) +option(CURL_DISABLE_LDAPS "Disable LDAPS" ${CURL_DISABLE_LDAP}) +mark_as_advanced(CURL_DISABLE_LDAPS) +option(CURL_DISABLE_LIBCURL_OPTION "Disable --libcurl option from the curl tool" OFF) +mark_as_advanced(CURL_DISABLE_LIBCURL_OPTION) +option(CURL_DISABLE_MIME "Disable MIME support" OFF) +mark_as_advanced(CURL_DISABLE_MIME) +cmake_dependent_option(CURL_DISABLE_FORM_API "Disable form-api" + OFF "NOT CURL_DISABLE_MIME" + ON) +mark_as_advanced(CURL_DISABLE_FORM_API) +option(CURL_DISABLE_MQTT "Disable MQTT" OFF) +mark_as_advanced(CURL_DISABLE_MQTT) +option(CURL_DISABLE_BINDLOCAL "Disable local binding support" OFF) +mark_as_advanced(CURL_DISABLE_BINDLOCAL) +option(CURL_DISABLE_NETRC "Disable netrc parser" OFF) +mark_as_advanced(CURL_DISABLE_NETRC) +option(CURL_DISABLE_NTLM "Disable NTLM support" OFF) +mark_as_advanced(CURL_DISABLE_NTLM) +option(CURL_DISABLE_PARSEDATE "Disable date parsing" OFF) +mark_as_advanced(CURL_DISABLE_PARSEDATE) +option(CURL_DISABLE_POP3 "Disable POP3" OFF) +mark_as_advanced(CURL_DISABLE_POP3) +option(CURL_DISABLE_PROGRESS_METER "Disable built-in progress meter" OFF) +mark_as_advanced(CURL_DISABLE_PROGRESS_METER) +option(CURL_DISABLE_PROXY "Disable proxy support" OFF) +mark_as_advanced(CURL_DISABLE_PROXY) +option(CURL_DISABLE_IPFS "Disable IPFS" OFF) +mark_as_advanced(CURL_DISABLE_IPFS) +option(CURL_DISABLE_RTSP "Disable RTSP" OFF) +mark_as_advanced(CURL_DISABLE_SHA512_256) +option(CURL_DISABLE_SHA512_256 "Disable SHA-512/256 hash algorithm" OFF) +mark_as_advanced(CURL_DISABLE_RTSP) +option(CURL_DISABLE_SHUFFLE_DNS "Disable shuffle DNS feature" OFF) +mark_as_advanced(CURL_DISABLE_SHUFFLE_DNS) +option(CURL_DISABLE_SMB "Disable SMB" OFF) +mark_as_advanced(CURL_DISABLE_SMB) +option(CURL_DISABLE_SMTP "Disable SMTP" OFF) +mark_as_advanced(CURL_DISABLE_SMTP) +option(CURL_DISABLE_SOCKETPAIR "Disable use of socketpair for curl_multi_poll" OFF) +mark_as_advanced(CURL_DISABLE_SOCKETPAIR) +option(CURL_DISABLE_WEBSOCKETS "Disable WebSocket" OFF) +mark_as_advanced(CURL_DISABLE_WEBSOCKETS) +option(CURL_DISABLE_TELNET "Disable Telnet" OFF) +mark_as_advanced(CURL_DISABLE_TELNET) +option(CURL_DISABLE_TFTP "Disable TFTP" OFF) +mark_as_advanced(CURL_DISABLE_TFTP) +option(CURL_DISABLE_VERBOSE_STRINGS "Disable verbose strings" OFF) +mark_as_advanced(CURL_DISABLE_VERBOSE_STRINGS) + +if(CURL_DISABLE_HTTP) + set(CURL_DISABLE_IPFS ON) + set(CURL_DISABLE_RTSP ON) + set(CURL_DISABLE_ALTSVC ON) + set(CURL_DISABLE_HSTS ON) +endif() + +# Corresponds to HTTP_ONLY in lib/curl_setup.h +option(HTTP_ONLY "Disable all protocols except HTTP (This overrides all CURL_DISABLE_* options)" OFF) +mark_as_advanced(HTTP_ONLY) + +if(HTTP_ONLY) + set(CURL_DISABLE_DICT ON) + set(CURL_DISABLE_FILE ON) + set(CURL_DISABLE_FTP ON) + set(CURL_DISABLE_GOPHER ON) + set(CURL_DISABLE_IMAP ON) + set(CURL_DISABLE_LDAP ON) + set(CURL_DISABLE_LDAPS ON) + set(CURL_DISABLE_MQTT ON) + set(CURL_DISABLE_POP3 ON) + set(CURL_DISABLE_IPFS ON) + set(CURL_DISABLE_RTSP ON) + set(CURL_DISABLE_SMB ON) + set(CURL_DISABLE_SMTP ON) + set(CURL_DISABLE_TELNET ON) + set(CURL_DISABLE_TFTP ON) +endif() + +if(WINDOWS_STORE) + set(CURL_DISABLE_TELNET ON) # telnet code needs fixing to compile for UWP. +endif() + +option(ENABLE_IPV6 "Enable IPv6 support" ON) +mark_as_advanced(ENABLE_IPV6) +if(ENABLE_IPV6 AND NOT WIN32) + include(CheckStructHasMember) + check_struct_has_member("struct sockaddr_in6" "sin6_addr" "netinet/in.h" HAVE_SOCKADDR_IN6_SIN6_ADDR) + check_struct_has_member("struct sockaddr_in6" "sin6_scope_id" "netinet/in.h" HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) + if(NOT HAVE_SOCKADDR_IN6_SIN6_ADDR) + message(WARNING "struct sockaddr_in6 not available, disabling IPv6 support") + # Force the feature off as this name is used as guard macro... + set(ENABLE_IPV6 OFF CACHE BOOL "Enable IPv6 support" FORCE) + endif() + + if(APPLE AND NOT ENABLE_ARES) + set(_use_core_foundation_and_core_services ON) + + find_library(SYSTEMCONFIGURATION_FRAMEWORK "SystemConfiguration") + mark_as_advanced(SYSTEMCONFIGURATION_FRAMEWORK) + if(NOT SYSTEMCONFIGURATION_FRAMEWORK) + message(FATAL_ERROR "SystemConfiguration framework not found") + endif() + + list(APPEND CURL_LIBS "-framework SystemConfiguration") + endif() +endif() +if(ENABLE_IPV6) + set(USE_IPV6 ON) +endif() + +find_package(Perl) + +option(BUILD_LIBCURL_DOCS "Build libcurl man pages" ON) +option(BUILD_MISC_DOCS "Build misc man pages (e.g. curl-config and mk-ca-bundle)" ON) +option(ENABLE_CURL_MANUAL "Build the man page for curl and enable its -M/--manual option" ON) + +if(ENABLE_CURL_MANUAL OR BUILD_LIBCURL_DOCS) + if(PERL_FOUND) + set(HAVE_MANUAL_TOOLS ON) + endif() + if(NOT HAVE_MANUAL_TOOLS) + message(WARNING "Perl not found. Will not build manuals.") + endif() +endif() + +# Disable warnings on Borland to avoid changing 3rd party code. +if(BORLAND) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-") +endif() + +# If we are on AIX, do the _ALL_SOURCE magic +if(CMAKE_SYSTEM_NAME STREQUAL "AIX") + add_definitions("-D_ALL_SOURCE") +endif() + +# If we are on Haiku, make sure that the network library is brought in. +if(CMAKE_SYSTEM_NAME STREQUAL "Haiku") + list(APPEND CURL_LIBS "network") +endif() + +# Include all the necessary files for macros +include(CMakePushCheckState) +include(CheckFunctionExists) +include(CheckIncludeFile) +include(CheckIncludeFiles) +include(CheckLibraryExists) +include(CheckSymbolExists) +include(CheckTypeSize) +include(CheckCSourceCompiles) + +# Preload settings on Windows +if(WIN32) + include("${CMAKE_CURRENT_SOURCE_DIR}/CMake/Platforms/WindowsCache.cmake") +elseif(APPLE) + # Fast-track predictable feature detections + set(HAVE_EVENTFD 0) + set(HAVE_GETPASS_R 0) + set(HAVE_SENDMMSG 0) +endif() + +if(ENABLE_THREADED_RESOLVER) + if(WIN32) + set(USE_THREADS_WIN32 ON) + else() + find_package(Threads REQUIRED) + set(USE_THREADS_POSIX ${CMAKE_USE_PTHREADS_INIT}) + set(HAVE_PTHREAD_H ${CMAKE_USE_PTHREADS_INIT}) + list(APPEND CURL_LIBS ${CMAKE_THREAD_LIBS_INIT}) + endif() +endif() + +# Check for all needed libraries +if(NOT WIN32 AND NOT APPLE) + check_library_exists("socket" "connect" "" HAVE_LIBSOCKET) + if(HAVE_LIBSOCKET) + set(CURL_LIBS "socket;${CURL_LIBS}") + endif() +endif() + +check_function_exists("gethostname" HAVE_GETHOSTNAME) + +if(WIN32) + list(APPEND CURL_LIBS "ws2_32" "bcrypt") +endif() + +# Check SSL libraries +option(CURL_ENABLE_SSL "Enable SSL support" ON) + +if(CURL_DEFAULT_SSL_BACKEND) + set(_valid_default_ssl_backend FALSE) +endif() + +if(APPLE) + cmake_dependent_option(CURL_USE_SECTRANSP "Enable Apple OS native SSL/TLS (Secure Transport)" OFF CURL_ENABLE_SSL OFF) +endif() +if(WIN32) + cmake_dependent_option(CURL_USE_SCHANNEL "Enable Windows native SSL/TLS (Schannel)" OFF CURL_ENABLE_SSL OFF) + option(CURL_WINDOWS_SSPI "Enable SSPI on Windows" ${CURL_USE_SCHANNEL}) +endif() +cmake_dependent_option(CURL_USE_MBEDTLS "Enable mbedTLS for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_BEARSSL "Enable BearSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_WOLFSSL "Enable wolfSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_GNUTLS "Enable GnuTLS for SSL/TLS" OFF CURL_ENABLE_SSL OFF) +cmake_dependent_option(CURL_USE_RUSTLS "Enable Rustls for SSL/TLS" OFF CURL_ENABLE_SSL OFF) + +if(WIN32 OR + CURL_USE_SECTRANSP OR + CURL_USE_SCHANNEL OR + CURL_USE_MBEDTLS OR + CURL_USE_BEARSSL OR + CURL_USE_WOLFSSL OR + CURL_USE_GNUTLS OR + CURL_USE_RUSTLS) + set(_openssl_default OFF) +else() + set(_openssl_default ON) +endif() +cmake_dependent_option(CURL_USE_OPENSSL "Enable OpenSSL for SSL/TLS" ${_openssl_default} CURL_ENABLE_SSL OFF) +option(USE_OPENSSL_QUIC "Use OpenSSL and nghttp3 libraries for HTTP/3 support" OFF) +if(USE_OPENSSL_QUIC AND NOT CURL_USE_OPENSSL) + message(WARNING "OpenSSL QUIC has been requested, but without enabling OpenSSL. Will not enable QUIC.") + set(USE_OPENSSL_QUIC OFF) +endif() +option(CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG "Disable automatic loading of OpenSSL configuration" OFF) + +count_true(_enabled_ssl_options_count + CURL_USE_SCHANNEL + CURL_USE_SECTRANSP + CURL_USE_OPENSSL + CURL_USE_MBEDTLS + CURL_USE_BEARSSL + CURL_USE_WOLFSSL + CURL_USE_GNUTLS + CURL_USE_RUSTLS +) +if(_enabled_ssl_options_count GREATER 1) + set(CURL_WITH_MULTI_SSL ON) +elseif(_enabled_ssl_options_count EQUAL 0) + set(CURL_DISABLE_HSTS ON) +endif() + +if(CURL_USE_SCHANNEL) + set(_ssl_enabled ON) + set(USE_SCHANNEL ON) # Windows native SSL/TLS support + set(USE_WINDOWS_SSPI ON) # CURL_USE_SCHANNEL implies CURL_WINDOWS_SSPI + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "schannel") + set(_valid_default_ssl_backend TRUE) + endif() +endif() +if(CURL_WINDOWS_SSPI) + set(USE_WINDOWS_SSPI ON) +endif() + +if(CURL_USE_SECTRANSP) + set(_use_core_foundation_and_core_services ON) + + find_library(SECURITY_FRAMEWORK "Security") + mark_as_advanced(SECURITY_FRAMEWORK) + if(NOT SECURITY_FRAMEWORK) + message(FATAL_ERROR "Security framework not found") + endif() + + set(_ssl_enabled ON) + set(USE_SECTRANSP ON) + list(APPEND CURL_LIBS "-framework Security") + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "secure-transport") + set(_valid_default_ssl_backend TRUE) + endif() + + message(WARNING "Secure Transport does not support TLS 1.3.") +endif() + +if(_use_core_foundation_and_core_services) + find_library(COREFOUNDATION_FRAMEWORK "CoreFoundation") + mark_as_advanced(COREFOUNDATION_FRAMEWORK) + find_library(CORESERVICES_FRAMEWORK "CoreServices") + mark_as_advanced(CORESERVICES_FRAMEWORK) + + if(NOT COREFOUNDATION_FRAMEWORK) + message(FATAL_ERROR "CoreFoundation framework not found") + endif() + if(NOT CORESERVICES_FRAMEWORK) + message(FATAL_ERROR "CoreServices framework not found") + endif() + + list(APPEND CURL_LIBS "-framework CoreFoundation" "-framework CoreServices") +endif() + +if(CURL_USE_OPENSSL) + find_package(OpenSSL REQUIRED) + set(_ssl_enabled ON) + set(USE_OPENSSL ON) + + # Depend on OpenSSL via imported targets. This allows our dependents to + # get our dependencies transitively. + list(APPEND CURL_LIBS OpenSSL::SSL OpenSSL::Crypto) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "openssl") + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "openssl") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) + + cmake_push_check_state() + set(CMAKE_REQUIRED_INCLUDES ${OPENSSL_INCLUDE_DIR}) + if(NOT DEFINED HAVE_BORINGSSL) + check_symbol_exists("OPENSSL_IS_BORINGSSL" "openssl/base.h" HAVE_BORINGSSL) + endif() + if(NOT DEFINED HAVE_AWSLC) + check_symbol_exists("OPENSSL_IS_AWSLC" "openssl/base.h" HAVE_AWSLC) + endif() + cmake_pop_check_state() +endif() + +if(CURL_USE_MBEDTLS) + find_package(MbedTLS REQUIRED) + set(_ssl_enabled ON) + set(USE_MBEDTLS ON) + list(APPEND CURL_LIBS ${MBEDTLS_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${MBEDTLS_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE ${MBEDTLS_PC_REQUIRES}) + include_directories(SYSTEM ${MBEDTLS_INCLUDE_DIRS}) + link_directories(${MBEDTLS_LIBRARY_DIRS}) + if(MBEDTLS_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MBEDTLS_CFLAGS}") + endif() + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "mbedtls") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) +endif() + +if(CURL_USE_BEARSSL) + find_package(BearSSL REQUIRED) + set(_ssl_enabled ON) + set(USE_BEARSSL ON) + list(APPEND CURL_LIBS ${BEARSSL_LIBRARIES}) + include_directories(SYSTEM ${BEARSSL_INCLUDE_DIRS}) + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "bearssl") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) + + message(WARNING "BearSSL does not support TLS 1.3.") +endif() + +if(CURL_USE_WOLFSSL) + find_package(WolfSSL REQUIRED) + set(_ssl_enabled ON) + set(USE_WOLFSSL ON) + list(APPEND CURL_LIBS ${WOLFSSL_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${WOLFSSL_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "wolfssl") + include_directories(SYSTEM ${WOLFSSL_INCLUDE_DIRS}) + link_directories(${WOLFSSL_LIBRARY_DIRS}) + if(WOLFSSL_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WOLFSSL_CFLAGS}") + endif() + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "wolfssl") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) +endif() + +if(CURL_USE_GNUTLS) + if(CURL_USE_PKGCONFIG) + find_package(PkgConfig QUIET) + pkg_check_modules(GNUTLS "gnutls") + if(GNUTLS_FOUND) + set(GNUTLS_LIBRARIES ${GNUTLS_LINK_LIBRARIES}) + endif() + endif() + if(NOT GNUTLS_FOUND) + find_package(GnuTLS REQUIRED) + endif() + find_package(Nettle REQUIRED) + set(_ssl_enabled ON) + set(USE_GNUTLS ON) + list(APPEND CURL_LIBS ${GNUTLS_LIBRARIES} ${NETTLE_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${NETTLE_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "gnutls" "nettle") + include_directories(SYSTEM ${GNUTLS_INCLUDE_DIRS} ${NETTLE_INCLUDE_DIRS}) + link_directories(${NETTLE_LIBRARY_DIRS}) + if(NETTLE_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${NETTLE_CFLAGS}") + endif() + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "gnutls") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) + + if(NOT DEFINED HAVE_GNUTLS_SRP AND NOT CURL_DISABLE_SRP) + cmake_push_check_state() + set(CMAKE_REQUIRED_INCLUDES ${GNUTLS_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${GNUTLS_LIBRARIES}) + check_symbol_exists("gnutls_srp_verifier" "gnutls/gnutls.h" HAVE_GNUTLS_SRP) + cmake_pop_check_state() + endif() +endif() + +if(CURL_USE_RUSTLS) + find_package(Rustls REQUIRED) + set(_ssl_enabled ON) + set(USE_RUSTLS ON) + list(APPEND CURL_LIBS ${RUSTLS_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${RUSTLS_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE ${RUSTLS_PC_REQUIRES}) + include_directories(SYSTEM ${RUSTLS_INCLUDE_DIRS}) + link_directories(${RUSTLS_LIBRARY_DIRS}) + if(RUSTLS_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${RUSTLS_CFLAGS}") + endif() + + if(CURL_DEFAULT_SSL_BACKEND AND CURL_DEFAULT_SSL_BACKEND STREQUAL "rustls") + set(_valid_default_ssl_backend TRUE) + endif() + set(_curl_ca_bundle_supported TRUE) +endif() + +if(CURL_DEFAULT_SSL_BACKEND AND NOT _valid_default_ssl_backend) + message(FATAL_ERROR "CURL_DEFAULT_SSL_BACKEND '${CURL_DEFAULT_SSL_BACKEND}' not enabled.") +endif() + +# Keep ZLIB detection after TLS detection, +# and before calling openssl_check_symbol_exists(). + +set(HAVE_LIBZ OFF) +curl_dependency_option(ZLIB) +if(ZLIB_FOUND) + set(HAVE_LIBZ ON) + + # Depend on ZLIB via imported targets. This allows our dependents to + # get our dependencies transitively. + list(APPEND CURL_LIBS ZLIB::ZLIB) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "zlib") +endif() + +option(CURL_BROTLI "Use brotli" OFF) +set(HAVE_BROTLI OFF) +if(CURL_BROTLI) + find_package(Brotli REQUIRED) + if(BROTLI_FOUND) + set(HAVE_BROTLI ON) + list(APPEND CURL_LIBS ${BROTLI_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libbrotlidec") + include_directories(SYSTEM ${BROTLI_INCLUDE_DIRS}) + endif() +endif() + +option(CURL_ZSTD "Use zstd" OFF) +set(HAVE_ZSTD OFF) +if(CURL_ZSTD) + find_package(Zstd REQUIRED) + if(ZSTD_FOUND AND NOT ZSTD_VERSION VERSION_LESS 1.0.0) + set(HAVE_ZSTD ON) + list(APPEND CURL_LIBS ${ZSTD_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libzstd") + include_directories(SYSTEM ${ZSTD_INCLUDE_DIRS}) + else() + message(WARNING "zstd v1.0.0 or newer is required, disabling zstd support.") + endif() +endif() + +# Check symbol in an OpenSSL-like TLS backend, or in _extra_libs depending on it. +macro(openssl_check_symbol_exists _symbol _files _variable _extra_libs) + cmake_push_check_state() + if(USE_OPENSSL) + set(CMAKE_REQUIRED_INCLUDES "${OPENSSL_INCLUDE_DIR}") + set(CMAKE_REQUIRED_LIBRARIES "${OPENSSL_LIBRARIES}") + if(HAVE_LIBZ) + list(APPEND CMAKE_REQUIRED_LIBRARIES "${ZLIB_LIBRARIES}") + endif() + if(WIN32) + list(APPEND CMAKE_REQUIRED_LIBRARIES "ws2_32") + list(APPEND CMAKE_REQUIRED_LIBRARIES "bcrypt") # for OpenSSL/LibreSSL + endif() + elseif(USE_WOLFSSL) + set(CMAKE_REQUIRED_INCLUDES "${WOLFSSL_INCLUDE_DIRS}") + set(CMAKE_REQUIRED_LIBRARIES "${WOLFSSL_LIBRARIES}") + curl_required_libpaths("${WOLFSSL_LIBRARY_DIRS}") + if(HAVE_LIBZ) + list(APPEND CMAKE_REQUIRED_INCLUDES "${ZLIB_INCLUDE_DIRS}") # Public wolfSSL headers require zlib headers + list(APPEND CMAKE_REQUIRED_LIBRARIES "${ZLIB_LIBRARIES}") + endif() + if(WIN32) + list(APPEND CMAKE_REQUIRED_LIBRARIES "ws2_32" "crypt32") + endif() + list(APPEND CMAKE_REQUIRED_DEFINITIONS "-DHAVE_UINTPTR_T") # to pull in stdint.h (as of wolfSSL v5.5.4) + endif() + list(APPEND CMAKE_REQUIRED_LIBRARIES "${_extra_libs}") + check_symbol_exists("${_symbol}" "${_files}" "${_variable}") + cmake_pop_check_state() +endmacro() + +# Ensure that the OpenSSL fork actually supports QUIC. +macro(openssl_check_quic) + if(NOT DEFINED HAVE_SSL_CTX_SET_QUIC_METHOD) + if(USE_OPENSSL) + openssl_check_symbol_exists("SSL_CTX_set_quic_method" "openssl/ssl.h" HAVE_SSL_CTX_SET_QUIC_METHOD "") + elseif(USE_WOLFSSL) + openssl_check_symbol_exists("wolfSSL_set_quic_method" "wolfssl/options.h;wolfssl/openssl/ssl.h" + HAVE_SSL_CTX_SET_QUIC_METHOD "") + endif() + endif() + if(NOT HAVE_SSL_CTX_SET_QUIC_METHOD) + message(FATAL_ERROR "QUIC support is missing in OpenSSL fork. Try setting -DOPENSSL_ROOT_DIR") + endif() +endmacro() + +if(USE_WOLFSSL) + openssl_check_symbol_exists("wolfSSL_DES_ecb_encrypt" "wolfssl/options.h;wolfssl/openssl/des.h" HAVE_WOLFSSL_DES_ECB_ENCRYPT "") + openssl_check_symbol_exists("wolfSSL_BIO_new" "wolfssl/options.h;wolfssl/ssl.h" HAVE_WOLFSSL_BIO "") + openssl_check_symbol_exists("wolfSSL_BIO_set_shutdown" "wolfssl/options.h;wolfssl/ssl.h" HAVE_WOLFSSL_FULL_BIO "") +endif() + +if(USE_OPENSSL OR USE_WOLFSSL) + if(NOT DEFINED HAVE_SSL_SET0_WBIO) + openssl_check_symbol_exists("SSL_set0_wbio" "openssl/ssl.h" HAVE_SSL_SET0_WBIO "") + endif() + if(NOT DEFINED HAVE_OPENSSL_SRP AND NOT CURL_DISABLE_SRP) + openssl_check_symbol_exists("SSL_CTX_set_srp_username" "openssl/ssl.h" HAVE_OPENSSL_SRP "") + endif() +endif() + +option(USE_HTTPSRR "Enable HTTPS RR support" OFF) +option(USE_ECH "Enable ECH support" OFF) +if(USE_ECH) + if(USE_OPENSSL OR USE_WOLFSSL) + # Be sure that the TLS library actually supports ECH. + if(NOT DEFINED HAVE_ECH) + if(USE_OPENSSL AND (HAVE_BORINGSSL OR HAVE_AWSLC)) + openssl_check_symbol_exists("SSL_set1_ech_config_list" "openssl/ssl.h" HAVE_ECH "") + elseif(USE_OPENSSL) + openssl_check_symbol_exists("SSL_ech_set1_echconfig" "openssl/ech.h" HAVE_ECH "") + elseif(USE_WOLFSSL) + openssl_check_symbol_exists("wolfSSL_CTX_GenerateEchConfig" "wolfssl/options.h;wolfssl/ssl.h" HAVE_ECH "") + endif() + endif() + if(NOT HAVE_ECH) + message(FATAL_ERROR "ECH support missing in OpenSSL/BoringSSL/AWS-LC/wolfSSL") + else() + message(STATUS "ECH enabled.") + endif() + else() + message(FATAL_ERROR "ECH requires ECH-enablded OpenSSL, BoringSSL, AWS-LC or wolfSSL") + endif() +endif() + +option(USE_NGHTTP2 "Use nghttp2 library" ON) +if(USE_NGHTTP2) + find_package(NGHTTP2) + if(NGHTTP2_FOUND) + include_directories(SYSTEM ${NGHTTP2_INCLUDE_DIRS}) + list(APPEND CURL_LIBS ${NGHTTP2_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libnghttp2") + else() + set(USE_NGHTTP2 OFF) + endif() +endif() + +option(USE_NGTCP2 "Use ngtcp2 and nghttp3 libraries for HTTP/3 support" OFF) +if(USE_NGTCP2) + if(USE_OPENSSL OR USE_WOLFSSL) + if(USE_WOLFSSL) + find_package(NGTCP2 REQUIRED "wolfSSL") + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libngtcp2_crypto_wolfssl") + elseif(HAVE_BORINGSSL OR HAVE_AWSLC) + find_package(NGTCP2 REQUIRED "BoringSSL") + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libngtcp2_crypto_boringssl") + else() + find_package(NGTCP2 REQUIRED "quictls") + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libngtcp2_crypto_quictls") + endif() + openssl_check_quic() + elseif(USE_GNUTLS) + find_package(NGTCP2 REQUIRED "GnuTLS") + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libngtcp2_crypto_gnutls") + else() + message(FATAL_ERROR "ngtcp2 requires OpenSSL, wolfSSL or GnuTLS") + endif() + include_directories(SYSTEM ${NGTCP2_INCLUDE_DIRS}) + list(APPEND CURL_LIBS ${NGTCP2_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libngtcp2") + + find_package(NGHTTP3 REQUIRED) + set(USE_NGHTTP3 ON) + include_directories(SYSTEM ${NGHTTP3_INCLUDE_DIRS}) + list(APPEND CURL_LIBS ${NGHTTP3_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libnghttp3") +endif() + +option(USE_QUICHE "Use quiche library for HTTP/3 support" OFF) +if(USE_QUICHE) + if(USE_NGTCP2) + message(FATAL_ERROR "Only one HTTP/3 backend can be selected") + endif() + find_package(Quiche REQUIRED) + if(NOT HAVE_BORINGSSL) + message(FATAL_ERROR "quiche requires BoringSSL") + endif() + openssl_check_quic() + list(APPEND CURL_LIBS ${QUICHE_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${QUICHE_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "quiche") + include_directories(SYSTEM ${QUICHE_INCLUDE_DIRS}) + link_directories(${QUICHE_LIBRARY_DIRS}) + if(QUICHE_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${QUICHE_CFLAGS}") + endif() + if(NOT DEFINED HAVE_QUICHE_CONN_SET_QLOG_FD) + cmake_push_check_state() + set(CMAKE_REQUIRED_INCLUDES "${QUICHE_INCLUDE_DIRS}") + set(CMAKE_REQUIRED_LIBRARIES "${QUICHE_LIBRARIES}") + check_symbol_exists("quiche_conn_set_qlog_fd" "quiche.h" HAVE_QUICHE_CONN_SET_QLOG_FD) + cmake_pop_check_state() + endif() +endif() + +option(USE_MSH3 "Use msh3/msquic library for HTTP/3 support" OFF) +if(USE_MSH3) + if(USE_NGTCP2 OR USE_QUICHE) + message(FATAL_ERROR "Only one HTTP/3 backend can be selected") + endif() + if(NOT WIN32) + if(NOT USE_OPENSSL) + message(FATAL_ERROR "msh3/msquic requires OpenSSL fork with QUIC API") + endif() + openssl_check_quic() + endif() + find_package(MSH3 REQUIRED) + list(APPEND CURL_LIBS ${MSH3_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${MSH3_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE ${MSH3_PC_REQUIRES}) + include_directories(SYSTEM ${MSH3_INCLUDE_DIRS}) + link_directories(${MSH3_LIBRARY_DIRS}) + if(MSH3_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MSH3_CFLAGS}") + endif() +endif() + +if(USE_OPENSSL_QUIC) + if(USE_NGTCP2 OR USE_QUICHE OR USE_MSH3) + message(FATAL_ERROR "Only one HTTP/3 backend can be selected") + endif() + find_package(OpenSSL 3.3.0 REQUIRED) + + find_package(NGHTTP3 REQUIRED) + set(USE_NGHTTP3 ON) + include_directories(SYSTEM ${NGHTTP3_INCLUDE_DIRS}) + list(APPEND CURL_LIBS ${NGHTTP3_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libnghttp3") +endif() + +if(CURL_WITH_MULTI_SSL AND (USE_NGTCP2 OR USE_QUICHE OR USE_MSH3 OR USE_OPENSSL_QUIC)) + message(FATAL_ERROR "MultiSSL cannot be enabled with HTTP/3 and vice versa.") +endif() + +if(NOT CURL_DISABLE_SRP AND (HAVE_GNUTLS_SRP OR HAVE_OPENSSL_SRP)) + set(USE_TLS_SRP 1) +endif() + +if(NOT CURL_DISABLE_LDAP) + if(WIN32 AND NOT WINDOWS_STORE) + option(USE_WIN32_LDAP "Use Windows LDAP implementation" ON) + if(USE_WIN32_LDAP) + list(APPEND CURL_LIBS "wldap32") + if(NOT CURL_DISABLE_LDAPS) + set(HAVE_LDAP_SSL ON) + endif() + endif() + endif() + + # Now that we know, we are not using Windows LDAP... + if(NOT USE_WIN32_LDAP) + if(NOT DEFINED LDAP_LIBRARY) + set(LDAP_LIBRARY "ldap" CACHE STRING "Name or full path to ldap library") + endif() + if(NOT DEFINED LDAP_LBER_LIBRARY) + set(LDAP_LBER_LIBRARY "lber" CACHE STRING "Name or full path to lber library") + endif() + if(NOT DEFINED LDAP_INCLUDE_DIR) + set(LDAP_INCLUDE_DIR "" CACHE STRING "Path to LDAP include directory") + endif() + + # Check for LDAP + cmake_push_check_state() + if(USE_OPENSSL) + set(CMAKE_REQUIRED_LIBRARIES ${OPENSSL_LIBRARIES}) + endif() + check_library_exists("${LDAP_LIBRARY}" "ldap_init" "" HAVE_LIBLDAP) + if(HAVE_LIBLDAP) + check_library_exists("${LDAP_LIBRARY};${LDAP_LBER_LIBRARY}" "ber_init" "" HAVE_LIBLBER) + else() + check_library_exists("${LDAP_LBER_LIBRARY}" "ber_init" "" HAVE_LIBLBER) + endif() + + if(LDAP_INCLUDE_DIR) + list(APPEND CMAKE_REQUIRED_INCLUDES ${LDAP_INCLUDE_DIR}) + endif() + + unset(_include_list) + check_include_file("lber.h" HAVE_LBER_H) + if(HAVE_LBER_H) + list(APPEND _include_list "lber.h") + endif() + check_include_files("${_include_list};ldap.h" HAVE_LDAP_H) + unset(_include_list) + + if(NOT HAVE_LDAP_H) + message(STATUS "LDAP_H not found CURL_DISABLE_LDAP set ON") + set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) + elseif(NOT HAVE_LIBLDAP) + message(STATUS "LDAP library '${LDAP_LIBRARY}' not found CURL_DISABLE_LDAP set ON") + set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) + else() + if(LDAP_INCLUDE_DIR) + include_directories(SYSTEM ${LDAP_INCLUDE_DIR}) + endif() + list(APPEND CMAKE_REQUIRED_DEFINITIONS "-DLDAP_DEPRECATED=1") + list(APPEND CMAKE_REQUIRED_LIBRARIES ${LDAP_LIBRARY}) + set(CURL_LIBS "${LDAP_LIBRARY};${CURL_LIBS}") + # FIXME: uncomment once pkg-config-based detection landed: https://github.com/curl/curl/pull/15273 + # set(LIBCURL_PC_REQUIRES_PRIVATE "${LDAP_PC_REQUIRES};${LIBCURL_PC_REQUIRES_PRIVATE}") + if(HAVE_LIBLBER) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${LDAP_LBER_LIBRARY}) + set(CURL_LIBS "${LDAP_LBER_LIBRARY};${CURL_LIBS}") + endif() + + check_function_exists("ldap_url_parse" HAVE_LDAP_URL_PARSE) + check_function_exists("ldap_init_fd" HAVE_LDAP_INIT_FD) + + check_include_file("ldap_ssl.h" HAVE_LDAP_SSL_H) + + if(HAVE_LDAP_INIT_FD) + set(USE_OPENLDAP ON) + add_definitions("-DLDAP_DEPRECATED=1") + endif() + if(NOT CURL_DISABLE_LDAPS) + set(HAVE_LDAP_SSL ON) + endif() + endif() + cmake_pop_check_state() + endif() +endif() + +# No ldap, no ldaps. +if(CURL_DISABLE_LDAP) + if(NOT CURL_DISABLE_LDAPS) + message(STATUS "LDAP needs to be enabled to support LDAPS") + set(CURL_DISABLE_LDAPS ON CACHE BOOL "" FORCE) + endif() +endif() + +if(WIN32) + option(USE_WIN32_IDN "Use WinIDN for IDN support" OFF) + if(USE_WIN32_IDN) + list(APPEND CURL_LIBS "normaliz") + endif() +else() + set(USE_WIN32_IDN OFF) +endif() + +if(APPLE) + option(USE_APPLE_IDN "Use Apple built-in IDN support" OFF) + if(USE_APPLE_IDN) + cmake_push_check_state() + set(CMAKE_REQUIRED_LIBRARIES "icucore") + check_symbol_exists("uidna_openUTS46" "unicode/uidna.h" HAVE_APPLE_IDN) + cmake_pop_check_state() + if(HAVE_APPLE_IDN) + list(APPEND CURL_LIBS "icucore" "iconv") + else() + set(USE_APPLE_IDN OFF) + endif() + endif() +else() + set(USE_APPLE_IDN OFF) +endif() + +# Check for libidn2 +option(USE_LIBIDN2 "Use libidn2 for IDN support" ON) +set(HAVE_IDN2_H OFF) +set(HAVE_LIBIDN2 OFF) +if(USE_LIBIDN2 AND NOT USE_APPLE_IDN AND NOT USE_WIN32_IDN) + find_package(Libidn2) + if(LIBIDN2_FOUND) + set(CURL_LIBS "${LIBIDN2_LIBRARIES};${CURL_LIBS}") + list(APPEND CURL_LIBDIRS ${LIBIDN2_LIBRARY_DIRS}) + set(LIBCURL_PC_REQUIRES_PRIVATE "libidn2;${LIBCURL_PC_REQUIRES_PRIVATE}") + include_directories(SYSTEM ${LIBIDN2_INCLUDE_DIRS}) + link_directories(${LIBIDN2_LIBRARY_DIRS}) + if(LIBIDN2_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${LIBIDN2_CFLAGS}") + endif() + set(HAVE_IDN2_H 1) + set(HAVE_LIBIDN2 1) + endif() +endif() + +# libpsl +option(CURL_USE_LIBPSL "Use libpsl" ON) +mark_as_advanced(CURL_USE_LIBPSL) +set(USE_LIBPSL OFF) + +if(CURL_USE_LIBPSL) + find_package(Libpsl) # TODO: add REQUIRED to match autotools + if(LIBPSL_FOUND) + list(APPEND CURL_LIBS ${LIBPSL_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libpsl") + include_directories(SYSTEM ${LIBPSL_INCLUDE_DIRS}) + set(USE_LIBPSL ON) + else() + message(WARNING "libpsl is enabled, but not found.") + endif() +endif() + +# libssh2 +option(CURL_USE_LIBSSH2 "Use libssh2" ON) +mark_as_advanced(CURL_USE_LIBSSH2) +set(USE_LIBSSH2 OFF) + +if(CURL_USE_LIBSSH2) + find_package(Libssh2) + if(LIBSSH2_FOUND) + list(APPEND CURL_LIBS ${LIBSSH2_LIBRARIES}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libssh2") + include_directories(SYSTEM ${LIBSSH2_INCLUDE_DIRS}) + set(USE_LIBSSH2 ON) + endif() +endif() + +# libssh +option(CURL_USE_LIBSSH "Use libssh" OFF) +mark_as_advanced(CURL_USE_LIBSSH) +if(NOT USE_LIBSSH2 AND CURL_USE_LIBSSH) + find_package(Libssh REQUIRED) + if(LIBSSH_FOUND) + list(APPEND CURL_LIBS ${LIBSSH_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${LIBSSH_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libssh") + include_directories(SYSTEM ${LIBSSH_INCLUDE_DIRS}) + link_directories(${LIBSSH_LIBRARY_DIRS}) + if(LIBSSH_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${LIBSSH_CFLAGS}") + endif() + set(USE_LIBSSH ON) + endif() +endif() + +# wolfSSH +option(CURL_USE_WOLFSSH "Use wolfSSH" OFF) +mark_as_advanced(CURL_USE_WOLFSSH) +set(USE_WOLFSSH OFF) +if(NOT USE_LIBSSH2 AND NOT USE_LIBSSH AND CURL_USE_WOLFSSH) + if(USE_WOLFSSL) + find_package(WolfSSH) + if(WOLFSSH_FOUND) + list(APPEND CURL_LIBS ${WOLFSSH_LIBRARIES}) + include_directories(SYSTEM ${WOLFSSH_INCLUDE_DIRS}) + set(USE_WOLFSSH ON) + endif() + else() + message(WARNING "wolfSSH requires wolfSSL. Skipping.") + endif() +endif() + +option(CURL_USE_GSASL "Use libgsasl" OFF) +mark_as_advanced(CURL_USE_GSASL) +if(CURL_USE_GSASL) + find_package(Libgsasl REQUIRED) + if(LIBGSASL_FOUND) + list(APPEND CURL_LIBS ${LIBGSASL_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${LIBGSASL_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libgsasl") + include_directories(SYSTEM ${LIBGSASL_INCLUDE_DIRS}) + link_directories(${LIBGSASL_LIBRARY_DIRS}) + if(LIBGSASL_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${LIBGSASL_CFLAGS}") + endif() + set(USE_GSASL ON) + endif() +endif() + +option(CURL_USE_GSSAPI "Use GSSAPI implementation" OFF) +mark_as_advanced(CURL_USE_GSSAPI) + +if(CURL_USE_GSSAPI) + find_package(GSS) + + set(HAVE_GSSAPI ${GSS_FOUND}) + if(GSS_FOUND) + if(GSS_FLAVOUR STREQUAL "GNU") + set(HAVE_GSSGNU 1) + else() + cmake_push_check_state() + list(APPEND CMAKE_REQUIRED_INCLUDES ${GSS_INCLUDE_DIRS}) + + set(_include_list "") + check_include_file("gssapi/gssapi.h" HAVE_GSSAPI_GSSAPI_H) + if(HAVE_GSSAPI_GSSAPI_H) + list(APPEND _include_list "gssapi/gssapi.h") + endif() + check_include_files("${_include_list};gssapi/gssapi_generic.h" HAVE_GSSAPI_GSSAPI_GENERIC_H) + + if(GSS_FLAVOUR STREQUAL "MIT") + check_include_files("${_include_list};gssapi/gssapi_krb5.h" _have_gssapi_gssapi_krb5_h) + if(HAVE_GSSAPI_GSSAPI_GENERIC_H) + list(APPEND _include_list "gssapi/gssapi_generic.h") + endif() + if(_have_gssapi_gssapi_krb5_h) + list(APPEND _include_list "gssapi/gssapi_krb5.h") + endif() + + if(NOT DEFINED HAVE_GSS_C_NT_HOSTBASED_SERVICE) + set(CMAKE_REQUIRED_FLAGS ${GSS_CFLAGS}) + set(CMAKE_REQUIRED_LIBRARIES ${GSS_LIBRARIES}) + curl_required_libpaths("${GSS_LIBRARY_DIRS}") + check_symbol_exists("GSS_C_NT_HOSTBASED_SERVICE" "${_include_list}" HAVE_GSS_C_NT_HOSTBASED_SERVICE) + endif() + if(NOT HAVE_GSS_C_NT_HOSTBASED_SERVICE) + set(HAVE_OLD_GSSMIT ON) + endif() + endif() + unset(_include_list) + cmake_pop_check_state() + endif() + + list(APPEND CURL_LIBS ${GSS_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${GSS_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE ${GSS_PC_REQUIRES}) + include_directories(SYSTEM ${GSS_INCLUDE_DIRS}) + link_directories(${GSS_LIBRARY_DIRS}) + if(GSS_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GSS_CFLAGS}") + endif() + else() + message(WARNING "GSSAPI has been requested, but no supporting libraries found. Skipping.") + endif() +endif() + +# libuv +option(CURL_USE_LIBUV "Use libuv for event-based tests" OFF) +if(CURL_USE_LIBUV) + if(NOT ENABLE_DEBUG) + message(FATAL_ERROR "Using libuv without debug support enabled is useless") + endif() + find_package(Libuv REQUIRED) + if(LIBUV_FOUND) + list(APPEND CURL_LIBS ${LIBUV_LIBRARIES}) + list(APPEND CURL_LIBDIRS ${LIBUV_LIBRARY_DIRS}) + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "libuv") + include_directories(SYSTEM ${LIBUV_INCLUDE_DIRS}) + link_directories(${LIBUV_LIBRARY_DIRS}) + if(LIBUV_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${LIBUV_CFLAGS}") + endif() + set(USE_LIBUV ON) + set(HAVE_UV_H ON) + endif() +endif() + +option(USE_LIBRTMP "Enable librtmp from rtmpdump" OFF) +if(USE_LIBRTMP) + set(_extra_libs "rtmp") + if(WIN32) + list(APPEND _extra_libs "winmm") + endif() + openssl_check_symbol_exists("RTMP_Init" "librtmp/rtmp.h" HAVE_LIBRTMP "${_extra_libs}") + if(HAVE_LIBRTMP) + list(APPEND CURL_LIBS "rtmp") + list(APPEND LIBCURL_PC_REQUIRES_PRIVATE "librtmp") + if(WIN32) + list(APPEND CURL_LIBS "winmm") + endif() + else() + message(WARNING "librtmp has been requested, but not found or missing OpenSSL. Skipping.") + set(USE_LIBRTMP OFF) + endif() +endif() + +option(ENABLE_UNIX_SOCKETS "Enable Unix domain sockets support" ON) +if(ENABLE_UNIX_SOCKETS) + if(WIN32) + set(USE_UNIX_SOCKETS ON) + else() + include(CheckStructHasMember) + check_struct_has_member("struct sockaddr_un" "sun_path" "sys/un.h" USE_UNIX_SOCKETS) + endif() +else() + unset(USE_UNIX_SOCKETS CACHE) +endif() + +# +# CA handling +# +if(_curl_ca_bundle_supported) + set(CURL_CA_BUNDLE "auto" CACHE + STRING "Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_FALLBACK OFF CACHE BOOL + "Use built-in CA store of TLS backend. Defaults to OFF") + set(CURL_CA_PATH "auto" CACHE + STRING "Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_EMBED "" CACHE + STRING "Path to the CA bundle to embed in the curl tool.") + + if(CURL_CA_BUNDLE STREQUAL "") + message(FATAL_ERROR "Invalid value of CURL_CA_BUNDLE. Use 'none', 'auto' or file path.") + elseif(CURL_CA_BUNDLE STREQUAL "none") + unset(CURL_CA_BUNDLE CACHE) + elseif(CURL_CA_BUNDLE STREQUAL "auto") + unset(CURL_CA_BUNDLE CACHE) + if(NOT CMAKE_CROSSCOMPILING AND NOT WIN32) + set(_curl_ca_bundle_autodetect TRUE) + endif() + else() + set(CURL_CA_BUNDLE_SET TRUE) + endif() + mark_as_advanced(CURL_CA_BUNDLE_SET) + + if(CURL_CA_PATH STREQUAL "") + message(FATAL_ERROR "Invalid value of CURL_CA_PATH. Use 'none', 'auto' or directory path.") + elseif(CURL_CA_PATH STREQUAL "none") + unset(CURL_CA_PATH CACHE) + elseif(CURL_CA_PATH STREQUAL "auto") + unset(CURL_CA_PATH CACHE) + if(NOT CMAKE_CROSSCOMPILING AND NOT WIN32) + set(_curl_ca_path_autodetect TRUE) + endif() + else() + set(CURL_CA_PATH_SET TRUE) + endif() + mark_as_advanced(CURL_CA_PATH_SET) + + if(CURL_CA_BUNDLE_SET AND _curl_ca_path_autodetect) + # Skip auto-detection of unset CA path because CA bundle is set explicitly + elseif(CURL_CA_PATH_SET AND _curl_ca_bundle_autodetect) + # Skip auto-detection of unset CA bundle because CA path is set explicitly + elseif(_curl_ca_bundle_autodetect OR _curl_ca_path_autodetect) + # First try auto-detecting a CA bundle, then a CA path + + if(_curl_ca_bundle_autodetect) + foreach(_search_ca_bundle_path IN ITEMS + "/etc/ssl/certs/ca-certificates.crt" + "/etc/pki/tls/certs/ca-bundle.crt" + "/usr/share/ssl/certs/ca-bundle.crt" + "/usr/local/share/certs/ca-root-nss.crt" + "/etc/ssl/cert.pem") + if(EXISTS "${_search_ca_bundle_path}") + message(STATUS "Found CA bundle: ${_search_ca_bundle_path}") + set(CURL_CA_BUNDLE "${_search_ca_bundle_path}" CACHE + STRING "Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_BUNDLE_SET TRUE CACHE BOOL "Path to the CA bundle has been set") + break() + endif() + endforeach() + endif() + + if(_curl_ca_path_autodetect AND NOT CURL_CA_PATH_SET) + set(_search_ca_path "/etc/ssl/certs") + file(GLOB _curl_ca_files_found "${_search_ca_path}/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].0") + if(_curl_ca_files_found) + unset(_curl_ca_files_found) + message(STATUS "Found CA path: ${_search_ca_path}") + set(CURL_CA_PATH "${_search_ca_path}" CACHE + STRING "Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.") + set(CURL_CA_PATH_SET TRUE CACHE BOOL "Path to the CA bundle has been set") + endif() + endif() + endif() + + set(CURL_CA_EMBED_SET FALSE) + if(BUILD_CURL_EXE AND NOT CURL_CA_EMBED STREQUAL "") + if(EXISTS "${CURL_CA_EMBED}") + set(CURL_CA_EMBED_SET TRUE) + message(STATUS "Found CA bundle to embed: ${CURL_CA_EMBED}") + else() + message(FATAL_ERROR "CA bundle to embed is missing: '${CURL_CA_EMBED}'") + endif() + endif() +endif() + +if(WIN32) + option(CURL_DISABLE_CA_SEARCH "Disable unsafe CA bundle search in PATH on Windows" OFF) + option(CURL_CA_SEARCH_SAFE "Enable safe CA bundle search (within the curl tool directory) on Windows" OFF) +endif() + +# Check for header files +if(WIN32) + list(APPEND CURL_INCLUDES "winsock2.h") + list(APPEND CURL_INCLUDES "ws2tcpip.h") + + if(HAVE_WIN32_WINNT) + if(HAVE_WIN32_WINNT LESS 0x0501) + # Windows XP is required for freeaddrinfo, getaddrinfo + message(FATAL_ERROR "Building for Windows XP or newer is required.") + endif() + + # Pre-fill detection results based on target OS version + if(MINGW OR MSVC) + if(HAVE_WIN32_WINNT LESS 0x0600) + set(HAVE_INET_NTOP 0) + set(HAVE_INET_PTON 0) + else() # Windows Vista or newer + set(HAVE_INET_NTOP 1) + set(HAVE_INET_PTON 1) + endif() + unset(HAVE_INET_NTOP CACHE) + unset(HAVE_INET_PTON CACHE) + endif() + endif() +endif() + +# Detect headers + +# Use check_include_file_concat() for headers required by subsequent +# check_include_file_concat() or check_symbol_exists() detections. +# Order for these is significant. +check_include_file("sys/eventfd.h" HAVE_SYS_EVENTFD_H) +check_include_file("sys/filio.h" HAVE_SYS_FILIO_H) +check_include_file("sys/wait.h" HAVE_SYS_WAIT_H) +check_include_file("sys/ioctl.h" HAVE_SYS_IOCTL_H) +check_include_file("sys/param.h" HAVE_SYS_PARAM_H) +check_include_file("sys/poll.h" HAVE_SYS_POLL_H) +check_include_file("sys/resource.h" HAVE_SYS_RESOURCE_H) +check_include_file_concat("sys/select.h" HAVE_SYS_SELECT_H) +check_include_file_concat("sys/socket.h" HAVE_SYS_SOCKET_H) +check_include_file("sys/sockio.h" HAVE_SYS_SOCKIO_H) +check_include_file("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file_concat("sys/time.h" HAVE_SYS_TIME_H) +check_include_file_concat("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file("sys/un.h" HAVE_SYS_UN_H) +check_include_file("sys/utime.h" HAVE_SYS_UTIME_H) +check_include_file("sys/xattr.h" HAVE_SYS_XATTR_H) + +check_include_file_concat("arpa/inet.h" HAVE_ARPA_INET_H) +check_include_file("dirent.h" HAVE_DIRENT_H) +check_include_file("fcntl.h" HAVE_FCNTL_H) +check_include_file_concat("ifaddrs.h" HAVE_IFADDRS_H) +check_include_file("io.h" HAVE_IO_H) +check_include_file_concat("libgen.h" HAVE_LIBGEN_H) +check_include_file("linux/tcp.h" HAVE_LINUX_TCP_H) +check_include_file("locale.h" HAVE_LOCALE_H) +check_include_file("net/if.h" HAVE_NET_IF_H) +check_include_file_concat("netdb.h" HAVE_NETDB_H) +check_include_file_concat("netinet/in.h" HAVE_NETINET_IN_H) +check_include_file("netinet/in6.h" HAVE_NETINET_IN6_H) +check_include_file_concat("netinet/tcp.h" HAVE_NETINET_TCP_H) # sys/types.h (e.g. Cygwin) netinet/in.h +check_include_file_concat("netinet/udp.h" HAVE_NETINET_UDP_H) # sys/types.h (e.g. Cygwin) +check_include_file("poll.h" HAVE_POLL_H) +check_include_file("pwd.h" HAVE_PWD_H) +check_include_file("stdatomic.h" HAVE_STDATOMIC_H) +check_include_file("stdbool.h" HAVE_STDBOOL_H) +check_include_file("strings.h" HAVE_STRINGS_H) +check_include_file("stropts.h" HAVE_STROPTS_H) +check_include_file("termio.h" HAVE_TERMIO_H) +check_include_file("termios.h" HAVE_TERMIOS_H) +check_include_file_concat("unistd.h" HAVE_UNISTD_H) +check_include_file("utime.h" HAVE_UTIME_H) + +if(CMAKE_SYSTEM_NAME MATCHES "AmigaOS") + check_include_file_concat("proto/bsdsocket.h" HAVE_PROTO_BSDSOCKET_H) +endif() + +# Pass these detection results to curl_internal_test() for use in CurlTests.c +# Add here all feature flags referenced from CurlTests.c +foreach(_variable IN ITEMS + HAVE_STDATOMIC_H + HAVE_STDBOOL_H + HAVE_STROPTS_H + HAVE_SYS_IOCTL_H + HAVE_SYS_SOCKET_H + HAVE_SYS_TYPES_H + HAVE_UNISTD_H + ) + if(${_variable}) + set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -D${_variable}") + endif() +endforeach() + +check_type_size("size_t" SIZEOF_SIZE_T) +check_type_size("ssize_t" SIZEOF_SSIZE_T) +check_type_size("long long" SIZEOF_LONG_LONG) +check_type_size("long" SIZEOF_LONG) +check_type_size("int" SIZEOF_INT) +check_type_size("__int64" SIZEOF___INT64) +check_type_size("time_t" SIZEOF_TIME_T) +check_type_size("suseconds_t" SIZEOF_SUSECONDS_T) +if(NOT HAVE_SIZEOF_SSIZE_T) + if(SIZEOF_LONG EQUAL SIZEOF_SIZE_T) + set(ssize_t "long") + endif() + if(NOT ssize_t AND SIZEOF___INT64 EQUAL SIZEOF_SIZE_T) + set(ssize_t "__int64") + endif() +endif() +# off_t is sized later, after the HAVE_FILE_OFFSET_BITS test + +if(SIZEOF_LONG_LONG) + set(HAVE_LONGLONG 1) +endif() +if(SIZEOF_SUSECONDS_T) + set(HAVE_SUSECONDS_T 1) +endif() + +# Check for some functions that are used +if(WIN32) + list(APPEND CMAKE_REQUIRED_LIBRARIES "ws2_32") # Apply to all feature checks +elseif(HAVE_LIBSOCKET) + list(APPEND CMAKE_REQUIRED_LIBRARIES "socket") # Apply to all feature checks +endif() + +check_function_exists("fnmatch" HAVE_FNMATCH) +check_symbol_exists("basename" "${CURL_INCLUDES};string.h" HAVE_BASENAME) # libgen.h unistd.h +check_symbol_exists("opendir" "dirent.h" HAVE_OPENDIR) +check_function_exists("poll" HAVE_POLL) # poll.h +check_symbol_exists("socket" "${CURL_INCLUDES}" HAVE_SOCKET) # winsock2.h sys/socket.h +check_function_exists("sched_yield" HAVE_SCHED_YIELD) +check_symbol_exists("socketpair" "${CURL_INCLUDES}" HAVE_SOCKETPAIR) # sys/socket.h +check_symbol_exists("recv" "${CURL_INCLUDES}" HAVE_RECV) # proto/bsdsocket.h sys/types.h sys/socket.h +check_symbol_exists("send" "${CURL_INCLUDES}" HAVE_SEND) # proto/bsdsocket.h sys/types.h sys/socket.h +check_function_exists("sendmsg" HAVE_SENDMSG) +check_function_exists("sendmmsg" HAVE_SENDMMSG) +check_symbol_exists("select" "${CURL_INCLUDES}" HAVE_SELECT) # proto/bsdsocket.h sys/select.h sys/socket.h +check_symbol_exists("strdup" "string.h" HAVE_STRDUP) +check_symbol_exists("strtok_r" "string.h" HAVE_STRTOK_R) +check_symbol_exists("strcasecmp" "string.h" HAVE_STRCASECMP) +check_symbol_exists("stricmp" "string.h" HAVE_STRICMP) +check_symbol_exists("strcmpi" "string.h" HAVE_STRCMPI) +check_symbol_exists("memrchr" "string.h" HAVE_MEMRCHR) +check_symbol_exists("alarm" "unistd.h" HAVE_ALARM) +check_symbol_exists("fcntl" "fcntl.h" HAVE_FCNTL) +check_function_exists("getppid" HAVE_GETPPID) +check_function_exists("utimes" HAVE_UTIMES) + +check_function_exists("gettimeofday" HAVE_GETTIMEOFDAY) # sys/time.h +check_symbol_exists("closesocket" "${CURL_INCLUDES}" HAVE_CLOSESOCKET) # winsock2.h +check_symbol_exists("sigsetjmp" "setjmp.h" HAVE_SIGSETJMP) +check_function_exists("getpass_r" HAVE_GETPASS_R) +check_function_exists("getpwuid" HAVE_GETPWUID) +check_function_exists("getpwuid_r" HAVE_GETPWUID_R) +check_function_exists("geteuid" HAVE_GETEUID) +check_function_exists("utime" HAVE_UTIME) +check_symbol_exists("gmtime_r" "stdlib.h;time.h" HAVE_GMTIME_R) + +check_symbol_exists("gethostbyname_r" "netdb.h" HAVE_GETHOSTBYNAME_R) + +check_symbol_exists("signal" "signal.h" HAVE_SIGNAL) +check_symbol_exists("strtoll" "stdlib.h" HAVE_STRTOLL) +check_symbol_exists("strerror_r" "stdlib.h;string.h" HAVE_STRERROR_R) +check_symbol_exists("sigaction" "signal.h" HAVE_SIGACTION) +check_symbol_exists("siginterrupt" "signal.h" HAVE_SIGINTERRUPT) +check_symbol_exists("getaddrinfo" "${CURL_INCLUDES};stdlib.h;string.h" HAVE_GETADDRINFO) # ws2tcpip.h sys/socket.h netdb.h +check_symbol_exists("getifaddrs" "${CURL_INCLUDES};stdlib.h" HAVE_GETIFADDRS) # ifaddrs.h +check_symbol_exists("freeaddrinfo" "${CURL_INCLUDES}" HAVE_FREEADDRINFO) # ws2tcpip.h sys/socket.h netdb.h +check_function_exists("pipe" HAVE_PIPE) +check_function_exists("eventfd" HAVE_EVENTFD) +check_symbol_exists("ftruncate" "unistd.h" HAVE_FTRUNCATE) +check_symbol_exists("getpeername" "${CURL_INCLUDES}" HAVE_GETPEERNAME) # winsock2.h unistd.h proto/bsdsocket.h +check_symbol_exists("getsockname" "${CURL_INCLUDES}" HAVE_GETSOCKNAME) # winsock2.h unistd.h proto/bsdsocket.h +check_function_exists("if_nametoindex" HAVE_IF_NAMETOINDEX) # winsock2.h net/if.h +check_function_exists("getrlimit" HAVE_GETRLIMIT) +check_function_exists("setlocale" HAVE_SETLOCALE) +check_function_exists("setmode" HAVE_SETMODE) +check_function_exists("setrlimit" HAVE_SETRLIMIT) + +if(WIN32 OR CYGWIN) + check_function_exists("_setmode" HAVE__SETMODE) +endif() + +if(CMAKE_SYSTEM_NAME MATCHES "AmigaOS") + check_symbol_exists("CloseSocket" "${CURL_INCLUDES}" HAVE_CLOSESOCKET_CAMEL) # sys/socket.h proto/bsdsocket.h +endif() + +if(NOT _ssl_enabled) + check_symbol_exists("arc4random" "${CURL_INCLUDES};stdlib.h" HAVE_ARC4RANDOM) +endif() + +if(NOT MSVC OR (MSVC_VERSION GREATER_EQUAL 1900)) + # Earlier MSVC compilers had faulty snprintf implementations + check_function_exists("snprintf" HAVE_SNPRINTF) +endif() +if(APPLE) + check_function_exists("mach_absolute_time" HAVE_MACH_ABSOLUTE_TIME) +endif() +check_symbol_exists("inet_ntop" "${CURL_INCLUDES};stdlib.h;string.h" HAVE_INET_NTOP) # arpa/inet.h +if(MSVC AND (MSVC_VERSION LESS_EQUAL 1600)) + set(HAVE_INET_NTOP OFF) +endif() +check_symbol_exists("inet_pton" "${CURL_INCLUDES};stdlib.h;string.h" HAVE_INET_PTON) # arpa/inet.h + +check_symbol_exists("fsetxattr" "sys/xattr.h" HAVE_FSETXATTR) +if(HAVE_FSETXATTR) + curl_internal_test(HAVE_FSETXATTR_5) + curl_internal_test(HAVE_FSETXATTR_6) +endif() + +cmake_push_check_state() +if(WIN32) + set(CMAKE_EXTRA_INCLUDE_FILES "winsock2.h") + check_type_size("ADDRESS_FAMILY" SIZEOF_ADDRESS_FAMILY) + set(HAVE_ADDRESS_FAMILY ${HAVE_SIZEOF_ADDRESS_FAMILY}) +elseif(HAVE_SYS_SOCKET_H) + set(CMAKE_EXTRA_INCLUDE_FILES "sys/socket.h") + check_type_size("sa_family_t" SIZEOF_SA_FAMILY_T) + set(HAVE_SA_FAMILY_T ${HAVE_SIZEOF_SA_FAMILY_T}) +endif() +cmake_pop_check_state() + +# Do curl specific tests +foreach(_curl_test IN ITEMS + HAVE_FCNTL_O_NONBLOCK + HAVE_IOCTLSOCKET + HAVE_IOCTLSOCKET_CAMEL + HAVE_IOCTLSOCKET_CAMEL_FIONBIO + HAVE_IOCTLSOCKET_FIONBIO + HAVE_IOCTL_FIONBIO + HAVE_IOCTL_SIOCGIFADDR + HAVE_SETSOCKOPT_SO_NONBLOCK + HAVE_O_NONBLOCK + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6 + HAVE_GETHOSTBYNAME_R_3_REENTRANT + HAVE_GETHOSTBYNAME_R_5_REENTRANT + HAVE_GETHOSTBYNAME_R_6_REENTRANT + HAVE_IN_ADDR_T + HAVE_BOOL_T + STDC_HEADERS + HAVE_FILE_OFFSET_BITS + HAVE_ATOMIC + ) + curl_internal_test(${_curl_test}) +endforeach() + +cmake_push_check_state() +if(HAVE_FILE_OFFSET_BITS) + set(_FILE_OFFSET_BITS 64) + set(CMAKE_REQUIRED_DEFINITIONS "-D_FILE_OFFSET_BITS=64") +endif() +check_type_size("off_t" SIZEOF_OFF_T) + +# fseeko may not exist with _FILE_OFFSET_BITS=64 but can exist with +# _FILE_OFFSET_BITS unset or 32 (e.g. Android ARMv7 with NDK 26b and API level < 24) +# so we need to test fseeko after testing for _FILE_OFFSET_BITS +check_symbol_exists("fseeko" "${CURL_INCLUDES};stdio.h" HAVE_FSEEKO) + +if(HAVE_FSEEKO) + set(HAVE_DECL_FSEEKO 1) +endif() + +# Include this header to get the type +cmake_push_check_state() +set(CMAKE_REQUIRED_INCLUDES "${PROJECT_SOURCE_DIR}/include") +set(CMAKE_EXTRA_INCLUDE_FILES "curl/system.h") +check_type_size("curl_off_t" SIZEOF_CURL_OFF_T) +set(CMAKE_EXTRA_INCLUDE_FILES "curl/curl.h") +check_type_size("curl_socket_t" SIZEOF_CURL_SOCKET_T) +cmake_pop_check_state() # pop curl system headers +cmake_pop_check_state() # pop -D_FILE_OFFSET_BITS=64 + +if(NOT WIN32 AND NOT CMAKE_CROSSCOMPILING) + # On non-Windows and not cross-compiling, check for writable argv[] + include(CheckCSourceRuns) + check_c_source_runs(" + int main(int argc, char **argv) + { + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; + }" HAVE_WRITABLE_ARGV) +endif() + +curl_internal_test(HAVE_GLIBC_STRERROR_R) +curl_internal_test(HAVE_POSIX_STRERROR_R) + +# Check for reentrant +foreach(_curl_test IN ITEMS + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6) + if(NOT ${_curl_test}) + if(${_curl_test}_REENTRANT) + set(NEED_REENTRANT 1) + endif() + endif() +endforeach() + +if(NEED_REENTRANT) + foreach(_curl_test IN ITEMS + HAVE_GETHOSTBYNAME_R_3 + HAVE_GETHOSTBYNAME_R_5 + HAVE_GETHOSTBYNAME_R_6) + set(${_curl_test} 0) + if(${_curl_test}_REENTRANT) + set(${_curl_test} 1) + endif() + endforeach() +endif() + +if(NOT WIN32) + curl_internal_test(HAVE_CLOCK_GETTIME_MONOTONIC) # Check clock_gettime(CLOCK_MONOTONIC, x) support +endif() + +if(APPLE) + curl_internal_test(HAVE_BUILTIN_AVAILABLE) # Check compiler support of __builtin_available() +endif() + +# Some other minor tests + +if(NOT HAVE_IN_ADDR_T) + set(in_addr_t "unsigned long") +endif() + +# Check for nonblocking +set(HAVE_DISABLED_NONBLOCKING 1) +if(HAVE_FIONBIO OR + HAVE_IOCTLSOCKET OR + HAVE_IOCTLSOCKET_CASE OR + HAVE_O_NONBLOCK) + unset(HAVE_DISABLED_NONBLOCKING) +endif() + +if(CMAKE_COMPILER_IS_GNUCC AND APPLE) + include(CheckCCompilerFlag) + check_c_compiler_flag("-Wno-long-double" HAVE_C_FLAG_Wno_long_double) + if(HAVE_C_FLAG_Wno_long_double) + # The Mac version of GCC warns about use of long double. Disable it. + get_source_file_property(_mprintf_compile_flags "mprintf.c" COMPILE_FLAGS) + if(_mprintf_compile_flags) + set(_mprintf_compile_flags "${_mprintf_compile_flags} -Wno-long-double") + else() + set(_mprintf_compile_flags "-Wno-long-double") + endif() + set_source_files_properties("mprintf.c" PROPERTIES + COMPILE_FLAGS ${_mprintf_compile_flags}) + endif() +endif() + +if(_cmake_try_compile_target_type_save) + set(CMAKE_TRY_COMPILE_TARGET_TYPE ${_cmake_try_compile_target_type_save}) + unset(_cmake_try_compile_target_type_save) +endif() + +include(CMake/OtherTests.cmake) + +add_definitions("-DHAVE_CONFIG_H") + +# For Windows, all compilers used by CMake should support large files +if(WIN32) + set(USE_WIN32_LARGE_FILES ON) + + # Use the manifest embedded in the Windows Resource + set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} -DCURL_EMBED_MANIFEST") + + # We use crypto functions that are not available for UWP apps + if(NOT WINDOWS_STORE) + set(USE_WIN32_CRYPTO ON) + endif() + + # Link required libraries for USE_WIN32_CRYPTO or USE_SCHANNEL + if(USE_WIN32_CRYPTO OR USE_SCHANNEL) + list(APPEND CURL_LIBS "advapi32" "crypt32") + endif() +endif() + +if(MSVC) + # Disable default manifest added by CMake + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /MANIFEST:NO") + + add_definitions("-D_CRT_SECURE_NO_DEPRECATE" "-D_CRT_NONSTDC_NO_DEPRECATE") + if(CMAKE_C_FLAGS MATCHES "/W[0-4]") + string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") + else() + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4") + endif() + + # Use multithreaded compilation on VS 2008+ + if(CMAKE_C_COMPILER_ID STREQUAL "MSVC" AND MSVC_VERSION GREATER_EQUAL 1500) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /MP") + endif() +endif() + +if(CURL_WERROR) + if(MSVC) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX") + else() + # This assumes clang or gcc style options + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror") + endif() +endif() + +if(CURL_LTO) + if(CMAKE_VERSION VERSION_LESS 3.9) + message(FATAL_ERROR "LTO has been requested, but your cmake version ${CMAKE_VERSION} is to old. You need at least 3.9") + endif() + + cmake_policy(SET CMP0069 NEW) + + include(CheckIPOSupported) + check_ipo_supported(RESULT CURL_HAS_LTO OUTPUT _lto_error LANGUAGES C) + if(CURL_HAS_LTO) + message(STATUS "LTO supported and enabled") + else() + message(FATAL_ERROR "LTO has been requested, but the compiler does not support it\n${_lto_error}") + endif() +endif() + + +# Ugly (but functional) way to include "Makefile.inc" by transforming it +# (= regenerate it). +function(transform_makefile_inc _input_file _output_file) + file(READ ${_input_file} _makefile_inc_text) + string(REPLACE "$(top_srcdir)" "\${PROJECT_SOURCE_DIR}" _makefile_inc_text ${_makefile_inc_text}) + string(REPLACE "$(top_builddir)" "\${PROJECT_BINARY_DIR}" _makefile_inc_text ${_makefile_inc_text}) + + string(REGEX REPLACE "\\\\\n" "!π!α!" _makefile_inc_text ${_makefile_inc_text}) + string(REGEX REPLACE "([a-zA-Z_][a-zA-Z0-9_]*)[\t ]*=[\t ]*([^\n]*)" "set(\\1 \\2)" _makefile_inc_text ${_makefile_inc_text}) + string(REPLACE "!π!α!" "\n" _makefile_inc_text ${_makefile_inc_text}) + + # Replace $() with ${} + string(REGEX REPLACE "\\$\\(([a-zA-Z_][a-zA-Z0-9_]*)\\)" "\${\\1}" _makefile_inc_text ${_makefile_inc_text}) + # Replace @@ with ${}, even if that may not be read by CMake scripts. + string(REGEX REPLACE "@([a-zA-Z_][a-zA-Z0-9_]*)@" "\${\\1}" _makefile_inc_text ${_makefile_inc_text}) + + file(WRITE ${_output_file} ${_makefile_inc_text}) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_input_file}") +endfunction() + +include(GNUInstallDirs) + +set(_install_cmake_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") +set(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") +set(_generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") +set(_project_config "${_generated_dir}/${PROJECT_NAME}Config.cmake") +set(_version_config "${_generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") + +option(BUILD_TESTING "Build tests" ON) +if(BUILD_TESTING AND PERL_FOUND AND NOT CURL_DISABLE_TESTS) + set(CURL_BUILD_TESTING ON) +else() + set(CURL_BUILD_TESTING OFF) +endif() + +if(HAVE_MANUAL_TOOLS) + set(CURL_MANPAGE "${PROJECT_BINARY_DIR}/docs/cmdline-opts/curl.1") + set(CURL_ASCIIPAGE "${PROJECT_BINARY_DIR}/docs/cmdline-opts/curl.txt") + add_subdirectory(docs) +endif() + +add_subdirectory(lib) + +if(BUILD_CURL_EXE) + add_subdirectory(src) +endif() + +option(BUILD_EXAMPLES "Build libcurl examples" ON) +if(BUILD_EXAMPLES) + add_subdirectory(docs/examples) +endif() + +if(CURL_BUILD_TESTING) + add_subdirectory(tests) +endif() + +# Helper to populate a list (_items) with a label when conditions +# (the remaining args) are satisfied +macro(_add_if _label) + # Needs to be a macro to allow this indirection + if(${ARGN}) + set(_items ${_items} "${_label}") + endif() +endmacro() + +# NTLM support requires crypto functions from various SSL libs. +# These conditions must match those in lib/curl_setup.h. +if(NOT CURL_DISABLE_NTLM AND + (USE_OPENSSL OR + USE_MBEDTLS OR + USE_GNUTLS OR + USE_SECTRANSP OR + USE_WIN32_CRYPTO OR + (USE_WOLFSSL AND HAVE_WOLFSSL_DES_ECB_ENCRYPT))) + set(_use_curl_ntlm_core ON) +endif() + +# Clear list and try to detect available protocols +unset(_items) +_add_if("HTTP" NOT CURL_DISABLE_HTTP) +_add_if("HTTPS" NOT CURL_DISABLE_HTTP AND _ssl_enabled) +_add_if("FTP" NOT CURL_DISABLE_FTP) +_add_if("FTPS" NOT CURL_DISABLE_FTP AND _ssl_enabled) +_add_if("FILE" NOT CURL_DISABLE_FILE) +_add_if("TELNET" NOT CURL_DISABLE_TELNET) +_add_if("LDAP" NOT CURL_DISABLE_LDAP) +# CURL_DISABLE_LDAP implies CURL_DISABLE_LDAPS +_add_if("LDAPS" NOT CURL_DISABLE_LDAPS AND + ((USE_OPENLDAP AND _ssl_enabled) OR + (NOT USE_OPENLDAP AND HAVE_LDAP_SSL))) +_add_if("DICT" NOT CURL_DISABLE_DICT) +_add_if("TFTP" NOT CURL_DISABLE_TFTP) +_add_if("GOPHER" NOT CURL_DISABLE_GOPHER) +_add_if("GOPHERS" NOT CURL_DISABLE_GOPHER AND _ssl_enabled) +_add_if("POP3" NOT CURL_DISABLE_POP3) +_add_if("POP3S" NOT CURL_DISABLE_POP3 AND _ssl_enabled) +_add_if("IMAP" NOT CURL_DISABLE_IMAP) +_add_if("IMAPS" NOT CURL_DISABLE_IMAP AND _ssl_enabled) +_add_if("SMB" NOT CURL_DISABLE_SMB AND + _use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4)) +_add_if("SMBS" NOT CURL_DISABLE_SMB AND _ssl_enabled AND + _use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4)) +_add_if("SMTP" NOT CURL_DISABLE_SMTP) +_add_if("SMTPS" NOT CURL_DISABLE_SMTP AND _ssl_enabled) +_add_if("SCP" USE_LIBSSH2 OR USE_LIBSSH OR USE_WOLFSSH) +_add_if("SFTP" USE_LIBSSH2 OR USE_LIBSSH OR USE_WOLFSSH) +_add_if("IPFS" NOT CURL_DISABLE_IPFS) +_add_if("IPNS" NOT CURL_DISABLE_IPFS) +_add_if("RTSP" NOT CURL_DISABLE_RTSP) +_add_if("RTMP" USE_LIBRTMP) +_add_if("MQTT" NOT CURL_DISABLE_MQTT) +_add_if("WS" NOT CURL_DISABLE_WEBSOCKETS) +_add_if("WSS" NOT CURL_DISABLE_WEBSOCKETS AND _ssl_enabled) +if(_items) + list(SORT _items) +endif() +string(REPLACE ";" " " SUPPORT_PROTOCOLS "${_items}") +string(TOLOWER "${SUPPORT_PROTOCOLS}" _support_protocols_lower) +message(STATUS "Protocols: ${_support_protocols_lower}") + +# Clear list and try to detect available features +unset(_items) +_add_if("SSL" _ssl_enabled) +_add_if("IPv6" ENABLE_IPV6) +_add_if("UnixSockets" USE_UNIX_SOCKETS) +_add_if("libz" HAVE_LIBZ) +_add_if("brotli" HAVE_BROTLI) +_add_if("gsasl" USE_GSASL) +_add_if("zstd" HAVE_ZSTD) +_add_if("AsynchDNS" USE_ARES OR USE_THREADS_POSIX OR USE_THREADS_WIN32) +_add_if("IDN" (HAVE_LIBIDN2 AND HAVE_IDN2_H) OR + USE_WIN32_IDN OR + USE_APPLE_IDN) +_add_if("Largefile" (SIZEOF_CURL_OFF_T GREATER 4) AND + ((SIZEOF_OFF_T GREATER 4) OR USE_WIN32_LARGE_FILES)) +_add_if("SSPI" USE_WINDOWS_SSPI) +_add_if("GSS-API" HAVE_GSSAPI) +_add_if("alt-svc" NOT CURL_DISABLE_ALTSVC) +_add_if("HSTS" NOT CURL_DISABLE_HSTS) +_add_if("SPNEGO" NOT CURL_DISABLE_NEGOTIATE_AUTH AND + (HAVE_GSSAPI OR USE_WINDOWS_SSPI)) +_add_if("Kerberos" NOT CURL_DISABLE_KERBEROS_AUTH AND + (HAVE_GSSAPI OR USE_WINDOWS_SSPI)) +_add_if("NTLM" NOT (CURL_DISABLE_NTLM) AND + (_use_curl_ntlm_core OR USE_WINDOWS_SSPI)) +_add_if("TLS-SRP" USE_TLS_SRP) +_add_if("HTTP2" USE_NGHTTP2) +_add_if("HTTP3" USE_NGTCP2 OR USE_QUICHE OR USE_MSH3 OR USE_OPENSSL_QUIC) +_add_if("MultiSSL" CURL_WITH_MULTI_SSL) +_add_if("HTTPS-proxy" _ssl_enabled AND (USE_OPENSSL OR USE_GNUTLS + OR USE_SCHANNEL OR USE_RUSTLS OR USE_BEARSSL OR + USE_MBEDTLS OR USE_SECTRANSP OR + (USE_WOLFSSL AND HAVE_WOLFSSL_BIO))) +_add_if("Unicode" ENABLE_UNICODE) +_add_if("threadsafe" HAVE_ATOMIC OR + (USE_THREADS_POSIX AND HAVE_PTHREAD_H) OR + (WIN32 AND HAVE_WIN32_WINNT GREATER_EQUAL 0x0600)) +_add_if("Debug" ENABLE_DEBUG) +_add_if("TrackMemory" ENABLE_CURLDEBUG) +_add_if("ECH" _ssl_enabled AND HAVE_ECH) +_add_if("PSL" USE_LIBPSL) +_add_if("CAcert" CURL_CA_EMBED_SET) +if(_items) + if(NOT CMAKE_VERSION VERSION_LESS 3.13) + list(SORT _items CASE INSENSITIVE) + else() + list(SORT _items) + endif() +endif() +string(REPLACE ";" " " SUPPORT_FEATURES "${_items}") +message(STATUS "Features: ${SUPPORT_FEATURES}") + +# Clear list and collect SSL backends +unset(_items) +_add_if("Schannel" _ssl_enabled AND USE_SCHANNEL) +_add_if("OpenSSL" _ssl_enabled AND USE_OPENSSL AND OPENSSL_VERSION VERSION_LESS 3.0.0) +_add_if("OpenSSL v3+" _ssl_enabled AND USE_OPENSSL AND NOT OPENSSL_VERSION VERSION_LESS 3.0.0) +_add_if("Secure Transport" _ssl_enabled AND USE_SECTRANSP) +_add_if("mbedTLS" _ssl_enabled AND USE_MBEDTLS) +_add_if("BearSSL" _ssl_enabled AND USE_BEARSSL) +_add_if("wolfSSL" _ssl_enabled AND USE_WOLFSSL) +_add_if("GnuTLS" _ssl_enabled AND USE_GNUTLS) +_add_if("rustls" _ssl_enabled AND USE_RUSTLS) + +if(_items) + if(NOT CMAKE_VERSION VERSION_LESS 3.13) + list(SORT _items CASE INSENSITIVE) + else() + list(SORT _items) + endif() +endif() +string(REPLACE ";" " " SSL_BACKENDS "${_items}") +message(STATUS "Enabled SSL backends: ${SSL_BACKENDS}") +if(CURL_DEFAULT_SSL_BACKEND) + message(STATUS "Default SSL backend: ${CURL_DEFAULT_SSL_BACKEND}") +endif() + +if(NOT CURL_DISABLE_INSTALL) + + # curl-config needs the following options to be set. + set(CC "${CMAKE_C_COMPILER}") + # TODO: probably put a -D... options here? + set(CONFIGURE_OPTIONS "") + set(CURLVERSION "${_curl_version}") + set(VERSIONNUM "${_curl_version_num}") + set(prefix "${CMAKE_INSTALL_PREFIX}") + set(exec_prefix "\${prefix}") + if(IS_ABSOLUTE ${CMAKE_INSTALL_INCLUDEDIR}) + set(includedir "${CMAKE_INSTALL_INCLUDEDIR}") + else() + set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") + endif() + if(IS_ABSOLUTE ${CMAKE_INSTALL_LIBDIR}) + set(libdir "${CMAKE_INSTALL_LIBDIR}") + else() + set(libdir "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}") + endif() + # "a" (Linux) or "lib" (Windows) + string(REPLACE "." "" libext "${CMAKE_STATIC_LIBRARY_SUFFIX}") + + set(_ldflags "") + set(LIBCURL_PC_LIBS_PRIVATE "") + + # Filter CMAKE_SHARED_LINKER_FLAGS for libs and libpaths + string(STRIP "${CMAKE_SHARED_LINKER_FLAGS}" _custom_ldflags) + string(REGEX REPLACE " +-([^ \\t;]*)" ";-\\1" _custom_ldflags "${_custom_ldflags}") + + set(_custom_libs "") + set(_custom_libdirs "") + foreach(_flag IN LISTS _custom_ldflags) + if(_flag MATCHES "^-l") + string(REGEX REPLACE "^-l" "" _flag "${_flag}") + list(APPEND _custom_libs "${_flag}") + elseif(_flag MATCHES "^-framework|^-F") + list(APPEND _custom_libs "${_flag}") + elseif(_flag MATCHES "^-L") + string(REGEX REPLACE "^-L" "" _flag "${_flag}") + list(APPEND _custom_libdirs "${_flag}") + elseif(_flag MATCHES "^--library-path=") + string(REGEX REPLACE "^--library-path=" "" _flag "${_flag}") + list(APPEND _custom_libdirs "${_flag}") + endif() + endforeach() + + # Avoid getting unnecessary -L options for known system directories. + unset(_sys_libdirs) + foreach(_libdir IN LISTS CMAKE_SYSTEM_PREFIX_PATH) + if(_libdir MATCHES "/$") + set(_libdir "${_libdir}lib") + else() + set(_libdir "${_libdir}/lib") + endif() + if(IS_DIRECTORY "${_libdir}") + list(APPEND _sys_libdirs "${_libdir}") + endif() + if(DEFINED CMAKE_LIBRARY_ARCHITECTURE) + set(_libdir "${_libdir}/${CMAKE_LIBRARY_ARCHITECTURE}") + if(IS_DIRECTORY "${_libdir}") + list(APPEND _sys_libdirs "${_libdir}") + endif() + endif() + endforeach() + + foreach(_libdir IN LISTS _custom_libdirs CURL_LIBDIRS) + list(FIND _sys_libdirs "${_libdir}" _libdir_index) + if(_libdir_index LESS 0) + list(APPEND _ldflags "-L${_libdir}") + endif() + endforeach() + + unset(_implicit_libs) + if(NOT MINGW AND NOT UNIX) + set(_implicit_libs ${CMAKE_C_IMPLICIT_LINK_LIBRARIES}) + endif() + + foreach(_lib IN LISTS _implicit_libs _custom_libs CURL_LIBS) + if(TARGET "${_lib}") + set(_libname "${_lib}") + get_target_property(_imported "${_libname}" IMPORTED) + if(NOT _imported) + # Reading the LOCATION property on non-imported target will error out. + # Assume the user will not need this information in the .pc file. + continue() + endif() + get_target_property(_lib "${_libname}" LOCATION) + if(NOT _lib) + message(WARNING "Bad lib in library list: ${_libname}") + continue() + endif() + endif() + if(_lib MATCHES "^-") # '-framework ' + list(APPEND _ldflags "${_lib}") + elseif(_lib MATCHES ".*/.*") + # This gets a bit more complex, because we want to specify the + # directory separately, and only once per directory + get_filename_component(_libdir ${_lib} DIRECTORY) + get_filename_component(_libname ${_lib} NAME_WE) + if(_libname MATCHES "^lib") + list(FIND _sys_libdirs "${_libdir}" _libdir_index) + if(_libdir_index LESS 0) + list(APPEND _ldflags "-L${_libdir}") + endif() + string(REGEX REPLACE "^lib" "" _libname "${_libname}") + list(APPEND LIBCURL_PC_LIBS_PRIVATE "-l${_libname}") + else() + list(APPEND LIBCURL_PC_LIBS_PRIVATE "${_lib}") + endif() + else() + list(APPEND LIBCURL_PC_LIBS_PRIVATE "-l${_lib}") + endif() + endforeach() + + if(LIBCURL_PC_REQUIRES_PRIVATE) + string(REPLACE ";" "," LIBCURL_PC_REQUIRES_PRIVATE "${LIBCURL_PC_REQUIRES_PRIVATE}") + endif() + if(LIBCURL_PC_LIBS_PRIVATE) + string(REPLACE ";" " " LIBCURL_PC_LIBS_PRIVATE "${LIBCURL_PC_LIBS_PRIVATE}") + endif() + if(_ldflags) + list(REMOVE_DUPLICATES _ldflags) + string(REPLACE ";" " " _ldflags "${_ldflags}") + set(LIBCURL_PC_LDFLAGS_PRIVATE "${_ldflags}") + string(STRIP "${LIBCURL_PC_LDFLAGS_PRIVATE}" LIBCURL_PC_LDFLAGS_PRIVATE) + else() + set(LIBCURL_PC_LDFLAGS_PRIVATE "") + endif() + set(LIBCURL_PC_CFLAGS_PRIVATE "-DCURL_STATICLIB") + + # Merge pkg-config private fields into public ones when static-only + if(BUILD_SHARED_LIBS) + set(ENABLE_SHARED "yes") + set(LIBCURL_PC_REQUIRES "") + set(LIBCURL_PC_LIBS "") + set(LIBCURL_PC_CFLAGS "") + else() + set(ENABLE_SHARED "no") + set(LIBCURL_PC_REQUIRES "${LIBCURL_PC_REQUIRES_PRIVATE}") + set(LIBCURL_PC_LIBS "${LIBCURL_PC_LIBS_PRIVATE}") + set(LIBCURL_PC_CFLAGS "${LIBCURL_PC_CFLAGS_PRIVATE}") + endif() + if(BUILD_STATIC_LIBS) + set(ENABLE_STATIC "yes") + else() + set(ENABLE_STATIC "no") + endif() + + # Generate a "curl-config" matching this config. + # Consumed variables: + # CC + # CONFIGURE_OPTIONS + # CURLVERSION + # CURL_CA_BUNDLE + # ENABLE_SHARED + # ENABLE_STATIC + # exec_prefix + # includedir + # LIBCURL_PC_CFLAGS + # LIBCURL_PC_LDFLAGS_PRIVATE + # LIBCURL_PC_LIBS_PRIVATE + # libdir + # libext + # prefix + # SSL_BACKENDS + # SUPPORT_FEATURES + # SUPPORT_PROTOCOLS + # VERSIONNUM + configure_file( + "${PROJECT_SOURCE_DIR}/curl-config.in" + "${PROJECT_BINARY_DIR}/curl-config" @ONLY) + install(FILES "${PROJECT_BINARY_DIR}/curl-config" + DESTINATION ${CMAKE_INSTALL_BINDIR} + PERMISSIONS + OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ WORLD_EXECUTE) + + # Generate a pkg-config file matching this config. + # Consumed variables: + # CURLVERSION + # exec_prefix + # includedir + # LIBCURL_PC_CFLAGS + # LIBCURL_PC_CFLAGS_PRIVATE + # LIBCURL_PC_LDFLAGS_PRIVATE + # LIBCURL_PC_LIBS + # LIBCURL_PC_LIBS_PRIVATE + # LIBCURL_PC_REQUIRES + # LIBCURL_PC_REQUIRES_PRIVATE + # libdir + # prefix + # SUPPORT_FEATURES + # SUPPORT_PROTOCOLS + # Documentation: + # https://people.freedesktop.org/~dbn/pkg-config-guide.html + # https://manpages.debian.org/unstable/pkgconf/pkg-config.1.en.html + # https://manpages.debian.org/unstable/pkg-config/pkg-config.1.en.html + # https://www.msys2.org/docs/pkgconfig/ + configure_file( + "${PROJECT_SOURCE_DIR}/libcurl.pc.in" + "${PROJECT_BINARY_DIR}/libcurl.pc" @ONLY) + install(FILES "${PROJECT_BINARY_DIR}/libcurl.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + + # Install headers + install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/curl" + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + FILES_MATCHING PATTERN "*.h") + + include(CMakePackageConfigHelpers) + write_basic_package_version_file( + "${_version_config}" + VERSION ${_curl_version} + COMPATIBILITY SameMajorVersion) + file(READ "${_version_config}" _generated_version_config) + file(WRITE "${_version_config}" " + if(NOT PACKAGE_FIND_VERSION_RANGE AND PACKAGE_FIND_VERSION_MAJOR STREQUAL \"7\") + # Version 8 satisfies version 7... requirements + set(PACKAGE_FIND_VERSION_MAJOR 8) + set(PACKAGE_FIND_VERSION_COUNT 1) + endif() + ${_generated_version_config}") + + # Consumed custom variables: + # LIB_SELECTED + # TARGETS_EXPORT_NAME + # USE_OPENSSL + # HAVE_LIBZ + configure_package_config_file("CMake/curl-config.cmake.in" + "${_project_config}" + INSTALL_DESTINATION ${_install_cmake_dir} + PATH_VARS CMAKE_INSTALL_INCLUDEDIR) + + if(CURL_ENABLE_EXPORT_TARGET) + install(EXPORT "${TARGETS_EXPORT_NAME}" + NAMESPACE "${PROJECT_NAME}::" + DESTINATION ${_install_cmake_dir}) + endif() + + install(FILES ${_version_config} ${_project_config} + DESTINATION ${_install_cmake_dir}) + + # Workaround for MSVS10 to avoid the Dialog Hell + # FIXME: This could be removed with future version of CMake. + if(MSVC_VERSION EQUAL 1600) + set(_curl_sln_filename "${CMAKE_CURRENT_BINARY_DIR}/CURL.sln") + if(EXISTS "${_curl_sln_filename}") + file(APPEND "${_curl_sln_filename}" "\n# This should be regenerated!\n") + endif() + endif() + + if(NOT TARGET curl_uninstall) + configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake" + @ONLY) + + add_custom_target(curl_uninstall + COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake") + endif() + + install(FILES "${PROJECT_SOURCE_DIR}/scripts/mk-ca-bundle.pl" + DESTINATION ${CMAKE_INSTALL_BINDIR} + PERMISSIONS + OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ WORLD_EXECUTE) + + # The `-DEV` part is important + string(REGEX REPLACE "([0-9]+\.[0-9]+)\.([0-9]+.*)" "\\2" CPACK_PACKAGE_VERSION_PATCH "${_curl_version}") + set(CPACK_GENERATOR "TGZ") + include(CPack) +endif() + +# Save build info for test runner to pick up and log +if(CMAKE_OSX_SYSROOT) + set(_cmake_sysroot ${CMAKE_OSX_SYSROOT}) +elseif(CMAKE_SYSROOT) + set(_cmake_sysroot ${CMAKE_SYSROOT}) +endif() +set(_buildinfo "\ +buildinfo.configure.tool: cmake +buildinfo.configure.command: ${CMAKE_COMMAND} +buildinfo.configure.version: ${CMAKE_VERSION} +buildinfo.configure.args:${_cmake_args} +buildinfo.configure.generator: ${CMAKE_GENERATOR} +buildinfo.configure.make: ${CMAKE_MAKE_PROGRAM} +buildinfo.host.cpu: ${CMAKE_HOST_SYSTEM_PROCESSOR} +buildinfo.host.os: ${CMAKE_HOST_SYSTEM_NAME} +buildinfo.target.cpu: ${CMAKE_SYSTEM_PROCESSOR} +buildinfo.target.os: ${CMAKE_SYSTEM_NAME} +buildinfo.target.flags:${_target_flags} +buildinfo.compiler: ${CMAKE_C_COMPILER_ID} +buildinfo.compiler.version: ${CMAKE_C_COMPILER_VERSION} +buildinfo.sysroot: ${_cmake_sysroot} +") +file(WRITE "${PROJECT_BINARY_DIR}/buildinfo.txt" "# This is a generated file. Do not edit.\n${_buildinfo}") +if(NOT "$ENV{CURL_BUILDINFO}$ENV{CURL_CI}$ENV{CI}" STREQUAL "") + message(STATUS "\n${_buildinfo}") +endif() diff --git a/local-test-curl-delta-01/afc-curl/COPYING b/local-test-curl-delta-01/afc-curl/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..d9e7e0bef3e78e39d2dde092e469d7a680c2047b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/COPYING @@ -0,0 +1,22 @@ +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2024, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. diff --git a/local-test-curl-delta-01/afc-curl/Dockerfile b/local-test-curl-delta-01/afc-curl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..84f0c9789385b6e4d6a936815ea04d31befbd059 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/Dockerfile @@ -0,0 +1,41 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +# Self-contained build environment to match the release environment. +# +# Build and set the timestamp for the date corresponding to the release +# +# docker build --build-arg SOURCE_DATE_EPOCH=1711526400 --build-arg UID=$(id -u) --build-arg GID=$(id -g) -t curl/curl . +# +# Then run commands from within the build environment, for example +# +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl autoreconf -fi +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl ./configure --without-ssl --without-libpsl +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl make +# docker run --rm -it -u $(id -u):$(id -g) -v $(pwd):/usr/src -w /usr/src curl/curl ./scripts/maketgz 8.7.1 +# +# or get into a shell in the build environment, for example +# +# docker run --rm -it -u $(id -u):$(id -g) -v (pwd):/usr/src -w /usr/src curl/curl bash +# $ autoreconf -fi +# $ ./configure --without-ssl --without-libpsl +# $ make +# $ ./scripts/maketgz 8.7.1 + +# To update, get the latest digest e.g. from https://hub.docker.com/_/debian/tags +FROM debian:bookworm-slim@sha256:b73bf02f32434c9be21adf83b9aedf33e731784d8d2dacbbd3ce5f4993f2a2de + +RUN apt-get update -qq && apt-get install -qq -y --no-install-recommends \ + build-essential make autoconf automake libtool git perl zip zlib1g-dev gawk && \ + rm -rf /var/lib/apt/lists/* + +ARG UID=1000 GID=1000 + +RUN groupadd --gid $UID dev && \ + useradd --uid $UID --gid dev --shell /bin/bash --create-home dev + +USER dev:dev + +ARG SOURCE_DATE_EPOCH +ENV SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH:-1} diff --git a/local-test-curl-delta-01/afc-curl/GIT-INFO.md b/local-test-curl-delta-01/afc-curl/GIT-INFO.md new file mode 100644 index 0000000000000000000000000000000000000000..71a8b0375c60ee4cd0a7dbbd6815f6da945d59ed --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/GIT-INFO.md @@ -0,0 +1,32 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + +# GIT-INFO + +This file is only present in git - never in release archives. It contains +information about other files and things that the git repository keeps in its +inner sanctum. + +To build in environments that support configure, after having extracted +everything from git, do this: + + autoreconf -fi + ./configure --with-openssl + make + +Daniel uses a configure line similar to this for easier development: + + ./configure --disable-shared --enable-debug --enable-maintainer-mode + +In environments that don't support configure (i.e. Windows), do this: + + buildconf.bat + +## REQUIREMENTS + +See [docs/INTERNALS.md][0] for requirement details. + +[0]: docs/INTERNALS.md diff --git a/local-test-curl-delta-01/afc-curl/Makefile.am b/local-test-curl-delta-01/afc-curl/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..fbfb8b044730a5d9aacaf4fb8f06c7d2ccfc53e6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/Makefile.am @@ -0,0 +1,252 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +AUTOMAKE_OPTIONS = foreign + +ACLOCAL_AMFLAGS = -I m4 + +CMAKE_DIST = \ + CMake/cmake_uninstall.cmake.in \ + CMake/CMakeConfigurableFile.in \ + CMake/curl-config.cmake.in \ + CMake/CurlSymbolHiding.cmake \ + CMake/CurlTests.c \ + CMake/FindBearSSL.cmake \ + CMake/FindBrotli.cmake \ + CMake/FindCares.cmake \ + CMake/FindGSS.cmake \ + CMake/FindLibgsasl.cmake \ + CMake/FindLibidn2.cmake \ + CMake/FindLibpsl.cmake \ + CMake/FindLibssh.cmake \ + CMake/FindLibssh2.cmake \ + CMake/FindLibuv.cmake \ + CMake/FindMbedTLS.cmake \ + CMake/FindMSH3.cmake \ + CMake/FindMbedTLS.cmake \ + CMake/FindNGHTTP2.cmake \ + CMake/FindNGHTTP3.cmake \ + CMake/FindNGTCP2.cmake \ + CMake/FindNettle.cmake \ + CMake/FindQuiche.cmake \ + CMake/FindRustls.cmake \ + CMake/FindWolfSSH.cmake \ + CMake/FindWolfSSL.cmake \ + CMake/FindZstd.cmake \ + CMake/Macros.cmake \ + CMake/OtherTests.cmake \ + CMake/PickyWarnings.cmake \ + CMake/Platforms/WindowsCache.cmake \ + CMake/Utilities.cmake \ + CMakeLists.txt + +VC_DIST = projects/README.md \ + projects/build-openssl.bat \ + projects/build-wolfssl.bat \ + projects/checksrc.bat \ + projects/generate.bat \ + projects/wolfssl_options.h \ + projects/wolfssl_override.props + +WINBUILD_DIST = winbuild/README.md \ + winbuild/MakefileBuild.vc winbuild/Makefile.vc winbuild/makedebug.bat + +PLAN9_DIST = plan9/include/mkfile \ + plan9/include/mkfile \ + plan9/mkfile.proto \ + plan9/mkfile \ + plan9/README \ + plan9/lib/mkfile.inc \ + plan9/lib/mkfile \ + plan9/src/mkfile.inc \ + plan9/src/mkfile + +EXTRA_DIST = CHANGES.md COPYING Makefile.dist \ + RELEASE-NOTES $(CMAKE_DIST) $(VC_DIST) $(WINBUILD_DIST) \ + $(PLAN9_DIST) buildconf.bat Dockerfile + +CLEANFILES = $(VC14_LIBVCXPROJ) $(VC14_SRCVCXPROJ) \ + $(VC14_10_LIBVCXPROJ) $(VC14_10_SRCVCXPROJ) \ + $(VC14_20_LIBVCXPROJ) $(VC14_20_SRCVCXPROJ) \ + $(VC14_30_LIBVCXPROJ) $(VC14_30_SRCVCXPROJ) + +DISTCLEANFILES = buildinfo.txt + +bin_SCRIPTS = curl-config + +SUBDIRS = lib docs src scripts +DIST_SUBDIRS = $(SUBDIRS) tests packages include docs + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libcurl.pc + +# List of files required to generate VC IDE .dsp, .vcproj and .vcxproj files +include lib/Makefile.inc +include src/Makefile.inc + +dist-hook: + rm -rf $(top_builddir)/tests/log + find $(distdir) -name "*.dist" -a \! -name Makefile.dist -exec rm {} \; + (distit=`find $(srcdir) -name "*.dist" | grep -v Makefile`; \ + for file in $$distit; do \ + strip=`echo $$file | sed -e s/^$(srcdir)// -e s/\.dist//`; \ + cp -p $$file $(distdir)$$strip; \ + done) + +check: test examples check-docs + +if CROSSCOMPILING +test-full: test +test-nonflaky: test +test-torture: test +test-event: test +test-am: test +test-ci: test +pytest: test +pytest-ci: test + +test: + @echo "NOTICE: we can't run the tests when cross-compiling!" + +else + +test: + @(cd tests; $(MAKE) all quiet-test) + +test-full: + @(cd tests; $(MAKE) all full-test) + +test-nonflaky: + @(cd tests; $(MAKE) all nonflaky-test) + +test-torture: + @(cd tests; $(MAKE) all torture-test) + +test-event: + @(cd tests; $(MAKE) all event-test) + +test-am: + @(cd tests; $(MAKE) all am-test) + +test-ci: + @(cd tests; $(MAKE) all ci-test) + +pytest: + @(cd tests; $(MAKE) all default-pytest) + +pytest-ci: + @(cd tests; $(MAKE) all ci-pytest) + +endif + +examples: + @(cd docs/examples; $(MAKE) check) + +check-docs: + @(cd docs/libcurl; $(MAKE) check) + +# Build source and binary rpms. For rpm-3.0 and above, the ~/.rpmmacros +# must contain the following line: +# %_topdir /home/loic/local/rpm +# and that /home/loic/local/rpm contains the directory SOURCES, BUILD etc. +# +# cd /home/loic/local/rpm ; mkdir -p SOURCES BUILD RPMS/i386 SPECS SRPMS +# +# If additional configure flags are needed to build the package, add the +# following in ~/.rpmmacros +# %configure CFLAGS="%{optflags}" ./configure %{_target_platform} --prefix=%{_prefix} ${AM_CONFIGFLAGS} +# and run make rpm in the following way: +# AM_CONFIGFLAGS='--with-uri=/home/users/loic/local/RedHat-6.2' make rpm +# + +rpms: + $(MAKE) RPMDIST=curl rpm + $(MAKE) RPMDIST=curl-ssl rpm + +rpm: + RPM_TOPDIR=`rpm --showrc | $(PERL) -n -e 'print if(s/.*_topdir\s+(.*)/$$1/)'` ; \ + cp $(srcdir)/packages/Linux/RPM/$(RPMDIST).spec $$RPM_TOPDIR/SPECS ; \ + cp $(PACKAGE)-$(VERSION).tar.gz $$RPM_TOPDIR/SOURCES ; \ + rpm -ba --clean --rmsource $$RPM_TOPDIR/SPECS/$(RPMDIST).spec ; \ + mv $$RPM_TOPDIR/RPMS/i386/$(RPMDIST)-*.rpm . ; \ + mv $$RPM_TOPDIR/SRPMS/$(RPMDIST)-*.src.rpm . + +# +# Build a Solaris pkgadd format file +# run 'make pkgadd' once you've done './configure' and 'make' to make a Solaris pkgadd format +# file (which ends up back in this directory). +# The pkgadd file is in 'pkgtrans' format, so to install on Solaris, do +# pkgadd -d ./HAXXcurl-* +# + +# gak - libtool requires an absolute directory, hence the pwd below... +pkgadd: + umask 022 ; \ + $(MAKE) install DESTDIR=`/bin/pwd`/packages/Solaris/root ; \ + cat COPYING > $(srcdir)/packages/Solaris/copyright ; \ + cd $(srcdir)/packages/Solaris && $(MAKE) package + +# +# Build a Cygwin binary tarball installation file +# resulting .tar.bz2 file will end up at packages/Win32/cygwin +cygwinbin: + $(MAKE) -C packages/Win32/cygwin cygwinbin + +# We extend the standard install with a custom hook: +if BUILD_DOCS +install-data-hook: + (cd include && $(MAKE) install) + (cd docs && $(MAKE) install) + (cd docs/libcurl && $(MAKE) install) +else +install-data-hook: + (cd include && $(MAKE) install) + (cd docs && $(MAKE) install) +endif + +# We extend the standard uninstall with a custom hook: +uninstall-hook: + (cd include && $(MAKE) uninstall) + (cd docs && $(MAKE) uninstall) + (cd docs/libcurl && $(MAKE) uninstall) + +ca-bundle: $(srcdir)/scripts/mk-ca-bundle.pl + @echo "generating a fresh ca-bundle.crt" + @perl $(srcdir)/scripts/mk-ca-bundle.pl -b -l -u lib/ca-bundle.crt + +ca-firefox: $(srcdir)/scripts/firefox-db2pem.sh + @echo "generating a fresh ca-bundle.crt" + $(srcdir)/scripts/firefox-db2pem.sh lib/ca-bundle.crt + +checksrc: + (cd lib && $(MAKE) checksrc) + (cd src && $(MAKE) checksrc) + (cd tests && $(MAKE) checksrc) + (cd include/curl && $(MAKE) checksrc) + (cd docs/examples && $(MAKE) checksrc) + (cd packages && $(MAKE) checksrc) + +tidy: + (cd src && $(MAKE) tidy) + (cd lib && $(MAKE) tidy) diff --git a/local-test-curl-delta-01/afc-curl/Makefile.dist b/local-test-curl-delta-01/afc-curl/Makefile.dist new file mode 100644 index 0000000000000000000000000000000000000000..e9132040325ad5d56f33ac2dc174a0d03e98404e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/Makefile.dist @@ -0,0 +1,71 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +all: + ./configure + make + +ssl: + ./configure --with-openssl + make + +vc: + cd winbuild + nmake /f Makefile.vc MACHINE=x86 + +vc-x64: + cd winbuild + nmake /f Makefile.vc MACHINE=x64 + +djgpp%: + $(MAKE) -C lib -f Makefile.mk CFG=$@ CROSSPREFIX=i586-pc-msdosdjgpp- + $(MAKE) -C src -f Makefile.mk CFG=$@ CROSSPREFIX=i586-pc-msdosdjgpp- + +cygwin: + ./configure + make + +cygwin-ssl: + ./configure --with-openssl + make + +amiga%: + $(MAKE) -C lib -f Makefile.mk CFG=$@ CROSSPREFIX=m68k-amigaos- + $(MAKE) -C src -f Makefile.mk CFG=$@ CROSSPREFIX=m68k-amigaos- + +unix: all + +unix-ssl: ssl + +linux: all + +linux-ssl: ssl + +ca-bundle: scripts/mk-ca-bundle.pl + @echo "generate a fresh ca-bundle.crt" + @perl $< -b -l -u lib/ca-bundle.crt + +ca-firefox: scripts/firefox-db2pem.sh + @echo "generate a fresh ca-bundle.crt" + ./scripts/firefox-db2pem.sh lib/ca-bundle.crt diff --git a/local-test-curl-delta-01/afc-curl/README b/local-test-curl-delta-01/afc-curl/README new file mode 100644 index 0000000000000000000000000000000000000000..f5efbd70a69decce435bacce9f0da0702edecb6e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/README @@ -0,0 +1,55 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + +README + + Curl is a command line tool for transferring data specified with URL + syntax. Find out how to use curl by reading the curl.1 man page or the + MANUAL document. Find out how to install Curl by reading the INSTALL + document. + + libcurl is the library curl is using to do its job. It is readily + available to be used by your software. Read the libcurl.3 man page to + learn how. + + You find answers to the most frequent questions we get in the FAQ document. + + Study the COPYING file for distribution terms. + + Those documents and more can be found in the docs/ directory. + +CONTACT + + If you have problems, questions, ideas or suggestions, please contact us + by posting to a suitable mailing list. See https://curl.se/mail/ + + All contributors to the project are listed in the THANKS document. + +WEBSITE + + Visit the curl website for the latest news and downloads: + + https://curl.se/ + +GIT + + To download the latest source code off the GIT server, do this: + + git clone https://github.com/curl/curl.git + + (you will get a directory named curl created, filled with the source code) + +SECURITY PROBLEMS + + Report suspected security problems via our HackerOne page and not in public. + + https://hackerone.com/curl + +NOTICE + + Curl contains pieces of source code that is Copyright (c) 1998, 1999 + Kungliga Tekniska Högskolan. This notice is included here to comply with the + distribution terms. diff --git a/local-test-curl-delta-01/afc-curl/README.md b/local-test-curl-delta-01/afc-curl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..703e0e2a931edb2b8851a4a0968bf44a16cc7f0c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/README.md @@ -0,0 +1,68 @@ + + +# [![curl logo](https://curl.se/logo/curl-logo.svg)](https://curl.se/) + +Curl is a command-line tool for transferring data specified with URL syntax. +Learn how to use curl by reading [the +manpage](https://curl.se/docs/manpage.html) or [everything +curl](https://everything.curl.dev/). + +Find out how to install curl by reading [the INSTALL +document](https://curl.se/docs/install.html). + +libcurl is the library curl is using to do its job. It is readily available to +be used by your software. Read [the libcurl +manpage](https://curl.se/libcurl/c/libcurl.html) to learn how. + +## Open Source + +curl is Open Source and is distributed under an MIT-like +[license](https://curl.se/docs/copyright.html). + +## Contact + +Contact us on a suitable [mailing list](https://curl.se/mail/) or +use GitHub [issues](https://github.com/curl/curl/issues)/ +[pull requests](https://github.com/curl/curl/pulls)/ +[discussions](https://github.com/curl/curl/discussions). + +All contributors to the project are listed in [the THANKS +document](https://curl.se/docs/thanks.html). + +## Commercial support + +For commercial support, maybe private and dedicated help with your problems or +applications using (lib)curl visit [the support page](https://curl.se/support.html). + +## Website + +Visit the [curl website](https://curl.se/) for the latest news and downloads. + +## Source code + +Download the latest source from the Git server: + + git clone https://github.com/curl/curl.git + +## Security problems + +Report suspected security problems via [our HackerOne +page](https://hackerone.com/curl) and not in public. + +## Notice + +Curl contains pieces of source code that is Copyright (c) 1998, 1999 Kungliga +Tekniska Högskolan. This notice is included here to comply with the +distribution terms. + +## Backers + +Thank you to all our backers 🙏 [Become a backer](https://opencollective.com/curl#section-contribute). + +## Sponsors + +Support this project by becoming a [sponsor](https://curl.se/sponsors.html). diff --git a/local-test-curl-delta-01/afc-curl/RELEASE-NOTES b/local-test-curl-delta-01/afc-curl/RELEASE-NOTES new file mode 100644 index 0000000000000000000000000000000000000000..59d40bdf4d1fc8d1da3ce868d318f54da26e6179 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/RELEASE-NOTES @@ -0,0 +1,197 @@ +curl and libcurl 8.11.1 + + Public curl releases: 263 + Command line options: 266 + curl_easy_setopt() options: 306 + Public functions in libcurl: 94 + Contributors: 3298 + +This release includes the following changes: + + +This release includes the following bugfixes: + + o build: fix ECH to always enable HTTPS RR [35] + o build: fix MSVC UWP builds [32] + o build: omit certain deps from `libcurl.pc` unless found via `pkg-config` [27] + o build: use `_fseeki64()` on Windows, drop detections [41] + o cmake: do not echo most inherited `LDFLAGS` to config files [55] + o cmake: drop cmake args list from `buildinfo.txt` [8] + o cmake: include `wolfssl/options.h` first [53] + o cmake: remove legacy unused IMMEDIATE keyword [21] + o cmake: restore cmake args list in `buildinfo.txt` [26] + o cmake: set `CURL_STATICLIB` for static lib when `SHARE_LIB_OBJECT=OFF` [64] + o cmake: sync GSS config code with other deps [28] + o cmake: typo in comment + o cmake: work around `ios.toolchain.cmake` breaking feature-detections [37] + o cmakelint: fix to check root `CMakeLists.txt` [36] + o cmdline/ech.md: formatting cleanups [13] + o configure: add FIXMEs for disabled pkg-config references + o configure: do not echo most inherited `LDFLAGS` to config files [31] + o configure: replace `$#` shell syntax [25] + o cookie: treat cookie name case sensitively [4] + o curl-rustls.m4: keep existing `CPPFLAGS`/`LDFLAGS` when detected [40] + o curl.h: mark two error codes as obsolete [19] + o curl: --continue-at is mutually exclusive with --no-clobber [51] + o curl: --continue-at is mutually exclusive with --range [61] + o curl: --continue-at is mutually exclusive with --remove-on-error [50] + o curl: --test-duphandle in debug builds runs "duphandled" [6] + o curl: do more command line parsing in sub functions [71] + o curl: rename struct var to fix AIX build [24] + o curl: use realtime in trace timestamps [52] + o curl_multi_socket_all.md: soften the deprecation warning [56] + o CURLOPT_PREREQFUNCTION.md: add result code on failure [23] + o digest: produce a shorter cnonce in Digest headers [70] + o DISTROS: update Alt Linux links + o dmaketgz: use --no-cache when building docker image [66] + o docs: document default `User-Agent` [57] + o docs: suggest --ssl-reqd instead of --ftp-ssl [62] + o duphandle: also init netrc [3] + o ECH: enable support for the AWS-LC backend [5] + o hostip: don't use the resolver for FQDN localhost [45] + o http_negotiate: allow for a one byte larger channel binding buffer [63] + o http_proxy: move dynhds_add_custom here from http.c [18] + o KNOWN_BUGS: setting a disabled option should return CURLE_NOT_BUILT_IN [74] + o krb5: fix socket/sockindex confusion, MSVC compiler warnings [22] + o lib: fixes for wolfSSL OPENSSL_COEXIST [73] + o libssh: use libssh sftp_aio to upload file [47] + o libssh: when using IPv6 numerical address, add brackets [43] + o macos: disable gcc `availability` workaround as needed [7] + o mbedtls: call psa_crypt_init() in global init [2] + o mime: fix reader stall on small read lengths [65] + o mk-ca-bundle: remove CKA_NSS_SERVER_DISTRUST_AFTER conditions [39] + o multi: add clarifying comment for wakeup_write() [9] + o multi: fix callback for `CURLMOPT_TIMERFUNCTION` not being called again when... [48] + o netrc: address several netrc parser flaws [17] + o netrc: support large file, longer lines, longer tokens [14] + o nghttp2: use custom memory functions [1] + o OpenSSL: improvde error message on expired certificate [59] + o openssl: remove three "Useless Assignments" [72] + o openssl: stop using SSL_CTX_ function prefix for our functions [20] + o os400: Fix IBMi builds [33] + o os400: Fix IBMi EBCDIC conversion of arguments [34] + o pytest: add test for use of CURLMOPT_MAX_HOST_CONNECTIONS [60] + o rtsp: check EOS in the RTSP receive and return an error code [49] + o schannel: remove TLS 1.3 ciphersuite-list support [54] + o setopt: fix CURLOPT_HTTP_CONTENT_DECODING [15] + o setopt: fix missing options for builds without HTTP & MQTT [10] + o show-headers.md: clarify the headers are saved with the data [58] + o socket: handle binding to "host!" [16] + o socketpair: fix enabling `USE_EVENTFD` [30] + o strtok: use namespaced `strtok_r` macro instead of redefining it [29] + o tests: add the ending time stamp in testcurl.pl + o tests: re-enable 2086, and 472, 1299, 1613 for Windows [38] + o TODO: consider OCSP stapling by default [11] + o tool_formparse: remove use of sscanf() [68] + o tool_getparam: parse --localport without using sscanf [67] + o tool_getpass: fix UWP `-Wnull-dereference` [46] + o tool_getpass: replace `getch()` call with `_getch()` on Windows [42] + o tool_urlglob: parse character globbing range without sscanf [69] + o vtls: fix compile warning when ALPN is not available [12] + +This release includes the following known bugs: + + See docs/KNOWN_BUGS (https://curl.se/docs/knownbugs.html) + +For all changes ever done in curl: + + See https://curl.se/changes.html + +Planned upcoming removals include: + + o TLS libraries not supporting TLS 1.3 + + See https://curl.se/dev/deprecate.html for details + +This release would not have looked like this without help, code, reports and +advice from friends like these: + + Alexis Savin, Andrew Ayer, Andrew Kirillov, Andy Fiddaman, Ben Greear, + Bo Anderson, Brendon Smith, chemodax, Dan Fandrich, Daniel Engberg, + Daniel Pouzzner, Daniel Stenberg, Dan Rosser, delogicsreal on github, + dengjfzh on github, Ethan Everett, Florian Eckert, galen11 on github, + Harmen Stoppels, Harry Sintonen, henrikjehgmti on github, hiimmat on github, + Jacob Champion, Jeroen Ooms, Jesus Malo Poyatos, jethrogb on github, + Kai Pastor, Logan Buth, Maarten Billemont, marcos-ng on github, Moritz, + newfunction on hackerone, Nicolas F., Peter Kokot, Peter Marko, Ray Satiro, + renovate[bot], Samuel Henrique, Stefan Eissing, SuperStormer on github, + Tal Regev, Thomas, tinyboxvk, tkzv on github, tranzystorekk on github, + Viktor Szakats, Vladislavs Sokurenko, wxiaoguang on github, Wyatt O'Day, + xiaofeng, Yoshimasa Ohno + (51 contributors) + +References to bug reports and discussions on issues: + + [1] = https://curl.se/bug/?i=15527 + [2] = https://curl.se/bug/?i=15500 + [3] = https://curl.se/bug/?i=15496 + [4] = https://curl.se/bug/?i=15492 + [5] = https://curl.se/bug/?i=15499 + [6] = https://curl.se/bug/?i=15504 + [7] = https://curl.se/bug/?i=15508 + [8] = https://curl.se/bug/?i=15501 + [9] = https://curl.se/bug/?i=15600 + [10] = https://curl.se/bug/?i=15634 + [11] = https://curl.se/bug/?i=15483 + [12] = https://curl.se/bug/?i=15515 + [13] = https://curl.se/bug/?i=15506 + [14] = https://curl.se/bug/?i=15513 + [15] = https://curl.se/bug/?i=15511 + [16] = https://curl.se/bug/?i=15553 + [17] = https://curl.se/bug/?i=15586 + [18] = https://curl.se/bug/?i=15672 + [19] = https://curl.se/bug/?i=15538 + [20] = https://curl.se/bug/?i=15673 + [21] = https://curl.se/bug/?i=15661 + [22] = https://curl.se/bug/?i=15585 + [23] = https://curl.se/bug/?i=15542 + [24] = https://curl.se/bug/?i=15580 + [25] = https://curl.se/bug/?i=15584 + [26] = https://curl.se/bug/?i=15563 + [27] = https://curl.se/bug/?i=15469 + [28] = https://curl.se/bug/?i=15545 + [29] = https://curl.se/bug/?i=15549 + [30] = https://curl.se/bug/?i=15561 + [31] = https://curl.se/bug/?i=15533 + [32] = https://curl.se/bug/?i=15657 + [33] = https://curl.se/bug/?i=15566 + [34] = https://curl.se/bug/?i=15570 + [35] = https://curl.se/bug/?i=15648 + [36] = https://curl.se/bug/?i=15565 + [37] = https://curl.se/bug/?i=15557 + [38] = https://curl.se/bug/?i=15644 + [39] = https://curl.se/bug/?i=15547 + [40] = https://curl.se/bug/?i=15546 + [41] = https://curl.se/bug/?i=15525 + [42] = https://curl.se/bug/?i=15642 + [43] = https://curl.se/bug/?i=15522 + [45] = https://curl.se/bug/?i=15676 + [46] = https://curl.se/bug/?i=15638 + [47] = https://curl.se/bug/?i=15625 + [48] = https://curl.se/bug/?i=15627 + [49] = https://curl.se/bug/?i=15624 + [50] = https://curl.se/bug/?i=15645 + [51] = https://curl.se/bug/?i=15645 + [52] = https://curl.se/bug/?i=15614 + [53] = https://curl.se/bug/?i=15620 + [54] = https://hackerone.com/reports/2792484 + [55] = https://curl.se/bug/?i=15617 + [56] = https://curl.se/mail/lib-2024-11/0029.html + [57] = https://curl.se/bug/?i=15608 + [58] = https://curl.se/bug/?i=15605 + [59] = https://curl.se/bug/?i=15612 + [60] = https://curl.se/bug/?i=15494 + [61] = https://curl.se/bug/?i=15646 + [62] = https://curl.se/bug/?i=15658 + [63] = https://curl.se/bug/?i=15685 + [64] = https://curl.se/bug/?i=15695 + [65] = https://curl.se/bug/?i=15688 + [66] = https://curl.se/bug/?i=15689 + [67] = https://curl.se/bug/?i=15681 + [68] = https://curl.se/bug/?i=15683 + [69] = https://curl.se/bug/?i=15682 + [70] = https://curl.se/bug/?i=15653 + [71] = https://curl.se/bug/?i=15680 + [72] = https://curl.se/bug/?i=15679 + [73] = https://curl.se/bug/?i=15650 + [74] = https://curl.se/bug/?i=15472 diff --git a/local-test-curl-delta-01/afc-curl/REUSE.toml b/local-test-curl-delta-01/afc-curl/REUSE.toml new file mode 100644 index 0000000000000000000000000000000000000000..e242452d8ff0e529b18b4f4dc91805f5e4836afe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/REUSE.toml @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: curl +# SPDX-FileCopyrightText: Daniel Stenberg, , et al. + +# This file describes the licensing and copyright situation for files that +# cannot be annotated directly, for example because of being simply +# uncommentable. Unless this is the case, a file should be annotated directly. +# +# This follows the REUSE specification: https://reuse.software/spec-3.2/#reusetoml + +version = 1 +SPDX-PackageName = "curl" +SPDX-PackageDownloadLocation = "https://curl.se/" + +[[annotations]] +path = [ + ".mailmap", + "docs/FAQ", + "docs/INSTALL", + "docs/KNOWN_BUGS", + "docs/libcurl/symbols-in-versions", + "docs/MAIL-ETIQUETTE", + "docs/options-in-versions", + "docs/THANKS", + "docs/TODO", + "GIT-INFO.md", + "lib/libcurl.vers.in", + "lib/libcurl.def", + "packages/OS400/README.OS400", + "packages/vms/build_vms.com", + "packages/vms/curl_release_note_start.txt", + "packages/vms/curlmsg.sdl", + "packages/vms/macro32_exactcase.patch", + "packages/vms/readme", + "plan9/README", + "projects/Windows/**", "projects/wolfssl_override.props", + "README", + "RELEASE-NOTES", + "renovate.json", + "tests/certs/**", + "tests/data/test**", + "tests/stunnel.pem", + "tests/valgrind.supp", + # checksrc control files + "docs/examples/.checksrc", + "lib/.checksrc", + "lib/vauth/.checksrc", + "lib/vquic/.checksrc", + "lib/vssh/.checksrc", + "lib/vtls/.checksrc", + "src/.checksrc", + "tests/libtest/.checksrc", + "tests/server/.checksrc", +] +SPDX-FileCopyrightText = "Daniel Stenberg, , et al." +SPDX-License-Identifier = "curl" +# If there is licensing/copyright information in or next to these files, prefer that +precedence = "closest" diff --git a/local-test-curl-delta-01/afc-curl/SECURITY.md b/local-test-curl-delta-01/afc-curl/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..64e0d2feabbabc6a718b8b067a1519b34b328a22 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/SECURITY.md @@ -0,0 +1,29 @@ + + +# Security Policy + +Read our [Vulnerability Disclosure Policy](docs/VULN-DISCLOSURE-POLICY.md). + +## Reporting a Vulnerability + +If you have found or just suspect a security problem somewhere in curl or +libcurl, report it on [HackerOne](https://hackerone.com/curl). + +We treat security issues with confidentiality until controlled and disclosed responsibly. + +## OpenSSF Best Practices + +curl has achieved Gold status on the Open Source Security Foundation (OpenSSF) +[Best Practices](https://bestpractices.dev/) (formerly Core Infrastructure +Initiative Best Practices), reflecting its adherence to rigorous +security and best practice standards. This achievement highlights curl's +comprehensive documentation, secure development processes, effective change +control mechanisms, and strong maintenance routines. Meeting these criteria +demonstrates curl's commitment to security and reliability, ensuring the +project's sustainability and trustworthiness. This underscores curl's role as +a leader in open-source software practices. More information can be found on +[curl's OpenSSF Best Practices project page](https://www.bestpractices.dev/projects/63). diff --git a/local-test-curl-delta-01/afc-curl/acinclude.m4 b/local-test-curl-delta-01/afc-curl/acinclude.m4 new file mode 100644 index 0000000000000000000000000000000000000000..916130b393f704a3f219bd672f50925aae99fa52 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/acinclude.m4 @@ -0,0 +1,1697 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +dnl CURL_CHECK_DEF (SYMBOL, [INCLUDES], [SILENT]) +dnl ------------------------------------------------- +dnl Use the C preprocessor to find out if the given object-style symbol +dnl is defined and get its expansion. This macro will not use default +dnl includes even if no INCLUDES argument is given. This macro will run +dnl silently when invoked with three arguments. If the expansion would +dnl result in a set of double-quoted strings the returned expansion will +dnl actually be a single double-quoted string concatenating all them. + +AC_DEFUN([CURL_CHECK_DEF], [ + AC_REQUIRE([CURL_CPP_P])dnl + OLDCPPFLAGS=$CPPFLAGS + # CPPPFLAG comes from CURL_CPP_P + CPPFLAGS="$CPPFLAGS $CPPPFLAG" + AS_VAR_PUSHDEF([ac_HaveDef], [curl_cv_have_def_$1])dnl + AS_VAR_PUSHDEF([ac_Def], [curl_cv_def_$1])dnl + if test -z "$SED"; then + AC_MSG_ERROR([SED not set. Cannot continue without SED being set.]) + fi + if test -z "$GREP"; then + AC_MSG_ERROR([GREP not set. Cannot continue without GREP being set.]) + fi + ifelse($3,,[AC_MSG_CHECKING([for preprocessor definition of $1])]) + tmp_exp="" + AC_PREPROC_IFELSE([ + AC_LANG_SOURCE( +ifelse($2,,,[$2])[[ + #ifdef $1 + CURL_DEF_TOKEN $1 + #endif + ]]) + ],[ + tmp_exp=`eval "$ac_cpp conftest.$ac_ext" 2>/dev/null | \ + "$GREP" CURL_DEF_TOKEN 2>/dev/null | \ + "$SED" 's/.*CURL_DEF_TOKEN[[ ]][[ ]]*//' 2>/dev/null | \ + "$SED" 's/[["]][[ ]]*[["]]//g' 2>/dev/null` + if test -z "$tmp_exp" || test "$tmp_exp" = "$1"; then + tmp_exp="" + fi + ]) + if test -z "$tmp_exp"; then + AS_VAR_SET(ac_HaveDef, no) + ifelse($3,,[AC_MSG_RESULT([no])]) + else + AS_VAR_SET(ac_HaveDef, yes) + AS_VAR_SET(ac_Def, $tmp_exp) + ifelse($3,,[AC_MSG_RESULT([$tmp_exp])]) + fi + AS_VAR_POPDEF([ac_Def])dnl + AS_VAR_POPDEF([ac_HaveDef])dnl + CPPFLAGS=$OLDCPPFLAGS +]) + + +dnl CURL_CHECK_DEF_CC (SYMBOL, [INCLUDES], [SILENT]) +dnl ------------------------------------------------- +dnl Use the C compiler to find out only if the given symbol is defined +dnl or not, this can not find out its expansion. This macro will not use +dnl default includes even if no INCLUDES argument is given. This macro +dnl will run silently when invoked with three arguments. + +AC_DEFUN([CURL_CHECK_DEF_CC], [ + AS_VAR_PUSHDEF([ac_HaveDef], [curl_cv_have_def_$1])dnl + ifelse($3,,[AC_MSG_CHECKING([for compiler definition of $1])]) + AC_COMPILE_IFELSE([ + AC_LANG_SOURCE( +ifelse($2,,,[$2])[[ + int main(void) + { + #ifdef $1 + return 0; + #else + #error force compilation error + #endif + } + ]]) + ],[ + tst_symbol_defined="yes" + ],[ + tst_symbol_defined="no" + ]) + if test "$tst_symbol_defined" = "yes"; then + AS_VAR_SET(ac_HaveDef, yes) + ifelse($3,,[AC_MSG_RESULT([yes])]) + else + AS_VAR_SET(ac_HaveDef, no) + ifelse($3,,[AC_MSG_RESULT([no])]) + fi + AS_VAR_POPDEF([ac_HaveDef])dnl +]) + + +dnl CURL_CHECK_LIB_XNET +dnl ------------------------------------------------- +dnl Verify if X/Open network library is required. + +AC_DEFUN([CURL_CHECK_LIB_XNET], [ + AC_MSG_CHECKING([if X/Open network library is required]) + tst_lib_xnet_required="no" + AC_COMPILE_IFELSE([ + AC_LANG_SOURCE([[ + int main(void) + { + #if defined(__hpux) && defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 600) + return 0; + #elif defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED) + return 0; + #else + #error force compilation error + #endif + } + ]]) + ],[ + tst_lib_xnet_required="yes" + LIBS="-lxnet $LIBS" + ]) + AC_MSG_RESULT([$tst_lib_xnet_required]) +]) + + +dnl CURL_CHECK_AIX_ALL_SOURCE +dnl ------------------------------------------------- +dnl Provides a replacement of traditional AC_AIX with +dnl an uniform behavior across all autoconf versions, +dnl and with our own placement rules. + +AC_DEFUN([CURL_CHECK_AIX_ALL_SOURCE], [ + AH_VERBATIM([_ALL_SOURCE], + [/* Define to 1 if OS is AIX. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif]) + AC_BEFORE([$0], [AC_SYS_LARGEFILE])dnl + AC_BEFORE([$0], [CURL_CONFIGURE_REENTRANT])dnl + AC_MSG_CHECKING([if OS is AIX (to define _ALL_SOURCE)]) + AC_EGREP_CPP([yes_this_is_aix],[ +#ifdef _AIX + yes_this_is_aix +#endif + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(_ALL_SOURCE) + ],[ + AC_MSG_RESULT([no]) + ]) +]) + + +dnl CURL_CHECK_NATIVE_WINDOWS +dnl ------------------------------------------------- +dnl Check if building a native Windows target + +AC_DEFUN([CURL_CHECK_NATIVE_WINDOWS], [ + AC_CACHE_CHECK([whether build target is a native Windows one], [curl_cv_native_windows], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + #ifdef _WIN32 + int dummy=1; + #else + #error Not a native Windows build target. + #endif + ]]) + ],[ + curl_cv_native_windows="yes" + ],[ + curl_cv_native_windows="no" + ]) + ]) + AM_CONDITIONAL(DOING_NATIVE_WINDOWS, test "x$curl_cv_native_windows" = xyes) +]) + + +dnl CURL_CHECK_HEADER_LBER +dnl ------------------------------------------------- +dnl Check for compilable and valid lber.h header, +dnl and check if it is needed even with ldap.h + +AC_DEFUN([CURL_CHECK_HEADER_LBER], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_CACHE_CHECK([for lber.h], [curl_cv_header_lber_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #endif + #ifndef NULL + #define NULL (void *)0 + #endif + #include + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_header_lber_h="yes" + ],[ + curl_cv_header_lber_h="no" + ]) + ]) + if test "$curl_cv_header_lber_h" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_LBER_H, 1, + [Define to 1 if you have the lber.h header file.]) + # + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #endif + #ifndef NULL + #define NULL (void *)0 + #endif + #ifndef LDAP_DEPRECATED + #define LDAP_DEPRECATED 1 + #endif + #include + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_need_header_lber_h="no" + ],[ + curl_cv_need_header_lber_h="yes" + ]) + # + case "$curl_cv_need_header_lber_h" in + yes) + AC_DEFINE_UNQUOTED(NEED_LBER_H, 1, + [Define to 1 if you need the lber.h header file even with ldap.h]) + ;; + esac + fi +]) + + +dnl CURL_CHECK_HEADER_LDAP +dnl ------------------------------------------------- +dnl Check for compilable and valid ldap.h header + +AC_DEFUN([CURL_CHECK_HEADER_LDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_LBER])dnl + AC_CACHE_CHECK([for ldap.h], [curl_cv_header_ldap_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #endif + #ifndef LDAP_DEPRECATED + #define LDAP_DEPRECATED 1 + #endif + #ifdef NEED_LBER_H + #include + #endif + #include + ]],[[ + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + ]]) + ],[ + curl_cv_header_ldap_h="yes" + ],[ + curl_cv_header_ldap_h="no" + ]) + ]) + case "$curl_cv_header_ldap_h" in + yes) + AC_DEFINE_UNQUOTED(HAVE_LDAP_H, 1, + [Define to 1 if you have the ldap.h header file.]) + ;; + esac +]) + + +dnl CURL_CHECK_HEADER_LDAP_SSL +dnl ------------------------------------------------- +dnl Check for compilable and valid ldap_ssl.h header + +AC_DEFUN([CURL_CHECK_HEADER_LDAP_SSL], [ + AC_REQUIRE([CURL_CHECK_HEADER_LDAP])dnl + AC_CACHE_CHECK([for ldap_ssl.h], [curl_cv_header_ldap_ssl_h], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #endif + #ifndef LDAP_DEPRECATED + #define LDAP_DEPRECATED 1 + #endif + #ifdef NEED_LBER_H + #include + #endif + #ifdef HAVE_LDAP_H + #include + #endif + #include + ]],[[ + LDAP *ldp = ldapssl_init("0.0.0.0", LDAPS_PORT, 1); + ]]) + ],[ + curl_cv_header_ldap_ssl_h="yes" + ],[ + curl_cv_header_ldap_ssl_h="no" + ]) + ]) + case "$curl_cv_header_ldap_ssl_h" in + yes) + AC_DEFINE_UNQUOTED(HAVE_LDAP_SSL_H, 1, + [Define to 1 if you have the ldap_ssl.h header file.]) + ;; + esac +]) + + +dnl CURL_CHECK_LIBS_WINLDAP +dnl ------------------------------------------------- +dnl Check for libraries needed for WINLDAP support, +dnl and prepended to LIBS any needed libraries. +dnl This macro can take an optional parameter with a +dnl whitespace separated list of libraries to check +dnl before the WINLDAP default ones. + +AC_DEFUN([CURL_CHECK_LIBS_WINLDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_WINBER])dnl + # + AC_MSG_CHECKING([for WINLDAP libraries]) + # + u_libs="" + # + ifelse($1,,,[ + for x_lib in $1; do + case "$x_lib" in + -l*) + l_lib="$x_lib" + ;; + *) + l_lib="-l$x_lib" + ;; + esac + if test -z "$u_libs"; then + u_libs="$l_lib" + else + u_libs="$u_libs $l_lib" + fi + done + ]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_ldap_LIBS="unknown" + # + for x_nlibs in '' "$u_libs" \ + '-lwldap32' ; do + if test "$curl_cv_ldap_LIBS" = "unknown"; then + if test -z "$x_nlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_nlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include + #ifdef HAVE_WINBER_H + #include + #endif + #endif + ]],[[ + BERVAL *bvp = NULL; + BerElement *bep = ber_init(bvp); + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + ULONG res = ldap_unbind(ldp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_ldap_LIBS="$x_nlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find WINLDAP libraries]) + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_ldap_LIBS" + else + LIBS="$curl_cv_ldap_LIBS $curl_cv_save_LIBS" + fi + AC_MSG_RESULT([$curl_cv_ldap_LIBS]) + ;; + esac + # +]) + + +dnl CURL_CHECK_LIBS_LDAP +dnl ------------------------------------------------- +dnl Check for libraries needed for LDAP support, +dnl and prepended to LIBS any needed libraries. +dnl This macro can take an optional parameter with a +dnl whitespace separated list of libraries to check +dnl before the default ones. + +AC_DEFUN([CURL_CHECK_LIBS_LDAP], [ + AC_REQUIRE([CURL_CHECK_HEADER_LDAP])dnl + # + AC_MSG_CHECKING([for LDAP libraries]) + # + u_libs="" + # + ifelse($1,,,[ + for x_lib in $1; do + case "$x_lib" in + -l*) + l_lib="$x_lib" + ;; + *) + l_lib="-l$x_lib" + ;; + esac + if test -z "$u_libs"; then + u_libs="$l_lib" + else + u_libs="$u_libs $l_lib" + fi + done + ]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_ldap_LIBS="unknown" + # + for x_nlibs in '' "$u_libs" \ + '-lldap' \ + '-lldap -llber' \ + '-llber -lldap' \ + '-lldapssl -lldapx -lldapsdk' \ + '-lldapsdk -lldapx -lldapssl' \ + '-lldap -llber -lssl -lcrypto'; do + + if test "$curl_cv_ldap_LIBS" = "unknown"; then + if test -z "$x_nlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_nlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #endif + #ifndef NULL + #define NULL (void *)0 + #endif + #ifndef LDAP_DEPRECATED + #define LDAP_DEPRECATED 1 + #endif + #ifdef NEED_LBER_H + #include + #endif + #ifdef HAVE_LDAP_H + #include + #endif + ]],[[ + BerValue *bvp = NULL; + BerElement *bep = ber_init(bvp); + LDAP *ldp = ldap_init("0.0.0.0", LDAP_PORT); + int res = ldap_unbind(ldp); + ber_free(bep, 1); + ]]) + ],[ + curl_cv_ldap_LIBS="$x_nlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find LDAP libraries]) + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_ldap_LIBS" + else + LIBS="$curl_cv_ldap_LIBS $curl_cv_save_LIBS" + fi + # FIXME: Enable when ldap was detected via pkg-config + if false; then + LIBCURL_PC_REQUIRES_PRIVATE="ldap $LIBCURL_PC_REQUIRES_PRIVATE" + fi + AC_MSG_RESULT([$curl_cv_ldap_LIBS]) + ;; + esac + # +]) + + +dnl TYPE_SOCKADDR_STORAGE +dnl ------------------------------------------------- +dnl Check for struct sockaddr_storage. Most IPv6-enabled +dnl hosts have it, but AIX 4.3 is one known exception. + +AC_DEFUN([TYPE_SOCKADDR_STORAGE], +[ + AC_CHECK_TYPE([struct sockaddr_storage], + AC_DEFINE(HAVE_STRUCT_SOCKADDR_STORAGE, 1, + [if struct sockaddr_storage is defined]), , + [ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #ifdef HAVE_NETINET_IN_H + #include + #endif + #ifdef HAVE_ARPA_INET_H + #include + #endif + #endif + ]) +]) + +dnl CURL_CHECK_FUNC_RECV +dnl ------------------------------------------------- +dnl Test if the socket recv() function is available, + +AC_DEFUN([CURL_CHECK_FUNC_RECV], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + # + AC_MSG_CHECKING([for recv]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + $curl_includes_bsdsocket + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #endif + ]],[[ + recv(0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_recv="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_recv="no" + ]) + # + if test "$curl_cv_recv" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_RECV, 1, + [Define to 1 if you have the recv function.]) + curl_cv_func_recv="yes" + else + AC_MSG_ERROR([Unable to link function recv]) + fi +]) + + +dnl CURL_CHECK_FUNC_SEND +dnl ------------------------------------------------- +dnl Test if the socket send() function is available, + +AC_DEFUN([CURL_CHECK_FUNC_SEND], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + # + AC_MSG_CHECKING([for send]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + $curl_includes_bsdsocket + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #endif + ]],[[ + send(0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_send="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_send="no" + ]) + # + if test "$curl_cv_send" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_SEND, 1, + [Define to 1 if you have the send function.]) + curl_cv_func_send="yes" + else + AC_MSG_ERROR([Unable to link function send]) + fi +]) + +dnl CURL_CHECK_MSG_NOSIGNAL +dnl ------------------------------------------------- +dnl Check for MSG_NOSIGNAL + +AC_DEFUN([CURL_CHECK_MSG_NOSIGNAL], [ + AC_CHECK_HEADERS(sys/types.h sys/socket.h) + AC_CACHE_CHECK([for MSG_NOSIGNAL], [curl_cv_msg_nosignal], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #endif + ]],[[ + int flag=MSG_NOSIGNAL; + ]]) + ],[ + curl_cv_msg_nosignal="yes" + ],[ + curl_cv_msg_nosignal="no" + ]) + ]) + case "$curl_cv_msg_nosignal" in + yes) + AC_DEFINE_UNQUOTED(HAVE_MSG_NOSIGNAL, 1, + [Define to 1 if you have the MSG_NOSIGNAL flag.]) + ;; + esac +]) + + +dnl CURL_CHECK_STRUCT_TIMEVAL +dnl ------------------------------------------------- +dnl Check for timeval struct + +AC_DEFUN([CURL_CHECK_STRUCT_TIMEVAL], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_CHECK_HEADERS(sys/types.h sys/time.h sys/socket.h) + AC_CACHE_CHECK([for struct timeval], [curl_cv_struct_timeval], [ + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #endif + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + ]],[[ + struct timeval ts; + ts.tv_sec = 0; + ts.tv_usec = 0; + ]]) + ],[ + curl_cv_struct_timeval="yes" + ],[ + curl_cv_struct_timeval="no" + ]) + ]) + case "$curl_cv_struct_timeval" in + yes) + AC_DEFINE_UNQUOTED(HAVE_STRUCT_TIMEVAL, 1, + [Define to 1 if you have the timeval struct.]) + ;; + esac +]) + + +dnl TYPE_IN_ADDR_T +dnl ------------------------------------------------- +dnl Check for in_addr_t: it is used to receive the return code of inet_addr() +dnl and a few other things. + +AC_DEFUN([TYPE_IN_ADDR_T], [ + AC_CHECK_TYPE([in_addr_t], ,[ + dnl in_addr_t not available + AC_CACHE_CHECK([for in_addr_t equivalent], + [curl_cv_in_addr_t_equiv], [ + curl_cv_in_addr_t_equiv="unknown" + for t in "unsigned long" int size_t unsigned long; do + if test "$curl_cv_in_addr_t_equiv" = "unknown"; then + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #ifdef HAVE_NETINET_IN_H + #include + #endif + #ifdef HAVE_ARPA_INET_H + #include + #endif + #endif + ]],[[ + $t data = inet_addr ("1.2.3.4"); + ]]) + ],[ + curl_cv_in_addr_t_equiv="$t" + ]) + fi + done + ]) + case "$curl_cv_in_addr_t_equiv" in + unknown) + AC_MSG_ERROR([Cannot find a type to use in place of in_addr_t]) + ;; + *) + AC_DEFINE_UNQUOTED(in_addr_t, $curl_cv_in_addr_t_equiv, + [Type to use in place of in_addr_t when system does not provide it.]) + ;; + esac + ],[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #else + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + #ifdef HAVE_NETINET_IN_H + #include + #endif + #ifdef HAVE_ARPA_INET_H + #include + #endif + #endif + ]) +]) + + +dnl CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC +dnl ------------------------------------------------- +dnl Check if monotonic clock_gettime is available. + +AC_DEFUN([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC], [ + AC_CHECK_HEADERS(sys/types.h sys/time.h) + AC_MSG_CHECKING([for monotonic clock_gettime]) + # + if test "x$dontwant_rt" = "xno" ; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_func_clock_gettime="yes" + ],[ + AC_MSG_RESULT([no]) + curl_func_clock_gettime="no" + ]) + fi + dnl Definition of HAVE_CLOCK_GETTIME_MONOTONIC is intentionally postponed + dnl until library linking and run-time checks for clock_gettime succeed. +]) + +dnl CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW +dnl ------------------------------------------------- +dnl Check if monotonic clock_gettime is available. + +AC_DEFUN([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW], [ + AC_CHECK_HEADERS(sys/types.h sys/time.h) + AC_MSG_CHECKING([for raw monotonic clock_gettime]) + # + if test "x$dontwant_rt" = "xno" ; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_CLOCK_GETTIME_MONOTONIC_RAW, 1, + [Define to 1 if you have the clock_gettime function and raw monotonic timer.]) + ],[ + AC_MSG_RESULT([no]) + ]) + fi +]) + + +dnl CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC +dnl ------------------------------------------------- +dnl If monotonic clock_gettime is available then, +dnl check and prepended to LIBS any needed libraries. + +AC_DEFUN([CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC], [ + AC_REQUIRE([CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC])dnl + # + if test "$curl_func_clock_gettime" = "yes"; then + # + AC_MSG_CHECKING([for clock_gettime in libraries]) + # + curl_cv_save_LIBS="$LIBS" + curl_cv_gclk_LIBS="unknown" + # + for x_xlibs in '' '-lrt' '-lposix4' ; do + if test "$curl_cv_gclk_LIBS" = "unknown"; then + if test -z "$x_xlibs"; then + LIBS="$curl_cv_save_LIBS" + else + LIBS="$x_xlibs $curl_cv_save_LIBS" + fi + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + ]],[[ + struct timespec ts; + (void)clock_gettime(CLOCK_MONOTONIC, &ts); + ]]) + ],[ + curl_cv_gclk_LIBS="$x_xlibs" + ]) + fi + done + # + LIBS="$curl_cv_save_LIBS" + # + case X-"$curl_cv_gclk_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find clock_gettime]) + AC_MSG_WARN([HAVE_CLOCK_GETTIME_MONOTONIC will not be defined]) + curl_func_clock_gettime="no" + ;; + X-) + AC_MSG_RESULT([no additional lib required]) + curl_func_clock_gettime="yes" + ;; + *) + if test -z "$curl_cv_save_LIBS"; then + LIBS="$curl_cv_gclk_LIBS" + else + LIBS="$curl_cv_gclk_LIBS $curl_cv_save_LIBS" + fi + AC_MSG_RESULT([$curl_cv_gclk_LIBS]) + curl_func_clock_gettime="yes" + ;; + esac + # + dnl only do runtime verification when not cross-compiling + if test "x$cross_compiling" != "xyes" && + test "$curl_func_clock_gettime" = "yes"; then + AC_MSG_CHECKING([if monotonic clock_gettime works]) + CURL_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + #include + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + ]],[[ + struct timespec ts; + if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) + exit(0); + else + exit(1); + ]]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_WARN([HAVE_CLOCK_GETTIME_MONOTONIC will not be defined]) + curl_func_clock_gettime="no" + LIBS="$curl_cv_save_LIBS" + ]) + fi + # + case "$curl_func_clock_gettime" in + yes) + AC_DEFINE_UNQUOTED(HAVE_CLOCK_GETTIME_MONOTONIC, 1, + [Define to 1 if you have the clock_gettime function and monotonic timer.]) + ;; + esac + # + fi + # +]) + + +dnl CURL_CHECK_LIBS_CONNECT +dnl ------------------------------------------------- +dnl Verify if network connect function is already available +dnl using current libraries or if another one is required. + +AC_DEFUN([CURL_CHECK_LIBS_CONNECT], [ + AC_REQUIRE([CURL_INCLUDES_WINSOCK2])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_MSG_CHECKING([for connect in libraries]) + tst_connect_save_LIBS="$LIBS" + tst_connect_need_LIBS="unknown" + for tst_lib in '' '-lsocket' ; do + if test "$tst_connect_need_LIBS" = "unknown"; then + LIBS="$tst_lib $tst_connect_save_LIBS" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + $curl_includes_winsock2 + $curl_includes_bsdsocket + #if !defined(_WIN32) && !defined(HAVE_PROTO_BSDSOCKET_H) + int connect(int, void*, int); + #endif + ]],[[ + if(0 != connect(0, 0, 0)) + return 1; + ]]) + ],[ + tst_connect_need_LIBS="$tst_lib" + ]) + fi + done + LIBS="$tst_connect_save_LIBS" + # + case X-"$tst_connect_need_LIBS" in + X-unknown) + AC_MSG_RESULT([cannot find connect]) + AC_MSG_ERROR([cannot find connect function in libraries.]) + ;; + X-) + AC_MSG_RESULT([yes]) + ;; + *) + AC_MSG_RESULT([$tst_connect_need_LIBS]) + LIBS="$tst_connect_need_LIBS $tst_connect_save_LIBS" + ;; + esac +]) + + +dnl CURL_CHECK_FUNC_SELECT +dnl ------------------------------------------------- +dnl Test if the socket select() function is available. + +AC_DEFUN([CURL_CHECK_FUNC_SELECT], [ + AC_REQUIRE([CURL_CHECK_STRUCT_TIMEVAL])dnl + AC_REQUIRE([CURL_INCLUDES_BSDSOCKET])dnl + AC_CHECK_HEADERS(sys/select.h sys/socket.h) + # + AC_MSG_CHECKING([for select]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #endif + #ifdef HAVE_SYS_TYPES_H + #include + #endif + #ifdef HAVE_SYS_TIME_H + #include + #endif + #include + #ifndef _WIN32 + #ifdef HAVE_SYS_SELECT_H + #include + #elif defined(HAVE_UNISTD_H) + #include + #endif + #ifdef HAVE_SYS_SOCKET_H + #include + #endif + $curl_includes_bsdsocket + #endif + ]],[[ + select(0, 0, 0, 0, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + curl_cv_select="yes" + ],[ + AC_MSG_RESULT([no]) + curl_cv_select="no" + ]) + # + if test "$curl_cv_select" = "yes"; then + AC_DEFINE_UNQUOTED(HAVE_SELECT, 1, + [Define to 1 if you have the select function.]) + curl_cv_func_select="yes" + fi +]) + + +dnl CURL_VERIFY_RUNTIMELIBS +dnl ------------------------------------------------- +dnl Verify that the shared libs found so far can be used when running +dnl programs, since otherwise the situation will create odd configure errors +dnl that are misleading people. +dnl +dnl Make sure this test is run BEFORE the first test in the script that +dnl runs anything, which at the time of this writing is the AC_CHECK_SIZEOF +dnl macro. It must also run AFTER all lib-checking macros are complete. + +AC_DEFUN([CURL_VERIFY_RUNTIMELIBS], [ + + dnl this test is of course not sensible if we are cross-compiling! + if test "x$cross_compiling" != xyes; then + + dnl just run a program to verify that the libs checked for previous to this + dnl point also is available run-time! + AC_MSG_CHECKING([run-time libs availability]) + CURL_RUN_IFELSE([ + int main() + { + return 0; + } + ], + AC_MSG_RESULT([fine]), + AC_MSG_RESULT([failed]) + AC_MSG_ERROR([one or more libs available at link-time are not available run-time. Libs used at link-time: $LIBS]) + ) + + dnl if this test fails, configure has already stopped + fi +]) + + +dnl CURL_CHECK_CA_BUNDLE +dnl ------------------------------------------------- +dnl Check if a default ca-bundle should be used +dnl +dnl regarding the paths this will scan: +dnl /etc/ssl/certs/ca-certificates.crt Debian systems +dnl /etc/pki/tls/certs/ca-bundle.crt Redhat and Mandriva +dnl /usr/share/ssl/certs/ca-bundle.crt old(er) Redhat +dnl /usr/local/share/certs/ca-root-nss.crt MidnightBSD +dnl /etc/ssl/cert.pem OpenBSD, MidnightBSD (symlink) +dnl /etc/ssl/certs (CA path) SUSE, FreeBSD + +AC_DEFUN([CURL_CHECK_CA_BUNDLE], [ + + AC_MSG_CHECKING([default CA cert bundle/path]) + + AC_ARG_WITH(ca-bundle, +AS_HELP_STRING([--with-ca-bundle=FILE], + [Absolute path to a file containing CA certificates (example: /etc/ca-bundle.crt)]) +AS_HELP_STRING([--without-ca-bundle], [Don't use a default CA bundle]), + [ + want_ca="$withval" + if test "x$want_ca" = "xyes"; then + AC_MSG_ERROR([--with-ca-bundle=FILE requires a path to the CA bundle]) + fi + ], + [ want_ca="unset" ]) + AC_ARG_WITH(ca-path, +AS_HELP_STRING([--with-ca-path=DIRECTORY], + [Absolute path to a directory containing CA certificates stored individually, with \ +their filenames in a hash format. This option can be used with the OpenSSL, \ +GnuTLS, mbedTLS and wolfSSL backends. Refer to OpenSSL c_rehash for details. \ +(example: /etc/certificates)]) +AS_HELP_STRING([--without-ca-path], [Don't use a default CA path]), + [ + want_capath="$withval" + if test "x$want_capath" = "xyes"; then + AC_MSG_ERROR([--with-ca-path=DIRECTORY requires a path to the CA path directory]) + fi + ], + [ want_capath="unset"]) + + ca_warning=" (warning: certs not found)" + capath_warning=" (warning: certs not found)" + check_capath="" + + if test "x$want_ca" != "xno" -a "x$want_ca" != "xunset" -a \ + "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + dnl both given + ca="$want_ca" + capath="$want_capath" + elif test "x$want_ca" != "xno" -a "x$want_ca" != "xunset"; then + dnl --with-ca-bundle given + ca="$want_ca" + capath="no" + elif test "x$want_capath" != "xno" -a "x$want_capath" != "xunset"; then + dnl --with-ca-path given + capath="$want_capath" + ca="no" + else + dnl First try auto-detecting a CA bundle, then a CA path. + dnl Both auto-detections can be skipped by --without-ca-* + ca="no" + capath="no" + if test "x$cross_compiling" != "xyes" -a \ + "x$curl_cv_native_windows" != "xyes"; then + dnl NOT cross-compiling and... + dnl neither of the --with-ca-* options are provided + if test "x$want_ca" = "xunset"; then + dnl the path we previously would have installed the curl CA bundle + dnl to, and thus we now check for an already existing cert in that + dnl place in case we find no other + if test "x$prefix" != xNONE; then + cac="${prefix}/share/curl/curl-ca-bundle.crt" + else + cac="$ac_default_prefix/share/curl/curl-ca-bundle.crt" + fi + + for a in /etc/ssl/certs/ca-certificates.crt \ + /etc/pki/tls/certs/ca-bundle.crt \ + /usr/share/ssl/certs/ca-bundle.crt \ + /usr/local/share/certs/ca-root-nss.crt \ + /etc/ssl/cert.pem \ + "$cac"; do + if test -f "$a"; then + ca="$a" + break + fi + done + fi + AC_MSG_NOTICE([want $want_capath ca $ca]) + if test "x$want_capath" = "xunset"; then + check_capath="/etc/ssl/certs" + fi + else + dnl no option given and cross-compiling + AC_MSG_WARN([skipped the ca-cert path detection when cross-compiling]) + fi + fi + + if test "x$ca" = "xno" || test -f "$ca"; then + ca_warning="" + fi + + if test "x$capath" != "xno"; then + check_capath="$capath" + fi + + if test ! -z "$check_capath"; then + for a in "$check_capath"; do + if test -d "$a" && ls "$a"/[[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]].0 >/dev/null 2>/dev/null; then + if test "x$capath" = "xno"; then + capath="$a" + fi + capath_warning="" + break + fi + done + fi + + if test "x$capath" = "xno"; then + capath_warning="" + fi + + if test "x$ca" != "xno"; then + CURL_CA_BUNDLE="$ca" + AC_DEFINE_UNQUOTED(CURL_CA_BUNDLE, "$ca", [Location of default ca bundle]) + AC_SUBST(CURL_CA_BUNDLE) + AC_MSG_RESULT([$ca]) + fi + if test "x$capath" != "xno"; then + CURL_CA_PATH="\"$capath\"" + AC_DEFINE_UNQUOTED(CURL_CA_PATH, "$capath", [Location of default ca path]) + AC_MSG_RESULT([$capath (capath)]) + fi + if test "x$ca" = "xno" && test "x$capath" = "xno"; then + AC_MSG_RESULT([no]) + fi + + AC_MSG_CHECKING([whether to use built-in CA store of SSL library]) + AC_ARG_WITH(ca-fallback, +AS_HELP_STRING([--with-ca-fallback], [Use the built-in CA store of the SSL library]) +AS_HELP_STRING([--without-ca-fallback], [Don't use the built-in CA store of the SSL library]), + [ + if test "x$with_ca_fallback" != "xyes" -a "x$with_ca_fallback" != "xno"; then + AC_MSG_ERROR([--with-ca-fallback only allows yes or no as parameter]) + fi + ], + [ with_ca_fallback="no"]) + AC_MSG_RESULT([$with_ca_fallback]) + if test "x$with_ca_fallback" = "xyes"; then + if test "x$OPENSSL_ENABLED" != "x1" -a "x$GNUTLS_ENABLED" != "x1"; then + AC_MSG_ERROR([--with-ca-fallback only works with OpenSSL or GnuTLS]) + fi + AC_DEFINE_UNQUOTED(CURL_CA_FALLBACK, 1, [define "1" to use built-in CA store of SSL library]) + fi +]) + + +dnl CURL_CHECK_CA_EMBED +dnl ------------------------------------------------- +dnl Check if a ca-bundle should be embedded + +AC_DEFUN([CURL_CHECK_CA_EMBED], [ + + AC_MSG_CHECKING([CA cert bundle path to embed in the curl tool]) + + AC_ARG_WITH(ca-embed, +AS_HELP_STRING([--with-ca-embed=FILE], + [Absolute path to a file containing CA certificates to embed in the curl tool (example: /etc/ca-bundle.crt)]) +AS_HELP_STRING([--without-ca-embed], [Don't embed a default CA bundle in the curl tool]), + [ + want_ca_embed="$withval" + if test "x$want_ca_embed" = "xyes"; then + AC_MSG_ERROR([--with-ca-embed=FILE requires a path to the CA bundle]) + fi + ], + [ want_ca_embed="unset" ]) + + CURL_CA_EMBED='' + if test "x$want_ca_embed" != "xno" -a "x$want_ca_embed" != "xunset" -a -f "$want_ca_embed"; then + CURL_CA_EMBED="$want_ca_embed" + AC_SUBST(CURL_CA_EMBED) + AC_MSG_RESULT([$want_ca_embed]) + else + AC_MSG_RESULT([no]) + fi +]) + +dnl CURL_CHECK_WIN32_LARGEFILE +dnl ------------------------------------------------- +dnl Check if curl's Win32 large file will be used + +AC_DEFUN([CURL_CHECK_WIN32_LARGEFILE], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_MSG_CHECKING([whether build target supports Win32 file API]) + curl_win32_file_api="no" + if test "$curl_cv_native_windows" = "yes"; then + if test x"$enable_largefile" != "xno"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + #if !defined(_WIN32_WCE) && (defined(__MINGW32__) || defined(_MSC_VER)) + int dummy=1; + #else + #error Win32 large file API not supported. + #endif + ]]) + ],[ + curl_win32_file_api="win32_large_files" + ]) + fi + if test "$curl_win32_file_api" = "no"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + #if defined(_WIN32_WCE) || defined(__MINGW32__) || defined(_MSC_VER) + int dummy=1; + #else + #error Win32 small file API not supported. + #endif + ]]) + ],[ + curl_win32_file_api="win32_small_files" + ]) + fi + fi + case "$curl_win32_file_api" in + win32_large_files) + AC_MSG_RESULT([yes (large file enabled)]) + AC_DEFINE_UNQUOTED(USE_WIN32_LARGE_FILES, 1, + [Define to 1 if you are building a Windows target with large file support.]) + AC_SUBST(USE_WIN32_LARGE_FILES, [1]) + ;; + win32_small_files) + AC_MSG_RESULT([yes (large file disabled)]) + AC_DEFINE_UNQUOTED(USE_WIN32_SMALL_FILES, 1, + [Define to 1 if you are building a Windows target without large file support.]) + AC_SUBST(USE_WIN32_SMALL_FILES, [1]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +]) + +dnl CURL_CHECK_WIN32_CRYPTO +dnl ------------------------------------------------- +dnl Check if curl's Win32 crypto lib can be used + +AC_DEFUN([CURL_CHECK_WIN32_CRYPTO], [ + AC_REQUIRE([CURL_CHECK_NATIVE_WINDOWS])dnl + AC_MSG_CHECKING([whether build target supports Win32 crypto API]) + curl_win32_crypto_api="no" + if test "$curl_cv_native_windows" = "yes"; then + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #undef inline + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include + ]],[[ + HCRYPTPROV hCryptProv; + if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + CryptReleaseContext(hCryptProv, 0); + } + ]]) + ],[ + curl_win32_crypto_api="yes" + ]) + fi + case "$curl_win32_crypto_api" in + yes) + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(USE_WIN32_CRYPTO, 1, + [Define to 1 if you are building a Windows target with crypto API support.]) + AC_SUBST(USE_WIN32_CRYPTO, [1]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +]) + +dnl CURL_EXPORT_PCDIR ($pcdir) +dnl ------------------------ +dnl if $pcdir is not empty, set PKG_CONFIG_LIBDIR to $pcdir and export +dnl +dnl we need this macro since pkg-config distinguishes among empty and unset +dnl variable while checking PKG_CONFIG_LIBDIR +dnl + +AC_DEFUN([CURL_EXPORT_PCDIR], [ + if test -n "$1"; then + PKG_CONFIG_LIBDIR="$1" + export PKG_CONFIG_LIBDIR + fi +]) + +dnl CURL_CHECK_PKGCONFIG ($module, [$pcdir]) +dnl ------------------------ +dnl search for the pkg-config tool. Set the PKGCONFIG variable to hold the +dnl path to it, or 'no' if not found/present. +dnl +dnl If pkg-config is present, check that it has info about the $module or +dnl return "no" anyway! +dnl +dnl Optionally PKG_CONFIG_LIBDIR may be given as $pcdir. +dnl + +AC_DEFUN([CURL_CHECK_PKGCONFIG], [ + if test -n "$PKG_CONFIG"; then + PKGCONFIG="$PKG_CONFIG" + else + AC_PATH_TOOL([PKGCONFIG], [pkg-config], [no], + [$PATH:/usr/bin:/usr/local/bin]) + fi + + if test "x$PKGCONFIG" != "xno"; then + AC_MSG_CHECKING([for $1 options with pkg-config]) + dnl ask pkg-config about $1 + itexists=`CURL_EXPORT_PCDIR([$2]) dnl + $PKGCONFIG --exists $1 >/dev/null 2>&1 && echo 1` + + if test -z "$itexists"; then + dnl pkg-config does not have info about the given module! set the + dnl variable to 'no' + PKGCONFIG="no" + AC_MSG_RESULT([no]) + else + AC_MSG_RESULT([found]) + fi + fi +]) + + +dnl CURL_PREPARE_CONFIGUREHELP_PM +dnl ------------------------------------------------- +dnl Prepare test harness configurehelp.pm module, defining and +dnl initializing some perl variables with values which are known +dnl when the configure script runs. For portability reasons, test +dnl harness needs information on how to run the C preprocessor. + +AC_DEFUN([CURL_PREPARE_CONFIGUREHELP_PM], [ + AC_REQUIRE([AC_PROG_CPP])dnl + tmp_cpp=`eval echo "$ac_cpp" 2>/dev/null` + if test -z "$tmp_cpp"; then + tmp_cpp='cpp' + fi + AC_SUBST(CURL_CPP, $tmp_cpp) +]) + + +dnl CURL_PREPARE_BUILDINFO +dnl ------------------------------------------------- +dnl Save build info for test runner to pick up and log + +AC_DEFUN([CURL_PREPARE_BUILDINFO], [ + curl_pflags="" + case $host in + *-apple-*) curl_pflags="${curl_pflags} APPLE";; + esac + if test "$curl_cv_native_windows" = 'yes'; then + curl_pflags="${curl_pflags} WIN32" + else + case $host in + *-*-*bsd*|*-*-aix*|*-*-hpux*|*-*-interix*|*-*-irix*|*-*-linux*|*-*-solaris*|*-*-sunos*|*-apple-*|*-*-cygwin*|*-*-msys*) + curl_pflags="${curl_pflags} UNIX";; + esac + case $host in + *-*-*bsd*) + curl_pflags="${curl_pflags} BSD";; + esac + fi + if test "$curl_cv_cygwin" = 'yes'; then + curl_pflags="${curl_pflags} CYGWIN" + fi + case $host_os in + msys*) curl_pflags="${curl_pflags} MSYS";; + esac + if test "x$compiler_id" = 'xGNU_C'; then + curl_pflags="${curl_pflags} GCC" + fi + case $host_os in + mingw*) curl_pflags="${curl_pflags} MINGW";; + esac + if test "x$cross_compiling" = 'xyes'; then + curl_pflags="${curl_pflags} CROSS" + fi + squeeze curl_pflags + curl_buildinfo=" +buildinfo.configure.tool: configure +buildinfo.configure.args: $ac_configure_args +buildinfo.host: $build +buildinfo.host.cpu: $build_cpu +buildinfo.host.os: $build_os +buildinfo.target: $host +buildinfo.target.cpu: $host_cpu +buildinfo.target.os: $host_os +buildinfo.target.flags: $curl_pflags +buildinfo.compiler: $compiler_id +buildinfo.compiler.version: $compiler_ver +buildinfo.sysroot: $lt_sysroot" +]) + + +dnl CURL_CPP_P +dnl +dnl Check if $cpp -P should be used for extract define values due to gcc 5 +dnl splitting up strings and defines between line outputs. gcc by default +dnl (without -P) will show TEST EINVAL TEST as +dnl +dnl # 13 "conftest.c" +dnl TEST +dnl # 13 "conftest.c" 3 4 +dnl 22 +dnl # 13 "conftest.c" +dnl TEST + +AC_DEFUN([CURL_CPP_P], [ + AC_MSG_CHECKING([if cpp -P is needed]) + AC_EGREP_CPP([TEST.*TEST], [ + #include +TEST EINVAL TEST + ], [cpp=no], [cpp=yes]) + AC_MSG_RESULT([$cpp]) + + dnl we need cpp -P so check if it works then + if test "x$cpp" = "xyes"; then + AC_MSG_CHECKING([if cpp -P works]) + OLDCPPFLAGS=$CPPFLAGS + CPPFLAGS="$CPPFLAGS -P" + AC_EGREP_CPP([TEST.*TEST], [ + #include +TEST EINVAL TEST + ], [cpp_p=yes], [cpp_p=no]) + AC_MSG_RESULT([$cpp_p]) + + if test "x$cpp_p" = "xno"; then + AC_MSG_WARN([failed to figure out cpp -P alternative]) + # without -P + CPPPFLAG="" + else + # with -P + CPPPFLAG="-P" + fi + dnl restore CPPFLAGS + CPPFLAGS=$OLDCPPFLAGS + else + # without -P + CPPPFLAG="" + fi +]) + + +dnl CURL_DARWIN_CFLAGS +dnl +dnl Set -Werror=partial-availability to detect possible breaking code +dnl with very low deployment targets. +dnl + +AC_DEFUN([CURL_DARWIN_CFLAGS], [ + + tst_cflags="no" + case $host in + *-apple-*) + tst_cflags="yes" + ;; + esac + + AC_MSG_CHECKING([for good-to-use Darwin CFLAGS]) + AC_MSG_RESULT([$tst_cflags]); + + if test "$tst_cflags" = "yes"; then + old_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror=partial-availability" + AC_MSG_CHECKING([whether $CC accepts -Werror=partial-availability]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM()], + [AC_MSG_RESULT([yes])], + [AC_MSG_RESULT([no]) + CFLAGS=$old_CFLAGS]) + fi + +]) + + +dnl CURL_SUPPORTS_BUILTIN_AVAILABLE +dnl +dnl Check to see if the compiler supports __builtin_available. This built-in +dnl compiler function first appeared in Apple LLVM 9.0.0. It's so new that, at +dnl the time this macro was written, the function was not yet documented. Its +dnl purpose is to return true if the code is running under a certain OS version +dnl or later. + +AC_DEFUN([CURL_SUPPORTS_BUILTIN_AVAILABLE], [ + AC_MSG_CHECKING([to see if the compiler supports __builtin_available()]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + if(__builtin_available(macOS 10.12, iOS 5.0, *)) {} + ]]) + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE_UNQUOTED(HAVE_BUILTIN_AVAILABLE, 1, + [Define to 1 if you have the __builtin_available function.]) + ],[ + AC_MSG_RESULT([no]) + ]) +]) diff --git a/local-test-curl-delta-01/afc-curl/appveyor.sh b/local-test-curl-delta-01/afc-curl/appveyor.sh new file mode 100644 index 0000000000000000000000000000000000000000..46501437dcfba4897d024d0b63043a0bce8b5d9c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/appveyor.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# shellcheck disable=SC3040,SC2039 +set -eux; [ -n "${BASH:-}${ZSH_NAME:-}" ] && set -o pipefail + +# build + +if [ "${APPVEYOR_BUILD_WORKER_IMAGE}" = 'Visual Studio 2022' ]; then + openssl_root_win='C:/OpenSSL-v33-Win64' +else + openssl_root_win='C:/OpenSSL-v111-Win64' +fi +openssl_root="$(cygpath "${openssl_root_win}")" + +if [ "${BUILD_SYSTEM}" = 'CMake' ]; then + options='' + [[ "${TARGET:-}" = *'ARM64'* ]] && SKIP_RUN='ARM64 architecture' + [ -n "${TOOLSET:-}" ] && options+=" -T ${TOOLSET}" + [ "${OPENSSL}" = 'ON' ] && options+=" -DOPENSSL_ROOT_DIR=${openssl_root_win}" + [ -n "${CURLDEBUG:-}" ] && options+=" -DENABLE_CURLDEBUG=${CURLDEBUG}" + [ "${PRJ_CFG}" = 'Debug' ] && options+=' -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG=' + [ "${PRJ_CFG}" = 'Release' ] && options+=' -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE=' + [[ "${PRJ_GEN}" = *'Visual Studio'* ]] && options+=' -DCMAKE_VS_GLOBALS=TrackFileAccess=false' + if [ "${PRJ_GEN}" = 'Visual Studio 9 2008' ]; then + [ "${DEBUG}" = 'ON' ] && [ "${SHARED}" = 'ON' ] && SKIP_RUN='Crash on startup in ENABLE_DEBUG=ON shared builds' + # Fails to run without this due to missing MSVCR90.dll / MSVCR90D.dll + options+=' -DCURL_STATIC_CRT=ON' + fi + # shellcheck disable=SC2086 + cmake -B _bld "-G${PRJ_GEN}" ${TARGET:-} ${options} \ + "-DCURL_USE_OPENSSL=${OPENSSL}" \ + "-DCURL_USE_SCHANNEL=${SCHANNEL}" \ + "-DHTTP_ONLY=${HTTP_ONLY}" \ + "-DBUILD_SHARED_LIBS=${SHARED}" \ + "-DCMAKE_UNITY_BUILD=${UNITY}" \ + '-DCURL_TEST_BUNDLES=ON' \ + '-DCURL_WERROR=ON' \ + "-DENABLE_DEBUG=${DEBUG}" \ + "-DENABLE_UNICODE=${ENABLE_UNICODE}" \ + '-DCMAKE_INSTALL_PREFIX=C:/curl' \ + "-DCMAKE_BUILD_TYPE=${PRJ_CFG}" \ + '-DCURL_USE_LIBPSL=OFF' + if false; then + cat _bld/CMakeFiles/CMakeConfigureLog.yaml 2>/dev/null || true + fi + echo 'curl_config.h'; grep -F '#define' _bld/lib/curl_config.h | sort || true + # shellcheck disable=SC2086 + if ! cmake --build _bld --config "${PRJ_CFG}" --parallel 2 -- ${BUILD_OPT:-}; then + if [ "${PRJ_GEN}" = 'Visual Studio 9 2008' ]; then + find . -name BuildLog.htm -exec dos2unix '{}' + + find . -name BuildLog.htm -exec cat '{}' + + fi + false + fi + if [ "${SHARED}" = 'ON' ]; then + PATH="$PWD/_bld/lib:$PATH" + fi + if [ "${OPENSSL}" = 'ON' ]; then + PATH="$PWD/_bld/lib:${openssl_root}:$PATH" + fi + curl='_bld/src/curl.exe' +elif [ "${BUILD_SYSTEM}" = 'VisualStudioSolution' ]; then + ( + cd projects + ./generate.bat "${VC_VERSION}" + msbuild.exe -maxcpucount "-property:Configuration=${PRJ_CFG}" "Windows/${VC_VERSION}/curl-all.sln" + ) + curl="build/Win32/${VC_VERSION}/${PRJ_CFG}/curld.exe" +elif [ "${BUILD_SYSTEM}" = 'winbuild_vs2015' ]; then + ./buildconf.bat + ( + cd winbuild + cat << EOF > _make.bat + call "C:/Program Files/Microsoft SDKs/Windows/v7.1/Bin/SetEnv.cmd" /x64 + call "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/vcvarsall.bat" x86_amd64 + nmake -f Makefile.vc mode=dll VC=14 "SSL_PATH=${openssl_root_win}" WITH_SSL=dll MACHINE=x64 DEBUG=${DEBUG} ENABLE_UNICODE=${ENABLE_UNICODE} +EOF + ./_make.bat + rm _make.bat + ) + curl="builds/libcurl-vc14-x64-${PATHPART}-dll-ssl-dll-ipv6-sspi/bin/curl.exe" +elif [ "${BUILD_SYSTEM}" = 'winbuild_vs2017' ]; then + ./buildconf.bat + ( + cd winbuild + cat << EOF > _make.bat + call "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build/vcvars64.bat" + nmake -f Makefile.vc mode=dll VC=14.10 "SSL_PATH=${openssl_root_win}" WITH_SSL=dll MACHINE=x64 DEBUG=${DEBUG} ENABLE_UNICODE=${ENABLE_UNICODE} +EOF + ./_make.bat + rm _make.bat + ) + curl="builds/libcurl-vc14.10-x64-${PATHPART}-dll-ssl-dll-ipv6-sspi/bin/curl.exe" +fi + +find . -name '*.exe' -o -name '*.dll' +if [ -z "${SKIP_RUN:-}" ]; then + "${curl}" --disable --version +else + echo "Skip running curl.exe. Reason: ${SKIP_RUN}" +fi + +# build tests + +if [[ "${TFLAGS}" != 'skipall' ]] && \ + [ "${BUILD_SYSTEM}" = 'CMake' ]; then + cmake --build _bld --config "${PRJ_CFG}" --parallel 2 --target testdeps +fi + +# run tests + +if [[ "${TFLAGS}" != 'skipall' ]] && \ + [[ "${TFLAGS}" != 'skiprun' ]]; then + if [ -x "$(cygpath "${SYSTEMROOT}/System32/curl.exe")" ]; then + TFLAGS+=" -ac $(cygpath "${SYSTEMROOT}/System32/curl.exe")" + elif [ -x "$(cygpath 'C:/msys64/usr/bin/curl.exe')" ]; then + TFLAGS+=" -ac $(cygpath 'C:/msys64/usr/bin/curl.exe')" + fi + TFLAGS+=' -j0' + if [ "${BUILD_SYSTEM}" = 'CMake' ]; then + cmake --build _bld --config "${PRJ_CFG}" --target test-ci + else + ( + TFLAGS="-a -p !flaky -r -rm ${TFLAGS}" + cd _bld/tests + ./runtests.pl + ) + fi +fi + +# build examples + +if [[ "${EXAMPLES}" = 'ON' ]] && \ + [ "${BUILD_SYSTEM}" = 'CMake' ]; then + cmake --build _bld --config "${PRJ_CFG}" --parallel 2 --target curl-examples +fi diff --git a/local-test-curl-delta-01/afc-curl/appveyor.yml b/local-test-curl-delta-01/afc-curl/appveyor.yml new file mode 100644 index 0000000000000000000000000000000000000000..8209cd119bdaf1308f9be6ccb5107e7ec5210b0a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/appveyor.yml @@ -0,0 +1,222 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# https://ci.appveyor.com/project/curlorg/curl/history +# AppVeyor configuration: +# https://www.appveyor.com/docs/appveyor-yml/ +# AppVeyor worker images: +# https://www.appveyor.com/docs/windows-images-software/ + +version: 7.50.0.{build} + +environment: + UNITY: 'ON' + OPENSSL: 'OFF' + DEBUG: 'ON' + SHARED: 'OFF' + HTTP_ONLY: 'OFF' + TFLAGS: 'skiprun' + EXAMPLES: 'OFF' + + matrix: + + # generated CMake-based Visual Studio builds + + - job_name: 'CMake, VS2008, Release, x86, Schannel, Shared, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 9 2008' + PRJ_CFG: Release + DEBUG: 'OFF' + SCHANNEL: 'ON' + ENABLE_UNICODE: 'OFF' + SHARED: 'ON' + - job_name: 'CMake, VS2008, Debug, x86, Schannel, Shared, Build-tests & examples' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 9 2008' + PRJ_CFG: Debug + SCHANNEL: 'ON' + ENABLE_UNICODE: 'OFF' + SHARED: 'ON' + EXAMPLES: 'ON' + - job_name: 'CMake, VS2022, Release, x64, OpenSSL 3.3, Shared, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Release + OPENSSL: 'ON' + SCHANNEL: 'OFF' + ENABLE_UNICODE: 'OFF' + SHARED: 'ON' + - job_name: 'CMake, VS2022, Release, arm64, Schannel, Static, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A ARM64' + PRJ_CFG: Release + SCHANNEL: 'ON' + ENABLE_UNICODE: 'OFF' + DEBUG: 'OFF' + CURLDEBUG: 'ON' + - job_name: 'CMake, VS2010, Debug, x64, Schannel, Static, Build-tests & examples' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 10 2010 Win64' + PRJ_CFG: Debug + SCHANNEL: 'ON' + ENABLE_UNICODE: 'OFF' + EXAMPLES: 'ON' + - job_name: 'CMake, VS2022, Debug, x64, Schannel, Static, Unicode, Build-tests & examples, clang-cl' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Debug + SCHANNEL: 'ON' + ENABLE_UNICODE: 'ON' + EXAMPLES: 'ON' + TOOLSET: 'ClangCl' + - job_name: 'CMake, VS2022, Debug, x64, Schannel, Static, Unicode, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Debug + SCHANNEL: 'ON' + ENABLE_UNICODE: 'ON' + - job_name: 'CMake, VS2022, Release, x64, Schannel, Shared, Unicode, DEBUGBUILD, no-CURLDEBUG, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Release + SCHANNEL: 'ON' + ENABLE_UNICODE: 'ON' + SHARED: 'ON' + CURLDEBUG: 'OFF' + - job_name: 'CMake, VS2022, Debug, x64, no SSL, Static, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Debug + SCHANNEL: 'OFF' + ENABLE_UNICODE: 'OFF' + - job_name: 'CMake, VS2022, Debug, x64, no SSL, Static, HTTP only, Build-tests' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022' + BUILD_SYSTEM: CMake + PRJ_GEN: 'Visual Studio 17 2022' + TARGET: '-A x64' + PRJ_CFG: Debug + SCHANNEL: 'OFF' + ENABLE_UNICODE: 'OFF' + HTTP_ONLY: 'ON' + + # winbuild-based builds + + - job_name: 'winbuild, VS2015, Debug, x64, OpenSSL 1.1.1, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: winbuild_vs2015 + DEBUG: 'yes' + PATHPART: debug + ENABLE_UNICODE: 'no' + - job_name: 'winbuild, VS2015, Release, x64, OpenSSL 1.1.1, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: winbuild_vs2015 + DEBUG: 'no' + PATHPART: release + ENABLE_UNICODE: 'no' + - job_name: 'winbuild, VS2017, Debug, x64, OpenSSL 1.1.1, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2017' + BUILD_SYSTEM: winbuild_vs2017 + DEBUG: 'yes' + PATHPART: debug + ENABLE_UNICODE: 'no' + - job_name: 'winbuild, VS2017, Release, x64, OpenSSL 1.1.1, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2017' + BUILD_SYSTEM: winbuild_vs2017 + DEBUG: 'no' + PATHPART: release + ENABLE_UNICODE: 'no' + - job_name: 'winbuild, VS2015, Debug, x64, OpenSSL 1.1.1, Unicode, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: winbuild_vs2015 + DEBUG: 'yes' + PATHPART: debug + ENABLE_UNICODE: 'yes' + - job_name: 'winbuild, VS2015, Release, x64, OpenSSL 1.1.1, Unicode, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: winbuild_vs2015 + DEBUG: 'no' + PATHPART: release + ENABLE_UNICODE: 'yes' + - job_name: 'winbuild, VS2017, Debug, x64, OpenSSL 1.1.1, Unicode, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2017' + BUILD_SYSTEM: winbuild_vs2017 + DEBUG: 'yes' + PATHPART: debug + ENABLE_UNICODE: 'yes' + - job_name: 'winbuild, VS2017, Release, x64, OpenSSL 1.1.1, Unicode, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2017' + BUILD_SYSTEM: winbuild_vs2017 + DEBUG: 'no' + PATHPART: release + ENABLE_UNICODE: 'yes' + + # generated VisualStudioSolution-based builds + + - job_name: 'VisualStudioSolution, VS2013, Debug, x86, Schannel, Build-only' + APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2015' + BUILD_SYSTEM: VisualStudioSolution + PRJ_CFG: 'DLL Debug - DLL Windows SSPI - DLL WinIDN' + VC_VERSION: VC12 + +install: + - ps: $env:PATH = "C:/msys64/usr/bin;$env:PATH" + +build_script: + - cmd: sh -c ./appveyor.sh + +clone_depth: 10 + +# select branches to avoid testing feature branches twice (as branch and as pull request) +branches: + only: + - master + - /\/ci$/ + +skip_commits: + files: + - '.circleci/*' + - '.github/**/*' + - 'packages/**/*' + - 'plan9/**/*' + +#artifacts: +# - path: '**/curl.exe' +# name: curl +# - path: '**/*curl*.dll' +# name: libcurl dll diff --git a/local-test-curl-delta-01/afc-curl/buildconf b/local-test-curl-delta-01/afc-curl/buildconf new file mode 100644 index 0000000000000000000000000000000000000000..ee6a2800beafcb7e42e16c3fa719a1c95683576f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/buildconf @@ -0,0 +1,8 @@ +#!/bin/sh +# +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +echo "*** Do not use buildconf. Instead, just use: autoreconf -fi" >&2 +exec ${AUTORECONF:-autoreconf} -fi "${@}" diff --git a/local-test-curl-delta-01/afc-curl/buildconf.bat b/local-test-curl-delta-01/afc-curl/buildconf.bat new file mode 100644 index 0000000000000000000000000000000000000000..bef4874799a30b064136294012d1476da39cd313 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/buildconf.bat @@ -0,0 +1,265 @@ +@echo off +rem *************************************************************************** +rem * _ _ ____ _ +rem * Project ___| | | | _ \| | +rem * / __| | | | |_) | | +rem * | (__| |_| | _ <| |___ +rem * \___|\___/|_| \_\_____| +rem * +rem * Copyright (C) Daniel Stenberg, , et al. +rem * +rem * This software is licensed as described in the file COPYING, which +rem * you should have received as part of this distribution. The terms +rem * are also available at https://curl.se/docs/copyright.html. +rem * +rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell +rem * copies of the Software, and permit persons to whom the Software is +rem * furnished to do so, under the terms of the COPYING file. +rem * +rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +rem * KIND, either express or implied. +rem * +rem * SPDX-License-Identifier: curl +rem * +rem *************************************************************************** + +rem NOTES +rem +rem This batch file must be used to set up a git tree to build on systems where +rem there is no autotools support (i.e. DOS and Windows). +rem + +:begin + rem Set our variables + if "%OS%" == "Windows_NT" setlocal + set MODE=GENERATE + + rem Switch to this batch file's directory + cd /d "%~0\.." 1>NUL 2>&1 + + rem Check we are running from a curl git repository + if not exist GIT-INFO.md goto norepo + +:parseArgs + if "%~1" == "" goto start + + if /i "%~1" == "-clean" ( + set MODE=CLEAN + ) else if /i "%~1" == "-?" ( + goto syntax + ) else if /i "%~1" == "-h" ( + goto syntax + ) else if /i "%~1" == "-help" ( + goto syntax + ) else ( + goto unknown + ) + + shift & goto parseArgs + +:start + if "%MODE%" == "GENERATE" ( + echo. + echo Generating prerequisite files + + call :generate + if errorlevel 3 goto nogenhugehelp + if errorlevel 2 goto nogenmakefile + if errorlevel 1 goto warning + + ) else ( + echo. + echo Removing prerequisite files + + call :clean + if errorlevel 2 goto nocleanhugehelp + if errorlevel 1 goto nocleanmakefile + ) + + goto success + +rem Main generate function. +rem +rem Returns: +rem +rem 0 - success +rem 1 - success with simplified tool_hugehelp.c +rem 2 - failed to generate Makefile +rem 3 - failed to generate tool_hugehelp.c +rem +:generate + if "%OS%" == "Windows_NT" setlocal + set BASIC_HUGEHELP=0 + + rem Create Makefile + echo * %CD%\Makefile + if exist Makefile.dist ( + copy /Y Makefile.dist Makefile 1>NUL 2>&1 + if errorlevel 1 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 2 + ) + ) + + rem Create tool_hugehelp.c + echo * %CD%\src\tool_hugehelp.c + call :genHugeHelp + if errorlevel 2 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 3 + ) + if errorlevel 1 ( + set BASIC_HUGEHELP=1 + ) + cmd /c exit 0 + + if "%BASIC_HUGEHELP%" == "1" ( + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + ) + + if "%OS%" == "Windows_NT" endlocal + exit /B 0 + +rem Main clean function. +rem +rem Returns: +rem +rem 0 - success +rem 1 - failed to clean Makefile +rem 2 - failed to clean tool_hugehelp.c +rem +:clean + rem Remove Makefile + echo * %CD%\Makefile + if exist Makefile ( + del Makefile 2>NUL + if exist Makefile ( + exit /B 1 + ) + ) + + rem Remove tool_hugehelp.c + echo * %CD%\src\tool_hugehelp.c + if exist src\tool_hugehelp.c ( + del src\tool_hugehelp.c 2>NUL + if exist src\tool_hugehelp.c ( + exit /B 2 + ) + ) + + exit /B + +rem Function to generate src\tool_hugehelp.c +rem +rem Returns: +rem +rem 0 - full tool_hugehelp.c generated +rem 1 - simplified tool_hugehelp.c +rem 2 - failure +rem +:genHugeHelp + if "%OS%" == "Windows_NT" setlocal + set LC_ALL=C + set BASIC=1 + + if exist src\tool_hugehelp.c.cvs ( + copy /Y src\tool_hugehelp.c.cvs src\tool_hugehelp.c 1>NUL 2>&1 + ) else ( + echo #include "tool_setup.h"> src\tool_hugehelp.c + echo #include "tool_hugehelp.h">> src\tool_hugehelp.c + echo.>> src\tool_hugehelp.c + echo void hugehelp(void^)>> src\tool_hugehelp.c + echo {>> src\tool_hugehelp.c + echo #ifdef USE_MANUAL>> src\tool_hugehelp.c + echo fputs("Built-in manual not included\n", stdout^);>> src\tool_hugehelp.c + echo #endif>> src\tool_hugehelp.c + echo }>> src\tool_hugehelp.c + ) + + findstr "/C:void hugehelp(void)" src\tool_hugehelp.c 1>NUL 2>&1 + if errorlevel 1 ( + if "%OS%" == "Windows_NT" endlocal + exit /B 2 + ) + + if "%BASIC%" == "1" ( + if "%OS%" == "Windows_NT" endlocal + exit /B 1 + ) + + if "%OS%" == "Windows_NT" endlocal + exit /B 0 + +rem Function to clean-up local variables under DOS, Windows 3.x and +rem Windows 9x as setlocal isn't available until Windows NT +rem +:dosCleanup + set MODE= + set BASIC_HUGEHELP= + set LC_ALL + set BASIC= + + exit /B + +:syntax + rem Display the help + echo. + echo Usage: buildconf [-clean] + echo. + echo -clean - Removes the files + goto error + +:unknown + echo. + echo Error: Unknown argument '%1' + goto error + +:norepo + echo. + echo Error: This batch file should only be used with a curl git repository + goto error + +:nogenmakefile + echo. + echo Error: Unable to generate Makefile + goto error + +:nogenhugehelp + echo. + echo Error: Unable to generate src\tool_hugehelp.c + goto error + +:nocleanmakefile + echo. + echo Error: Unable to clean Makefile + goto error + +:nocleanhugehelp + echo. + echo Error: Unable to clean src\tool_hugehelp.c + goto error + +:warning + echo. + echo Warning: The curl manual could not be integrated in the source. This means when + echo you build curl the manual will not be available (curl --manual^). Integration of + echo the manual is not required and a summary of the options will still be available + echo (curl --help^). To integrate the manual build with configure or cmake. + goto success + +:error + if "%OS%" == "Windows_NT" ( + endlocal + ) else ( + call :dosCleanup + ) + exit /B 1 + +:success + if "%OS%" == "Windows_NT" ( + endlocal + ) else ( + call :dosCleanup + ) + exit /B 0 diff --git a/local-test-curl-delta-01/afc-curl/configure.ac b/local-test-curl-delta-01/afc-curl/configure.ac new file mode 100644 index 0000000000000000000000000000000000000000..e3ecf00c6188a54633487d1a025ebe988e3c26c9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/configure.ac @@ -0,0 +1,5565 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** +dnl Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.59) + +dnl We don't know the version number "statically" so we use a dash here +AC_INIT([curl], [-], [a suitable curl mailing list: https://curl.se/mail/]) + +XC_OVR_ZZ50 +XC_OVR_ZZ60 +CURL_OVERRIDE_AUTOCONF + +dnl configure script copyright +AC_COPYRIGHT([Copyright (C) Daniel Stenberg, +This configure script may be copied, distributed and modified under the +terms of the curl license; see COPYING for more details]) + +AC_CONFIG_SRCDIR([lib/urldata.h]) +AC_CONFIG_HEADERS(lib/curl_config.h) +AC_CONFIG_MACRO_DIR([m4]) +AM_MAINTAINER_MODE +m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) + +CURL_CHECK_OPTION_DEBUG +AM_CONDITIONAL(DEBUGBUILD, test x$want_debug = xyes) +CURL_CHECK_OPTION_OPTIMIZE +CURL_CHECK_OPTION_WARNINGS +CURL_CHECK_OPTION_WERROR +CURL_CHECK_OPTION_CURLDEBUG +CURL_CHECK_OPTION_SYMBOL_HIDING +CURL_CHECK_OPTION_ARES +CURL_CHECK_OPTION_RT +CURL_CHECK_OPTION_HTTPSRR +CURL_CHECK_OPTION_ECH + +XC_CHECK_PATH_SEPARATOR + +# +# save the configure arguments +# +CONFIGURE_OPTIONS="\"$ac_configure_args\"" +AC_SUBST(CONFIGURE_OPTIONS) + +dnl SED is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$SED"; then + dnl allow it to be overridden + AC_PATH_PROG([SED], [sed], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$SED" || test "$SED" = "not_found"; then + AC_MSG_ERROR([sed not found in PATH. Cannot continue without sed.]) + fi +fi +AC_SUBST([SED]) + +dnl GREP is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$GREP"; then + dnl allow it to be overridden + AC_PATH_PROG([GREP], [grep], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$GREP" || test "$GREP" = "not_found"; then + AC_MSG_ERROR([grep not found in PATH. Cannot continue without grep.]) + fi +fi +AC_SUBST([GREP]) + +dnl 'grep -E' is mandatory for configure process and libtool. +dnl Set it now, allowing it to be changed later. +if test -z "$EGREP"; then + dnl allow it to be overridden + AC_MSG_CHECKING([that grep -E works]) + if echo a | ($GREP -E '(a|b)') >/dev/null 2>&1; then + EGREP="$GREP -E" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + AC_PATH_PROG([EGREP], [egrep], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + fi +fi +if test -z "$EGREP" || test "$EGREP" = "not_found"; then + AC_MSG_ERROR([grep -E is not working and egrep is not found in PATH. Cannot continue.]) +fi +AC_SUBST([EGREP]) + +dnl AR is mandatory for configure process and libtool. +dnl This is target dependent, so check it as a tool. +if test -z "$AR"; then + dnl allow it to be overridden + AC_PATH_TOOL([AR], [ar], [not_found], + [$PATH:/usr/bin:/usr/local/bin]) + if test -z "$AR" || test "$AR" = "not_found"; then + AC_MSG_ERROR([ar not found in PATH. Cannot continue without ar.]) + fi +fi +AC_SUBST([AR]) + +AC_SUBST(libext) + +dnl figure out the libcurl version +CURLVERSION=`$SED -ne 's/^#define LIBCURL_VERSION "\(.*\)".*/\1/p' ${srcdir}/include/curl/curlver.h` +XC_CHECK_PROG_CC +CURL_ATOMIC + +dnl for --enable-code-coverage +CURL_COVERAGE + +XC_AUTOMAKE +AC_MSG_CHECKING([curl version]) +AC_MSG_RESULT($CURLVERSION) + +AC_SUBST(CURLVERSION) + +dnl +dnl we extract the numerical version for curl-config only +VERSIONNUM=`$SED -ne 's/^#define LIBCURL_VERSION_NUM 0x\([0-9A-Fa-f]*\).*/\1/p' ${srcdir}/include/curl/curlver.h` +AC_SUBST(VERSIONNUM) + +dnl Solaris pkgadd support definitions +PKGADD_PKG="HAXXcurl" +PKGADD_NAME="curl - a client that groks URLs" +PKGADD_VENDOR="curl.se" +AC_SUBST(PKGADD_PKG) +AC_SUBST(PKGADD_NAME) +AC_SUBST(PKGADD_VENDOR) + +dnl +dnl initialize all the info variables + curl_ssl_msg="no (--with-{openssl,gnutls,mbedtls,wolfssl,schannel,secure-transport,amissl,bearssl,rustls} )" + curl_ssh_msg="no (--with-{libssh,libssh2})" + curl_zlib_msg="no (--with-zlib)" + curl_brotli_msg="no (--with-brotli)" + curl_zstd_msg="no (--with-zstd)" + curl_gss_msg="no (--with-gssapi)" + curl_gsasl_msg="no (--with-gsasl)" +curl_tls_srp_msg="no (--enable-tls-srp)" + curl_res_msg="default (--enable-ares / --enable-threaded-resolver)" + curl_ipv6_msg="no (--enable-ipv6)" +curl_unix_sockets_msg="no (--enable-unix-sockets)" + curl_idn_msg="no (--with-{libidn2,winidn})" + curl_docs_msg="enabled (--disable-docs)" + curl_manual_msg="no (--enable-manual)" +curl_libcurl_msg="enabled (--disable-libcurl-option)" +curl_verbose_msg="enabled (--disable-verbose)" + curl_sspi_msg="no (--enable-sspi)" + curl_ldap_msg="no (--enable-ldap / --with-ldap-lib / --with-lber-lib)" + curl_ldaps_msg="no (--enable-ldaps)" + curl_ipfs_msg="no (--enable-ipfs)" + curl_rtsp_msg="no (--enable-rtsp)" + curl_rtmp_msg="no (--with-librtmp)" + curl_psl_msg="no (--with-libpsl)" + curl_altsvc_msg="enabled (--disable-alt-svc)" +curl_headers_msg="enabled (--disable-headers-api)" + curl_hsts_msg="enabled (--disable-hsts)" + ssl_backends= + curl_h1_msg="enabled (internal)" + curl_h2_msg="no (--with-nghttp2)" + curl_h3_msg="no (--with-ngtcp2 --with-nghttp3, --with-quiche, --with-openssl-quic, --with-msh3)" + +enable_altsvc="yes" +hsts="yes" + +dnl +dnl Save some initial values the user might have provided +dnl +INITIAL_LDFLAGS=$LDFLAGS +INITIAL_LIBS=$LIBS + +dnl +dnl Generates a shell script to run the compiler with LD_LIBRARY_PATH set to +dnl the value used right now. This lets CURL_RUN_IFELSE set LD_LIBRARY_PATH to +dnl something different but only have that affect the execution of the results +dnl of the compile, not change the libraries for the compiler itself. +dnl +compilersh="run-compiler" +CURL_SAVED_CC="$CC" +export CURL_SAVED_CC +CURL_SAVED_LD_LIBRARY_PATH="$LD_LIBRARY_PATH" +export CURL_SAVED_LD_LIBRARY_PATH +cat <<\EOF > "$compilersh" +CC="$CURL_SAVED_CC" +export CC +LD_LIBRARY_PATH="$CURL_SAVED_LD_LIBRARY_PATH" +export LD_LIBRARY_PATH +exec $CC "$@" +EOF + +dnl ********************************************************************** +dnl See which TLS backend(s) that are requested. Just do all the +dnl TLS AC_ARG_WITH() invokes here and do the checks later +dnl ********************************************************************** +OPT_SCHANNEL=no +AC_ARG_WITH(schannel,dnl +AS_HELP_STRING([--with-schannel],[enable Windows native SSL/TLS]), + OPT_SCHANNEL=$withval + TLSCHOICE="schannel") + +OPT_SECURETRANSPORT=no +AC_ARG_WITH(secure-transport,dnl +AS_HELP_STRING([--with-secure-transport],[enable Apple OS native SSL/TLS]),[ + OPT_SECURETRANSPORT=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }Secure-Transport" +]) + +OPT_AMISSL=no +AC_ARG_WITH(amissl,dnl +AS_HELP_STRING([--with-amissl],[enable Amiga native SSL/TLS (AmiSSL)]),[ + OPT_AMISSL=$withval + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }AmiSSL" +]) + +OPT_OPENSSL=no +dnl Default to no CA bundle +ca="no" +AC_ARG_WITH(ssl,dnl +AS_HELP_STRING([--with-ssl=PATH],[old version of --with-openssl]) +AS_HELP_STRING([--without-ssl], [build without any TLS library]),[ + OPT_SSL=$withval + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + else + SSL_DISABLED="D" + fi +]) + +AC_ARG_WITH(openssl,dnl +AS_HELP_STRING([--with-openssl=PATH],[Where to look for OpenSSL, PATH points to the SSL installation (default: /usr/local/ssl); when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]),[ + OPT_OPENSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }OpenSSL" + fi +]) + +OPT_GNUTLS=no +AC_ARG_WITH(gnutls,dnl +AS_HELP_STRING([--with-gnutls=PATH],[where to look for GnuTLS, PATH points to the installation root]),[ + OPT_GNUTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }GnuTLS" + fi +]) + +OPT_MBEDTLS=no +AC_ARG_WITH(mbedtls,dnl +AS_HELP_STRING([--with-mbedtls=PATH],[where to look for mbedTLS, PATH points to the installation root]),[ + OPT_MBEDTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }mbedTLS" + fi +]) + +OPT_WOLFSSL=no +AC_ARG_WITH(wolfssl,dnl +AS_HELP_STRING([--with-wolfssl=PATH],[where to look for wolfSSL, PATH points to the installation root (default: system lib default)]),[ + OPT_WOLFSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }wolfSSL" + fi +]) + +OPT_BEARSSL=no +AC_ARG_WITH(bearssl,dnl +AS_HELP_STRING([--with-bearssl=PATH],[where to look for BearSSL, PATH points to the installation root]),[ + OPT_BEARSSL=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }BearSSL" + fi +]) + +OPT_RUSTLS=no +AC_ARG_WITH(rustls,dnl +AS_HELP_STRING([--with-rustls=PATH],[where to look for Rustls, PATH points to the installation root]),[ + OPT_RUSTLS=$withval + if test X"$withval" != Xno; then + TLSCHOICE="${TLSCHOICE:+$TLSCHOICE, }rustls" + experimental="$experimental rustls" + fi +]) + +TEST_NGHTTPX=nghttpx +AC_ARG_WITH(test-nghttpx,dnl +AS_HELP_STRING([--with-test-nghttpx=PATH],[where to find nghttpx for testing]), + TEST_NGHTTPX=$withval + if test X"$OPT_TEST_NGHTTPX" = "Xno"; then + TEST_NGHTTPX="" + fi +) +AC_SUBST(TEST_NGHTTPX) + +CADDY=/usr/bin/caddy +AC_ARG_WITH(test-caddy,dnl +AS_HELP_STRING([--with-test-caddy=PATH],[where to find caddy for testing]), + CADDY=$withval + if test X"$OPT_CADDY" = "Xno"; then + CADDY="" + fi +) +AC_SUBST(CADDY) + +VSFTPD=/usr/sbin/vsftpd +AC_ARG_WITH(test-vsftpd,dnl +AS_HELP_STRING([--with-test-vsftpd=PATH],[where to find vsftpd for testing]), + VSFTPD=$withval + if test X"$OPT_VSFTPD" = "Xno"; then + VSFTPD="" + fi +) +AC_SUBST(VSFTPD) + +dnl we'd like a httpd+apachectl as test server +dnl +HTTPD_ENABLED="maybe" +AC_ARG_WITH(test-httpd, [AS_HELP_STRING([--with-test-httpd=PATH], + [where to find httpd/apache2 for testing])], + [request_httpd=$withval], [request_httpd=check]) +if test x"$request_httpd" = "xcheck" -o x"$request_httpd" = "xyes"; then + if test -x "/usr/sbin/apache2" -a -x "/usr/sbin/apache2ctl"; then + # common location on distros (debian/ubuntu) + HTTPD="/usr/sbin/apache2" + APACHECTL="/usr/sbin/apache2ctl" + AC_PATH_PROG([APXS], [apxs]) + if test "x$APXS" = "x"; then + AC_MSG_NOTICE([apache2-dev not installed, httpd tests disabled]) + HTTPD_ENABLED="no" + fi + else + AC_PATH_PROG([HTTPD], [httpd]) + if test "x$HTTPD" = "x"; then + AC_PATH_PROG([HTTPD], [apache2]) + fi + AC_PATH_PROG([APACHECTL], [apachectl]) + AC_PATH_PROG([APXS], [apxs]) + if test "x$HTTPD" = "x" -o "x$APACHECTL" = "x"; then + AC_MSG_NOTICE([httpd/apache2 not in PATH, http tests disabled]) + HTTPD_ENABLED="no" + fi + if test "x$APXS" = "x"; then + AC_MSG_NOTICE([apxs not in PATH, http tests disabled]) + HTTPD_ENABLED="no" + fi + fi +elif test x"$request_httpd" != "xno"; then + HTTPD="${request_httpd}/bin/httpd" + APACHECTL="${request_httpd}/bin/apachectl" + APXS="${request_httpd}/bin/apxs" + if test ! -x "${HTTPD}"; then + AC_MSG_NOTICE([httpd not found as ${HTTPD}, http tests disabled]) + HTTPD_ENABLED="no" + elif test ! -x "${APACHECTL}"; then + AC_MSG_NOTICE([apachectl not found as ${APACHECTL}, http tests disabled]) + HTTPD_ENABLED="no" + elif test ! -x "${APXS}"; then + AC_MSG_NOTICE([apxs not found as ${APXS}, http tests disabled]) + HTTPD_ENABLED="no" + else + AC_MSG_NOTICE([using HTTPD=$HTTPD for tests]) + fi +fi +if test x"$HTTPD_ENABLED" = "xno"; then + HTTPD="" + APACHECTL="" + APXS="" +fi +AC_SUBST(HTTPD) +AC_SUBST(APACHECTL) +AC_SUBST(APXS) + +dnl the nghttpx we might use in httpd testing +if test "x$TEST_NGHTTPX" != "x" -a "x$TEST_NGHTTPX" != "xnghttpx"; then + HTTPD_NGHTTPX="$TEST_NGHTTPX" +else + AC_PATH_PROG([HTTPD_NGHTTPX], [nghttpx], [], + [$PATH:/usr/bin:/usr/local/bin]) +fi +AC_SUBST(HTTPD_NGHTTPX) + +dnl the Caddy server we might use in testing +if test "x$TEST_CADDY" != "x"; then + CADDY="$TEST_CADDY" +else + AC_PATH_PROG([CADDY], [caddy]) +fi +AC_SUBST(CADDY) + +dnl If no TLS choice has been made, check if it was explicitly disabled or +dnl error out to force the user to decide. +if test -z "$TLSCHOICE"; then + if test "x$OPT_SSL" != "xno"; then + AC_MSG_ERROR([select TLS backend(s) or disable TLS with --without-ssl. + +Select from these: + + --with-amissl + --with-bearssl + --with-gnutls + --with-mbedtls + --with-openssl (also works for BoringSSL and LibreSSL) + --with-rustls + --with-schannel + --with-secure-transport + --with-wolfssl +]) + fi +fi + +AC_ARG_WITH(darwinssl,, + AC_MSG_ERROR([--with-darwin-ssl and --without-darwin-ssl no longer work!])) + +dnl +dnl Detect the canonical host and target build environment +dnl + +AC_CANONICAL_HOST +dnl Get system canonical name +AC_DEFINE_UNQUOTED(CURL_OS, "${host}", [cpu-machine-OS]) + +# Silence warning: ar: 'u' modifier ignored since 'D' is the default +AC_SUBST(AR_FLAGS, [cr]) + +dnl This defines _ALL_SOURCE for AIX +CURL_CHECK_AIX_ALL_SOURCE + +dnl Our configure and build reentrant settings +CURL_CONFIGURE_THREAD_SAFE +CURL_CONFIGURE_REENTRANT + +dnl check for how to do large files +AC_SYS_LARGEFILE + +XC_LIBTOOL + +LT_LANG([Windows Resource]) + +# +# Automake conditionals based on libtool related checks +# + +AM_CONDITIONAL([CURL_LT_SHLIB_USE_VERSION_INFO], + [test "x$xc_lt_shlib_use_version_info" = 'xyes']) +AM_CONDITIONAL([CURL_LT_SHLIB_USE_NO_UNDEFINED], + [test "x$xc_lt_shlib_use_no_undefined" = 'xyes']) +AM_CONDITIONAL([CURL_LT_SHLIB_USE_MIMPURE_TEXT], + [test "x$xc_lt_shlib_use_mimpure_text" = 'xyes']) + +# +# Due to libtool and automake machinery limitations of not allowing +# specifying separate CPPFLAGS or CFLAGS when compiling objects for +# inclusion of these in shared or static libraries, we are forced to +# build using separate configure runs for shared and static libraries +# on systems where different CPPFLAGS or CFLAGS are mandatory in order +# to compile objects for each kind of library. Notice that relying on +# the '-DPIC' CFLAG that libtool provides is not valid given that the +# user might for example choose to build static libraries with PIC. +# + +# +# Make our Makefile.am files use the staticlib CPPFLAG only when strictly +# targeting a static library and not building its shared counterpart. +# + +AM_CONDITIONAL([USE_CPPFLAG_CURL_STATICLIB], + [test "x$xc_lt_build_static_only" = 'xyes']) + +# +# Make staticlib CPPFLAG variable and its definition visible in output +# files unconditionally, providing an empty definition unless strictly +# targeting a static library and not building its shared counterpart. +# + +LIBCURL_PC_CFLAGS_PRIVATE='-DCURL_STATICLIB' +AC_SUBST(LIBCURL_PC_CFLAGS_PRIVATE) + +LIBCURL_PC_CFLAGS= +if test "x$xc_lt_build_static_only" = 'xyes'; then + LIBCURL_PC_CFLAGS="${LIBCURL_PC_CFLAGS_PRIVATE}" +fi +AC_SUBST([LIBCURL_PC_CFLAGS]) + + +dnl ********************************************************************** +dnl platform/compiler/architecture specific checks/flags +dnl ********************************************************************** + +CURL_CHECK_COMPILER +CURL_CHECK_NATIVE_WINDOWS +CURL_SET_COMPILER_BASIC_OPTS +CURL_SET_COMPILER_DEBUG_OPTS +CURL_SET_COMPILER_OPTIMIZE_OPTS +CURL_SET_COMPILER_WARNING_OPTS + +if test "$compiler_id" = "INTEL_UNIX_C"; then + # + if test "$compiler_num" -ge "1000"; then + dnl icc 10.X or later + CFLAGS="$CFLAGS -shared-intel" + elif test "$compiler_num" -ge "900"; then + dnl icc 9.X specific + CFLAGS="$CFLAGS -i-dynamic" + fi + # +fi + +CURL_CFLAG_EXTRAS="" +if test X"$want_werror" = Xyes; then + CURL_CFLAG_EXTRAS="-Werror" + if test "$compiler_id" = "GNU_C"; then + dnl enable -pedantic-errors for GCC 5 and later, + dnl as before that it was the same as -Werror=pedantic + if test "$compiler_num" -ge "500"; then + CURL_CFLAG_EXTRAS="$CURL_CFLAG_EXTRAS -pedantic-errors" + fi + elif test "$compiler_id" = "CLANG" -o "$compiler_id" = "APPLECLANG"; then + CURL_CFLAG_EXTRAS="$CURL_CFLAG_EXTRAS -pedantic-errors" + fi +fi +AC_SUBST(CURL_CFLAG_EXTRAS) + +CURL_CHECK_COMPILER_HALT_ON_ERROR +CURL_CHECK_COMPILER_ARRAY_SIZE_NEGATIVE +CURL_CHECK_COMPILER_PROTOTYPE_MISMATCH +CURL_CHECK_COMPILER_SYMBOL_HIDING + +supports_unittests=yes +# cross-compilation of unit tests static library/programs fails when +# libcurl shared library is built. This might be due to a libtool or +# automake issue. In this case we disable unit tests. +if test "x$cross_compiling" != "xno" && + test "x$enable_shared" != "xno"; then + supports_unittests=no +fi + +# IRIX 6.5.24 gcc 3.3 autobuilds fail unittests library compilation due to +# a problem related with OpenSSL headers and library versions not matching. +# Disable unit tests while time to further investigate this is found. +case $host in + mips-sgi-irix6.5) + if test "$compiler_id" = "GNU_C"; then + supports_unittests=no + fi + ;; +esac + +# All AIX autobuilds fails unit tests linking against unittests library +# due to unittests library being built with no symbols or members. Libtool ? +# Disable unit tests while time to further investigate this is found. +case $host_os in + aix*) + supports_unittests=no + ;; +esac + +# In order to detect support of sendmmsg(), we need to escape the POSIX +# jail by defining _GNU_SOURCE or will not expose it. +case $host_os in + linux*) + CPPFLAGS="$CPPFLAGS -D_GNU_SOURCE" + ;; +esac + +dnl Build unit tests when option --enable-debug is given. +if test "x$want_debug" = "xyes" && + test "x$supports_unittests" = "xyes"; then + want_unittests=yes +else + want_unittests=no +fi +AM_CONDITIONAL(BUILD_UNITTESTS, test x$want_unittests = xyes) + +dnl ********************************************************************** +dnl Compilation based checks should not be done before this point. +dnl ********************************************************************** + +CURL_CHECK_WIN32_LARGEFILE +CURL_CHECK_WIN32_CRYPTO + +CURL_DARWIN_CFLAGS + +case $host in + *-apple-*) + CURL_SUPPORTS_BUILTIN_AVAILABLE + ;; +esac + +curl_cv_cygwin='no' +case $host_os in + cygwin*|msys*) curl_cv_cygwin='yes';; +esac + +AM_CONDITIONAL([HAVE_WINDRES], + [test "$curl_cv_native_windows" = "yes" && test -n "${RC}"]) + +if test "$curl_cv_native_windows" = "yes"; then + AM_COND_IF([HAVE_WINDRES],, + [AC_MSG_ERROR([windres not found in PATH. Windows builds require windres. Cannot continue.])]) +fi + +dnl ---------------------------------------- +dnl whether use "unity" mode for lib and src +dnl ---------------------------------------- + +want_unity='no' +AC_MSG_CHECKING([whether to build libcurl and curl in "unity" mode]) +AC_ARG_ENABLE(unity, +AS_HELP_STRING([--enable-unity],[Enable unity mode]) +AS_HELP_STRING([--disable-unity],[Disable unity (default)]), +[ case "$enableval" in + yes) + want_unity='yes' + AC_MSG_RESULT([yes]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac ], + AC_MSG_RESULT([no]) +) + +AM_CONDITIONAL([USE_UNITY], [test "$want_unity" = 'yes']) + +dnl ----------------------- +dnl whether to bundle tests +dnl ----------------------- + +want_test_bundles='no' +AC_MSG_CHECKING([whether to build tests into single-binary bundles]) +AC_ARG_ENABLE(test-bundles, +AS_HELP_STRING([--enable-test-bundles],[Enable test bundles]) +AS_HELP_STRING([--disable-test-bundles],[Disable test bundles (default)]), +[ case "$enableval" in + yes) + want_test_bundles='yes' + AC_MSG_RESULT([yes]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac ], + AC_MSG_RESULT([no]) +) + +AM_CONDITIONAL([USE_TEST_BUNDLES], [test "$want_test_bundles" = 'yes']) + +dnl ************************************************************ +dnl switch off particular protocols +dnl +AC_MSG_CHECKING([whether to support http]) +AC_ARG_ENABLE(http, +AS_HELP_STRING([--enable-http],[Enable HTTP support]) +AS_HELP_STRING([--disable-http],[Disable HTTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_HTTP, 1, [to disable HTTP]) + disable_http="yes" + AC_MSG_WARN([disable HTTP disables FTP over proxy, IPFS and RTSP]) + AC_SUBST(CURL_DISABLE_HTTP, [1]) + AC_DEFINE(CURL_DISABLE_IPFS, 1, [to disable IPFS]) + AC_SUBST(CURL_DISABLE_IPFS, [1]) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) + dnl toggle off alt-svc too when HTTP is disabled + AC_DEFINE(CURL_DISABLE_ALTSVC, 1, [disable alt-svc]) + AC_DEFINE(CURL_DISABLE_HSTS, 1, [disable HSTS]) + curl_h1_msg="no (--enable-http, --with-hyper)" + curl_altsvc_msg="no"; + curl_hsts_msg="no (--enable-hsts)"; + enable_altsvc="no" + hsts="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support ftp]) +AC_ARG_ENABLE(ftp, +AS_HELP_STRING([--enable-ftp],[Enable FTP support]) +AS_HELP_STRING([--disable-ftp],[Disable FTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FTP, 1, [to disable FTP]) + AC_SUBST(CURL_DISABLE_FTP, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support file]) +AC_ARG_ENABLE(file, +AS_HELP_STRING([--enable-file],[Enable FILE support]) +AS_HELP_STRING([--disable-file],[Disable FILE support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FILE, 1, [to disable FILE]) + AC_SUBST(CURL_DISABLE_FILE, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) +AC_MSG_CHECKING([whether to support IPFS]) +AC_ARG_ENABLE(ipfs, +AS_HELP_STRING([--enable-ipfs],[Enable IPFS support]) +AS_HELP_STRING([--disable-ipfs],[Disable IPFS support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_IPFS, 1, [to disable IPFS]) + AC_SUBST(CURL_DISABLE_IPFS, [1]) + ;; + *) + if test x$CURL_DISABLE_HTTP = x1; then + AC_MSG_ERROR(HTTP support needs to be enabled in order to enable IPFS support!) + else + AC_MSG_RESULT(yes) + curl_ipfs_msg="enabled" + fi + ;; + esac ], + if test "x$CURL_DISABLE_HTTP" != "x1"; then + AC_MSG_RESULT(yes) + curl_ipfs_msg="enabled" + else + AC_MSG_RESULT(no) + fi +) +AC_MSG_CHECKING([whether to support ldap]) +AC_ARG_ENABLE(ldap, +AS_HELP_STRING([--enable-ldap],[Enable LDAP support]) +AS_HELP_STRING([--disable-ldap],[Disable LDAP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + ;; + yes) + ldap_askedfor="yes" + AC_MSG_RESULT(yes) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ],[ + AC_MSG_RESULT(yes) ] +) +AC_MSG_CHECKING([whether to support ldaps]) +AC_ARG_ENABLE(ldaps, +AS_HELP_STRING([--enable-ldaps],[Enable LDAPS support]) +AS_HELP_STRING([--disable-ldaps],[Disable LDAPS support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + ;; + *) + if test "x$CURL_DISABLE_LDAP" = "x1"; then + AC_MSG_RESULT(LDAP needs to be enabled to support LDAPS) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + else + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_LDAP_SSL, 1, [Use LDAPS implementation]) + AC_SUBST(HAVE_LDAP_SSL, [1]) + fi + ;; + esac ],[ + if test "x$CURL_DISABLE_LDAP" = "x1"; then + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + else + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_LDAP_SSL, 1, [Use LDAPS implementation]) + AC_SUBST(HAVE_LDAP_SSL, [1]) + fi ] +) + +dnl ********************************************************************** +dnl Check for Hyper +dnl ********************************************************************** + +OPT_HYPER="no" + +AC_ARG_WITH(hyper, +AS_HELP_STRING([--with-hyper=PATH],[Enable hyper usage]) +AS_HELP_STRING([--without-hyper],[Disable hyper usage]), + [OPT_HYPER=$withval]) +case "$OPT_HYPER" in + no) + dnl --without-hyper option used + want_hyper="no" + ;; + yes) + dnl --with-hyper option used without path + want_hyper="default" + want_hyper_path="" + ;; + *) + dnl --with-hyper option used with path + want_hyper="yes" + want_hyper_path="$withval" + ;; +esac + +if test X"$want_hyper" != Xno; then + if test "x$disable_http" = "xyes"; then + AC_MSG_ERROR([--with-hyper is not compatible with --disable-http]) + fi + + dnl backup the pre-hyper variables + CLEANLDFLAGS="$LDFLAGS" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(hyper, $want_hyper_path) + + if test "$PKGCONFIG" != "no"; then + LIB_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) + $PKGCONFIG --libs-only-l hyper` + CPP_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) dnl + $PKGCONFIG --cflags-only-I hyper` + LD_HYPER=`CURL_EXPORT_PCDIR([$want_hyper_path]) + $PKGCONFIG --libs-only-L hyper` + else + dnl no hyper pkg-config found + LIB_HYPER="-lhyper -ldl -lpthread -lm" + if test X"$want_hyper" != Xdefault; then + CPP_HYPER=-I"$want_hyper_path/capi/include" + LD_HYPER="-L$want_hyper_path/target/release -L$want_hyper_path/target/debug" + fi + fi + if test -n "$LIB_HYPER"; then + AC_MSG_NOTICE([-l is $LIB_HYPER]) + AC_MSG_NOTICE([-I is $CPP_HYPER]) + AC_MSG_NOTICE([-L is $LD_HYPER]) + + LDFLAGS="$LDFLAGS $LD_HYPER" + CPPFLAGS="$CPPFLAGS $CPP_HYPER" + LIBS="$LIB_HYPER $LIBS" + + if test "x$cross_compiling" != "xyes"; then + dnl remove -L, separate with colon if more than one + DIR_HYPER=`echo $LD_HYPER | $SED -e 's/^-L//' -e 's/ -L/:/g'` + fi + + AC_CHECK_LIB(hyper, hyper_io_new, + [ + AC_CHECK_HEADERS(hyper.h, + experimental="$experimental Hyper" + AC_MSG_NOTICE([Hyper support is experimental]) + curl_h1_msg="enabled (Hyper)" + HYPER_ENABLED=1 + AC_DEFINE(USE_HYPER, 1, [if hyper is in use]) + AC_SUBST(USE_HYPER, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_HYPER" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_HYPER to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE hyper" + ) + ], + for d in `echo $DIR_HYPER | $SED -e 's/:/ /'`; do + if test -f "$d/libhyper.a"; then + AC_MSG_ERROR([hyper was found in $d but was probably built with wrong flags. See docs/HYPER.md.]) + fi + done + AC_MSG_ERROR([--with-hyper but hyper was not found. See docs/HYPER.md.]) + ) + fi +fi + +if test X"$want_hyper" != Xno; then + AC_MSG_NOTICE([Disable RTSP support with hyper]) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) +else + AC_MSG_CHECKING([whether to support rtsp]) + AC_ARG_ENABLE(rtsp, +AS_HELP_STRING([--enable-rtsp],[Enable RTSP support]) +AS_HELP_STRING([--disable-rtsp],[Disable RTSP support]), + [ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_RTSP, 1, [to disable RTSP]) + AC_SUBST(CURL_DISABLE_RTSP, [1]) + ;; + *) + if test x$CURL_DISABLE_HTTP = x1; then + AC_MSG_ERROR(HTTP support needs to be enabled in order to enable RTSP support!) + else + AC_MSG_RESULT(yes) + curl_rtsp_msg="enabled" + fi + ;; + esac ], + if test "x$CURL_DISABLE_HTTP" != "x1"; then + AC_MSG_RESULT(yes) + curl_rtsp_msg="enabled" + else + AC_MSG_RESULT(no) + fi + ) +fi + +AC_MSG_CHECKING([whether to support proxies]) +AC_ARG_ENABLE(proxy, +AS_HELP_STRING([--enable-proxy],[Enable proxy support]) +AS_HELP_STRING([--disable-proxy],[Disable proxy support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PROXY, 1, [to disable proxies]) + AC_SUBST(CURL_DISABLE_PROXY, [1]) + https_proxy="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support dict]) +AC_ARG_ENABLE(dict, +AS_HELP_STRING([--enable-dict],[Enable DICT support]) +AS_HELP_STRING([--disable-dict],[Disable DICT support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DICT, 1, [to disable DICT]) + AC_SUBST(CURL_DISABLE_DICT, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support telnet]) +AC_ARG_ENABLE(telnet, +AS_HELP_STRING([--enable-telnet],[Enable TELNET support]) +AS_HELP_STRING([--disable-telnet],[Disable TELNET support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_TELNET, 1, [to disable TELNET]) + AC_SUBST(CURL_DISABLE_TELNET, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support tftp]) +AC_ARG_ENABLE(tftp, +AS_HELP_STRING([--enable-tftp],[Enable TFTP support]) +AS_HELP_STRING([--disable-tftp],[Disable TFTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_TFTP, 1, [to disable TFTP]) + AC_SUBST(CURL_DISABLE_TFTP, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support pop3]) +AC_ARG_ENABLE(pop3, +AS_HELP_STRING([--enable-pop3],[Enable POP3 support]) +AS_HELP_STRING([--disable-pop3],[Disable POP3 support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_POP3, 1, [to disable POP3]) + AC_SUBST(CURL_DISABLE_POP3, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support imap]) +AC_ARG_ENABLE(imap, +AS_HELP_STRING([--enable-imap],[Enable IMAP support]) +AS_HELP_STRING([--disable-imap],[Disable IMAP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_IMAP, 1, [to disable IMAP]) + AC_SUBST(CURL_DISABLE_IMAP, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support smb]) +AC_ARG_ENABLE(smb, +AS_HELP_STRING([--enable-smb],[Enable SMB/CIFS support]) +AS_HELP_STRING([--disable-smb],[Disable SMB/CIFS support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SMB, 1, [to disable SMB/CIFS]) + AC_SUBST(CURL_DISABLE_SMB, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support smtp]) +AC_ARG_ENABLE(smtp, +AS_HELP_STRING([--enable-smtp],[Enable SMTP support]) +AS_HELP_STRING([--disable-smtp],[Disable SMTP support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SMTP, 1, [to disable SMTP]) + AC_SUBST(CURL_DISABLE_SMTP, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support gopher]) +AC_ARG_ENABLE(gopher, +AS_HELP_STRING([--enable-gopher],[Enable Gopher support]) +AS_HELP_STRING([--disable-gopher],[Disable Gopher support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_GOPHER, 1, [to disable Gopher]) + AC_SUBST(CURL_DISABLE_GOPHER, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +AC_MSG_CHECKING([whether to support mqtt]) +AC_ARG_ENABLE(mqtt, +AS_HELP_STRING([--enable-mqtt],[Enable MQTT support]) +AS_HELP_STRING([--disable-mqtt],[Disable MQTT support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_MQTT, 1, [to disable MQTT]) + AC_SUBST(CURL_DISABLE_MQTT, [1]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(no) +) + +dnl ********************************************************************** +dnl Check for built-in manual +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to provide built-in manual]) +AC_ARG_ENABLE(manual, +AS_HELP_STRING([--enable-manual],[Enable built-in manual]) +AS_HELP_STRING([--disable-manual],[Disable built-in manual]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ;; + *) + AC_MSG_RESULT(yes) + USE_MANUAL="1" + ;; + esac ], + AC_MSG_RESULT(yes) + USE_MANUAL="1" +) +dnl The actual use of the USE_MANUAL variable is done much later in this +dnl script to allow other actions to disable it as well. + +dnl ********************************************************************** +dnl Check whether to build documentation +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to build documentation]) +AC_ARG_ENABLE(docs, +AS_HELP_STRING([--enable-docs],[Enable documentation]) +AS_HELP_STRING([--disable-docs],[Disable documentation]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + BUILD_DOCS=0 + dnl disable manual too because it needs built documentation + USE_MANUAL=0 + curl_docs_msg="no" + ;; + *) + AC_MSG_RESULT(yes) + BUILD_DOCS=1 + ;; + esac ], + AC_MSG_RESULT(yes) + BUILD_DOCS=1 +) + + +dnl ************************************************************ +dnl disable C code generation support +dnl +AC_MSG_CHECKING([whether to enable generation of C code]) +AC_ARG_ENABLE(libcurl_option, +AS_HELP_STRING([--enable-libcurl-option],[Enable --libcurl C code generation support]) +AS_HELP_STRING([--disable-libcurl-option],[Disable --libcurl C code generation support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_LIBCURL_OPTION, 1, [to disable --libcurl C code generation option]) + curl_libcurl_msg="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ********************************************************************** +dnl Checks for libraries. +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to use libgcc]) +AC_ARG_ENABLE(libgcc, +AS_HELP_STRING([--enable-libgcc],[use libgcc when linking]), +[ case "$enableval" in + yes) + LIBS="-lgcc $LIBS" + AC_MSG_RESULT(yes) + ;; + *) + AC_MSG_RESULT(no) + ;; + esac ], + AC_MSG_RESULT(no) +) + +CURL_CHECK_LIB_XNET + +dnl gethostbyname without lib or in the nsl lib? +AC_CHECK_FUNC(gethostbyname, + [ + HAVE_GETHOSTBYNAME="1" + ], + [ + AC_CHECK_LIB(nsl, gethostbyname, + [ + HAVE_GETHOSTBYNAME="1" + LIBS="-lnsl $LIBS" + ] + ) + ] +) + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl gethostbyname in the socket lib? + AC_CHECK_LIB(socket, gethostbyname, + [ + HAVE_GETHOSTBYNAME="1" + LIBS="-lsocket $LIBS" + ] + ) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl gethostbyname in the watt lib? + AC_CHECK_LIB(watt, gethostbyname, + [ + HAVE_GETHOSTBYNAME="1" + CPPFLAGS="-I${WATT_ROOT}/inc" + LDFLAGS="-L${WATT_ROOT}/lib" + LIBS="-lwatt $LIBS" + ] + ) +fi + +dnl At least one system has been identified to require BOTH nsl and socket +dnl libs at the same time to link properly. +if test "$HAVE_GETHOSTBYNAME" != "1"; then + AC_MSG_CHECKING([for gethostbyname with both nsl and socket libs]) + my_ac_save_LIBS=$LIBS + LIBS="-lnsl -lsocket $LIBS" + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + ]],[[ + gethostbyname(); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + LIBS=$my_ac_save_LIBS + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl This is for Winsock systems + if test "$curl_cv_native_windows" = "yes"; then + winsock_LIB="-lws2_32" + if test ! -z "$winsock_LIB"; then + my_ac_save_LIBS=$LIBS + LIBS="$winsock_LIB $LIBS" + AC_MSG_CHECKING([for gethostbyname in $winsock_LIB]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #ifdef _WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #endif + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + winsock_LIB="" + LIBS=$my_ac_save_LIBS + ]) + fi + fi +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl This is for Minix 3.1 + AC_MSG_CHECKING([for gethostbyname for Minix 3]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + /* Older Minix versions may need here instead */ + #include + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl This is for eCos with a stubbed DNS implementation + AC_MSG_CHECKING([for gethostbyname for eCos]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #include + #include + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1" -o "${with_amissl+set}" = set; then + dnl This is for AmigaOS with bsdsocket.library - needs testing before -lnet + AC_MSG_CHECKING([for gethostbyname for AmigaOS bsdsocket.library]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #define __USE_INLINE__ + #include + #ifdef __amigaos4__ + struct SocketIFace *ISocket = NULL; + #else + struct Library *SocketBase = NULL; + #endif + ]],[[ + gethostbyname("localhost"); + ]]) + ],[ + AC_MSG_RESULT([yes]) + HAVE_GETHOSTBYNAME="1" + HAVE_PROTO_BSDSOCKET_H="1" + AC_DEFINE(HAVE_PROTO_BSDSOCKET_H, 1, [if Amiga bsdsocket.library is in use]) + AC_SUBST(HAVE_PROTO_BSDSOCKET_H, [1]) + ],[ + AC_MSG_RESULT([no]) + ]) +fi + +if test "$HAVE_GETHOSTBYNAME" != "1"; then + dnl gethostbyname in the network lib - for Haiku OS + AC_CHECK_LIB(network, gethostbyname, + [ + HAVE_GETHOSTBYNAME="1" + LIBS="-lnetwork $LIBS" + ] + ) +fi + +CURL_CHECK_LIBS_CONNECT + +CURL_NETWORK_LIBS=$LIBS + +dnl ********************************************************************** +dnl In case that function clock_gettime with monotonic timer is available, +dnl check for additional required libraries. +dnl ********************************************************************** +CURL_CHECK_LIBS_CLOCK_GETTIME_MONOTONIC + +dnl Check for even better option +CURL_CHECK_FUNC_CLOCK_GETTIME_MONOTONIC_RAW + +dnl ********************************************************************** +dnl The preceding library checks are all potentially useful for test +dnl servers and libtest cases which require networking and clock_gettime +dnl support. Save the list of required libraries at this point for use +dnl while linking those test servers and programs. +dnl ********************************************************************** +CURL_NETWORK_AND_TIME_LIBS=$LIBS + +dnl ********************************************************************** +dnl Check for the presence of ZLIB libraries and headers +dnl ********************************************************************** + +dnl Check for & handle argument to --with-zlib. + +clean_CPPFLAGS=$CPPFLAGS +clean_LDFLAGS=$LDFLAGS +clean_LIBS=$LIBS +ZLIB_LIBS="" +AC_ARG_WITH(zlib, +AS_HELP_STRING([--with-zlib=PATH],[search for zlib in PATH]) +AS_HELP_STRING([--without-zlib],[disable use of zlib]), + [OPT_ZLIB="$withval"]) + +if test "$OPT_ZLIB" = "no"; then + AC_MSG_WARN([zlib disabled]) +else + if test "$OPT_ZLIB" = "yes"; then + OPT_ZLIB="" + fi + + if test -z "$OPT_ZLIB"; then + CURL_CHECK_PKGCONFIG(zlib) + + if test "$PKGCONFIG" != "no"; then + ZLIB_LIBS="`$PKGCONFIG --libs-only-l zlib`" + if test -n "$ZLIB_LIBS"; then + LDFLAGS="$LDFLAGS `$PKGCONFIG --libs-only-L zlib`" + else + ZLIB_LIBS="`$PKGCONFIG --libs zlib`" + fi + LIBS="$ZLIB_LIBS $LIBS" + CPPFLAGS="$CPPFLAGS `$PKGCONFIG --cflags zlib`" + OPT_ZLIB="" + HAVE_LIBZ="1" + fi + + if test -z "$HAVE_LIBZ"; then + + dnl Check for the lib without setting any new path, since many + dnl people have it in the default path + + AC_CHECK_LIB(z, inflateEnd, + dnl libz found, set the variable + [ + HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS" + ], + dnl if no lib found, try /usr/local + [ + OPT_ZLIB="/usr/local" + ] + ) + fi + fi + + dnl Add a nonempty path to the compiler flags + if test -n "$OPT_ZLIB"; then + CPPFLAGS="$CPPFLAGS -I$OPT_ZLIB/include" + LDFLAGS="$LDFLAGS -L$OPT_ZLIB/lib$libsuff" + fi + + AC_CHECK_HEADER(zlib.h, + [ + dnl zlib.h was found + HAVE_ZLIB_H="1" + dnl if the lib wasn't found already, try again with the new paths + if test "$HAVE_LIBZ" != "1"; then + AC_CHECK_LIB(z, gzread, + [ + dnl the lib was found! + HAVE_LIBZ="1" + ZLIB_LIBS="-lz" + LIBS="$ZLIB_LIBS $LIBS" + ], + [ + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + ] + ) + fi + ], + [ + dnl zlib.h was not found, restore the flags + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS] + ) + + if test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" != "1"; then + AC_MSG_WARN([configure found only the libz lib, not the header file!]) + HAVE_LIBZ="" + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" != "1" && test "$HAVE_ZLIB_H" = "1"; then + AC_MSG_WARN([configure found only the libz header file, not the lib!]) + CPPFLAGS=$clean_CPPFLAGS + LDFLAGS=$clean_LDFLAGS + LIBS=$clean_LIBS + ZLIB_LIBS="" + elif test "$HAVE_LIBZ" = "1" && test "$HAVE_ZLIB_H" = "1"; then + dnl both header and lib were found! + AC_SUBST(HAVE_LIBZ) + AC_DEFINE(HAVE_LIBZ, 1, [if zlib is available]) + LIBS="$ZLIB_LIBS $clean_LIBS" + + dnl replace 'HAVE_LIBZ' in the automake makefile.ams + AMFIXLIB="1" + AC_MSG_NOTICE([found both libz and libz.h header]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE zlib" + curl_zlib_msg="enabled" + fi +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(HAVE_LIBZ, test x"$AMFIXLIB" = x1) +AC_SUBST(ZLIB_LIBS) + +dnl ********************************************************************** +dnl Check for the presence of BROTLI decoder libraries and headers +dnl ********************************************************************** + +dnl Brotli project home page: https://github.com/google/brotli + +dnl Default to compiler & linker defaults for BROTLI files & libraries. +OPT_BROTLI=off +AC_ARG_WITH(brotli,dnl +AS_HELP_STRING([--with-brotli=PATH],[Where to look for brotli, PATH points to the BROTLI installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-brotli], [disable BROTLI]), + OPT_BROTLI=$withval) + +if test X"$OPT_BROTLI" != Xno; then + dnl backup the pre-brotli variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_BROTLI" in + yes) + dnl --with-brotli (without path) used + CURL_CHECK_PKGCONFIG(libbrotlidec) + + if test "$PKGCONFIG" != "no"; then + LIB_BROTLI=`$PKGCONFIG --libs-only-l libbrotlidec` + LD_BROTLI=`$PKGCONFIG --libs-only-L libbrotlidec` + CPP_BROTLI=`$PKGCONFIG --cflags-only-I libbrotlidec` + version=`$PKGCONFIG --modversion libbrotlidec` + DIR_BROTLI=`echo $LD_BROTLI | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-brotli option given, just check default places + ;; + *) + dnl use the given --with-brotli spot + PREFIX_BROTLI=$OPT_BROTLI + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_BROTLI"; then + LIB_BROTLI="-lbrotlidec" + LD_BROTLI=-L${PREFIX_BROTLI}/lib$libsuff + CPP_BROTLI=-I${PREFIX_BROTLI}/include + DIR_BROTLI=${PREFIX_BROTLI}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_BROTLI" + LDFLAGSPC="$LDFLAGSPC $LD_BROTLI" + CPPFLAGS="$CPPFLAGS $CPP_BROTLI" + LIBS="$LIB_BROTLI $LIBS" + + AC_CHECK_LIB(brotlidec, BrotliDecoderDecompress) + + AC_CHECK_HEADERS(brotli/decode.h, + curl_brotli_msg="enabled (libbrotlidec)" + HAVE_BROTLI=1 + AC_DEFINE(HAVE_BROTLI, 1, [if BROTLI is in use]) + AC_SUBST(HAVE_BROTLI, [1]) + ) + + if test X"$OPT_BROTLI" != Xoff && + test "$HAVE_BROTLI" != "1"; then + AC_MSG_ERROR([BROTLI libs and/or directories were not found where specified!]) + fi + + if test "$HAVE_BROTLI" = "1"; then + if test -n "$DIR_BROTLI"; then + dnl when the brotli shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_BROTLI" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_BROTLI to CURL_LIBRARY_PATH]) + fi + fi + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libbrotlidec" + else + dnl no brotli, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + +dnl ********************************************************************** +dnl Check for libzstd +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for libzstd +OPT_ZSTD=off +AC_ARG_WITH(zstd,dnl +AS_HELP_STRING([--with-zstd=PATH],[Where to look for libzstd, PATH points to the libzstd installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-zstd], [disable libzstd]), + OPT_ZSTD=$withval) + +if test X"$OPT_ZSTD" != Xno; then + dnl backup the pre-zstd variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_ZSTD" in + yes) + dnl --with-zstd (without path) used + CURL_CHECK_PKGCONFIG(libzstd) + + if test "$PKGCONFIG" != "no"; then + LIB_ZSTD=`$PKGCONFIG --libs-only-l libzstd` + LD_ZSTD=`$PKGCONFIG --libs-only-L libzstd` + CPP_ZSTD=`$PKGCONFIG --cflags-only-I libzstd` + version=`$PKGCONFIG --modversion libzstd` + DIR_ZSTD=`echo $LD_ZSTD | $SED -e 's/-L//'` + fi + + ;; + off) + dnl no --with-zstd option given, just check default places + ;; + *) + dnl use the given --with-zstd spot + PREFIX_ZSTD=$OPT_ZSTD + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_ZSTD"; then + LIB_ZSTD="-lzstd" + LD_ZSTD=-L${PREFIX_ZSTD}/lib$libsuff + CPP_ZSTD=-I${PREFIX_ZSTD}/include + DIR_ZSTD=${PREFIX_ZSTD}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_ZSTD" + LDFLAGSPC="$LDFLAGSPC $LD_ZSTD" + CPPFLAGS="$CPPFLAGS $CPP_ZSTD" + LIBS="$LIB_ZSTD $LIBS" + + AC_CHECK_LIB(zstd, ZSTD_createDStream) + + AC_CHECK_HEADERS(zstd.h, + curl_zstd_msg="enabled (libzstd)" + HAVE_ZSTD=1 + AC_DEFINE(HAVE_ZSTD, 1, [if libzstd is in use]) + AC_SUBST(HAVE_ZSTD, [1]) + ) + + if test X"$OPT_ZSTD" != Xoff && + test "$HAVE_ZSTD" != "1"; then + AC_MSG_ERROR([libzstd was not found where specified!]) + fi + + if test "$HAVE_ZSTD" = "1"; then + if test -n "$DIR_ZSTD"; then + dnl when the zstd shared lib were found in a path that the run-time + dnl linker doesn't search through, we need to add it to + dnl CURL_LIBRARY_PATH to prevent further configure tests to fail due to + dnl this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_ZSTD" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_ZSTD to CURL_LIBRARY_PATH]) + fi + fi + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libzstd" + else + dnl no zstd, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +fi + +dnl ********************************************************************** +dnl Check for LDAP +dnl ********************************************************************** + +LDAPLIBNAME="" +AC_ARG_WITH(ldap-lib, +AS_HELP_STRING([--with-ldap-lib=libname],[Specify name of ldap lib file]), + [LDAPLIBNAME="$withval"]) + +LBERLIBNAME="" +AC_ARG_WITH(lber-lib, +AS_HELP_STRING([--with-lber-lib=libname],[Specify name of lber lib file]), + [LBERLIBNAME="$withval"]) + +if test x$CURL_DISABLE_LDAP != x1; then + + CURL_CHECK_HEADER_LBER + CURL_CHECK_HEADER_LDAP + CURL_CHECK_HEADER_LDAP_SSL + + if test -z "$LDAPLIBNAME"; then + if test "$curl_cv_native_windows" = "yes"; then + dnl Windows uses a single and unique LDAP library name + LDAPLIBNAME="wldap32" + LBERLIBNAME="no" + fi + fi + + if test "$LDAPLIBNAME"; then + AC_CHECK_LIB("$LDAPLIBNAME", ldap_init,, [ + if test -n "$ldap_askedfor"; then + AC_MSG_ERROR([couldn't detect the LDAP libraries]) + fi + AC_MSG_WARN(["$LDAPLIBNAME" is not an LDAP library: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1])]) + else + dnl Try to find the right ldap libraries for this system + CURL_CHECK_LIBS_LDAP + case X-"$curl_cv_ldap_LIBS" in + X-unknown) + if test -n "$ldap_askedfor"; then + AC_MSG_ERROR([couldn't detect the LDAP libraries]) + fi + AC_MSG_WARN([Cannot find libraries for LDAP support: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1]) + ;; + esac + fi +fi + +if test x$CURL_DISABLE_LDAP != x1; then + + if test "$LBERLIBNAME"; then + dnl If name is "no" then don't define this library at all + dnl (it's only needed if libldap.so's dependencies are broken). + if test "$LBERLIBNAME" != "no"; then + AC_CHECK_LIB("$LBERLIBNAME", ber_free,, [ + AC_MSG_WARN(["$LBERLIBNAME" is not an LBER library: LDAP disabled]) + AC_DEFINE(CURL_DISABLE_LDAP, 1, [to disable LDAP]) + AC_SUBST(CURL_DISABLE_LDAP, [1]) + AC_DEFINE(CURL_DISABLE_LDAPS, 1, [to disable LDAPS]) + AC_SUBST(CURL_DISABLE_LDAPS, [1])]) + fi + fi +fi + +if test x$CURL_DISABLE_LDAP != x1; then + AC_CHECK_FUNCS([ldap_url_parse \ + ldap_init_fd]) + + if test "$LDAPLIBNAME" = "wldap32"; then + curl_ldap_msg="enabled (winldap)" + AC_DEFINE(USE_WIN32_LDAP, 1, [Use Windows LDAP implementation]) + else + if test "x$ac_cv_func_ldap_init_fd" = "xyes"; then + curl_ldap_msg="enabled (OpenLDAP)" + AC_DEFINE(USE_OPENLDAP, 1, [Use OpenLDAP-specific code]) + AC_SUBST(USE_OPENLDAP, [1]) + else + curl_ldap_msg="enabled (ancient OpenLDAP)" + fi + fi +fi + +if test x$CURL_DISABLE_LDAPS != x1; then + curl_ldaps_msg="enabled" +fi + +dnl ********************************************************************** +dnl Checks for IPv6 +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to enable IPv6]) +AC_ARG_ENABLE(ipv6, +AS_HELP_STRING([--enable-ipv6],[Enable IPv6 (with IPv4) support]) +AS_HELP_STRING([--disable-ipv6],[Disable IPv6 support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ipv6=no + ;; + *) + AC_MSG_RESULT(yes) + ipv6=yes + ;; + esac ], + + AC_RUN_IFELSE([AC_LANG_SOURCE([[ + /* are AF_INET6 and sockaddr_in6 available? */ + #include + #ifdef _WIN32 + #include + #include + #else + #include + #include + #if defined (__TANDEM) + # include + #endif + #endif + + int main(void) + { + struct sockaddr_in6 s; + (void)s; + return socket(AF_INET6, SOCK_STREAM, 0) < 0; + } + ]]) + ], + AC_MSG_RESULT(yes) + ipv6=yes, + AC_MSG_RESULT(no) + ipv6=no, + AC_MSG_RESULT(yes) + ipv6=yes +)) + +if test "$ipv6" = yes; then + curl_ipv6_msg="enabled" + AC_DEFINE(USE_IPV6, 1, [Define if you want to enable IPv6 support]) + IPV6_ENABLED=1 + AC_SUBST(IPV6_ENABLED) + + AC_MSG_CHECKING([if struct sockaddr_in6 has sin6_scope_id member]) + AC_COMPILE_IFELSE([ AC_LANG_PROGRAM([[ + #include + #ifdef _WIN32 + #include + #include + #else + #include + #if defined (__TANDEM) + # include + #endif + #endif + ]], [[ + struct sockaddr_in6 s; + s.sin6_scope_id = 0; + ]])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID, 1, [Define to 1 if struct sockaddr_in6 has the sin6_scope_id member]) + ], [ + AC_MSG_RESULT([no]) + ]) +fi + +dnl ********************************************************************** +dnl Check if the operating system allows programs to write to their own argv[] +dnl ********************************************************************** + +AC_MSG_CHECKING([if argv can be written to]) +CURL_RUN_IFELSE([[ +int main(int argc, char **argv) +{ +#ifdef _WIN32 + /* on Windows, writing to the argv does not hide the argument in + process lists so it can just be skipped */ + (void)argc; + (void)argv; + return 1; +#else + (void)argc; + argv[0][0] = ' '; + return (argv[0][0] == ' ')?0:1; +#endif +} +]],[ + curl_cv_writable_argv=yes +],[ + curl_cv_writable_argv=no +],[ + curl_cv_writable_argv=cross +]) +case $curl_cv_writable_argv in + yes) + AC_DEFINE(HAVE_WRITABLE_ARGV, 1, [Define this symbol if your OS supports changing the contents of argv]) + AC_MSG_RESULT(yes) + ;; + no) + AC_MSG_RESULT(no) + ;; + *) + AC_MSG_RESULT(no) + AC_MSG_WARN([the previous check could not be made default was used]) + ;; +esac + +dnl ********************************************************************** +dnl Check for GSS-API libraries +dnl ********************************************************************** + +dnl check for GSS-API stuff in the /usr as default + +GSSAPI_ROOT="/usr" +AC_ARG_WITH(gssapi-includes, + AS_HELP_STRING([--with-gssapi-includes=DIR], [Specify location of GSS-API headers]), [ + GSSAPI_INCS="-I$withval" + want_gss="yes" + ] +) + +AC_ARG_WITH(gssapi-libs, + AS_HELP_STRING([--with-gssapi-libs=DIR], [Specify location of GSS-API libs]), [ + GSSAPI_LIB_DIR="-L$withval" + want_gss="yes" + ] +) + +AC_ARG_WITH(gssapi, + AS_HELP_STRING([--with-gssapi=DIR], [Where to look for GSS-API]), [ + GSSAPI_ROOT="$withval" + if test x"$GSSAPI_ROOT" != xno; then + want_gss="yes" + if test x"$GSSAPI_ROOT" = xyes; then + dnl if yes, then use default root + GSSAPI_ROOT="/usr" + fi + fi + ] +) + +: ${KRB5CONFIG:="$GSSAPI_ROOT/bin/krb5-config"} + +save_CPPFLAGS="$CPPFLAGS" +AC_MSG_CHECKING([if GSS-API support is requested]) +if test x"$want_gss" = xyes; then + AC_MSG_RESULT(yes) + + if test $GSSAPI_ROOT != "/usr"; then + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi, $GSSAPI_ROOT/lib/pkgconfig) + else + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi) + fi + if test -z "$GSSAPI_INCS"; then + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + GSSAPI_INCS=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --cflags gssapi` + elif test "$PKGCONFIG" != "no"; then + GSSAPI_INCS=`$PKGCONFIG --cflags mit-krb5-gssapi` + elif test -f "$KRB5CONFIG"; then + GSSAPI_INCS=`$KRB5CONFIG --cflags gssapi` + elif test "$GSSAPI_ROOT" != "yes"; then + GSSAPI_INCS="-I$GSSAPI_ROOT/include" + fi + fi + + CPPFLAGS="$CPPFLAGS $GSSAPI_INCS" + + AC_CHECK_HEADER(gss.h, + [ + dnl found in the given dirs + AC_DEFINE(HAVE_GSSGNU, 1, [if you have GNU GSS]) + gnu_gss=yes + ], + [ + dnl not found, check Heimdal or MIT + AC_CHECK_HEADERS([gssapi/gssapi.h], [], [not_mit=1]) + AC_CHECK_HEADERS( + [gssapi/gssapi_generic.h gssapi/gssapi_krb5.h], + [], + [not_mit=1], + [ + AC_INCLUDES_DEFAULT + #ifdef HAVE_GSSAPI_GSSAPI_H + #include + #endif + ]) + if test "x$not_mit" = "x1"; then + dnl MIT not found, check for Heimdal + AC_CHECK_HEADER(gssapi.h, + [], + [ + dnl no header found, disabling GSS + want_gss=no + AC_MSG_WARN(disabling GSS-API support since no header files were found) + ] + ) + else + dnl MIT found + dnl check if we have a really old MIT Kerberos version (<= 1.2) + AC_MSG_CHECKING([if GSS-API headers declare GSS_C_NT_HOSTBASED_SERVICE]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + #include + #include + ]],[[ + gss_import_name( + (OM_uint32 *)0, + (gss_buffer_t)0, + GSS_C_NT_HOSTBASED_SERVICE, + (gss_name_t *)0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_DEFINE(HAVE_OLD_GSSMIT, 1, + [if you have an old MIT Kerberos version, lacking GSS_C_NT_HOSTBASED_SERVICE]) + ]) + fi + ] + ) +else + AC_MSG_RESULT(no) +fi +if test x"$want_gss" = xyes; then + AC_DEFINE(HAVE_GSSAPI, 1, [if you have GSS-API libraries]) + HAVE_GSSAPI=1 + curl_gss_msg="enabled (MIT Kerberos/Heimdal)" + link_pkgconfig='' + + if test -n "$gnu_gss"; then + curl_gss_msg="enabled (GNU GSS)" + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + LDFLAGSPC="$LDFLAGSPC $GSSAPI_LIB_DIR" + LIBS="-lgss $LIBS" + link_pkgconfig=1 + elif test -z "$GSSAPI_LIB_DIR"; then + case $host in + *-apple-*) + LIBS="-lgssapi_krb5 -lresolv $LIBS" + ;; + *) + if test $GSSAPI_ROOT != "/usr"; then + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi, $GSSAPI_ROOT/lib/pkgconfig) + else + CURL_CHECK_PKGCONFIG(mit-krb5-gssapi) + fi + if test -n "$host_alias" -a -f "$GSSAPI_ROOT/bin/$host_alias-krb5-config"; then + dnl krb5-config doesn't have --libs-only-L or similar, put everything + dnl into LIBS + gss_libs=`$GSSAPI_ROOT/bin/$host_alias-krb5-config --libs gssapi` + LIBS="$gss_libs $LIBS" + elif test "$PKGCONFIG" != "no"; then + gss_libs=`$PKGCONFIG --libs mit-krb5-gssapi` + LIBS="$gss_libs $LIBS" + link_pkgconfig=1 + elif test -f "$KRB5CONFIG"; then + dnl krb5-config doesn't have --libs-only-L or similar, put everything + dnl into LIBS + gss_libs=`$KRB5CONFIG --libs gssapi` + LIBS="$gss_libs $LIBS" + link_pkgconfig=1 + else + case $host in + *-hp-hpux*) + gss_libname="gss" + ;; + *) + gss_libname="gssapi" + ;; + esac + + if test "$GSSAPI_ROOT" != "yes"; then + LDFLAGS="$LDFLAGS -L$GSSAPI_ROOT/lib$libsuff" + LDFLAGSPC="$LDFLAGSPC -L$GSSAPI_ROOT/lib$libsuff" + LIBS="-l$gss_libname $LIBS" + else + LIBS="-l$gss_libname $LIBS" + fi + fi + ;; + esac + else + LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR" + LDFLAGSPC="$LDFLAGSPC $GSSAPI_LIB_DIR" + case $host in + *-hp-hpux*) + LIBS="-lgss $LIBS" + ;; + *) + LIBS="-lgssapi $LIBS" + ;; + esac + fi + if test -n "$link_pkgconfig"; then + if test -n "$gnu_gss"; then + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE gss" + elif test "x$not_mit" = "x1"; then + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE heimdal-gssapi" + else + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE mit-krb5-gssapi" + fi + fi +else + CPPFLAGS="$save_CPPFLAGS" +fi + +if test x"$want_gss" = xyes; then + AC_MSG_CHECKING([if we can link against GSS-API library]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([gss_init_sec_context]) + ],[ + AC_MSG_RESULT([yes]) + ],[ + AC_MSG_RESULT([no]) + AC_MSG_ERROR([--with-gssapi was specified, but a GSS-API library was not found.]) + ]) +fi + +build_libstubgss=no +if test x"$want_gss" = "xyes"; then + build_libstubgss=yes +fi + +AM_CONDITIONAL(BUILD_STUB_GSS, test "x$build_libstubgss" = "xyes") + +dnl ------------------------------------------------------------- +dnl parse --with-default-ssl-backend so it can be validated below +dnl ------------------------------------------------------------- + +DEFAULT_SSL_BACKEND=no +VALID_DEFAULT_SSL_BACKEND= +AC_ARG_WITH(default-ssl-backend, +AS_HELP_STRING([--with-default-ssl-backend=NAME],[Use NAME as default SSL backend]) +AS_HELP_STRING([--without-default-ssl-backend],[Use implicit default SSL backend]), + [DEFAULT_SSL_BACKEND=$withval]) +case "$DEFAULT_SSL_BACKEND" in + no) + dnl --without-default-ssl-backend option used + ;; + default|yes) + dnl --with-default-ssl-backend option used without name + AC_MSG_ERROR([The name of the default SSL backend is required.]) + ;; + *) + dnl --with-default-ssl-backend option used with name + AC_SUBST(DEFAULT_SSL_BACKEND) + dnl needs to be validated below + VALID_DEFAULT_SSL_BACKEND=no + ;; +esac + +CURL_WITH_SCHANNEL +CURL_WITH_SECURETRANSPORT +CURL_WITH_AMISSL +CURL_WITH_OPENSSL +CURL_WITH_GNUTLS +CURL_WITH_MBEDTLS +CURL_WITH_WOLFSSL +CURL_WITH_BEARSSL +CURL_WITH_RUSTLS + +dnl link required libraries for USE_WIN32_CRYPTO or USE_SCHANNEL +if test "x$USE_WIN32_CRYPTO" = "x1" -o "x$USE_SCHANNEL" = "x1"; then + LIBS="-ladvapi32 -lcrypt32 $LIBS" +fi + +dnl link bcrypt for BCryptGenRandom() (used when building for Vista or newer) +if test "x$curl_cv_native_windows" = "xyes"; then + LIBS="-lbcrypt $LIBS" +fi + +case "x$SSL_DISABLED$OPENSSL_ENABLED$GNUTLS_ENABLED$MBEDTLS_ENABLED$WOLFSSL_ENABLED$SCHANNEL_ENABLED$SECURETRANSPORT_ENABLED$BEARSSL_ENABLED$RUSTLS_ENABLED" in + x) + AC_MSG_ERROR([TLS not detected, you will not be able to use HTTPS, FTPS, NTLM and more. +Use --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl or --with-rustls to address this.]) + ;; + x1) + # one SSL backend is enabled + AC_SUBST(SSL_ENABLED) + SSL_ENABLED="1" + AC_MSG_NOTICE([built with one SSL backend]) + ;; + xD) + # explicitly built without TLS + ;; + xD*) + AC_MSG_ERROR([--without-ssl has been set together with an explicit option to use an ssl library +(e.g. --with-openssl, --with-gnutls, --with-wolfssl, --with-mbedtls, --with-schannel, --with-secure-transport, --with-amissl, --with-bearssl, --with-rustls). +Since these are conflicting parameters, verify which is the desired one and drop the other.]) + ;; + *) + # more than one SSL backend is enabled + AC_SUBST(SSL_ENABLED) + SSL_ENABLED="1" + AC_SUBST(CURL_WITH_MULTI_SSL) + CURL_WITH_MULTI_SSL="1" + AC_DEFINE(CURL_WITH_MULTI_SSL, 1, [built with multiple SSL backends]) + AC_MSG_NOTICE([built with multiple SSL backends]) + ;; +esac + +if test -n "$ssl_backends"; then + curl_ssl_msg="enabled ($ssl_backends)" +fi + +if test no = "$VALID_DEFAULT_SSL_BACKEND"; then + if test -n "$SSL_ENABLED"; then + AC_MSG_ERROR([Default SSL backend $DEFAULT_SSL_BACKEND not enabled!]) + else + AC_MSG_ERROR([Default SSL backend requires SSL!]) + fi +elif test yes = "$VALID_DEFAULT_SSL_BACKEND"; then + AC_DEFINE_UNQUOTED([CURL_DEFAULT_SSL_BACKEND], ["$DEFAULT_SSL_BACKEND"], [Default SSL backend]) +fi + +dnl ********************************************************************** +dnl Check for the CA bundle +dnl ********************************************************************** + +if test -n "$check_for_ca_bundle"; then + CURL_CHECK_CA_BUNDLE + CURL_CHECK_CA_EMBED +fi + +AM_CONDITIONAL(CURL_CA_EMBED_SET, test "x$CURL_CA_EMBED" != "x") + +dnl ---------------------- +dnl check unsafe CA search +dnl ---------------------- + +if test "$curl_cv_native_windows" = "yes"; then + AC_MSG_CHECKING([whether to enable unsafe CA bundle search in PATH on Windows]) + AC_ARG_ENABLE(ca-search, +AS_HELP_STRING([--enable-ca-search],[Enable unsafe CA bundle search in PATH on Windows (default)]) +AS_HELP_STRING([--disable-ca-search],[Disable unsafe CA bundle search in PATH on Windows]), + [ case "$enableval" in + no) + AC_MSG_RESULT([no]) + AC_DEFINE(CURL_DISABLE_CA_SEARCH, 1, [If unsafe CA bundle search in PATH on Windows is disabled]) + ;; + *) + AC_MSG_RESULT([yes]) + ;; + esac ], + AC_MSG_RESULT([yes]) + ) +fi + +dnl -------------------- +dnl check safe CA search +dnl -------------------- + +if test "$curl_cv_native_windows" = "yes"; then + AC_MSG_CHECKING([whether to enable safe CA bundle search (within the curl tool directory) on Windows]) + AC_ARG_ENABLE(ca-search-safe, +AS_HELP_STRING([--enable-ca-search-safe],[Enable safe CA bundle search]) +AS_HELP_STRING([--disable-ca-search-safe],[Disable safe CA bundle search (default)]), + [ case "$enableval" in + yes) + AC_MSG_RESULT([yes]) + AC_DEFINE(CURL_CA_SEARCH_SAFE, 1, [If safe CA bundle search is enabled]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac ], + AC_MSG_RESULT([no]) + ) +fi + +dnl ********************************************************************** +dnl Check for libpsl +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for LIBPSL files & libraries. +OPT_LIBPSL=off +AC_ARG_WITH(libpsl,dnl +AS_HELP_STRING([--with-libpsl=PATH],[Where to look for libpsl, PATH points to the LIBPSL installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-libpsl], [disable LIBPSL]), + OPT_LIBPSL=$withval) + +if test X"$OPT_LIBPSL" != Xno; then + dnl backup the pre-libpsl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBPSL" in + yes|off) + dnl --with-libpsl (without path) used + CURL_CHECK_PKGCONFIG(libpsl) + + if test "$PKGCONFIG" != "no"; then + LIB_PSL=`$PKGCONFIG --libs-only-l libpsl` + LD_PSL=`$PKGCONFIG --libs-only-L libpsl` + CPP_PSL=`$PKGCONFIG --cflags-only-I libpsl` + else + dnl no libpsl pkg-config found + LIB_PSL="-lpsl" + fi + + ;; + *) + dnl use the given --with-libpsl spot + LIB_PSL="-lpsl" + PREFIX_PSL=$OPT_LIBPSL + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_PSL"; then + LD_PSL=-L${PREFIX_PSL}/lib$libsuff + CPP_PSL=-I${PREFIX_PSL}/include + fi + + LDFLAGS="$LDFLAGS $LD_PSL" + LDFLAGSPC="$LDFLAGSPC $LD_PSL" + CPPFLAGS="$CPPFLAGS $CPP_PSL" + LIBS="$LIB_PSL $LIBS" + + AC_CHECK_LIB(psl, psl_builtin, + [ + AC_CHECK_HEADERS(libpsl.h, + curl_psl_msg="enabled" + LIBPSL_ENABLED=1 + AC_DEFINE(USE_LIBPSL, 1, [if libpsl is in use]) + AC_SUBST(USE_LIBPSL, [1]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libpsl" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + if test "$LIBPSL_ENABLED" != "1"; then + AC_MSG_ERROR([libpsl libs and/or directories were not found where specified!]) + fi +fi +AM_CONDITIONAL([USE_LIBPSL], [test "$curl_psl_msg" = "enabled"]) + + +dnl ********************************************************************** +dnl Check for libgsasl +dnl ********************************************************************** + +AC_ARG_WITH(libgsasl, + AS_HELP_STRING([--without-libgsasl], + [disable libgsasl support for SCRAM]), + with_libgsasl=$withval, + with_libgsasl=yes) +if test $with_libgsasl != "no"; then + AC_SEARCH_LIBS(gsasl_init, gsasl, + [curl_gsasl_msg="enabled"; + AC_DEFINE([USE_GSASL], [1], [GSASL support enabled]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libgsasl" + ], + [curl_gsasl_msg="no (libgsasl not found)"; + AC_MSG_WARN([libgsasl was not found]) + ] + ) +fi +AM_CONDITIONAL([USE_GSASL], [test "$curl_gsasl_msg" = "enabled"]) + +AC_ARG_WITH(libmetalink,, + AC_MSG_ERROR([--with-libmetalink and --without-libmetalink no longer work!])) + +dnl ********************************************************************** +dnl Check for the presence of libssh2 libraries and headers +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for libssh2 files & libraries. +OPT_LIBSSH2=off +AC_ARG_WITH(libssh2,dnl +AS_HELP_STRING([--with-libssh2=PATH],[Where to look for libssh2, PATH points to the libssh2 installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-libssh2], [enable libssh2]), + OPT_LIBSSH2=$withval, OPT_LIBSSH2=no) + + +OPT_LIBSSH=off +AC_ARG_WITH(libssh,dnl +AS_HELP_STRING([--with-libssh=PATH],[Where to look for libssh, PATH points to the libssh installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-libssh], [enable libssh]), + OPT_LIBSSH=$withval, OPT_LIBSSH=no) + +OPT_WOLFSSH=off +AC_ARG_WITH(wolfssh,dnl +AS_HELP_STRING([--with-wolfssh=PATH],[Where to look for wolfssh, PATH points to the wolfSSH installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--with-wolfssh], [enable wolfssh]), + OPT_WOLFSSH=$withval, OPT_WOLFSSH=no) + +if test X"$OPT_LIBSSH2" != Xno; then + dnl backup the pre-libssh2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH2" in + yes) + dnl --with-libssh2 (without path) used + CURL_CHECK_PKGCONFIG(libssh2) + + if test "$PKGCONFIG" != "no"; then + LIB_SSH2=`$PKGCONFIG --libs-only-l libssh2` + LD_SSH2=`$PKGCONFIG --libs-only-L libssh2` + CPP_SSH2=`$PKGCONFIG --cflags-only-I libssh2` + version=`$PKGCONFIG --modversion libssh2` + DIR_SSH2=`echo $LD_SSH2 | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-libssh2 option given, just check default places + ;; + *) + dnl use the given --with-libssh2 spot + PREFIX_SSH2=$OPT_LIBSSH2 + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_SSH2"; then + LIB_SSH2="-lssh2" + LD_SSH2=-L${PREFIX_SSH2}/lib$libsuff + CPP_SSH2=-I${PREFIX_SSH2}/include + DIR_SSH2=${PREFIX_SSH2}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH2" + LDFLAGSPC="$LDFLAGSPC $LD_SSH2" + CPPFLAGS="$CPPFLAGS $CPP_SSH2" + LIBS="$LIB_SSH2 $LIBS" + + dnl check for function added in libssh2 version 1.0 + AC_CHECK_LIB(ssh2, libssh2_session_block_directions) + + AC_CHECK_HEADER(libssh2.h, + curl_ssh_msg="enabled (libssh2)" + LIBSSH2_ENABLED=1 + AC_DEFINE(USE_LIBSSH2, 1, [if libssh2 is in use]) + AC_SUBST(USE_LIBSSH2, [1]) + ) + + if test X"$OPT_LIBSSH2" != Xoff && + test "$LIBSSH2_ENABLED" != "1"; then + AC_MSG_ERROR([libssh2 libs and/or directories were not found where specified!]) + fi + + if test "$LIBSSH2_ENABLED" = "1"; then + if test -n "$DIR_SSH2"; then + dnl when the libssh2 shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_SSH2 to CURL_LIBRARY_PATH]) + fi + fi + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libssh2" + else + dnl no libssh2, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_LIBSSH" != Xno; then + dnl backup the pre-libssh variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBSSH" in + yes) + dnl --with-libssh (without path) used + CURL_CHECK_PKGCONFIG(libssh) + + if test "$PKGCONFIG" != "no"; then + LIB_SSH=`$PKGCONFIG --libs-only-l libssh` + LD_SSH=`$PKGCONFIG --libs-only-L libssh` + CPP_SSH=`$PKGCONFIG --cflags-only-I libssh` + version=`$PKGCONFIG --modversion libssh` + DIR_SSH=`echo $LD_SSH | $SED -e 's/^-L//'` + fi + + ;; + off) + dnl no --with-libssh option given, just check default places + ;; + *) + dnl use the given --with-libssh spot + PREFIX_SSH=$OPT_LIBSSH + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_SSH"; then + LIB_SSH="-lssh" + LD_SSH=-L${PREFIX_SSH}/lib$libsuff + CPP_SSH=-I${PREFIX_SSH}/include + DIR_SSH=${PREFIX_SSH}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_SSH" + LDFLAGSPC="$LDFLAGSPC $LD_SSH" + CPPFLAGS="$CPPFLAGS $CPP_SSH" + LIBS="$LIB_SSH $LIBS" + + AC_CHECK_LIB(ssh, ssh_new) + + AC_CHECK_HEADER(libssh/libssh.h, + curl_ssh_msg="enabled (libssh)" + LIBSSH_ENABLED=1 + AC_DEFINE(USE_LIBSSH, 1, [if libssh is in use]) + AC_SUBST(USE_LIBSSH, [1]) + ) + + if test X"$OPT_LIBSSH" != Xoff && + test "$LIBSSH_ENABLED" != "1"; then + AC_MSG_ERROR([libssh libs and/or directories were not found where specified!]) + fi + + if test "$LIBSSH_ENABLED" = "1"; then + if test "$curl_cv_native_windows" = "yes"; then + dnl for if_nametoindex + LIBS="-liphlpapi $LIBS" + fi + if test -n "$DIR_SSH"; then + dnl when the libssh shared libs were found in a path that the run-time + dnl linker doesn't search through, we need to add it to CURL_LIBRARY_PATH + dnl to prevent further configure tests to fail due to this + + if test "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_SSH" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_SSH to CURL_LIBRARY_PATH]) + fi + fi + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libssh" + else + dnl no libssh, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + fi +elif test X"$OPT_WOLFSSH" != Xno; then + dnl backup the pre-wolfssh variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + if test "$OPT_WOLFSSH" != yes; then + WOLFCONFIG="$OPT_WOLFSSH/bin/wolfssh-config" + WOLFSSH_LIBS=`$WOLFCONFIG --libs` + LDFLAGS="$LDFLAGS $WOLFSSH_LIBS" + LDFLAGSPC="$LDFLAGSPC $WOLFSSH_LIBS" + CPPFLAGS="$CPPFLAGS `$WOLFCONFIG --cflags`" + fi + + AC_CHECK_LIB(wolfssh, wolfSSH_Init) + + AC_CHECK_HEADERS(wolfssh/ssh.h, + curl_ssh_msg="enabled (wolfSSH)" + WOLFSSH_ENABLED=1 + AC_DEFINE(USE_WOLFSSH, 1, [if wolfSSH is in use]) + AC_SUBST(USE_WOLFSSH, [1]) + ) +fi + +dnl ********************************************************************** +dnl Check for the presence of LIBRTMP libraries and headers +dnl ********************************************************************** + +dnl Default to compiler & linker defaults for LIBRTMP files & libraries. +OPT_LIBRTMP=off +AC_ARG_WITH(librtmp,dnl +AS_HELP_STRING([--with-librtmp=PATH],[Where to look for librtmp, PATH points to the LIBRTMP installation; when possible, set the PKG_CONFIG_PATH environment variable instead of using this option]) +AS_HELP_STRING([--without-librtmp], [disable LIBRTMP]), + OPT_LIBRTMP=$withval) + +if test X"$OPT_LIBRTMP" != Xno; then + dnl backup the pre-librtmp variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + case "$OPT_LIBRTMP" in + yes) + dnl --with-librtmp (without path) used + CURL_CHECK_PKGCONFIG(librtmp) + + if test "$PKGCONFIG" != "no"; then + LIB_RTMP=`$PKGCONFIG --libs-only-l librtmp` + LD_RTMP=`$PKGCONFIG --libs-only-L librtmp` + CPP_RTMP=`$PKGCONFIG --cflags-only-I librtmp` + version=`$PKGCONFIG --modversion librtmp` + DIR_RTMP=`echo $LD_RTMP | $SED -e 's/^-L//'` + else + dnl To avoid link errors, we do not allow --librtmp without + dnl a pkgconfig file + AC_MSG_ERROR([--librtmp was specified but could not find librtmp pkgconfig file.]) + fi + + ;; + off) + dnl no --with-librtmp option given, just check default places + LIB_RTMP="-lrtmp" + ;; + *) + dnl use the given --with-librtmp spot + LIB_RTMP="-lrtmp" + PREFIX_RTMP=$OPT_LIBRTMP + ;; + esac + + dnl if given with a prefix, we set -L and -I based on that + if test -n "$PREFIX_RTMP"; then + LD_RTMP=-L${PREFIX_RTMP}/lib$libsuff + CPP_RTMP=-I${PREFIX_RTMP}/include + DIR_RTMP=${PREFIX_RTMP}/lib$libsuff + fi + + LDFLAGS="$LDFLAGS $LD_RTMP" + LDFLAGSPC="$LDFLAGSPC $LD_RTMP" + CPPFLAGS="$CPPFLAGS $CPP_RTMP" + LIBS="$LIB_RTMP $LIBS" + + AC_CHECK_LIB(rtmp, RTMP_Init, + [ + AC_CHECK_HEADERS(librtmp/rtmp.h, + curl_rtmp_msg="enabled (librtmp)" + LIBRTMP_ENABLED=1 + AC_DEFINE(USE_LIBRTMP, 1, [if librtmp is in use]) + AC_SUBST(USE_LIBRTMP, [1]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE librtmp" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + if test X"$OPT_LIBRTMP" != Xoff && + test "$LIBRTMP_ENABLED" != "1"; then + AC_MSG_ERROR([librtmp libs and/or directories were not found where specified!]) + fi +fi + +dnl ********************************************************************** +dnl Check for linker switch for versioned symbols +dnl ********************************************************************** + +versioned_symbols_flavour= +AC_MSG_CHECKING([whether versioned symbols are wanted]) +AC_ARG_ENABLE(versioned-symbols, +AS_HELP_STRING([--enable-versioned-symbols], [Enable versioned symbols in shared library]) +AS_HELP_STRING([--disable-versioned-symbols], [Disable versioned symbols in shared library]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + ;; + *) + AC_MSG_RESULT(yes) + AC_MSG_CHECKING([if libraries can be versioned]) + GLD=`$LD --help < /dev/null 2>/dev/null | grep version-script` + if test -z "$GLD"; then + AC_MSG_RESULT(no) + AC_MSG_WARN([You need an ld version supporting the --version-script option]) + else + AC_MSG_RESULT(yes) + if test "x$enableval" != "xyes"; then + versioned_symbols_flavour="$enableval" + elif test "x$CURL_WITH_MULTI_SSL" = "x1"; then + versioned_symbols_flavour="MULTISSL_" + elif test "x$OPENSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="OPENSSL_" + elif test "x$MBEDTLS_ENABLED" = "x1"; then + versioned_symbols_flavour="MBEDTLS_" + elif test "x$BEARSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="BEARSSL_" + elif test "x$WOLFSSL_ENABLED" = "x1"; then + versioned_symbols_flavour="WOLFSSL_" + elif test "x$GNUTLS_ENABLED" = "x1"; then + versioned_symbols_flavour="GNUTLS_" + elif test "x$RUSTLS_ENABLED" = "x1"; then + versioned_symbols_flavour="RUSTLS_" + else + versioned_symbols_flavour="" + fi + versioned_symbols="yes" + fi + ;; + + esac +], [ + AC_MSG_RESULT(no) +] +) + +AC_SUBST([CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX], ["$versioned_symbols_flavour"]) +AC_SUBST([CURL_LIBCURL_VERSIONED_SYMBOLS_SONAME], ["4"]) dnl Keep in sync with VERSIONCHANGE - VERSIONDEL in lib/Makefile.soname +AM_CONDITIONAL([CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS], + [test "x$versioned_symbols" = 'xyes']) + +dnl ---------------------------- +dnl check Windows Unicode option +dnl ---------------------------- + +want_winuni="no" +if test "$curl_cv_native_windows" = "yes"; then + AC_MSG_CHECKING([whether to enable Windows Unicode (Windows native builds only)]) + AC_ARG_ENABLE(windows-unicode, +AS_HELP_STRING([--enable-windows-unicode],[Enable Windows Unicode]) +AS_HELP_STRING([--disable-windows-unicode],[Disable Windows Unicode (default)]), + [ case "$enableval" in + yes) + CPPFLAGS="${CPPFLAGS} -DUNICODE -D_UNICODE" + want_winuni="yes" + AC_MSG_RESULT([yes]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac ], + AC_MSG_RESULT([no]) + ) +fi + +AM_CONDITIONAL([USE_UNICODE], [test "$want_winuni" = "yes"]) + +dnl ------------------------------------------------- +dnl check WinIDN option before other IDN libraries +dnl ------------------------------------------------- + +tst_links_winidn='no' +if test "$curl_cv_native_windows" = 'yes'; then + AC_MSG_CHECKING([whether to enable Windows native IDN (Windows native builds only)]) + OPT_WINIDN="default" + AC_ARG_WITH(winidn, +AS_HELP_STRING([--with-winidn=PATH],[enable Windows native IDN]) +AS_HELP_STRING([--without-winidn], [disable Windows native IDN]), + OPT_WINIDN=$withval) + case "$OPT_WINIDN" in + no|default) + dnl --without-winidn option used or configure option not specified + want_winidn="no" + AC_MSG_RESULT([no]) + ;; + yes) + dnl --with-winidn option used without path + want_winidn="yes" + want_winidn_path="default" + AC_MSG_RESULT([yes]) + ;; + *) + dnl --with-winidn option used with path + want_winidn="yes" + want_winidn_path="$withval" + AC_MSG_RESULT([yes ($withval)]) + ;; + esac + + if test "$want_winidn" = "yes"; then + dnl WinIDN library support has been requested + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LDFLAGSPC="$LDFLAGSPC" + clean_LIBS="$LIBS" + WINIDN_LIBS="-lnormaliz" + WINIDN_CPPFLAGS="" + # + if test "$want_winidn_path" != "default"; then + dnl path has been specified + dnl pkg-config not available or provides no info + WINIDN_LDFLAGS="-L$want_winidn_path/lib$libsuff" + WINIDN_CPPFLAGS="-I$want_winidn_path/include" + fi + # + CPPFLAGS="$CPPFLAGS $WINIDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $WINIDN_LDFLAGS" + LDFLAGSPC="$LDFLAGSPC $WINIDN_LDFLAGS" + LIBS="$WINIDN_LIBS $LIBS" + # + AC_MSG_CHECKING([if IdnToUnicode can be linked]) + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #if (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x600) && \ + (!defined(WINVER) || WINVER < 0x600) + WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, + const WCHAR *lpASCIICharStr, + int cchASCIIChar, + WCHAR *lpUnicodeCharStr, + int cchUnicodeChar); + #endif + IdnToUnicode(0, NULL, 0, NULL, 0); + ]]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_winidn="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_winidn="no" + ]) + # + if test "$tst_links_winidn" = "yes"; then + AC_DEFINE(USE_WIN32_IDN, 1, [Define to 1 if you have the `normaliz' (WinIDN) library (-lnormaliz).]) + AC_SUBST([IDN_ENABLED], [1]) + curl_idn_msg="enabled (Windows-native)" + else + AC_MSG_WARN([Cannot find libraries for IDN support: IDN disabled]) + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LDFLAGSPC="$clean_LDFLAGSPC" + LIBS="$clean_LIBS" + fi + fi +fi + +dnl ********************************************************************** +dnl Check for the presence of AppleIDN +dnl ********************************************************************** + +tst_links_appleidn='no' +case $host in + *-apple-*) + AC_MSG_CHECKING([whether to build with Apple IDN]) + OPT_IDN="default" + AC_ARG_WITH(apple-idn, +AS_HELP_STRING([--with-apple-idn],[Enable AppleIDN]) +AS_HELP_STRING([--without-apple-idn],[Disable AppleIDN]), + [OPT_IDN=$withval]) + case "$OPT_IDN" in + yes) + dnl --with-apple-idn option used + AC_MSG_RESULT([yes, check]) + AC_CHECK_LIB(icucore, uidna_openUTS46, + [ + AC_CHECK_HEADERS(unicode/uidna.h, + curl_idn_msg="enabled (AppleIDN)" + AC_DEFINE(USE_APPLE_IDN, 1, [if AppleIDN]) + AC_SUBST(USE_APPLE_IDN, [1]) + AC_SUBST([IDN_ENABLED], [1]) + LIBS="-licucore -liconv $LIBS" + tst_links_appleidn='yes' + ) + ]) + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac + ;; +esac + +dnl ********************************************************************** +dnl Check for the presence of libidn2 +dnl ********************************************************************** + +AC_MSG_CHECKING([whether to build with libidn2]) +OPT_IDN="default" +AC_ARG_WITH(libidn2, +AS_HELP_STRING([--with-libidn2=PATH],[Enable libidn2 usage]) +AS_HELP_STRING([--without-libidn2],[Disable libidn2 usage]), + [OPT_IDN=$withval]) +if test "x$tst_links_winidn" = "xyes"; then + want_idn="no" + AC_MSG_RESULT([no (using WinIDN instead)]) +elif test "x$tst_links_appleidn" = "xyes"; then + want_idn="no" + AC_MSG_RESULT([no (using AppleIDN instead)]) +else + case "$OPT_IDN" in + no) + dnl --without-libidn2 option used + want_idn="no" + AC_MSG_RESULT([no]) + ;; + default) + dnl configure option not specified + want_idn="yes" + want_idn_path="default" + AC_MSG_RESULT([(assumed) yes]) + ;; + yes) + dnl --with-libidn2 option used without path + want_idn="yes" + want_idn_path="default" + AC_MSG_RESULT([yes]) + ;; + *) + dnl --with-libidn2 option used with path + want_idn="yes" + want_idn_path="$withval" + AC_MSG_RESULT([yes ($withval)]) + ;; + esac +fi + +if test "$want_idn" = "yes"; then + dnl idn library support has been requested + clean_CPPFLAGS="$CPPFLAGS" + clean_LDFLAGS="$LDFLAGS" + clean_LDFLAGSPC="$LDFLAGSPC" + clean_LIBS="$LIBS" + PKGCONFIG="no" + # + if test "$want_idn_path" != "default"; then + dnl path has been specified + IDN_PCDIR="$want_idn_path/lib$libsuff/pkgconfig" + CURL_CHECK_PKGCONFIG(libidn2, [$IDN_PCDIR]) + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=`CURL_EXPORT_PCDIR([$IDN_PCDIR]) dnl + $PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + dnl pkg-config not available or provides no info + IDN_LIBS="-lidn2" + IDN_LDFLAGS="-L$want_idn_path/lib$libsuff" + IDN_CPPFLAGS="-I$want_idn_path/include" + IDN_DIR="$want_idn_path/lib$libsuff" + fi + else + dnl path not specified + CURL_CHECK_PKGCONFIG(libidn2) + if test "$PKGCONFIG" != "no"; then + IDN_LIBS=`$PKGCONFIG --libs-only-l libidn2 2>/dev/null` + IDN_LDFLAGS=`$PKGCONFIG --libs-only-L libidn2 2>/dev/null` + IDN_CPPFLAGS=`$PKGCONFIG --cflags-only-I libidn2 2>/dev/null` + IDN_DIR=`echo $IDN_LDFLAGS | $SED -e 's/^-L//'` + else + dnl pkg-config not available or provides no info + IDN_LIBS="-lidn2" + fi + fi + # + if test "$PKGCONFIG" != "no"; then + AC_MSG_NOTICE([pkg-config: IDN_LIBS: "$IDN_LIBS"]) + AC_MSG_NOTICE([pkg-config: IDN_LDFLAGS: "$IDN_LDFLAGS"]) + AC_MSG_NOTICE([pkg-config: IDN_CPPFLAGS: "$IDN_CPPFLAGS"]) + AC_MSG_NOTICE([pkg-config: IDN_DIR: "$IDN_DIR"]) + else + AC_MSG_NOTICE([IDN_LIBS: "$IDN_LIBS"]) + AC_MSG_NOTICE([IDN_LDFLAGS: "$IDN_LDFLAGS"]) + AC_MSG_NOTICE([IDN_CPPFLAGS: "$IDN_CPPFLAGS"]) + AC_MSG_NOTICE([IDN_DIR: "$IDN_DIR"]) + fi + # + CPPFLAGS="$CPPFLAGS $IDN_CPPFLAGS" + LDFLAGS="$LDFLAGS $IDN_LDFLAGS" + LDFLAGSPC="$LDFLAGSPC $IDN_LDFLAGS" + LIBS="$IDN_LIBS $LIBS" + # + AC_MSG_CHECKING([if idn2_lookup_ul can be linked]) + AC_LINK_IFELSE([ + AC_LANG_FUNC_LINK_TRY([idn2_lookup_ul]) + ],[ + AC_MSG_RESULT([yes]) + tst_links_libidn="yes" + ],[ + AC_MSG_RESULT([no]) + tst_links_libidn="no" + ]) + # + AC_CHECK_HEADERS( idn2.h ) + + if test "$tst_links_libidn" = "yes"; then + AC_DEFINE(HAVE_LIBIDN2, 1, [Define to 1 if you have the `idn2' library (-lidn2).]) + dnl different versions of libidn have different setups of these: + + AC_SUBST([IDN_ENABLED], [1]) + curl_idn_msg="enabled (libidn2)" + if test -n "$IDN_DIR" -a "x$cross_compiling" != "xyes"; then + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$IDN_DIR" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $IDN_DIR to CURL_LIBRARY_PATH]) + fi + LIBCURL_PC_REQUIRES_PRIVATE="libidn2 $LIBCURL_PC_REQUIRES_PRIVATE" + else + AC_MSG_WARN([Cannot find libidn2]) + CPPFLAGS="$clean_CPPFLAGS" + LDFLAGS="$clean_LDFLAGS" + LDFLAGSPC="$clean_LDFLAGSPC" + LIBS="$clean_LIBS" + want_idn="no" + fi +fi + +dnl ********************************************************************** +dnl Check for nghttp2 +dnl ********************************************************************** + +OPT_H2="yes" + +if test "x$disable_http" = "xyes" -o X"$want_hyper" != Xno; then + # without HTTP or with Hyper, nghttp2 is no use + OPT_H2="no" +fi + +AC_ARG_WITH(nghttp2, +AS_HELP_STRING([--with-nghttp2=PATH],[Enable nghttp2 usage]) +AS_HELP_STRING([--without-nghttp2],[Disable nghttp2 usage]), + [OPT_H2=$withval]) +case "$OPT_H2" in + no) + dnl --without-nghttp2 option used + want_nghttp2="no" + ;; + yes) + dnl --with-nghttp2 option used without path + want_nghttp2="default" + want_nghttp2_path="" + want_nghttp2_pkg_config_path="" + ;; + *) + dnl --with-nghttp2 option used with path + want_nghttp2="yes" + want_nghttp2_path="$withval" + want_nghttp2_pkg_config_path="$withval/lib/pkgconfig" + ;; +esac + +if test X"$want_nghttp2" != Xno; then + dnl backup the pre-nghttp2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libnghttp2, $want_nghttp2_pkg_config_path) + + if test "$PKGCONFIG" != "no"; then + LIB_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) + $PKGCONFIG --libs-only-l libnghttp2` + AC_MSG_NOTICE([-l is $LIB_H2]) + + CPP_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) dnl + $PKGCONFIG --cflags-only-I libnghttp2` + AC_MSG_NOTICE([-I is $CPP_H2]) + + LD_H2=`CURL_EXPORT_PCDIR([$want_nghttp2_pkg_config_path]) + $PKGCONFIG --libs-only-L libnghttp2` + AC_MSG_NOTICE([-L is $LD_H2]) + + DIR_H2=`echo $LD_H2 | $SED -e 's/^-L//'` + elif test x"$want_nghttp2_path" != x; then + LIB_H2="-lnghttp2" + LD_H2=-L${want_nghttp2_path}/lib$libsuff + CPP_H2=-I${want_nghttp2_path}/include + DIR_H2=${want_nghttp2_path}/lib$libsuff + elif test X"$want_nghttp2" != Xdefault; then + dnl no nghttp2 pkg-config found and no custom directory specified, + dnl deal with it + AC_MSG_ERROR([--with-nghttp2 was specified but could not find libnghttp2 pkg-config file.]) + else + LIB_H2="-lnghttp2" + fi + + LDFLAGS="$LDFLAGS $LD_H2" + LDFLAGSPC="$LDFLAGSPC $LD_H2" + CPPFLAGS="$CPPFLAGS $CPP_H2" + LIBS="$LIB_H2 $LIBS" + + # use nghttp2_session_get_stream_local_window_size to require nghttp2 + # >= 1.15.0 + AC_CHECK_LIB(nghttp2, nghttp2_session_get_stream_local_window_size, + [ + AC_CHECK_HEADERS(nghttp2/nghttp2.h, + curl_h2_msg="enabled (nghttp2)" + NGHTTP2_ENABLED=1 + AC_DEFINE(USE_NGHTTP2, 1, [if nghttp2 is in use]) + AC_SUBST(USE_NGHTTP2, [1]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libnghttp2" + ) + + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_H2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_H2 to CURL_LIBRARY_PATH]) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) +fi + +dnl ********************************************************************** +dnl Check for ngtcp2 (QUIC) +dnl ********************************************************************** + +OPT_TCP2="no" + +if test "x$disable_http" = "xyes"; then + # without HTTP, ngtcp2 is no use + OPT_TCP2="no" +fi + +AC_ARG_WITH(ngtcp2, +AS_HELP_STRING([--with-ngtcp2=PATH],[Enable ngtcp2 usage]) +AS_HELP_STRING([--without-ngtcp2],[Disable ngtcp2 usage]), + [OPT_TCP2=$withval]) +case "$OPT_TCP2" in + no) + dnl --without-ngtcp2 option used + want_tcp2="no" + ;; + yes) + dnl --with-ngtcp2 option used without path + want_tcp2="default" + want_tcp2_path="" + ;; + *) + dnl --with-ngtcp2 option used with path + want_tcp2="yes" + want_tcp2_path="$withval/lib/pkgconfig" + ;; +esac + +curl_tcp2_msg="no (--with-ngtcp2)" +if test X"$want_tcp2" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-ngtcp2 a no-no]) + fi + + dnl backup the pre-ngtcp2 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2, $want_tcp2_path) + + if test "$PKGCONFIG" != "no"; then + LIB_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2` + AC_MSG_NOTICE([-l is $LIB_TCP2]) + + CPP_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2` + AC_MSG_NOTICE([-I is $CPP_TCP2]) + + LD_TCP2=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2` + AC_MSG_NOTICE([-L is $LD_TCP2]) + + LDFLAGS="$LDFLAGS $LD_TCP2" + LDFLAGSPC="$LDFLAGSPC $LD_TCP2" + CPPFLAGS="$CPPFLAGS $CPP_TCP2" + LIBS="$LIB_TCP2 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_TCP2=`echo $LD_TCP2 | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2, ngtcp2_conn_client_new_versioned, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2, 1, [if ngtcp2 is in use]) + AC_SUBST(USE_NGTCP2, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_TCP2" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_TCP2 to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libngtcp2" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2 pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2 pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" != "x1"; then + dnl backup the pre-ngtcp2_crypto_quictls variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_quictls, $want_tcp2_path) + + if test "$PKGCONFIG" != "no"; then + LIB_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_QUICTLS]) + + CPP_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_QUICTLS]) + + LD_NGTCP2_CRYPTO_QUICTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_quictls` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_QUICTLS]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_QUICTLS" + LDFLAGSPC="$LDFLAGSPC $LD_NGTCP2_CRYPTO_QUICTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_QUICTLS" + LIBS="$LIB_NGTCP2_CRYPTO_QUICTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_QUICTLS=`echo $LD_NGTCP2_CRYPTO_QUICTLS | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_quictls, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_QUICTLS, 1, [if ngtcp2_crypto_quictls is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_QUICTLS, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_QUICTLS" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_QUICTLS to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libngtcp2_crypto_quictls" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_quictls pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_quictls pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$OPENSSL_ENABLED" = "x1" -a "x$OPENSSL_IS_BORINGSSL" = "x1"; then + dnl backup the pre-ngtcp2_crypto_boringssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_boringssl, $want_tcp2_path) + + if test "$PKGCONFIG" != "no"; then + LIB_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_BORINGSSL]) + + CPP_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_BORINGSSL]) + + LD_NGTCP2_CRYPTO_BORINGSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_boringssl` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_BORINGSSL]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_BORINGSSL" + LDFLAGSPC="$LDFLAGSPC $LD_NGTCP2_CRYPTO_BORINGSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_BORINGSSL" + LIBS="$LIB_NGTCP2_CRYPTO_BORINGSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_BORINGSSL=`echo $LD_NGTCP2_CRYPTO_BORINGSSL | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_boringssl, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_BORINGSSL, 1, [if ngtcp2_crypto_boringssl is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_BORINGSSL, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_BORINGSSL" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_BORINGSSL to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libngtcp2_crypto_boringssl" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_boringssl pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_boringssl pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$GNUTLS_ENABLED" = "x1"; then + dnl backup the pre-ngtcp2_crypto_gnutls variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_gnutls, $want_tcp2_path) + + if test "$PKGCONFIG" != "no"; then + LIB_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_GNUTLS]) + + CPP_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_GNUTLS]) + + LD_NGTCP2_CRYPTO_GNUTLS=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_gnutls` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_GNUTLS]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_GNUTLS" + LDFLAGSPC="$LDFLAGSPC $LD_NGTCP2_CRYPTO_GNUTLS" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_GNUTLS" + LIBS="$LIB_NGTCP2_CRYPTO_GNUTLS $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_GNUTLS=`echo $LD_NGTCP2_CRYPTO_GNUTLS | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_gnutls, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_GNUTLS, 1, [if ngtcp2_crypto_gnutls is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_GNUTLS, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_GNUTLS" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_GNUTLS to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libngtcp2_crypto_gnutls" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_gnutls pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_gnutls pkg-config file.]) + fi + fi +fi + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$WOLFSSL_ENABLED" = "x1"; then + dnl backup the pre-ngtcp2_crypto_wolfssl variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libngtcp2_crypto_wolfssl, $want_tcp2_path) + + if test "$PKGCONFIG" != "no"; then + LIB_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-l libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-l is $LIB_NGTCP2_CRYPTO_WOLFSSL]) + + CPP_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) dnl + $PKGCONFIG --cflags-only-I libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-I is $CPP_NGTCP2_CRYPTO_WOLFSSL]) + + LD_NGTCP2_CRYPTO_WOLFSSL=`CURL_EXPORT_PCDIR([$want_tcp2_path]) + $PKGCONFIG --libs-only-L libngtcp2_crypto_wolfssl` + AC_MSG_NOTICE([-L is $LD_NGTCP2_CRYPTO_WOLFSSL]) + + LDFLAGS="$LDFLAGS $LD_NGTCP2_CRYPTO_WOLFSSL" + LDFLAGSPC="$LDFLAGSPC $LD_NGTCP2_CRYPTO_WOLFSSL" + CPPFLAGS="$CPPFLAGS $CPP_NGTCP2_CRYPTO_WOLFSSL" + LIBS="$LIB_NGTCP2_CRYPTO_WOLFSSL $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGTCP2_CRYPTO_WOLFSSL=`echo $LD_NGTCP2_CRYPTO_WOLFSSL | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(ngtcp2_crypto_wolfssl, ngtcp2_crypto_recv_client_initial_cb, + [ + AC_CHECK_HEADERS(ngtcp2/ngtcp2_crypto.h, + NGTCP2_ENABLED=1 + AC_DEFINE(USE_NGTCP2_CRYPTO_WOLFSSL, 1, [if ngtcp2_crypto_wolfssl is in use]) + AC_SUBST(USE_NGTCP2_CRYPTO_WOLFSSL, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGTCP2_CRYPTO_WOLFSSL" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGTCP2_CRYPTO_WOLFSSL to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libngtcp2_crypto_wolfssl" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no ngtcp2_crypto_wolfssl pkg-config found, deal with it + if test X"$want_tcp2" != Xdefault; then + dnl To avoid link errors, we do not allow --with-ngtcp2 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-ngtcp2 was specified but could not find ngtcp2_crypto_wolfssl pkg-config file.]) + fi + fi +fi + +dnl ********************************************************************** +dnl Check for OpenSSL QUIC +dnl ********************************************************************** + +OPT_OPENSSL_QUIC="no" + +if test "x$disable_http" = "xyes" -o "x$OPENSSL_ENABLED" != "x1"; then + # without HTTP or without openssl, no use + OPT_OPENSSL_QUIC="no" +fi + +AC_ARG_WITH(openssl-quic, +AS_HELP_STRING([--with-openssl-quic],[Enable OpenSSL QUIC usage]) +AS_HELP_STRING([--without-openssl-quic],[Disable OpenSSL QUIC usage]), + [OPT_OPENSSL_QUIC=$withval]) +case "$OPT_OPENSSL_QUIC" in + no) + dnl --without-openssl-quic option used + want_openssl_quic="no" + ;; + yes) + dnl --with-openssl-quic option used + want_openssl_quic="yes" + ;; +esac + +curl_openssl_quic_msg="no (--with-openssl-quic)" +if test "x$want_openssl_quic" = "xyes"; then + + if test "$NGTCP2_ENABLED" = 1; then + AC_MSG_ERROR([--with-openssl-quic and --with-ngtcp2 are mutually exclusive]) + fi + if test "$have_openssl_quic" != 1; then + AC_MSG_ERROR([--with-openssl-quic requires quic support and OpenSSL >= 3.3.0]) + fi + AC_DEFINE(USE_OPENSSL_QUIC, 1, [if openssl QUIC is in use]) + AC_SUBST(USE_OPENSSL_QUIC, [1]) +fi + +dnl ********************************************************************** +dnl Check for nghttp3 (HTTP/3 with ngtcp2) +dnl ********************************************************************** + +OPT_NGHTTP3="yes" + +if test "x$USE_NGTCP2" != "x1" -a "x$USE_OPENSSL_QUIC" != "x1"; then + # without ngtcp2 or openssl quic, nghttp3 is of no use for us + OPT_NGHTTP3="no" + want_nghttp3="no" +fi + +AC_ARG_WITH(nghttp3, +AS_HELP_STRING([--with-nghttp3=PATH],[Enable nghttp3 usage]) +AS_HELP_STRING([--without-nghttp3],[Disable nghttp3 usage]), + [OPT_NGHTTP3=$withval]) +case "$OPT_NGHTTP3" in + no) + dnl --without-nghttp3 option used + want_nghttp3="no" + ;; + yes) + dnl --with-nghttp3 option used without path + want_nghttp3="default" + want_nghttp3_path="" + ;; + *) + dnl --with-nghttp3 option used with path + want_nghttp3="yes" + want_nghttp3_path="$withval/lib/pkgconfig" + ;; +esac + +curl_http3_msg="no (--with-nghttp3)" +if test X"$want_nghttp3" != Xno; then + + if test "x$USE_NGTCP2" != "x1" -a "x$USE_OPENSSL_QUIC" != "x1"; then + # without ngtcp2 or openssl quic, nghttp3 is of no use for us + AC_MSG_ERROR([nghttp3 enabled without a QUIC library; enable ngtcp2 or OpenSSL-QUIC]) + fi + + dnl backup the pre-nghttp3 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libnghttp3, $want_nghttp3_path) + + if test "$PKGCONFIG" != "no"; then + LIB_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) + $PKGCONFIG --libs-only-l libnghttp3` + AC_MSG_NOTICE([-l is $LIB_NGHTTP3]) + + CPP_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) dnl + $PKGCONFIG --cflags-only-I libnghttp3` + AC_MSG_NOTICE([-I is $CPP_NGHTTP3]) + + LD_NGHTTP3=`CURL_EXPORT_PCDIR([$want_nghttp3_path]) + $PKGCONFIG --libs-only-L libnghttp3` + AC_MSG_NOTICE([-L is $LD_NGHTTP3]) + + LDFLAGS="$LDFLAGS $LD_NGHTTP3" + LDFLAGSPC="$LDFLAGSPC $LD_NGHTTP3" + CPPFLAGS="$CPPFLAGS $CPP_NGHTTP3" + LIBS="$LIB_NGHTTP3 $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_NGHTTP3=`echo $LD_NGHTTP3 | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(nghttp3, nghttp3_conn_client_new_versioned, + [ + AC_CHECK_HEADERS(nghttp3/nghttp3.h, + AC_DEFINE(USE_NGHTTP3, 1, [if nghttp3 is in use]) + AC_SUBST(USE_NGHTTP3, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_NGHTTP3" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_NGHTTP3 to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libnghttp3" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no nghttp3 pkg-config found, deal with it + if test X"$want_nghttp3" != Xdefault; then + dnl To avoid link errors, we do not allow --with-nghttp3 without + dnl a pkgconfig file + AC_MSG_ERROR([--with-nghttp3 was specified but could not find nghttp3 pkg-config file.]) + fi + fi +fi + +dnl ********************************************************************** +dnl Check for ngtcp2 and nghttp3 (HTTP/3 with ngtcp2 + nghttp3) +dnl ********************************************************************** + +if test "x$NGTCP2_ENABLED" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + AC_DEFINE(USE_NGTCP2_H3, 1, [if ngtcp2 + nghttp3 is in use]) + AC_SUBST(USE_NGTCP2_H3, [1]) + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (ngtcp2 + nghttp3)" +fi + +dnl ********************************************************************** +dnl Check for OpenSSL and nghttp3 (HTTP/3 with nghttp3 using OpenSSL QUIC) +dnl ********************************************************************** + +if test "x$USE_OPENSSL_QUIC" = "x1" -a "x$USE_NGHTTP3" = "x1"; then + experimental="$experimental HTTP3" + AC_DEFINE(USE_OPENSSL_H3, 1, [if openssl quic + nghttp3 is in use]) + AC_SUBST(USE_OPENSSL_H3, [1]) + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (openssl + nghttp3)" +fi + +dnl ********************************************************************** +dnl Check for quiche (QUIC) +dnl ********************************************************************** + +OPT_QUICHE="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, quiche is no use + OPT_QUICHE="no" +fi + +AC_ARG_WITH(quiche, +AS_HELP_STRING([--with-quiche=PATH],[Enable quiche usage]) +AS_HELP_STRING([--without-quiche],[Disable quiche usage]), + [OPT_QUICHE=$withval]) +case "$OPT_QUICHE" in + no) + dnl --without-quiche option used + want_quiche="no" + ;; + yes) + dnl --with-quiche option used without path + want_quiche="default" + want_quiche_path="" + ;; + *) + dnl --with-quiche option used with path + want_quiche="yes" + want_quiche_path="$withval" + ;; +esac + +if test X"$want_quiche" != Xno; then + + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-quiche a no-no]) + fi + + if test "$NGHTTP3_ENABLED" = 1; then + AC_MSG_ERROR([--with-quiche and --with-ngtcp2 are mutually exclusive]) + fi + + dnl backup the pre-quiche variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(quiche, $want_quiche_path) + + if test "$PKGCONFIG" != "no"; then + LIB_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) + $PKGCONFIG --libs-only-l quiche` + AC_MSG_NOTICE([-l is $LIB_QUICHE]) + + CPP_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) dnl + $PKGCONFIG --cflags-only-I quiche` + AC_MSG_NOTICE([-I is $CPP_QUICHE]) + + LD_QUICHE=`CURL_EXPORT_PCDIR([$want_quiche_path]) + $PKGCONFIG --libs-only-L quiche` + AC_MSG_NOTICE([-L is $LD_QUICHE]) + + LDFLAGS="$LDFLAGS $LD_QUICHE" + LDFLAGSPC="$LDFLAGSPC $LD_QUICHE" + CPPFLAGS="$CPPFLAGS $CPP_QUICHE" + LIBS="$LIB_QUICHE $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_QUICHE=`echo $LD_QUICHE | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(quiche, quiche_conn_send_ack_eliciting, + [ + AC_CHECK_HEADERS(quiche.h, + experimental="$experimental HTTP3" + AC_MSG_NOTICE([HTTP3 support is experimental]) + curl_h3_msg="enabled (quiche)" + QUICHE_ENABLED=1 + AC_DEFINE(USE_QUICHE, 1, [if quiche is in use]) + AC_SUBST(USE_QUICHE, [1]) + AC_CHECK_FUNCS([quiche_conn_set_qlog_fd]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_QUICHE" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_QUICHE to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE quiche", + [], + [ + AC_INCLUDES_DEFAULT + #include + ] + ) + ], + dnl not found, revert back to clean variables + AC_MSG_ERROR([couldn't use quiche]) + ) + else + dnl no quiche pkg-config found, deal with it + if test X"$want_quiche" != Xdefault; then + dnl To avoid link errors, we do not allow --with-quiche without + dnl a pkgconfig file + AC_MSG_ERROR([--with-quiche was specified but could not find quiche pkg-config file.]) + fi + fi +fi + +dnl ********************************************************************** +dnl Check for msh3/msquic (QUIC) +dnl ********************************************************************** + +OPT_MSH3="no" + +if test "x$disable_http" = "xyes" -o "x$USE_NGTCP" = "x1"; then + # without HTTP or with ngtcp2, msh3 is no use + OPT_MSH3="no" +fi + +AC_ARG_WITH(msh3, +AS_HELP_STRING([--with-msh3=PATH],[Enable msh3 usage]) +AS_HELP_STRING([--without-msh3],[Disable msh3 usage]), + [OPT_MSH3=$withval]) +case "$OPT_MSH3" in + no) + dnl --without-msh3 option used + want_msh3="no" + ;; + yes) + dnl --with-msh3 option used without path + want_msh3="default" + want_msh3_path="" + ;; + *) + dnl --with-msh3 option used with path + want_msh3="yes" + want_msh3_path="$withval" + ;; +esac + +if test X"$want_msh3" != Xno; then + + dnl msh3 on non-Windows needs an OpenSSL with the QUIC API + if test "$curl_cv_native_windows" != "yes"; then + if test "$QUIC_ENABLED" != "yes"; then + AC_MSG_ERROR([the detected TLS library does not support QUIC, making --with-msh3 a no-no]) + fi + if test "$OPENSSL_ENABLED" != "1"; then + AC_MSG_ERROR([msh3/msquic requires OpenSSL]) + fi + fi + + if test "$NGHTTP3_ENABLED" = 1; then + AC_MSG_ERROR([--with-msh3 and --with-ngtcp2 are mutually exclusive]) + fi + if test "$QUICHE_ENABLED" = 1; then + AC_MSG_ERROR([--with-msh3 and --with-quiche are mutually exclusive]) + fi + + dnl backup the pre-msh3 variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + if test -n "$want_msh3_path"; then + LD_MSH3="-L$want_msh3_path/lib" + CPP_MSH3="-I$want_msh3_path/include" + DIR_MSH3="$want_msh3_path/lib" + LDFLAGS="$LDFLAGS $LD_MSH3" + LDFLAGSPC="$LDFLAGSPC $LD_MSH3" + CPPFLAGS="$CPPFLAGS $CPP_MSH3" + fi + LIBS="-lmsh3 $LIBS" + + AC_CHECK_LIB(msh3, MsH3ApiOpen, + [ + AC_CHECK_HEADERS(msh3.h, + curl_h3_msg="enabled (msh3)" + MSH3_ENABLED=1 + AC_DEFINE(USE_MSH3, 1, [if msh3 is in use]) + AC_SUBST(USE_MSH3, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_MSH3" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_MSH3 to CURL_LIBRARY_PATH]) + dnl FIXME: Enable when msh3 was detected via pkg-config + if false; then + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libmsh3" + fi + experimental="$experimental HTTP3" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) +fi + +dnl ********************************************************************** +dnl libuv is only ever used for debug purposes +dnl ********************************************************************** + +OPT_LIBUV=no +AC_ARG_WITH(libuv, +AS_HELP_STRING([--with-libuv=PATH],[Enable libuv]) +AS_HELP_STRING([--without-libuv],[Disable libuv]), + [OPT_LIBUV=$withval]) +case "$OPT_LIBUV" in + no) + dnl --without-libuv option used + want_libuv="no" + ;; + yes) + dnl --with-libuv option used without path + want_libuv="default" + want_libuv_path="" + ;; + *) + dnl --with-libuv option used with path + want_libuv="yes" + want_libuv_path="$withval" + ;; +esac + +if test X"$want_libuv" != Xno; then + if test x$want_debug != xyes; then + AC_MSG_ERROR([Using libuv without debug support enabled is useless]) + fi + + dnl backup the pre-libuv variables + CLEANLDFLAGS="$LDFLAGS" + CLEANLDFLAGSPC="$LDFLAGSPC" + CLEANCPPFLAGS="$CPPFLAGS" + CLEANLIBS="$LIBS" + + CURL_CHECK_PKGCONFIG(libuv, $want_libuv_path) + + if test "$PKGCONFIG" != "no"; then + LIB_LIBUV=`CURL_EXPORT_PCDIR([$want_libuv_path]) + $PKGCONFIG --libs-only-l libuv` + AC_MSG_NOTICE([-l is $LIB_LIBUV]) + + CPP_LIBUV=`CURL_EXPORT_PCDIR([$want_libuv_path]) dnl + $PKGCONFIG --cflags-only-I libuv` + AC_MSG_NOTICE([-I is $CPP_LIBUV]) + + LD_LIBUV=`CURL_EXPORT_PCDIR([$want_libuv_path]) + $PKGCONFIG --libs-only-L libuv` + AC_MSG_NOTICE([-L is $LD_LIBUV]) + + LDFLAGS="$LDFLAGS $LD_LIBUV" + LDFLAGSPC="$LDFLAGSPC $LD_LIBUV" + CPPFLAGS="$CPPFLAGS $CPP_LIBUV" + LIBS="$LIB_LIBUV $LIBS" + + if test "x$cross_compiling" != "xyes"; then + DIR_LIBUV=`echo $LD_LIBUV | $SED -e 's/^-L//'` + fi + AC_CHECK_LIB(uv, uv_default_loop, + [ + AC_CHECK_HEADERS(uv.h, + LIBUV_ENABLED=1 + AC_DEFINE(USE_LIBUV, 1, [if libuv is in use]) + AC_SUBST(USE_LIBUV, [1]) + CURL_LIBRARY_PATH="$CURL_LIBRARY_PATH:$DIR_LIBUV" + export CURL_LIBRARY_PATH + AC_MSG_NOTICE([Added $DIR_LIBUV to CURL_LIBRARY_PATH]) + LIBCURL_PC_REQUIRES_PRIVATE="$LIBCURL_PC_REQUIRES_PRIVATE libuv" + ) + ], + dnl not found, revert back to clean variables + LDFLAGS=$CLEANLDFLAGS + LDFLAGSPC=$CLEANLDFLAGSPC + CPPFLAGS=$CLEANCPPFLAGS + LIBS=$CLEANLIBS + ) + + else + dnl no libuv pkg-config found, deal with it + if test X"$want_libuv" != Xdefault; then + dnl To avoid link errors, we do not allow --with-libuv without + dnl a pkgconfig file + AC_MSG_ERROR([--with-libuv was specified but could not find libuv pkg-config file.]) + fi + fi + +fi + +dnl ********************************************************************** +dnl Check for zsh completion path +dnl ********************************************************************** + +OPT_ZSH_FPATH=default +AC_ARG_WITH(zsh-functions-dir, +AS_HELP_STRING([--with-zsh-functions-dir=PATH],[Install zsh completions to PATH]) +AS_HELP_STRING([--without-zsh-functions-dir],[Do not install zsh completions]), + [OPT_ZSH_FPATH=$withval]) +case "$OPT_ZSH_FPATH" in + default|no) + dnl --without-zsh-functions-dir option used + ;; + yes) + dnl --with-zsh-functions-dir option used without path + ZSH_FUNCTIONS_DIR="$datarootdir/zsh/site-functions" + AC_SUBST(ZSH_FUNCTIONS_DIR) + ;; + *) + dnl --with-zsh-functions-dir option used with path + ZSH_FUNCTIONS_DIR="$withval" + AC_SUBST(ZSH_FUNCTIONS_DIR) + ;; +esac +AM_CONDITIONAL(USE_ZSH_COMPLETION, test x"$ZSH_FUNCTIONS_DIR" != x) + +dnl ********************************************************************** +dnl Check for fish completion path +dnl ********************************************************************** + +OPT_FISH_FPATH=default +AC_ARG_WITH(fish-functions-dir, +AS_HELP_STRING([--with-fish-functions-dir=PATH],[Install fish completions to PATH]) +AS_HELP_STRING([--without-fish-functions-dir],[Do not install fish completions]), + [OPT_FISH_FPATH=$withval]) +case "$OPT_FISH_FPATH" in + default|no) + dnl --without-fish-functions-dir option used + ;; + yes) + dnl --with-fish-functions-dir option used without path + CURL_CHECK_PKGCONFIG(fish) + if test "$PKGCONFIG" != "no"; then + FISH_FUNCTIONS_DIR=`$PKGCONFIG --variable completionsdir fish` + else + FISH_FUNCTIONS_DIR="$datarootdir/fish/vendor_completions.d" + fi + AC_SUBST(FISH_FUNCTIONS_DIR) + ;; + *) + dnl --with-fish-functions-dir option used with path + FISH_FUNCTIONS_DIR="$withval" + AC_SUBST(FISH_FUNCTIONS_DIR) + ;; +esac +AM_CONDITIONAL(USE_FISH_COMPLETION, test x"$FISH_FUNCTIONS_DIR" != x) + +dnl Now check for the very most basic headers. Then we can use these +dnl ones as default-headers when checking for the rest! +AC_CHECK_HEADERS( + sys/types.h \ + sys/time.h \ + sys/select.h \ + sys/socket.h \ + sys/ioctl.h \ + unistd.h \ + stdlib.h \ + arpa/inet.h \ + net/if.h \ + netinet/in.h \ + netinet/in6.h \ + sys/un.h \ + linux/tcp.h \ + netinet/tcp.h \ + netinet/udp.h \ + netdb.h \ + sys/sockio.h \ + sys/stat.h \ + sys/param.h \ + termios.h \ + termio.h \ + fcntl.h \ + io.h \ + pwd.h \ + utime.h \ + sys/utime.h \ + sys/poll.h \ + poll.h \ + sys/resource.h \ + libgen.h \ + locale.h \ + stdbool.h \ + sys/filio.h \ + sys/wait.h \ + sys/eventfd.h \ + setjmp.h, +dnl to do if not found +[], +dnl to do if found +[], +dnl default includes +[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include /* is this really required to detect other headers? */ +#endif +#ifdef HAVE_SYS_UN_H +#include /* is this really required to detect other headers? */ +#endif +] +) + + +dnl Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_TYPE_SIZE_T + +CURL_CHECK_STRUCT_TIMEVAL +CURL_VERIFY_RUNTIMELIBS + +CURL_SIZEOF(size_t) +CURL_SIZEOF(long) +CURL_SIZEOF(int) +CURL_SIZEOF(time_t) +CURL_SIZEOF(off_t) + +o=$CPPFLAGS +CPPFLAGS="-I$srcdir/include $CPPFLAGS" +CURL_SIZEOF(curl_off_t, [ +#include +]) +CURL_SIZEOF(curl_socket_t, [ +#include +]) +CPPFLAGS=$o + +AC_CHECK_TYPE(long long, + [AC_DEFINE(HAVE_LONGLONG, 1, + [Define to 1 if the compiler supports the 'long long' data type.])] + longlong="yes" +) + +if test ${ac_cv_sizeof_curl_off_t} -lt 8; then + AC_MSG_ERROR([64 bit curl_off_t is required]) +fi + +# check for ssize_t +AC_CHECK_TYPE(ssize_t, , + AC_DEFINE(ssize_t, int, [the signed version of size_t])) + +# check for bool type +AC_CHECK_TYPE([bool],[ + AC_DEFINE(HAVE_BOOL_T, 1, + [Define to 1 if bool is an available type.]) +], ,[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDBOOL_H +#include +#endif +]) + +# check for sa_family_t +AC_CHECK_TYPE(sa_family_t, + AC_DEFINE(CURL_SA_FAMILY_T, sa_family_t, [IP address type in sockaddr]), + [ + # The Windows name? + AC_CHECK_TYPE(ADDRESS_FAMILY, + AC_DEFINE(CURL_SA_FAMILY_T, ADDRESS_FAMILY, [IP address type in sockaddr]), + AC_DEFINE(CURL_SA_FAMILY_T, unsigned short, [IP address type in sockaddr]), + [ +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + ]) + ], +[ +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +]) + +# check for suseconds_t +AC_CHECK_TYPE([suseconds_t],[ + AC_DEFINE(HAVE_SUSECONDS_T, 1, + [Define to 1 if suseconds_t is an available type.]) +], ,[ +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +]) + +AC_MSG_CHECKING([if time_t is unsigned]) +CURL_RUN_IFELSE( + [ + #include + #include + int main(void) { + time_t t = -1; + return (t < 0); + } + ],[ + AC_MSG_RESULT([yes]) + AC_DEFINE(HAVE_TIME_T_UNSIGNED, 1, [Define this if time_t is unsigned]) +],[ + AC_MSG_RESULT([no]) +],[ + dnl cross-compiling, most systems are unsigned + AC_MSG_RESULT([no]) +]) + +TYPE_IN_ADDR_T + +TYPE_SOCKADDR_STORAGE + +CURL_CHECK_FUNC_SELECT + +CURL_CHECK_FUNC_RECV +CURL_CHECK_FUNC_SEND +CURL_CHECK_MSG_NOSIGNAL + +CURL_CHECK_FUNC_ALARM +CURL_CHECK_FUNC_BASENAME +CURL_CHECK_FUNC_CLOSESOCKET +CURL_CHECK_FUNC_CLOSESOCKET_CAMEL +CURL_CHECK_FUNC_FCNTL +CURL_CHECK_FUNC_FREEADDRINFO +CURL_CHECK_FUNC_FSETXATTR +CURL_CHECK_FUNC_FTRUNCATE +CURL_CHECK_FUNC_GETADDRINFO +CURL_CHECK_FUNC_GETHOSTBYNAME +CURL_CHECK_FUNC_GETHOSTBYNAME_R +CURL_CHECK_FUNC_GETHOSTNAME +CURL_CHECK_FUNC_GETPEERNAME +CURL_CHECK_FUNC_GETSOCKNAME +CURL_CHECK_FUNC_GETIFADDRS +CURL_CHECK_FUNC_GMTIME_R +CURL_CHECK_FUNC_INET_NTOP +CURL_CHECK_FUNC_INET_PTON +CURL_CHECK_FUNC_IOCTL +CURL_CHECK_FUNC_IOCTLSOCKET +CURL_CHECK_FUNC_IOCTLSOCKET_CAMEL +CURL_CHECK_FUNC_MEMRCHR +CURL_CHECK_FUNC_SIGACTION +CURL_CHECK_FUNC_SIGINTERRUPT +CURL_CHECK_FUNC_SIGNAL +CURL_CHECK_FUNC_SIGSETJMP +CURL_CHECK_FUNC_SOCKET +CURL_CHECK_FUNC_SOCKETPAIR +CURL_CHECK_FUNC_STRCASECMP +CURL_CHECK_FUNC_STRCMPI +CURL_CHECK_FUNC_STRDUP +CURL_CHECK_FUNC_STRERROR_R +CURL_CHECK_FUNC_STRICMP +CURL_CHECK_FUNC_STRTOK_R +CURL_CHECK_FUNC_STRTOLL + +case $host in + *msdosdjgpp) + ac_cv_func_pipe=no + skipcheck_pipe=yes + AC_MSG_NOTICE([skip check for pipe on msdosdjgpp]) + ;; +esac + +AC_CHECK_DECLS([getpwuid_r], [], [AC_DEFINE(HAVE_DECL_GETPWUID_R_MISSING, 1, "Set if getpwuid_r() declaration is missing")], + [[#include + #include ]]) + +AC_CHECK_FUNCS([\ + eventfd \ + fnmatch \ + geteuid \ + getpass_r \ + getppid \ + getpwuid \ + getpwuid_r \ + getrlimit \ + gettimeofday \ + if_nametoindex \ + mach_absolute_time \ + pipe \ + poll \ + sched_yield \ + sendmsg \ + sendmmsg \ + setlocale \ + setmode \ + setrlimit \ + snprintf \ + utime \ + utimes \ +]) + +if test "$curl_cv_native_windows" = 'yes' -o "$curl_cv_cygwin" = 'yes'; then + AC_CHECK_FUNCS([_setmode]) +fi + +if test -z "$ssl_backends"; then + AC_CHECK_FUNCS([arc4random]) +fi + +if test "$curl_cv_native_windows" != 'yes'; then + AC_CHECK_FUNCS([fseeko]) + + dnl On Android, the only way to know if fseeko can be used is to see if it is + dnl declared or not (for this API level), as the symbol always exists in the + dnl lib. + AC_CHECK_DECL([fseeko], + [AC_DEFINE([HAVE_DECL_FSEEKO], [1], + [Define to 1 if you have the fseeko declaration])], + [], + [[#include ]]) +fi + +CURL_CHECK_NONBLOCKING_SOCKET + +AC_PATH_PROG(PERL, perl,, + $PATH:/usr/local/bin/perl:/usr/bin/:/usr/local/bin) +AC_SUBST(PERL) + +if test "x$BUILD_DOCS" != "x0" -o "x$USE_MANUAL" != "x0" -o "x$CURL_CA_EMBED" != "x"; then + if test -z "$PERL"; then + AC_MSG_ERROR([perl was not found, needed for docs, manual and CA embed]) + fi +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(BUILD_DOCS, test x"$BUILD_DOCS" = x1) + +dnl ************************************************************************* +dnl If the manual variable still is set, then we go with providing a built-in +dnl manual + +if test "$USE_MANUAL" = "1"; then + curl_manual_msg="enabled" +fi + +dnl set variable for use in automakefile(s) +AM_CONDITIONAL(USE_MANUAL, test x"$USE_MANUAL" = x1) + +CURL_CHECK_LIB_ARES + +if test "x$want_ares" != xyes; then + CURL_CHECK_OPTION_THREADED_RESOLVER + + if test "$ipv6" = yes; then + CURL_DARWIN_SYSTEMCONFIGURATION + fi +fi + +dnl ************************************************************ +dnl disable POSIX threads +dnl +AC_MSG_CHECKING([whether to use POSIX threads for threaded resolver]) +AC_ARG_ENABLE(pthreads, +AS_HELP_STRING([--enable-pthreads], + [Enable POSIX threads (default for threaded resolver)]) +AS_HELP_STRING([--disable-pthreads],[Disable POSIX threads]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + want_pthreads=no + ;; + *) + AC_MSG_RESULT(yes) + want_pthreads=yes + ;; + esac ], [ + default_pthreads=1 + if test "$curl_cv_native_windows" = "yes"; then + default_pthreads=0 + else + case $host_os in + msdos*) + default_pthreads=0 + ;; + esac + fi + if test "$default_pthreads" = '0'; then + AC_MSG_RESULT(no) + want_pthreads=no + else + AC_MSG_RESULT(auto) + want_pthreads=auto + fi + ] +) + +dnl turn off pthreads if rt is disabled +if test "$want_pthreads" != "no"; then + if test "$want_pthreads" = "yes" && test "$dontwant_rt" = "yes"; then + AC_MSG_ERROR([options --enable-pthreads and --disable-rt are mutually exclusive]) + fi + if test "$dontwant_rt" != "no"; then + dnl if --enable-pthreads was explicit then warn it's being ignored + if test "$want_pthreads" = "yes"; then + AC_MSG_WARN([--enable-pthreads Ignored since librt is disabled.]) + fi + want_pthreads=no + fi +fi + +dnl turn off pthreads if no threaded resolver +if test "$want_pthreads" != "no" && test "$want_thres" != "yes"; then + want_pthreads=no +fi + +dnl detect pthreads +if test "$want_pthreads" != "no"; then + AC_CHECK_HEADER(pthread.h, + [ AC_DEFINE(HAVE_PTHREAD_H, 1, [if you have ]) + save_CFLAGS="$CFLAGS" + dnl When statically linking against BoringSSL, -lpthread is added to LIBS. + dnl Make sure to that this does not pass the check below, we really want + dnl -pthread in CFLAGS as recommended for GCC. This also ensures that + dnl lib1541 and lib1565 tests are built with these options. Otherwise + dnl they fail the build since tests/libtest/Makefile.am clears LIBS. + save_LIBS="$LIBS" + + LIBS= + dnl Check for libc variants without a separate pthread lib like bionic + AC_CHECK_FUNC(pthread_create, [USE_THREADS_POSIX=1] ) + LIBS="$save_LIBS" + + dnl on HP-UX, life is more complicated... + case $host in + *-hp-hpux*) + dnl it doesn't actually work without -lpthread + USE_THREADS_POSIX="" + ;; + *) + ;; + esac + + dnl if it wasn't found without lib, search for it in pthread lib + if test "$USE_THREADS_POSIX" != "1"; then + # assign PTHREAD for pkg-config use + PTHREAD=" -pthread" + + case $host in + *-ibm-aix*) + dnl Check if compiler is xlC + COMPILER_VERSION=`"$CC" -qversion 2>/dev/null` + if test x"$COMPILER_VERSION" = "x"; then + CFLAGS="$CFLAGS -pthread" + else + CFLAGS="$CFLAGS -qthreaded" + fi + ;; + powerpc-*amigaos*) + dnl No -pthread option, but link with -lpthread + PTHREAD=" -lpthread" + ;; + *) + CFLAGS="$CFLAGS -pthread" + ;; + esac + AC_CHECK_LIB(pthread, pthread_create, + [USE_THREADS_POSIX=1], + [ CFLAGS="$save_CFLAGS"]) + fi + + if test "x$USE_THREADS_POSIX" = "x1"; then + AC_DEFINE(USE_THREADS_POSIX, 1, [if you want POSIX threaded DNS lookup]) + curl_res_msg="POSIX threaded" + fi + ]) +fi + +dnl threaded resolver check +if test "$want_thres" = "yes" && test "x$USE_THREADS_POSIX" != "x1"; then + if test "$want_pthreads" = "yes"; then + AC_MSG_ERROR([--enable-pthreads but pthreads was not found]) + fi + dnl If native Windows fallback on Win32 threads since no POSIX threads + if test "$curl_cv_native_windows" = "yes"; then + USE_THREADS_WIN32=1 + AC_DEFINE(USE_THREADS_WIN32, 1, [if you want Win32 threaded DNS lookup]) + curl_res_msg="Win32 threaded" + else + AC_MSG_ERROR([Threaded resolver enabled but no thread library found]) + fi +fi + +AC_CHECK_HEADER(dirent.h, + [ AC_DEFINE(HAVE_DIRENT_H, 1, [if you have ]) + AC_CHECK_FUNC(opendir, AC_DEFINE(HAVE_OPENDIR, 1, [if you have opendir]) ) + ] +) + +CURL_CONVERT_INCLUDE_TO_ISYSTEM + +dnl ************************************************************ +dnl disable verbose text strings +dnl +AC_MSG_CHECKING([whether to enable verbose strings]) +AC_ARG_ENABLE(verbose, +AS_HELP_STRING([--enable-verbose],[Enable verbose strings]) +AS_HELP_STRING([--disable-verbose],[Disable verbose strings]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_VERBOSE_STRINGS, 1, [to disable verbose strings]) + curl_verbose_msg="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl enable SSPI support +dnl +AC_MSG_CHECKING([whether to enable SSPI support (Windows native builds only)]) +AC_ARG_ENABLE(sspi, +AS_HELP_STRING([--enable-sspi],[Enable SSPI]) +AS_HELP_STRING([--disable-sspi],[Disable SSPI]), +[ case "$enableval" in + yes) + if test "$curl_cv_native_windows" = "yes"; then + AC_MSG_RESULT(yes) + AC_DEFINE(USE_WINDOWS_SSPI, 1, [to enable SSPI support]) + AC_SUBST(USE_WINDOWS_SSPI, [1]) + curl_sspi_msg="enabled" + else + AC_MSG_RESULT(no) + AC_MSG_WARN([--enable-sspi Ignored. Only supported on native Windows builds.]) + fi + ;; + *) + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + AC_MSG_RESULT(yes) + else + AC_MSG_RESULT(no) + fi + ;; + esac ], + if test "x$SCHANNEL_ENABLED" = "x1"; then + # --with-schannel implies --enable-sspi + AC_MSG_RESULT(yes) + else + AC_MSG_RESULT(no) + fi +) + +dnl ************************************************************ +dnl disable basic authentication +dnl +AC_MSG_CHECKING([whether to enable basic authentication method]) +AC_ARG_ENABLE(basic-auth, +AS_HELP_STRING([--enable-basic-auth],[Enable basic authentication (default)]) +AS_HELP_STRING([--disable-basic-auth],[Disable basic authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BASIC_AUTH, 1, [to disable basic authentication]) + CURL_DISABLE_BASIC_AUTH=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable bearer authentication +dnl +AC_MSG_CHECKING([whether to enable bearer authentication method]) +AC_ARG_ENABLE(bearer-auth, +AS_HELP_STRING([--enable-bearer-auth],[Enable bearer authentication (default)]) +AS_HELP_STRING([--disable-bearer-auth],[Disable bearer authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BEARER_AUTH, 1, [to disable bearer authentication]) + CURL_DISABLE_BEARER_AUTH=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable digest authentication +dnl +AC_MSG_CHECKING([whether to enable digest authentication method]) +AC_ARG_ENABLE(digest-auth, +AS_HELP_STRING([--enable-digest-auth],[Enable digest authentication (default)]) +AS_HELP_STRING([--disable-digest-auth],[Disable digest authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DIGEST_AUTH, 1, [to disable digest authentication]) + CURL_DISABLE_DIGEST_AUTH=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable kerberos authentication +dnl +AC_MSG_CHECKING([whether to enable kerberos authentication method]) +AC_ARG_ENABLE(kerberos-auth, +AS_HELP_STRING([--enable-kerberos-auth],[Enable kerberos authentication (default)]) +AS_HELP_STRING([--disable-kerberos-auth],[Disable kerberos authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_KERBEROS_AUTH, 1, [to disable kerberos authentication]) + CURL_DISABLE_KERBEROS_AUTH=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable negotiate authentication +dnl +AC_MSG_CHECKING([whether to enable negotiate authentication method]) +AC_ARG_ENABLE(negotiate-auth, +AS_HELP_STRING([--enable-negotiate-auth],[Enable negotiate authentication (default)]) +AS_HELP_STRING([--disable-negotiate-auth],[Disable negotiate authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NEGOTIATE_AUTH, 1, [to disable negotiate authentication]) + CURL_DISABLE_NEGOTIATE_AUTH=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable aws +dnl +AC_MSG_CHECKING([whether to enable aws sig methods]) +AC_ARG_ENABLE(aws, +AS_HELP_STRING([--enable-aws],[Enable AWS sig support (default)]) +AS_HELP_STRING([--disable-aws],[Disable AWS sig support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_AWS, 1, [to disable AWS sig support]) + CURL_DISABLE_AWS=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable NTLM support +dnl +AC_MSG_CHECKING([whether to support NTLM]) +AC_ARG_ENABLE(ntlm, +AS_HELP_STRING([--enable-ntlm],[Enable NTLM support]) +AS_HELP_STRING([--disable-ntlm],[Disable NTLM support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NTLM, 1, [to disable NTLM support]) + CURL_DISABLE_NTLM=1 + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable TLS-SRP authentication +dnl +AC_MSG_CHECKING([whether to enable TLS-SRP authentication]) +AC_ARG_ENABLE(tls-srp, +AS_HELP_STRING([--enable-tls-srp],[Enable TLS-SRP authentication]) +AS_HELP_STRING([--disable-tls-srp],[Disable TLS-SRP authentication]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + want_tls_srp=no + ;; + *) + AC_MSG_RESULT(yes) + want_tls_srp=yes + ;; + esac ], + AC_MSG_RESULT(yes) + want_tls_srp=yes +) + +if test "$want_tls_srp" = "yes" && ( test "x$HAVE_GNUTLS_SRP" = "x1" || test "x$HAVE_OPENSSL_SRP" = "x1"); then + AC_DEFINE(USE_TLS_SRP, 1, [Use TLS-SRP authentication]) + USE_TLS_SRP=1 + curl_tls_srp_msg="enabled" +fi + +dnl ************************************************************ +dnl disable Unix domain sockets support +dnl +AC_MSG_CHECKING([whether to enable Unix domain sockets]) +AC_ARG_ENABLE(unix-sockets, +AS_HELP_STRING([--enable-unix-sockets],[Enable Unix domain sockets]) +AS_HELP_STRING([--disable-unix-sockets],[Disable Unix domain sockets]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + want_unix_sockets=no + ;; + *) + AC_MSG_RESULT(yes) + want_unix_sockets=yes + ;; + esac ], [ + AC_MSG_RESULT(auto) + want_unix_sockets=auto + ] +) +if test "x$want_unix_sockets" != "xno"; then + if test "x$curl_cv_native_windows" = "xyes"; then + USE_UNIX_SOCKETS=1 + AC_DEFINE(USE_UNIX_SOCKETS, 1, [Use Unix domain sockets]) + curl_unix_sockets_msg="enabled" + else + AC_CHECK_MEMBER([struct sockaddr_un.sun_path], [ + AC_DEFINE(USE_UNIX_SOCKETS, 1, [Use Unix domain sockets]) + AC_SUBST(USE_UNIX_SOCKETS, [1]) + curl_unix_sockets_msg="enabled" + ], [ + if test "x$want_unix_sockets" = "xyes"; then + AC_MSG_ERROR([--enable-unix-sockets is not available on this platform!]) + fi + ], [ + #include + ]) + fi +fi + +dnl ************************************************************ +dnl disable cookies support +dnl +AC_MSG_CHECKING([whether to support cookies]) +AC_ARG_ENABLE(cookies, +AS_HELP_STRING([--enable-cookies],[Enable cookies support]) +AS_HELP_STRING([--disable-cookies],[Disable cookies support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_COOKIES, 1, [to disable cookies support]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable socketpair +dnl +AC_MSG_CHECKING([whether to support socketpair]) +AC_ARG_ENABLE(socketpair, +AS_HELP_STRING([--enable-socketpair],[Enable socketpair support]) +AS_HELP_STRING([--disable-socketpair],[Disable socketpair support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SOCKETPAIR, 1, [to disable socketpair support]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable HTTP authentication support +dnl +AC_MSG_CHECKING([whether to support HTTP authentication]) +AC_ARG_ENABLE(http-auth, +AS_HELP_STRING([--enable-http-auth],[Enable HTTP authentication support]) +AS_HELP_STRING([--disable-http-auth],[Disable HTTP authentication support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_HTTP_AUTH, 1, [disable HTTP authentication]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable DoH support +dnl +AC_MSG_CHECKING([whether to support DoH]) +AC_ARG_ENABLE(doh, +AS_HELP_STRING([--enable-doh],[Enable DoH support]) +AS_HELP_STRING([--disable-doh],[Disable DoH support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_DOH, 1, [disable DoH]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable mime API support +dnl +AC_MSG_CHECKING([whether to support the MIME API]) +AC_ARG_ENABLE(mime, +AS_HELP_STRING([--enable-mime],[Enable mime API support]) +AS_HELP_STRING([--disable-mime],[Disable mime API support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_MIME, 1, [disable mime API]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable bindlocal +dnl +AC_MSG_CHECKING([whether to support binding connections locally]) +AC_ARG_ENABLE(bindlocal, +AS_HELP_STRING([--enable-bindlocal],[Enable local binding support]) +AS_HELP_STRING([--disable-bindlocal],[Disable local binding support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_BINDLOCAL, 1, [disable local binding support]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable form API support +dnl +AC_MSG_CHECKING([whether to support the form API]) +AC_ARG_ENABLE(form-api, +AS_HELP_STRING([--enable-form-api],[Enable form API support]) +AS_HELP_STRING([--disable-form-api],[Disable form API support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FORM_API, 1, [disable form API]) + ;; + *) + AC_MSG_RESULT(yes) + test "$enable_mime" = no && + AC_MSG_ERROR(MIME support needs to be enabled in order to enable form API support) + ;; + esac ], +[ + if test "$enable_mime" = no; then + enable_form_api=no + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_FORM_API, 1, [disable form API]) + else + AC_MSG_RESULT(yes) + fi ] +) + +dnl ************************************************************ +dnl disable date parsing +dnl +AC_MSG_CHECKING([whether to support date parsing]) +AC_ARG_ENABLE(dateparse, +AS_HELP_STRING([--enable-dateparse],[Enable date parsing]) +AS_HELP_STRING([--disable-dateparse],[Disable date parsing]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PARSEDATE, 1, [disable date parsing]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable netrc +dnl +AC_MSG_CHECKING([whether to support netrc parsing]) +AC_ARG_ENABLE(netrc, +AS_HELP_STRING([--enable-netrc],[Enable netrc parsing]) +AS_HELP_STRING([--disable-netrc],[Disable netrc parsing]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_NETRC, 1, [disable netrc parsing]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable progress-meter +dnl +AC_MSG_CHECKING([whether to support progress-meter]) +AC_ARG_ENABLE(progress-meter, +AS_HELP_STRING([--enable-progress-meter],[Enable progress-meter]) +AS_HELP_STRING([--disable-progress-meter],[Disable progress-meter]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_PROGRESS_METER, 1, [disable progress-meter]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable SHA-512/256 hash algorithm +dnl +AC_MSG_CHECKING([whether to support the SHA-512/256 hash algorithm]) +AC_ARG_ENABLE(sha512-256, +AS_HELP_STRING([--enable-sha512-256],[Enable SHA-512/256 hash algorithm (default)]) +AS_HELP_STRING([--disable-sha512-256],[Disable SHA-512/256 hash algorithm]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SHA512_256, 1, [disable SHA-512/256 hash algorithm]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable shuffle DNS support +dnl +AC_MSG_CHECKING([whether to support DNS shuffling]) +AC_ARG_ENABLE(dnsshuffle, +AS_HELP_STRING([--enable-dnsshuffle],[Enable DNS shuffling]) +AS_HELP_STRING([--disable-dnsshuffle],[Disable DNS shuffling]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_SHUFFLE_DNS, 1, [disable DNS shuffling]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl disable the curl_easy_options API +dnl +AC_MSG_CHECKING([whether to support curl_easy_option*]) +AC_ARG_ENABLE(get-easy-options, +AS_HELP_STRING([--enable-get-easy-options],[Enable curl_easy_options]) +AS_HELP_STRING([--disable-get-easy-options],[Disable curl_easy_options]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_GETOPTIONS, 1, [to disable curl_easy_options]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl switch on/off alt-svc +dnl +AC_MSG_CHECKING([whether to support alt-svc]) +AC_ARG_ENABLE(alt-svc, +AS_HELP_STRING([--enable-alt-svc],[Enable alt-svc support]) +AS_HELP_STRING([--disable-alt-svc],[Disable alt-svc support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_ALTSVC, 1, [disable alt-svc]) + curl_altsvc_msg="no"; + enable_altsvc="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl ************************************************************ +dnl switch on/off headers-api +dnl +AC_MSG_CHECKING([whether to support headers-api]) +AC_ARG_ENABLE(headers-api, +AS_HELP_STRING([--enable-headers-api],[Enable headers-api support]) +AS_HELP_STRING([--disable-headers-api],[Disable headers-api support]), +[ case "$enableval" in + no) + AC_MSG_RESULT(no) + curl_headers_msg="no (--enable-headers-api)" + AC_DEFINE(CURL_DISABLE_HEADERS_API, 1, [disable headers-api]) + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT(yes) +) + +dnl only check for HSTS if there's SSL present +if test -n "$SSL_ENABLED"; then + dnl ************************************************************ + dnl switch on/off hsts + dnl + AC_MSG_CHECKING([whether to support HSTS]) + AC_ARG_ENABLE(hsts, +AS_HELP_STRING([--enable-hsts],[Enable HSTS support]) +AS_HELP_STRING([--disable-hsts],[Disable HSTS support]), + [ case "$enableval" in + no) + AC_MSG_RESULT(no) + hsts="no" + ;; + *) + AC_MSG_RESULT(yes) + ;; + esac ], + AC_MSG_RESULT($hsts) + ) +else + AC_MSG_NOTICE([disables HSTS due to lack of SSL]) + hsts="no" +fi + +if test "x$hsts" != "xyes"; then + curl_hsts_msg="no (--enable-hsts)"; + AC_DEFINE(CURL_DISABLE_HSTS, 1, [disable alt-svc]) +fi + + +dnl ************************************************************* +dnl check whether HTTPSRR support if desired +dnl +if test "x$want_httpsrr" != "xno"; then + AC_MSG_RESULT([HTTPSRR support is available]) + AC_DEFINE(USE_HTTPSRR, 1, [enable HTTPS RR support]) + experimental="$experimental HTTPSRR" +fi + +dnl ************************************************************* +dnl check whether ECH support, if desired, is actually available +dnl +if test "x$want_ech" != "xno"; then + AC_MSG_CHECKING([whether ECH support is available]) + + dnl assume NOT and look for sufficient condition + ECH_ENABLED=0 + ECH_SUPPORT='' + + dnl check for OpenSSL + if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(SSL_ech_set1_echconfig, + ECH_SUPPORT="ECH support available via OpenSSL with SSL_ech_set1_echconfig" + ECH_ENABLED=1) + fi + dnl check for BoringSSL equivalent + if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(SSL_set1_ech_config_list, + ECH_SUPPORT="ECH support available via BoringSSL with SSL_set1_ech_config_list" + ECH_ENABLED=1) + fi + if test "x$WOLFSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS(wolfSSL_CTX_GenerateEchConfig, + ECH_SUPPORT="ECH support available via wolfSSL with wolfSSL_CTX_GenerateEchConfig" + ECH_ENABLED=1) + fi + + dnl now deal with whatever we found + if test "x$ECH_ENABLED" = "x1"; then + AC_DEFINE(USE_ECH, 1, [if ECH support is available]) + AC_MSG_RESULT($ECH_SUPPORT) + experimental="$experimental ECH" + else + AC_MSG_ERROR([--enable-ech ignored: No ECH support found]) + fi +fi + +dnl ************************************************************* +dnl check whether OpenSSL (lookalikes) have SSL_set0_wbio +dnl +if test "x$OPENSSL_ENABLED" = "x1"; then + AC_CHECK_FUNCS([SSL_set0_wbio]) +fi + +if test "x$CURL_DISABLE_HTTP" != "x1"; then + dnl ************************************************************* + dnl WebSockets + dnl + AC_MSG_CHECKING([whether to support WebSockets]) + AC_ARG_ENABLE(websockets, + AS_HELP_STRING([--enable-websockets],[Enable WebSockets support]) + AS_HELP_STRING([--disable-websockets],[Disable WebSockets support]), + [ case "$enableval" in + no) + AC_MSG_RESULT(no) + AC_DEFINE(CURL_DISABLE_WEBSOCKETS, [1], [disable WebSockets]) + AC_SUBST(CURL_DISABLE_WEBSOCKETS, [1]) + ;; + *) + if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + AC_MSG_RESULT(yes) + else + dnl WebSockets requires >32 bit curl_off_t + AC_MSG_RESULT(no) + AC_MSG_WARN([WebSockets disabled due to lack of >32 bit curl_off_t]) + AC_DEFINE(CURL_DISABLE_WEBSOCKETS, [1], [disable WebSockets]) + AC_SUBST(CURL_DISABLE_WEBSOCKETS, [1]) + fi + ;; + esac ], + AC_MSG_RESULT(yes) + ) +else + AC_MSG_WARN([WebSockets disabled because HTTP is disabled]) + AC_DEFINE(CURL_DISABLE_WEBSOCKETS, [1], [disable WebSockets]) + AC_SUBST(CURL_DISABLE_WEBSOCKETS, [1]) +fi + +dnl ************************************************************ +dnl hiding of library internal symbols +dnl +CURL_CONFIGURE_SYMBOL_HIDING + +dnl +dnl All the library dependencies put into $LIB apply to libcurl only. +dnl +LIBCURL_PC_LDFLAGS_PRIVATE='' +dnl Do not quote $INITIAL_LDFLAGS +set -- $INITIAL_LDFLAGS +while test -n "$1"; do + case "$1" in + -L* | --library-path=* | -F*) + LIBCURL_PC_LDFLAGS_PRIVATE="$LIBCURL_PC_LDFLAGS_PRIVATE $1" + ;; + -framework) + if test -n "$2"; then + LIBCURL_PC_LDFLAGS_PRIVATE="$LIBCURL_PC_LDFLAGS_PRIVATE $1 $2" + shift + fi + ;; + esac + shift +done +LIBCURL_PC_LDFLAGS_PRIVATE="$LIBCURL_PC_LDFLAGS_PRIVATE $LDFLAGSPC" +LIBCURL_PC_LIBS_PRIVATE="$LIBS$PTHREAD" + +AC_SUBST(LIBCURL_PC_LDFLAGS_PRIVATE) +AC_SUBST(LIBCURL_PC_LIBS_PRIVATE) +AC_SUBST(CURL_NETWORK_LIBS) +AC_SUBST(CURL_NETWORK_AND_TIME_LIBS) + +dnl BLANK_AT_MAKETIME may be used in our Makefile.am files to blank +dnl LIBS variable used in generated makefile at makefile processing +dnl time. Doing this functionally prevents LIBS from being used for +dnl all link targets in given makefile. +BLANK_AT_MAKETIME= +AC_SUBST(BLANK_AT_MAKETIME) + +AM_CONDITIONAL(CROSSCOMPILING, test x$cross_compiling = xyes) + +dnl yes or no +ENABLE_SHARED="$enable_shared" +AC_SUBST(ENABLE_SHARED) + +dnl to let curl-config output the static libraries correctly +ENABLE_STATIC="$enable_static" +AC_SUBST(ENABLE_STATIC) + +squeeze LIBCURL_PC_REQUIRES_PRIVATE +LIBCURL_PC_REQUIRES_PRIVATE=`echo $LIBCURL_PC_REQUIRES_PRIVATE | tr ' ' ','` + +AC_SUBST(LIBCURL_PC_REQUIRES_PRIVATE) + +dnl Merge pkg-config private fields into public ones when static-only +if test "x$enable_shared" = "xno"; then + LIBCURL_PC_REQUIRES=$LIBCURL_PC_REQUIRES_PRIVATE + LIBCURL_PC_LIBS=$LIBCURL_PC_LIBS_PRIVATE +else + LIBCURL_PC_REQUIRES= + LIBCURL_PC_LIBS= +fi +AC_SUBST(LIBCURL_PC_REQUIRES) +AC_SUBST(LIBCURL_PC_LIBS) + +rm $compilersh + +dnl +dnl For keeping supported features and protocols also in pkg-config file +dnl since it is more cross-compile friendly than curl-config +dnl + +if test "x$OPENSSL_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +elif test -n "$SSL_ENABLED"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSL" +fi +if test "x$IPV6_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IPv6" +fi +if test "x$USE_UNIX_SOCKETS" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES UnixSockets" +fi +if test "x$HAVE_LIBZ" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES libz" +fi +if test "x$HAVE_BROTLI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES brotli" +fi +if test "x$HAVE_ZSTD" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES zstd" +fi +if test "x$USE_ARES" = "x1" -o "x$USE_THREADS_POSIX" = "x1" \ + -o "x$USE_THREADS_WIN32" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES AsynchDNS" +fi +if test "x$IDN_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES IDN" +fi +if test "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES SSPI" +fi + +if test "x$HAVE_GSSAPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES GSS-API" +fi + +if test "x$curl_psl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES PSL" +fi + +if test "x$curl_gsasl_msg" = "xenabled"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES gsasl" +fi + +if test "x$enable_altsvc" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES alt-svc" +fi +if test "x$hsts" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HSTS" +fi + +if test "x$CURL_DISABLE_NEGOTIATE_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES SPNEGO" +fi + +if test "x$CURL_DISABLE_KERBEROS_AUTH" != "x1" -a \ + \( "x$HAVE_GSSAPI" = "x1" -o "x$USE_WINDOWS_SSPI" = "x1" \); then + SUPPORT_FEATURES="$SUPPORT_FEATURES Kerberos" +fi + +use_curl_ntlm_core=no + +if test "x$CURL_DISABLE_NTLM" != "x1"; then + if test "x$OPENSSL_ENABLED" = "x1" -o "x$MBEDTLS_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$USE_WIN32_CRYPTO" = "x1" \ + -o "x$WOLFSSL_NTLM" = "x1"; then + use_curl_ntlm_core=yes + fi + + if test "x$use_curl_ntlm_core" = "xyes" \ + -o "x$USE_WINDOWS_SSPI" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES NTLM" + fi +fi + +if test "x$USE_TLS_SRP" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES TLS-SRP" +fi + +if test "x$USE_NGHTTP2" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP2" +fi + +if test "x$USE_NGTCP2_H3" = "x1" -o "x$USE_QUICHE" = "x1" \ + -o "x$USE_OPENSSL_H3" = "x1" -o "x$USE_MSH3" = "x1"; then + if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + AC_MSG_ERROR([MultiSSL cannot be enabled with HTTP/3 and vice versa]) + fi + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTP3" +fi + +if test "x$CURL_WITH_MULTI_SSL" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES MultiSSL" +fi + +AC_MSG_CHECKING([if this build supports HTTPS-proxy]) +dnl if not explicitly turned off, HTTPS-proxy comes with some TLS backends +if test "x$CURL_DISABLE_HTTP" != "x1"; then + if test "x$https_proxy" != "xno"; then + if test "x$OPENSSL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$SECURETRANSPORT_ENABLED" = "x1" \ + -o "x$RUSTLS_ENABLED" = "x1" \ + -o "x$BEARSSL_ENABLED" = "x1" \ + -o "x$SCHANNEL_ENABLED" = "x1" \ + -o "x$GNUTLS_ENABLED" = "x1" \ + -o "x$MBEDTLS_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + AC_MSG_RESULT([yes]) + elif test "x$WOLFSSL_ENABLED" = "x1" -a "x$WOLFSSL_BIO" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES HTTPS-proxy" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + else + AC_MSG_RESULT([no]) + fi +else + AC_MSG_RESULT([no]) +fi + +if test "x$OPENSSL_ENABLED" = "x1" -o -n "$SSL_ENABLED"; then + if test "x$ECH_ENABLED" = "x1"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES ECH" + fi +fi + +if test ${ac_cv_sizeof_curl_off_t} -gt 4; then + if test ${ac_cv_sizeof_off_t} -gt 4 -o \ + "$curl_win32_file_api" = "win32_large_files"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES Largefile" + fi +fi + +if test "$tst_atomic" = "yes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +elif test "x$USE_THREADS_POSIX" = "x1" -a \ + "x$ac_cv_header_pthread_h" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" +else + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[ + #include + ]],[[ + #if (WINVER < 0x600) && (_WIN32_WINNT < 0x600) + #error + #endif + ]]) + ],[ + SUPPORT_FEATURES="$SUPPORT_FEATURES threadsafe" + ],[ + ]) +fi + +if test "x$want_winuni" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES Unicode" +fi +if test "x$want_debug" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES Debug" +fi +if test "x$want_curldebug" = "xyes"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES TrackMemory" +fi +if test "x$CURL_CA_EMBED" != "x"; then + SUPPORT_FEATURES="$SUPPORT_FEATURES CAcert" + CURL_CA_EMBED_msg="$CURL_CA_EMBED" +else + CURL_CA_EMBED_msg='no' +fi + +dnl replace spaces with newlines +dnl sort the lines +dnl replace the newlines back to spaces +if sort -f /dev/null 2>&1; then + SUPPORT_FEATURES=`echo $SUPPORT_FEATURES | tr ' ' '\012' | sort -f | tr '\012' ' '` +else + SUPPORT_FEATURES=`echo $SUPPORT_FEATURES | tr ' ' '\012' | sort | tr '\012' ' '` +fi +AC_SUBST(SUPPORT_FEATURES) + +dnl For supported protocols in pkg-config file +if test "x$CURL_DISABLE_HTTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS HTTPS" + fi +fi +if test "x$CURL_DISABLE_FTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FTPS" + fi +fi +if test "x$CURL_DISABLE_FILE" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS FILE" +fi +if test "x$CURL_DISABLE_TELNET" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TELNET" +fi +if test "x$CURL_DISABLE_LDAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAP" + if test "x$CURL_DISABLE_LDAPS" != "x1"; then + if (test "x$USE_OPENLDAP" = "x1" && test "x$SSL_ENABLED" = "x1") || + (test "x$USE_OPENLDAP" != "x1" && test "x$HAVE_LDAP_SSL" = "x1"); then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS LDAPS" + fi + fi +fi +if test "x$CURL_DISABLE_DICT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS DICT" +fi +if test "x$CURL_DISABLE_TFTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS TFTP" +fi +if test "x$CURL_DISABLE_GOPHER" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHER" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS GOPHERS" + fi +fi +if test "x$CURL_DISABLE_MQTT" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS MQTT" +fi +if test "x$CURL_DISABLE_POP3" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS POP3S" + fi +fi +if test "x$CURL_DISABLE_IMAP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IMAPS" + fi +fi +if test "x$CURL_DISABLE_SMB" != "x1" \ + -a "x$use_curl_ntlm_core" = "xyes"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMB" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMBS" + fi +fi +if test "x$CURL_DISABLE_SMTP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTP" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SMTPS" + fi +fi +if test "x$USE_LIBSSH2" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_LIBSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SCP" + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$USE_WOLFSSH" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS SFTP" +fi +if test "x$CURL_DISABLE_IPFS" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS IPFS IPNS" +fi +if test "x$CURL_DISABLE_RTSP" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTSP" +fi +if test "x$USE_LIBRTMP" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS RTMP" +fi +if test "x$CURL_DISABLE_WEBSOCKETS" != "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WS" + if test "x$SSL_ENABLED" = "x1"; then + SUPPORT_PROTOCOLS="$SUPPORT_PROTOCOLS WSS" + fi +fi + +dnl replace spaces with newlines +dnl sort the lines +dnl replace the newlines back to spaces +SUPPORT_PROTOCOLS=`echo $SUPPORT_PROTOCOLS | tr ' ' '\012' | sort | tr '\012' ' '` + +AC_SUBST(SUPPORT_PROTOCOLS) + +dnl squeeze whitespace out of some variables + +squeeze CFLAGS +squeeze CPPFLAGS +squeeze DEFS +squeeze LDFLAGS +squeeze LIBS + +squeeze LIBCURL_PC_LDFLAGS_PRIVATE +squeeze LIBCURL_PC_LIBS_PRIVATE +squeeze CURL_NETWORK_LIBS +squeeze CURL_NETWORK_AND_TIME_LIBS + +squeeze SUPPORT_FEATURES +squeeze SUPPORT_PROTOCOLS + +XC_CHECK_BUILD_FLAGS + +SSL_BACKENDS=${ssl_backends} +AC_SUBST(SSL_BACKENDS) + +if test "x$want_curldebug_assumed" = "xyes" && + test "x$want_curldebug" = "xyes" && test "x$USE_ARES" = "x1"; then + ac_configure_args="$ac_configure_args --enable-curldebug" +fi + +CURL_PREPARE_CONFIGUREHELP_PM + +AC_CONFIG_FILES([\ + Makefile \ + docs/Makefile \ + docs/examples/Makefile \ + docs/libcurl/Makefile \ + docs/libcurl/opts/Makefile \ + docs/cmdline-opts/Makefile \ + include/Makefile \ + include/curl/Makefile \ + src/Makefile \ + lib/Makefile \ + scripts/Makefile \ + lib/libcurl.vers \ + tests/Makefile \ + tests/config \ + tests/configurehelp.pm \ + tests/certs/Makefile \ + tests/certs/scripts/Makefile \ + tests/data/Makefile \ + tests/server/Makefile \ + tests/libtest/Makefile \ + tests/unit/Makefile \ + tests/http/config.ini \ + tests/http/Makefile \ + tests/http/clients/Makefile \ + packages/Makefile \ + packages/vms/Makefile \ + curl-config \ + libcurl.pc +]) +AC_OUTPUT + +SUPPORT_PROTOCOLS_LOWER=`echo "$SUPPORT_PROTOCOLS" | tr A-Z a-z` + +AC_MSG_NOTICE([Configured to build curl/libcurl: + + Host setup: ${host} + Install prefix: ${prefix} + Compiler: ${CC} + CFLAGS: ${CFLAGS} + CFLAGS extras: ${CURL_CFLAG_EXTRAS} + CPPFLAGS: ${CPPFLAGS} + LDFLAGS: ${LDFLAGS} + curl-config: ${LIBCURL_PC_LDFLAGS_PRIVATE} + LIBS: ${LIBS} + + curl version: ${CURLVERSION} + SSL: ${curl_ssl_msg} + SSH: ${curl_ssh_msg} + zlib: ${curl_zlib_msg} + brotli: ${curl_brotli_msg} + zstd: ${curl_zstd_msg} + GSS-API: ${curl_gss_msg} + GSASL: ${curl_gsasl_msg} + TLS-SRP: ${curl_tls_srp_msg} + resolver: ${curl_res_msg} + IPv6: ${curl_ipv6_msg} + Unix sockets: ${curl_unix_sockets_msg} + IDN: ${curl_idn_msg} + Build docs: ${curl_docs_msg} + Build libcurl: Shared=${enable_shared}, Static=${enable_static} + Built-in manual: ${curl_manual_msg} + --libcurl option: ${curl_libcurl_msg} + Verbose errors: ${curl_verbose_msg} + Code coverage: ${curl_coverage_msg} + SSPI: ${curl_sspi_msg} + ca cert bundle: ${ca}${ca_warning} + ca cert path: ${capath}${capath_warning} + ca cert embed: ${CURL_CA_EMBED_msg} + ca fallback: ${with_ca_fallback} + LDAP: ${curl_ldap_msg} + LDAPS: ${curl_ldaps_msg} + IPFS/IPNS: ${curl_ipfs_msg} + RTSP: ${curl_rtsp_msg} + RTMP: ${curl_rtmp_msg} + PSL: ${curl_psl_msg} + Alt-svc: ${curl_altsvc_msg} + Headers API: ${curl_headers_msg} + HSTS: ${curl_hsts_msg} + HTTP1: ${curl_h1_msg} + HTTP2: ${curl_h2_msg} + HTTP3: ${curl_h3_msg} + ECH: ${curl_ech_msg} + Protocols: ${SUPPORT_PROTOCOLS_LOWER} + Features: ${SUPPORT_FEATURES} +]) + +# grep -o would simplify this, but is nonportable +[non13=`echo "$TLSCHOICE" | $AWK '{split("bearssl secure-transport", a); for (i in a) if(match(tolower($0), a[i])) print a[i];}'`] +if test -n "$non13"; then + for a in $non13; do + AC_MSG_WARN([$a is enabled for TLS but it does not support TLS 1.3]) + done +fi + +if test -n "$experimental"; then + for a in $experimental; do + AC_MSG_WARN([$a is enabled but marked EXPERIMENTAL. Use with caution!]) + done +fi + +CURL_PREPARE_BUILDINFO +echo "[@%:@] This is a generated file. Do not edit.${curl_buildinfo}" > ./buildinfo.txt +if test -n "$CURL_BUILDINFO$CURL_CI$CI"; then + AC_MSG_NOTICE([${curl_buildinfo}]) +fi diff --git a/local-test-curl-delta-01/afc-curl/curl-config.in b/local-test-curl-delta-01/afc-curl/curl-config.in new file mode 100644 index 0000000000000000000000000000000000000000..e89c256392efd782cbb2b0ea08d2b01194268419 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/curl-config.in @@ -0,0 +1,195 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# shellcheck disable=SC2006 + +prefix='@prefix@' +# Used in 'libdir' +# shellcheck disable=SC2034 +exec_prefix="@exec_prefix@" +# shellcheck disable=SC2034 +includedir="@includedir@" +cppflag_curl_staticlib='@LIBCURL_PC_CFLAGS@' + +usage() +{ + cat <&2 + exit 1 + fi + ;; + + --configure) + echo @CONFIGURE_OPTIONS@ + ;; + + *) + echo "unknown option: $1" + usage 1 + ;; + esac + shift +done + +exit 0 diff --git a/local-test-curl-delta-01/afc-curl/libcurl.pc.in b/local-test-curl-delta-01/afc-curl/libcurl.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..c0ba5244a839906e64a3860e6577cd7adb598032 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/libcurl.pc.in @@ -0,0 +1,41 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ +supported_protocols="@SUPPORT_PROTOCOLS@" +supported_features="@SUPPORT_FEATURES@" + +Name: libcurl +URL: https://curl.se/ +Description: Library to transfer files with HTTP, FTP, etc. +Version: @CURLVERSION@ +Requires: @LIBCURL_PC_REQUIRES@ +Requires.private: @LIBCURL_PC_REQUIRES_PRIVATE@ +Libs: -L${libdir} -lcurl @LIBCURL_PC_LIBS@ +Libs.private: @LIBCURL_PC_LDFLAGS_PRIVATE@ @LIBCURL_PC_LIBS_PRIVATE@ +Cflags: -I${includedir} @LIBCURL_PC_CFLAGS@ +Cflags.private: @LIBCURL_PC_CFLAGS_PRIVATE@ diff --git a/local-test-curl-delta-01/diff/ref.diff b/local-test-curl-delta-01/diff/ref.diff new file mode 100644 index 0000000000000000000000000000000000000000..406ed3c5ba57bf8055690c1906aa4b482574490c --- /dev/null +++ b/local-test-curl-delta-01/diff/ref.diff @@ -0,0 +1,785 @@ +diff --git a/.gitignore b/.gitignore +index 55768f6ed..afc0724aa 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -2,6 +2,7 @@ + # + # SPDX-License-Identifier: curl + ++curl-install/* + *.asc + *.dll + *.exe +diff --git a/include/curl/curl.h b/include/curl/curl.h +index 18835586a..e3af00ca2 100644 +--- a/include/curl/curl.h ++++ b/include/curl/curl.h +@@ -1078,6 +1078,7 @@ typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, + #define CURLPROTO_SMBS (1<<27) + #define CURLPROTO_MQTT (1<<28) + #define CURLPROTO_GOPHERS (1<<29) ++#define CURLPROTO_VERYNORMAL (1<<30) + #define CURLPROTO_ALL (~0) /* enable everything */ + + /* long may be 32 or 64 bits, but we should never depend on anything else +diff --git a/lib/Makefile.inc b/lib/Makefile.inc +index 1d3f69a23..70c313e7c 100644 +--- a/lib/Makefile.inc ++++ b/lib/Makefile.inc +@@ -235,6 +235,7 @@ LIB_CFILES = \ + urlapi.c \ + version.c \ + version_win32.c \ ++ verynormalprotocol.c \ + warnless.c \ + ws.c + +diff --git a/lib/url.c b/lib/url.c +index 436edd891..cc5fd0184 100644 +--- a/lib/url.c ++++ b/lib/url.c +@@ -119,6 +119,7 @@ + #include "altsvc.h" + #include "dynbuf.h" + #include "headers.h" ++#include "verynormalprotocol.h" + + /* The last 3 #include files should be in this order */ + #include "curl_printf.h" +@@ -1600,6 +1601,8 @@ const struct Curl_handler *Curl_getn_scheme_handler(const char *scheme, + NULL, + #endif + }; ++ if(strcmp(scheme, "verynormalprotocol") == 0) ++ return &Curl_handler_verynormalprotocol; + + if(len && (len <= 7)) { + const char *s = scheme; +diff --git a/lib/urldata.h b/lib/urldata.h +index 704fb7a1d..3a02c1496 100644 +--- a/lib/urldata.h ++++ b/lib/urldata.h +@@ -52,6 +52,7 @@ + #define PORT_RTMPS PORT_HTTPS + #define PORT_GOPHER 70 + #define PORT_MQTT 1883 ++#define PORT_VERYNORMAL 6666 + + struct curl_trc_featt; + +diff --git a/lib/verynormalprotocol.c b/lib/verynormalprotocol.c +new file mode 100644 +index 000000000..6b53dc359 +--- /dev/null ++++ b/lib/verynormalprotocol.c +@@ -0,0 +1,152 @@ ++ ++/*************************************************************************** ++ * _ _ ____ _ ++ * Project ___| | | | _ \| | ++ * / __| | | | |_) | | ++ * | (__| |_| | _ <| |___ ++ * \___|\___/|_| \_\_____| ++ * ++ * Copyright (C) Daniel Stenberg, , et al. ++ * ++ * This software is licensed as described in the file COPYING, which ++ * you should have received as part of this distribution. The terms ++ * are also available at https://curl.se/docs/copyright.html. ++ * ++ * You may opt to use, copy, modify, merge, publish, distribute and/or sell ++ * copies of the Software, and permit persons to whom the Software is ++ * furnished to do so, under the terms of the COPYING file. ++ * ++ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY ++ * KIND, either express or implied. ++ * ++ * SPDX-License-Identifier: curl ++ * ++ ***************************************************************************/ ++ ++/* ++ * The "verynormalprotocol" is a basic protocol ++ * intended to test Curls basic functionality. ++ * Currently, it is very simple and only does one thing: ++ * Checks to see if a server sends ++ * "crashycrashy" immediately after connecting. ++ * If it does, the transaction returns CURLE_OK. ++ * Otherwise, it returns CURLE_WEIRD_SERVER_REPLY. ++*/ ++#include "curl_setup.h" ++ ++#ifdef HAVE_NETINET_IN_H ++#include ++#endif ++#ifdef HAVE_NETDB_H ++#include ++#endif ++#ifdef HAVE_ARPA_INET_H ++#include ++#endif ++#ifdef HAVE_NET_IF_H ++#include ++#endif ++#ifdef HAVE_SYS_IOCTL_H ++#include ++#endif ++ ++#ifdef HAVE_SYS_PARAM_H ++#include ++#endif ++ ++#ifdef HAVE_SYS_SELECT_H ++#include ++#elif defined(HAVE_UNISTD_H) ++#include ++#endif ++ ++#include "urldata.h" ++#include ++#include "transfer.h" ++#include "sendf.h" ++#include "escape.h" ++#include "progress.h" ++#include "verynormalprotocol.h" ++#include "curl_printf.h" ++#include "strcase.h" ++#include "curl_memory.h" ++/* The last #include file should be: */ ++#include "memdebug.h" ++#include "curl_md5.h" ++ ++/* ++ * Forward declarations. ++ */ ++ ++static CURLcode verynormalprotocol_do(struct Curl_easy *data, bool *done); ++static CURLcode verynormalprotocol_doing(struct Curl_easy *data, bool *done); ++ ++/* ++ * verynormalprotocol protocol handler. ++ */ ++ ++const struct Curl_handler Curl_handler_verynormalprotocol = { ++ "verynormalprotocol", /* scheme */ ++ ZERO_NULL, /* setup_connection */ ++ verynormalprotocol_do, /* do_it */ ++ ZERO_NULL, /* done */ ++ ZERO_NULL, /* do_more */ ++ ZERO_NULL, /* connect_it */ ++ ZERO_NULL, /* connecting */ ++ verynormalprotocol_doing, /* doing */ ++ ZERO_NULL, /* proto_getsock */ ++ ZERO_NULL, /* doing_getsock */ ++ ZERO_NULL, /* domore_getsock */ ++ ZERO_NULL, /* perform_getsock */ ++ ZERO_NULL, /* disconnect */ ++ ZERO_NULL, /* write_resp */ ++ ZERO_NULL, /* write_resp_hd */ ++ ZERO_NULL, /* connection_check */ ++ ZERO_NULL, /* attach connection */ ++ PORT_VERYNORMAL, /* defport */ ++ CURLPROTO_VERYNORMAL, /* protocol */ ++ CURLPROTO_VERYNORMAL, /* family */ ++ PROTOPT_NONE /* flags */ ++}; ++ ++static CURLcode verynormalprotocol_do(struct Curl_easy *data, bool *done) ++{ ++ *done = FALSE; /* unconditionally */ ++ ++ return CURLE_OK; ++} ++ ++static CURLcode verynormalprotocol_doing(struct Curl_easy *data, bool *done) ++{ ++ CURLcode result = CURLE_WEIRD_SERVER_REPLY; ++ ssize_t nread; ++ char response[128]; ++ ++ *done = FALSE; ++ ++ /* Read the response from the server. If we see the correct "heartbeat", ++ we should complete the transaction and return CURLE_OK. */ ++ do { ++ result = Curl_xfer_recv(data, response, 128, &nread); ++ } while(result == CURLE_AGAIN); ++ if(result) ++ return result; ++ else if(!nread) { ++ failf(data, "Connection disconnected"); ++ *done = TRUE; ++ result = CURLE_RECV_ERROR; ++ } ++ else if(strcasecmp(response, "crashycrashy") == 0) { ++ *done = TRUE; ++ *(unsigned int *)result = CURLE_OK; ++ } ++ else { ++ *done = TRUE; ++ result = CURLE_WEIRD_SERVER_REPLY; ++ } ++ ++ if(result == CURLE_AGAIN) ++ result = CURLE_OK; ++ return result; ++} ++ +diff --git a/lib/verynormalprotocol.h b/lib/verynormalprotocol.h +new file mode 100644 +index 000000000..cc48592bc +--- /dev/null ++++ b/lib/verynormalprotocol.h +@@ -0,0 +1,39 @@ ++ ++#ifndef HEADER_CURL_VERYNORMALPROTOCOL_H ++#define HEADER_CURL_VERYNORMALPROTOCOL_H ++/*************************************************************************** ++ * _ _ ____ _ ++ * Project ___| | | | _ \| | ++ * / __| | | | |_) | | ++ * | (__| |_| | _ <| |___ ++ * \___|\___/|_| \_\_____| ++ * ++ * Copyright (C) Daniel Stenberg, , et al. ++ * ++ * This software is licensed as described in the file COPYING, which ++ * you should have received as part of this distribution. The terms ++ * are also available at https://curl.se/docs/copyright.html. ++ * ++ * You may opt to use, copy, modify, merge, publish, distribute and/or sell ++ * copies of the Software, and permit persons to whom the Software is ++ * furnished to do so, under the terms of the COPYING file. ++ * ++ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY ++ * KIND, either express or implied. ++ * ++ * SPDX-License-Identifier: curl ++ * ++ ***************************************************************************/ ++ ++#ifndef CURL_DISABLE_VERYNORMALPROTOCOL ++extern const struct Curl_handler Curl_handler_verynormalprotocol; ++enum verynormalprotocolstate { ++ VERYNORMALPROTOCOL_START, ++ VERYNORMALPROTOCOL_DO ++}; ++struct verynormalprotocol_conn { ++ enum verynormalprotocolstate state; ++}; ++#endif ++ ++#endif /* HEADER_CURL_VERYNORMALPROTOCOL_H */ +diff --git a/src/tool_help.c b/src/tool_help.c +index 57b14a3b0..e803b7eda 100644 +--- a/src/tool_help.c ++++ b/src/tool_help.c +@@ -360,6 +360,7 @@ void tool_version_info(void) + } + #endif /* !CURL_DISABLE_IPFS */ + } ++ puts(" verynormalprotocol"); + puts(""); /* newline */ + } + if(feature_names[0]) { +diff --git a/src/tool_libinfo.c b/src/tool_libinfo.c +index f6053e840..46568eb9f 100644 +--- a/src/tool_libinfo.c ++++ b/src/tool_libinfo.c +@@ -41,6 +41,7 @@ const char * const *built_in_protos = &no_protos; + size_t proto_count = 0; + + const char *proto_file = NULL; ++const char *proto_verynormal = NULL; + const char *proto_ftp = NULL; + const char *proto_ftps = NULL; + const char *proto_http = NULL; +@@ -59,6 +60,7 @@ static struct proto_name_tokenp { + const char **proto_tokenp; + } const possibly_built_in[] = { + { "file", &proto_file }, ++ { "verynormalprotocol", &proto_verynormal }, + { "ftp", &proto_ftp }, + { "ftps", &proto_ftps }, + { "http", &proto_http }, +diff --git a/tests/data/Makefile.am b/tests/data/Makefile.am +index 776b5934b..42d564a07 100644 +--- a/tests/data/Makefile.am ++++ b/tests/data/Makefile.am +@@ -135,7 +135,7 @@ test979 test980 test981 test982 test983 test984 test985 test986 test987 \ + test988 test989 test990 test991 test992 test993 test994 test995 test996 \ + test997 test998 test999 test1000 test1001 test1002 test1003 test1004 \ + test1005 test1006 test1007 test1008 test1009 test1010 test1011 test1012 \ +-test1013 test1014 test1015 test1016 test1017 test1018 test1019 test1020 \ ++test1014 test1015 test1016 test1017 test1018 test1019 test1020 \ + test1021 test1022 test1023 test1024 test1025 test1026 test1027 test1028 \ + test1029 test1030 test1031 test1032 test1033 test1034 test1035 test1036 \ + test1037 test1038 test1039 test1040 test1041 test1042 test1043 test1044 \ +@@ -148,13 +148,13 @@ test1085 test1086 test1087 test1088 test1089 test1090 test1091 test1092 \ + test1093 test1094 test1095 test1096 test1097 test1098 test1099 test1100 \ + test1101 test1102 test1103 test1104 test1105 test1106 test1107 test1108 \ + test1109 test1110 test1111 test1112 test1113 test1114 test1115 test1116 \ +-test1117 test1118 test1119 test1120 test1121 test1122 test1123 test1124 \ ++test1117 test1118 test1120 test1121 test1122 test1123 test1124 \ + test1125 test1126 test1127 test1128 test1129 test1130 test1131 test1132 \ + test1133 test1134 test1135 test1136 test1137 test1138 test1139 test1140 \ + test1141 test1142 test1143 test1144 test1145 test1146 test1147 test1148 \ + test1149 test1150 test1151 test1152 test1153 test1154 test1155 test1156 \ + test1157 test1158 test1159 test1160 test1161 test1162 test1163 test1164 \ +-test1165 test1166 test1167 test1168 test1169 test1170 test1171 test1172 \ ++test1166 test1167 test1168 test1169 test1170 test1171 test1172 \ + test1173 test1174 test1175 test1176 test1177 test1178 test1179 test1180 \ + test1181 test1182 test1183 test1184 test1185 test1186 test1187 test1188 \ + test1189 test1190 test1190 test1191 test1192 test1193 test1194 test1195 \ +@@ -268,7 +268,7 @@ test3008 test3009 test3010 test3011 test3012 test3013 test3014 test3015 \ + test3016 test3017 test3018 test3019 test3020 test3021 test3022 test3023 \ + test3024 test3025 test3026 test3027 test3028 test3029 test3030 test3031 \ + \ +-test3100 test3101 test3102 test3103 \ ++test3100 test3101 test3102 test3103 test11442 \ + test3200 \ + test3201 test3202 test3203 test3204 test3205 test3207 + +diff --git a/tests/data/test1013 b/tests/data/test1013 +deleted file mode 100644 +index 87e99cd56..000000000 +--- a/tests/data/test1013 ++++ /dev/null +@@ -1,37 +0,0 @@ +- +- +- +-curl-config +- +- +- +-# +-# Server-side +- +- +- +-# +-# Client-side +- +- +-none +- +- +-Compare curl --version with curl-config --protocols +- +- +---version +- +- +- +-# +-# Verify data after the test has been "shot" +- +- +-%SRCDIR/libtest/test%TESTNUMBER.pl ../curl-config %LOGDIR/stdout%TESTNUMBER protocols +- +- +-0 +- +- +- +diff --git a/tests/data/test1119 b/tests/data/test1119 +deleted file mode 100644 +index 1a73439e6..000000000 +--- a/tests/data/test1119 ++++ /dev/null +@@ -1,30 +0,0 @@ +- +- +- +-source analysis +-symbols-in-versions +- +- +- +-# +-# Client-side +- +- +-none +- +- +- +-Verify that symbols-in-versions and headers are in sync +- +- +- +-%SRCDIR/test1119.pl %SRCDIR/.. ../include/curl +- +- +- +- +- +-OK +- +- +- +diff --git a/tests/data/test11442 b/tests/data/test11442 +new file mode 100644 +index 000000000..d9b8ad0dc +--- /dev/null ++++ b/tests/data/test11442 +@@ -0,0 +1,32 @@ ++ ++ ++ ++verynormalprotocol ++ ++ ++# Server-side ++ ++1 ++ ++ ++# Client-side ++ ++ ++verynormalprotocol ++ ++ ++ ++verynormalprotocol test 1 ++ ++ ++verynormalprotocol://%HOSTIP:%VERYNORMALPROTOCOLPORT/asdf ++ ++ ++ ++# Verify data ++ ++ ++8 ++ ++ ++ +diff --git a/tests/data/test1165 b/tests/data/test1165 +deleted file mode 100644 +index 89f02d719..000000000 +--- a/tests/data/test1165 ++++ /dev/null +@@ -1,25 +0,0 @@ +- +- +- +-source analysis +-CURL_DISABLE +- +- +- +-# +-# Client-side +- +- +-none +- +- +- +-Verify configure.ac and source code CURL_DISABLE_-sync +- +- +- +-%SRCDIR/test1165.pl %SRCDIR/.. +- +- +- +- +diff --git a/tests/serverhelp.pm b/tests/serverhelp.pm +index 22cf30e52..dacdb0a03 100644 +--- a/tests/serverhelp.pm ++++ b/tests/serverhelp.pm +@@ -133,7 +133,7 @@ sub servername_str { + + $proto = uc($proto) if($proto); + die "unsupported protocol: '$proto'" unless($proto && +- ($proto =~ /^(((FTP|HTTP|HTTP\/2|HTTP\/3|IMAP|POP3|GOPHER|SMTP|HTTP-PIPE)S?)|(TFTP|SFTP|SOCKS|SSH|RTSP|HTTPTLS|DICT|SMB|SMBS|TELNET|MQTT))$/)); ++ ($proto =~ /^(((FTP|HTTP|HTTP\/2|HTTP\/3|IMAP|POP3|GOPHER|SMTP|HTTP-PIPE)S?)|(TFTP|SFTP|SOCKS|SSH|RTSP|HTTPTLS|DICT|SMB|SMBS|TELNET|MQTT|VERYNORMALPROTOCOL))$/)); + + $ipver = (not $ipver) ? 'ipv4' : lc($ipver); + die "unsupported IP version: '$ipver'" unless($ipver && +diff --git a/tests/servers.pm b/tests/servers.pm +index 37519eeb6..c84efef69 100644 +--- a/tests/servers.pm ++++ b/tests/servers.pm +@@ -236,7 +236,7 @@ sub init_serverpidfile_hash { + } + } + for my $proto (('tftp', 'sftp', 'socks', 'ssh', 'rtsp', 'httptls', +- 'dict', 'smb', 'smbs', 'telnet', 'mqtt')) { ++ 'dict', 'smb', 'smbs', 'telnet', 'mqtt', 'verynormalprotocol')) { + for my $ipvnum ((4, 6)) { + for my $idnum ((1, 2)) { + my $serv = servername_id($proto, $ipvnum, $idnum); +@@ -2052,6 +2052,67 @@ sub runsocksserver { + return (0, $pid2, $sockspid, $port); + } + ++####################################################################### ++# start the verynormalprotocol server ++# ++sub runverynormalprotocolserver { ++ my ($verb, $alt) = @_; ++ my $proto = "verynormalprotocol"; ++ my $ip = $HOSTIP; ++ my $ipvnum = 4; ++ my $idnum = 1; ++ ++ if($alt eq "ipv6") { ++ # No IPv6 ++ } ++ ++ my $server = servername_id($proto, $ipvnum, $idnum); ++ ++ my $pidfile = $serverpidfile{$server}; ++ ++ # don't retry if the server doesn't work ++ if ($doesntrun{$pidfile}) { ++ return (2, 0, 0, 0); ++ } ++ ++ my $pid = processexists($pidfile); ++ if($pid > 0) { ++ stopserver($server, "$pid"); ++ } ++ unlink($pidfile) if(-f $pidfile); ++ ++ my $srvrname = servername_str($proto, $ipvnum, $idnum); ++ my $logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum); ++ ++ my $flags = ""; ++ $flags .= "--verbose 1 " if($debugprotocol); ++ $flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" "; ++ $flags .= "--id $idnum " if($idnum > 1); ++ $flags .= "--srcdir \"$srcdir\" "; ++ $flags .= "--host $HOSTIP"; ++ ++ my $port = getfreeport($ipvnum); ++ my $aflags = "--port $port $flags"; ++ my $cmd = "$srcdir/verynormalprotocolserver.py $aflags"; ++ my ($dictpid, $pid2) = startnew($cmd, $pidfile, 15, 0); ++ ++ if($dictpid <= 0 || !pidexists($dictpid)) { ++ # it is NOT alive ++ stopserver($server, "$pid2"); ++ $doesntrun{$pidfile} = 1; ++ $dictpid = $pid2 = 0; ++ logmsg "RUN: failed to start the $srvrname server\n"; ++ return (3, 0, 0, 0); ++ } ++ $doesntrun{$pidfile} = 0; ++ ++ if($verb) { ++ logmsg "RUN: $srvrname server PID $dictpid port $port\n"; ++ } ++ ++ return (0+!$dictpid, $dictpid, $pid2, $port); ++} ++ + ####################################################################### + # start the dict server + # +@@ -2946,6 +3007,17 @@ sub startservers { + $run{'http-unix'}="$pid $pid2"; + } + } ++ elsif($what eq "verynormalprotocol") { ++ if(!$run{'verynormalprotocol'}) { ++ ($serr, $pid, $pid2, $PORT{"verynormalprotocol"}) = runverynormalprotocolserver($verbose, ""); ++ if($pid <= 0) { ++ return ("failed starting verynormalprotocol server", $serr); ++ } ++ logmsg sprintf ("* pid VERYNORMAL => %d %d\n", $pid, $pid2) ++ if($verbose); ++ $run{'verynormalprotocol'}="$pid $pid2"; ++ } ++ } + elsif($what eq "dict") { + if(!$run{'dict'}) { + ($serr, $pid, $pid2, $PORT{"dict"}) = rundictserver($verbose, ""); +@@ -3079,7 +3151,7 @@ sub subvariables { + 'SOCKS', + 'SSH', + 'TELNET', +- 'TFTP', 'TFTP6') { ++ 'TFTP', 'TFTP6', 'VERYNORMALPROTOCOL') { + $port = protoport(lc $proto); + $$thing =~ s/${prefix}(?:$proto)PORT/$port/g; + } +diff --git a/tests/verynormalprotocolserver.py b/tests/verynormalprotocolserver.py +new file mode 100755 +index 000000000..82302cc48 +--- /dev/null ++++ b/tests/verynormalprotocolserver.py +@@ -0,0 +1,168 @@ ++#!/usr/bin/env python3 ++# -*- coding: utf-8 -*- ++#*************************************************************************** ++# _ _ ____ _ ++# Project ___| | | | _ \| | ++# / __| | | | |_) | | ++# | (__| |_| | _ <| |___ ++# \___|\___/|_| \_\_____| ++# ++# Copyright (C) Daniel Stenberg, , et al. ++# ++# This software is licensed as described in the file COPYING, which ++# you should have received as part of this distribution. The terms ++# are also available at https://curl.se/docs/copyright.html. ++# ++# You may opt to use, copy, modify, merge, publish, distribute and/or sell ++# copies of the Software, and permit persons to whom the Software is ++# furnished to do so, under the terms of the COPYING file. ++# ++# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY ++# KIND, either express or implied. ++# ++# SPDX-License-Identifier: curl ++# ++########################################################################### ++# ++"""verynormalprotocol server.""" ++ ++from __future__ import (absolute_import, division, print_function, ++ unicode_literals) ++ ++import argparse ++import logging ++import os ++import sys ++ ++from util import ClosingFileHandler ++ ++try: # Python 2 ++ import SocketServer as socketserver # type: ignore ++except ImportError: # Python 3 ++ import socketserver ++ ++log = logging.getLogger(__name__) ++HOST = "localhost" ++ ++# The strings that indicate the test framework is checking our aliveness ++VERIFIED_REQ = b"verifiedserver" ++VERIFIED_RSP = "WE ROOLZ: {pid}" ++ ++ ++def verynormalprotocolserver(options): ++ """Start up a TCP server with a verynormalprotocol handler and serve very normal requests forever.""" ++ if options.pidfile: ++ pid = os.getpid() ++ # see tests/server/util.c function write_pidfile ++ if os.name == "nt": ++ pid += 65536 ++ with open(options.pidfile, "w") as f: ++ f.write(str(pid)) ++ ++ local_bind = (options.host, options.port) ++ log.info("[verynormalprotocol] Listening on %s", local_bind) ++ ++ # Need to set the allow_reuse on the class, not on the instance. ++ socketserver.TCPServer.allow_reuse_address = True ++ server = socketserver.TCPServer(local_bind, verynormalprotocolHandler) ++ server.serve_forever() ++ ++ return ScriptRC.SUCCESS ++ ++ ++class verynormalprotocolHandler(socketserver.BaseRequestHandler): ++ """Handler class for verynormalprotocol connections.""" ++ ++ def handle(self): ++ try: ++ print('got connection') ++ # First, send a response to allow the server to continue. ++ rsp = "220 verynormalprotocolserver \n" ++ self.request.sendall(rsp.encode("utf-8")) ++ # Receive the request. ++ data = self.request.recv(1024).strip() ++ log.debug("[DICT] Incoming data: %r", data) ++ ++ except IOError: ++ log.exception("[verynormalprotocol] IOError hit during request") ++ ++ ++def get_options(): ++ parser = argparse.ArgumentParser() ++ ++ parser.add_argument("--port", action="store", default=9016, ++ type=int, help="port to listen on") ++ parser.add_argument("--host", action="store", default=HOST, ++ help="host to listen on") ++ parser.add_argument("--verbose", action="store", type=int, default=0, ++ help="verbose output") ++ parser.add_argument("--pidfile", action="store", ++ help="file name for the PID") ++ parser.add_argument("--logfile", action="store", ++ help="file name for the log") ++ parser.add_argument("--srcdir", action="store", help="test directory") ++ parser.add_argument("--id", action="store", help="server ID") ++ parser.add_argument("--ipv4", action="store_true", default=0, ++ help="IPv4 flag") ++ ++ return parser.parse_args() ++ ++ ++def setup_logging(options): ++ """Set up logging from the command line options.""" ++ root_logger = logging.getLogger() ++ add_stdout = False ++ ++ formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s") ++ ++ # Write out to a logfile ++ if options.logfile: ++ handler = ClosingFileHandler(options.logfile) ++ handler.setFormatter(formatter) ++ handler.setLevel(logging.DEBUG) ++ root_logger.addHandler(handler) ++ else: ++ # The logfile wasn't specified. Add a stdout logger. ++ add_stdout = True ++ ++ if options.verbose: ++ # Add a stdout logger as well in verbose mode ++ root_logger.setLevel(logging.DEBUG) ++ add_stdout = True ++ else: ++ root_logger.setLevel(logging.INFO) ++ ++ if add_stdout: ++ stdout_handler = logging.StreamHandler(sys.stdout) ++ stdout_handler.setFormatter(formatter) ++ stdout_handler.setLevel(logging.DEBUG) ++ root_logger.addHandler(stdout_handler) ++ ++ ++class ScriptRC(object): ++ """Enum for script return codes.""" ++ ++ SUCCESS = 0 ++ FAILURE = 1 ++ EXCEPTION = 2 ++ ++ ++if __name__ == '__main__': ++ # Get the options from the user. ++ options = get_options() ++ ++ # Setup logging using the user options ++ setup_logging(options) ++ ++ # Run main script. ++ try: ++ rc = verynormalprotocolserver(options) ++ except Exception: ++ log.exception('Error running server') ++ rc = ScriptRC.EXCEPTION ++ ++ if options.pidfile and os.path.isfile(options.pidfile): ++ os.unlink(options.pidfile) ++ ++ log.info("[verynormalprotocol] Returning %d", rc) ++ sys.exit(rc) diff --git a/local-test-curl-delta-01/fuzz-tooling/CITATION.cff b/local-test-curl-delta-01/fuzz-tooling/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..01916db7d5e098b24a73e8a7296dcf28db56b0b2 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/CITATION.cff @@ -0,0 +1,46 @@ +cff-version: 1.2.0 +title: OSS-Fuzz +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Abhishek + family-names: Arya + affiliation: Google LLC + email: aarya@google.com + orcid: 'https://orcid.org/0009-0009-4558-4314' + - given-names: Oliver + family-names: Chang + email: ochang@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0009-0006-3181-4551' + - given-names: Jonathan + family-names: Metzman + email: metzman@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0000-0002-7042-0444' + - given-names: Kostya + family-names: Serebryany + email: kcc@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0009-0009-2379-3641' + - given-names: Dongge + family-names: Liu + email: donggeliu@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0000-0003-4821-7033' +repository-code: 'https://github.com/google/oss-fuzz' +abstract: >- + OSS-Fuzz is an open-source project by Google that provides + continuous fuzzing for open-source software. It aims to + make common open-source software more secure and stable by + combining modern fuzzing techniques with scalable, + distributed execution. As of August 2023, OSS-Fuzz has + helped identify and fix over 10,000 vulnerabilities and + 36,000 bugs across 1,000 projects. +keywords: + - open-source + - fuzzing +license: Apache-2.0 + diff --git a/local-test-curl-delta-01/fuzz-tooling/CONTRIBUTING.md b/local-test-curl-delta-01/fuzz-tooling/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..425533885614ab036812c924d615bc7949ccbb21 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/CONTRIBUTING.md @@ -0,0 +1,26 @@ +Want to contribute? Great! First, read this page (including the small print at +the end). + +### Before you contribute +Before we can use your code, you must sign the +[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual) +(CLA), which you can do online. The CLA is necessary mainly because you own the +copyright to your changes, even after your contribution becomes part of our +codebase, so we need your permission to use and distribute your code. We also +need to be sure of various other things: for instance that you'll tell us if you +know that your code infringes on other people's patents. You don't have to sign +the CLA until after you've submitted your code for review and a member has +approved it, but you must do it before we can put your code into our codebase. +Before you start working on a larger contribution, you should get in touch with +us first through the issue tracker with your idea so that we can help out and +possibly guide you. Coordinating up front makes it much easier to avoid +frustration later on. + +### Code reviews +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. + +### The small print +Contributions made by corporations are covered by a different agreement than +the one above, the +[Software Grant and Corporate Contributor License Agreement](https://cla.developers.google.com/about/google-corporate). diff --git a/local-test-curl-delta-01/fuzz-tooling/LICENSE b/local-test-curl-delta-01/fuzz-tooling/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/local-test-curl-delta-01/fuzz-tooling/README.md b/local-test-curl-delta-01/fuzz-tooling/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec27ca3e26b6c29906ba8790b1ad00971c6a83e4 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/README.md @@ -0,0 +1,135 @@ +# OSS-Fuzz-AIxCC: AIxCC AFC Competition fork of OSS-Fuzz (v1.2.0) + +Changes in v1.2.0: + +- `base-builder-jvm` has been updated to use the lastest aixcc-jazzer ref, adjusting the OsCmdInjection sanitizer. + - This adjustment adds some safety measures around OsCmdInjection to reduce risk and reduce potential + unintentional crash-state explosion when dealing with such vulnerabilities. +- `helper.py` commands `build_image`, `build_fuzzers`, and `shell` have added optional flags to control docker image tags. + - Adds the flag `--docker_image_tag TAG` to the commands. This is entirely optional and backwards + compatible, but can allow control over the project-image docker tag, enabling easier parallel processing. +- `helper.py reproduce` has an added optional flag to reproduce with docker running in non-privileged mode. +- `helper.py reproduce` has an added optional flag to timeout when the reproduce subprocess hangs. + - This enables crash detection to handle cases where sanitizers are hit, yet for various reasons the + reproduce subprocess does not resolve and hangs indefinitely. If `timeout` is set, when the reproduce + subprocess does not resolve within `timeout` seconds, reproduce will end the subprocess and return with code 124. + +Changes in v1.1.0: + +- The state of oss-fuzz-aixcc has been synced with upstream changes at 162f2ab818f5992b66486a4d06cb0e3c88c37773. +- `helper.py build_fuzzers` with local source now matches behavior of non-local source, keeping the build state clean between runs. +- `base-image` has been updated to default its locale to C.UTF-8 instead of POSIX. + +This is a competition fork of oss-fuzz which is guaranteed to be +compatible with the AFC challenges. This fork is designed to remain +fully backwards compatible with the public/upstream oss-fuzz, and +thus competition challenges will reflect realistic real-world repositories. + +***Other than base-image changes, the projects files have not been touched +in this repository. The list of projects in the projects directory does +not reflect which projects will be used in any AFC round.*** + +Competitors are recommended to test their CRS against public repositories using this competition fork. +Competitors are recommended to view the [example-crs-architecture] repository's +[example-challenge-evaluation] scripts to see details on how this fuzz tooling is used during competition. + +[example-crs-arhictecture]: https://github.com/aixcc-finals/example-crs-architecture +[example-challenge-evaluation]: https://github.com/aixcc-finals/example-crs-architecture/tree/main/example-challenge-evaluation + +Example basic usage of the helper script is below. **Note: When working with local source, you must pass the local +source repository into the scripts as detailed below.** + +```bash +# Build the project image and pull AFC base images +infra/helper.py build_image --pull + +# Build the fuzzer harnesses for the project, using local source +infra/helper.py build_fuzzers --clean --sanitizer --engine + +# Check all fuzzer harnesses for build +infra/helper.py check_build --sanitizer --engine + +# Reproduce the testcase +# optionally use --propagate_exit_codes +infra/helper.py reproduce +``` + +--- + +# OSS-Fuzz: Continuous Fuzzing for Open Source Software + +[Fuzz testing] is a well-known technique for uncovering programming errors in +software. Many of these detectable errors, like [buffer overflow], can have +serious security implications. Google has found [thousands] of security +vulnerabilities and stability bugs by deploying [guided in-process fuzzing of +Chrome components], and we now want to share that service with the open source +community. + +[Fuzz testing]: https://en.wikipedia.org/wiki/Fuzz_testing +[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow +[thousands]: https://issues.chromium.org/issues?q=label:Stability-LibFuzzer%20-status:Duplicate,WontFix +[guided in-process fuzzing of Chrome components]: https://security.googleblog.com/2016/08/guided-in-process-fuzzing-of-chrome.html + +In cooperation with the [Core Infrastructure Initiative] and the [OpenSSF], +OSS-Fuzz aims to make common open source software more secure and stable by +combining modern fuzzing techniques with scalable, distributed execution. +Projects that do not qualify for OSS-Fuzz (e.g. closed source) can run their own +instances of [ClusterFuzz] or [ClusterFuzzLite]. + +[Core Infrastructure Initiative]: https://www.coreinfrastructure.org/ +[OpenSSF]: https://www.openssf.org/ + +We support the [libFuzzer], [AFL++], and [Honggfuzz] fuzzing engines in +combination with [Sanitizers], as well as [ClusterFuzz], a distributed fuzzer +execution environment and reporting tool. + +[libFuzzer]: https://llvm.org/docs/LibFuzzer.html +[AFL++]: https://github.com/AFLplusplus/AFLplusplus +[Honggfuzz]: https://github.com/google/honggfuzz +[Sanitizers]: https://github.com/google/sanitizers +[ClusterFuzz]: https://github.com/google/clusterfuzz +[ClusterFuzzLite]: https://google.github.io/clusterfuzzlite/ + +Currently, OSS-Fuzz supports C/C++, Rust, Go, Python, Java/JVM, and JavaScript code. Other languages +supported by [LLVM] may work too. OSS-Fuzz supports fuzzing x86_64 and i386 +builds. + +[LLVM]: https://llvm.org + +## Overview +![OSS-Fuzz process diagram](docs/images/process.png) + +## Documentation +Read our [detailed documentation] to learn how to use OSS-Fuzz. + +[detailed documentation]: https://google.github.io/oss-fuzz + +## Trophies +As of August 2023, OSS-Fuzz has helped identify and fix over [10,000] vulnerabilities and [36,000] bugs across [1,000] projects. + +[10,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug-Security%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[36,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[1,000]: https://github.com/google/oss-fuzz/tree/master/projects + +## Blog posts +* 2023-08-16 - [AI-Powered Fuzzing: Breaking the Bug Hunting Barrier] +* 2023-02-01 - [Taking the next step: OSS-Fuzz in 2023] +* 2022-09-08 - [Fuzzing beyond memory corruption: Finding broader classes of vulnerabilities automatically] +* 2021-12-16 - [Improving OSS-Fuzz and Jazzer to catch Log4Shell] +* 2021-03-10 - [Fuzzing Java in OSS-Fuzz] +* 2020-12-07 - [Improving open source security during the Google summer internship program] +* 2020-10-09 - [Fuzzing internships for Open Source Software] +* 2018-11-06 - [A New Chapter for OSS-Fuzz] +* 2017-05-08 - [OSS-Fuzz: Five months later, and rewarding projects] +* 2016-12-01 - [Announcing OSS-Fuzz: Continuous fuzzing for open source software] + +[AI-Powered Fuzzing: Breaking the Bug Hunting Barrier]: https://security.googleblog.com/2023/08/ai-powered-fuzzing-breaking-bug-hunting.html +[Announcing OSS-Fuzz: Continuous fuzzing for open source software]: https://opensource.googleblog.com/2016/12/announcing-oss-fuzz-continuous-fuzzing.html +[OSS-Fuzz: Five months later, and rewarding projects]: https://opensource.googleblog.com/2017/05/oss-fuzz-five-months-later-and.html +[A New Chapter for OSS-Fuzz]: https://security.googleblog.com/2018/11/a-new-chapter-for-oss-fuzz.html +[Fuzzing internships for Open Source Software]: https://security.googleblog.com/2020/10/fuzzing-internships-for-open-source.html +[Improving open source security during the Google summer internship program]: https://security.googleblog.com/2020/12/improving-open-source-security-during.html +[Fuzzing Java in OSS-Fuzz]: https://security.googleblog.com/2021/03/fuzzing-java-in-oss-fuzz.html +[Improving OSS-Fuzz and Jazzer to catch Log4Shell]: https://security.googleblog.com/2021/12/improving-oss-fuzz-and-jazzer-to-catch.html +[Fuzzing beyond memory corruption: Finding broader classes of vulnerabilities automatically]: https://security.googleblog.com/2022/09/fuzzing-beyond-memory-corruption.html +[Taking the next step: OSS-Fuzz in 2023]: https://security.googleblog.com/2023/02/taking-next-step-oss-fuzz-in-2023.html diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/.gitignore b/local-test-curl-delta-01/fuzz-tooling/docs/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..585ecc409146ce812d2e0889b646288ed008fb42 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/.gitignore @@ -0,0 +1,5 @@ +_site +.bundle +.sass-cache +.jekyll-metadata +vendor diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/404.html b/local-test-curl-delta-01/fuzz-tooling/docs/404.html new file mode 100644 index 0000000000000000000000000000000000000000..91053a62897826a79b7763abbbbe2471d03dad55 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/404.html @@ -0,0 +1,23 @@ +--- +layout: default +--- + + + +
+

404

+ +

Page not found :(

+
diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/Gemfile b/local-test-curl-delta-01/fuzz-tooling/docs/Gemfile new file mode 100644 index 0000000000000000000000000000000000000000..d4c69e8dde6a6867a17684af6b0beacf87e66e86 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" +gem 'github-pages', group: :jekyll_plugins + +gem "webrick", "~> 1.8" diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/README.md b/local-test-curl-delta-01/fuzz-tooling/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3ac9b680f016b16c169f26b55878328efa31a93d --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/README.md @@ -0,0 +1,19 @@ +# Readme + +Use the following instructions to make documentation changes locally. + +## Prerequisites +```bash +$ sudo apt install ruby bundler +$ bundle config set path 'vendor/bundle' +$ bundle install +``` + +## Serving locally +```bash +$ bundle exec jekyll serve +``` + +## Theme documentation +We are using the [just the docs](https://just-the-docs.github.io/just-the-docs/) +theme. diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/_config.yml b/local-test-curl-delta-01/fuzz-tooling/docs/_config.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2e32b70b14e23392b44f4f9f2ea01f08533c873 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/_config.yml @@ -0,0 +1,40 @@ +# Welcome to Jekyll! +# +# This config file is meant for settings that affect your whole blog, values +# which you are expected to set up once and rarely edit after that. If you find +# yourself editing this file very often, consider using Jekyll's data files +# feature for the data you need to update frequently. +# +# For technical reasons, this file is *NOT* reloaded automatically when you use +# 'bundle exec jekyll serve'. If you change this file, please restart the server process. + +# Site settings +# These are used to personalize your new site. If you look in the HTML files, +# you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. +# You can create any custom variable you would like, and they will be accessible +# in the templates via {{ site.myvariable }}. +title: OSS-Fuzz +description: Documentation for OSS-Fuzz +baseurl: "/oss-fuzz" # the subpath of your site, e.g. /blog +url: "" # the base hostname & protocol for your site, e.g. http://example.com + +# Build settings +markdown: kramdown +remote_theme: pmarsceill/just-the-docs +search_enabled: true + +ga_tracking: G-LRX1V3S5P + +aux_links: + "OSS-Fuzz on GitHub": + - https://github.com/google/oss-fuzz + +# Exclude from processing. +exclude: + - Gemfile + - Gemfile.lock + - node_modules + - vendor/bundle/ + - vendor/cache/ + - vendor/gems/ + - vendor/ruby/ diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/faq.md b/local-test-curl-delta-01/fuzz-tooling/docs/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..38ecfa9c495567ee5cf796c9c529d4618f2be6c2 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/faq.md @@ -0,0 +1,237 @@ +--- +layout: default +title: FAQ +nav_order: 7 +permalink: /faq/ +--- + +# Frequently Asked Questions + +- TOC +{:toc} +--- + +## Where can I learn more about fuzzing? + +We recommend reading [libFuzzer tutorial] and the other docs in [google/fuzzing] +repository. These and some other resources are listed on the +[useful links]({{ site.baseurl }}/reference/useful-links/#tutorials) page. + +[google/fuzzing]: https://github.com/google/fuzzing/tree/master/docs +[libFuzzer tutorial]: https://github.com/google/fuzzing/blob/master/tutorial/libFuzzerTutorial.md + +## What kind of projects are you accepting? + +We accept established projects that have a critical impact on infrastructure and +user security. We will consider each request on a case-by-case basis, but some +things we keep in mind are: + + - Exposure to remote attacks (e.g. libraries that are used to process + untrusted input). + - Number of users/other projects depending on this project. + +We hope to relax this requirement in the future though, so keep an eye out even +if we are not able to accept your project at this time! + +## How can I find potential fuzz targets in my open source project? + +You should look for places in your code that: + + - consume un-trusted data from users or from the network. + - consume complex input data even if it's 'trusted'. + - use an algorithm that has two or more implementations + (to verify their equivalence). + - look for existing fuzz target [examples](https://github.com/google/oss-fuzz/tree/master/projects) + and find similarities. + +## Where can I store fuzz target sources and the build script if it's not yet accepted upstream? + +Fuzz target sources as well as the build script may temporarily live inside the +`projects/` directory in the OSS-Fuzz repository. Note that we do +not accept integrations that rely on forked repositories. Refer to the +[ideal integration guide] for the preferred long term solution. + +## My project is not open source. Can I use OSS-Fuzz? + +You cannot use OSS-Fuzz, but you can use [ClusterFuzz] which OSS-Fuzz is based +on. ClusterFuzz is an open-source fuzzing infrastructure that you can deploy in +your own environment and run continuously at scale. + +OSS-Fuzz is a production instance of ClusterFuzz, plus the code living in +[OSS-Fuzz repository]: build scripts, `project.yaml` files with contacts, etc. + +[OSS-Fuzz repository]: https://github.com/google/oss-fuzz + +## Why do you use a [different issue tracker](https://bugs.chromium.org/p/oss-fuzz/issues/list) for reporting bugs in OSS projects? + +Security access control is important for the kind of issues that OSS-Fuzz detects, +hence why by default issues are only opened on the OSS-Fuzz tracker. +You can opt-in to have them on Github as well by adding the `file_github_issue` +attribute to your `project.yaml` file. Note that this is only for visibility's +purpose, and that the actual details can be found by following the link to the +OSS-Fuzz tracker. + +## Why do you require a Google account for authentication? + +Our [ClusterFuzz]({{ site.baseurl }}/further-reading/clusterfuzz) fuzzing +infrastructure and [issue tracker](https://bugs.chromium.org/p/oss-fuzz/issues/list) +require a Google account for authentication. Note that an alternate email +address associated with a Google account does not work due to appengine api +limitations. + +## Why do you use Docker? + +Building fuzzers requires building your project with a fresh Clang compiler and +special compiler flags. An easy-to-use Docker image is provided to simplify +toolchain distribution. This also simplifies our support for a variety of Linux +distributions and provides a reproducible environment for fuzzer +building and execution. + +## How do you handle timeouts and OOMs? + +If a single input to a [fuzz target]({{ site.baseurl }}/reference/glossary/#fuzz-target) +requires more than **~25 seconds** or more than **2.5GB RAM** to process, we +report this as a timeout or an OOM (out-of-memory) bug +(examples: [timeouts](https://bugs.chromium.org/p/oss-fuzz/issues/list?can=1&q=%22Crash+Type%3A+Timeout%22), +[OOMs](https://bugs.chromium.org/p/oss-fuzz/issues/list?can=1&q="Crash+Type%3A+Out-of-memory")). +This may or may not be considered as a real bug by the project owners, +but nevertheless we treat all timeouts and OOMs as bugs +since they significantly reduce the efficiency of fuzzing. + +Remember that fuzzing is executed with AddressSanitizer or other +sanitizers which introduces a certain overhead in RAM and CPU. + +We currently do not have a good way to deduplicate timeout or OOM bugs. +So, we report only one timeout and only one OOM bug per fuzz target. +Once that bug is fixed, we will file another one, and so on. + +Currently we do not offer ways to change the memory and time limits. + +## Can I launch an additional process (e.g. a daemon) from my fuzz target? + +No. In order to get all the benefits of in-process, coverage-guided fuzz testing, +it is required to run everything inside a single process. Any child processes +created outside the main process introduces heavy launch overhead and is not +monitored for code coverage. + +Another rule of thumb is: "the smaller fuzz target is, the better it is". It is +expected that your project will have many fuzz targets to test different +components, instead of a single fuzz target trying to cover everything. +Think of fuzz target as a unit test, though it is much more powerful since it +helps to test millions of data permutations rather than just one. + +## What if my fuzz target finds a bug in another project (dependency) ? + +Every bug report has a crash stack-trace that shows where the crash happened. +Using that, you can debug the root cause and see which category the bug falls in: + +- If this is a bug is due to an incorrect usage of the dependent project's API +in your project, then you need to fix your usage to call the API correctly. +- If this is a real bug in the dependent project, then you should CC the +maintainers of that project on the bug. Once CCed, they will get automatic +access to all the information necessary to reproduce the issue. If this project +is maintained in OSS-Fuzz, you can search for contacts in the respective +project.yaml file. + +## What if my fuzzer does not find anything? + +If your fuzz target is running for many days and does not find bugs or new +coverage, it may mean several things: +- We've covered all reachable code. In order to cover more code we need more + fuzz targets. +- The [seed corpus]({{ site.baseurl }}/getting-started/new-project-guide#seed-corpus) is not good enough and the + fuzzing engine(s) are not able to go deeper based on the existing seeds. + Need to add more seeds. +- There is some crypto/crc stuff in the code that will prevent any fuzzing + engine from going deeper, in which case the crypto should be disabled in + [fuzzing mode](https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode). + Examples: [openssl](https://github.com/openssl/openssl/tree/master/fuzz#reproducing-issues), + [boringssl](https://boringssl.googlesource.com/boringssl/+/HEAD/FUZZING.md#Fuzzer-mode) +- It is also possible that the fuzzer is running too slow + (you may check the speed of your targets at https://oss-fuzz.com/) + +In either case, look at the +[coverage reports]({{ site.baseurl }}/further-reading/clusterfuzz#coverage-reports) +for your target(s) and figure out why some parts of the code are not covered. + +## What if my fuzzer does not find new coverage or bugs after a while? + +It is common for fuzzers to plateau and stop finding new coverage or bugs. +[Fuzz Introspector](https://github.com/ossf/fuzz-introspector) helps you +evaluate your fuzzers' performance. +It can help you identify bottlenecks causing your fuzzers to plateau. +It provides aggregated and individual fuzzer reachability and coverage reports. +Developers can either introduce a new fuzz target or modify an existing one to +reach previously unreachable code. +Here are +[case studies](https://github.com/ossf/fuzz-introspector/blob/main/doc/CaseStudies.md) +where Fuzz Introspector helped developers improve fuzzing of a project. +Fuzz Introspector reports are available on the [OSS-Fuzz homepage](https://oss-fuzz.com/) +or through this [index](http://oss-fuzz-introspector.storage.googleapis.com/index.html). + +Developers can also use Fuzz Introspector on their local machines. +Detailed instructions are available +[here](https://github.com/ossf/fuzz-introspector/tree/main/oss_fuzz_integration#build-fuzz-introspector-with-oss-fuzz). + +## Why are code coverage reports public? + +We work with open source projects and try to keep as much information public as +possible. We believe that public code coverage reports do not put users at risk, +as they do not indicate the presence of bugs or lack thereof. + +## Why is the coverage command complaining about format compatibility issues? + +This may happen if the Docker images fetched locally become out of sync. Make +sure you run the following command to pull the most recent images: + +```bash +$ python infra/helper.py pull_images +``` + +Please refer to +[code coverage]({{ site.baseurl }}/advanced-topics/code-coverage/) for detailed +information on code coverage generation. + +## What happens when I rename a fuzz target ? + +If you rename your fuzz targets, the existing bugs for those targets will get +closed and fuzzing will start from scratch from a fresh corpora +(seed corpus only). Similar corpora will get accumulated over time depending on +the number of cpu cycles that original fuzz target has run. If this is not +desirable, make sure to copy the accumulated corpora from the original fuzz +target (instructions to download +[here]({{ site.baseurl }}/advanced-topics/corpora/#downloading-the-corpus)) and +restore it to the new GCS location later (instruction to find the +new location [here]({{ site.baseurl }}/advanced-topics/corpora/#viewing-the-corpus-for-a-fuzz-target)). + +## Does OSS-Fuzz support AFL or honggfuzz or Centipede? + +OSS-Fuzz *uses* the following +[fuzzing engines]({{ site.baseurl }}/reference/glossary/#fuzzing-engine): + +1. [libFuzzer](https://llvm.org/docs/LibFuzzer.html). +1. [AFL++](https://github.com/AFLplusplus/AFLplusplus), an improved and + well-maintained version of [AFL](https://lcamtuf.coredump.cx/afl/). +1. [Honggfuzz](https://github.com/google/honggfuzz). +1. [Centipede (Experimental)](https://github.com/google/centipede). + +Follow the [new project guide] and OSS-Fuzz will use all its fuzzing engines +on your code. + +## What are the specs on your machines? + +OSS-Fuzz builders have 32CPU/28.8GB RAM. + +Fuzzing machines only have a single core and fuzz targets should not use more +than 2.5GB of RAM. + +## Are there any restrictions on using test cases / corpora generated by OSS-Fuzz? + +No, you can freely use (i.e. share, add to your repo, etc.) the test cases and +corpora generated by OSS-Fuzz. OSS-Fuzz infrastructure is fully open source +(including [ClusterFuzz], various fuzzing engines, and other dependencies). We +have no intent to restrict the use of the artifacts produced by OSS-Fuzz. + +[ClusterFuzz]: https://github.com/google/clusterfuzz +[new project guide]: {{ site.baseurl }}/getting-started/new-project-guide/ +[ideal integration guide]: {{ site.baseurl }}/getting-started/new-project-guide/ diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/favicon.ico b/local-test-curl-delta-01/fuzz-tooling/docs/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..46a19509f373510556c04b529d8a3423f894ff9c Binary files /dev/null and b/local-test-curl-delta-01/fuzz-tooling/docs/favicon.ico differ diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/glossary.md b/local-test-curl-delta-01/fuzz-tooling/docs/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..e3355d3763bcafa42ba8cccd49a4ed29d2a0d184 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/glossary.md @@ -0,0 +1 @@ +This page has moved [here](https://google.github.io/oss-fuzz/reference/glossary/) diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/ideal_integration.md b/local-test-curl-delta-01/fuzz-tooling/docs/ideal_integration.md new file mode 100644 index 0000000000000000000000000000000000000000..986e7bc1c034bb591c9b6671a1cfd5f488153c73 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/ideal_integration.md @@ -0,0 +1 @@ +This page has moved [here](https://google.github.io/oss-fuzz/advanced-topics/ideal-integration) diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/index.md b/local-test-curl-delta-01/fuzz-tooling/docs/index.md new file mode 100644 index 0000000000000000000000000000000000000000..4e33b8f27b6e1be56068d8f0fe598db3caf5f7d2 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/index.md @@ -0,0 +1,88 @@ +--- +layout: default +title: OSS-Fuzz +permalink: / +nav_order: 1 +has_children: true +has_toc: false +--- + +# OSS-Fuzz + +[Fuzz testing] is a well-known technique for uncovering programming errors in +software. Many of these detectable errors, like [buffer overflow], can have +serious security implications. Google has found [thousands] of security +vulnerabilities and stability bugs by deploying [guided in-process fuzzing of +Chrome components], and we now want to share that service with the open source +community. + +[Fuzz testing]: https://en.wikipedia.org/wiki/Fuzz_testing +[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow +[thousands]: https://bugs.chromium.org/p/chromium/issues/list?q=label%3AStability-LibFuzzer%2CStability-AFL%20-status%3ADuplicate%2CWontFix&can=1 +[guided in-process fuzzing of Chrome components]: https://security.googleblog.com/2016/08/guided-in-process-fuzzing-of-chrome.html + +In cooperation with the [Core Infrastructure Initiative] and the [OpenSSF], +OSS-Fuzz aims to make common open source software more secure and stable by +combining modern fuzzing techniques with scalable, distributed execution. +Projects that do not qualify for OSS-Fuzz (e.g. closed source) can run their own +instances of [ClusterFuzz] or [ClusterFuzzLite]. + +[Core Infrastructure Initiative]: https://www.coreinfrastructure.org/ +[OpenSSF]: https://www.openssf.org/ + +We support the [libFuzzer], [AFL++], [Honggfuzz], and [Centipede] fuzzing engines in +combination with [Sanitizers], as well as [ClusterFuzz], a distributed fuzzer +execution environment and reporting tool. + +[libFuzzer]: https://llvm.org/docs/LibFuzzer.html +[AFL++]: https://github.com/AFLplusplus/AFLplusplus +[Honggfuzz]: https://github.com/google/honggfuzz +[Centipede]: https://github.com/google/centipede +[Sanitizers]: https://github.com/google/sanitizers +[ClusterFuzz]: https://github.com/google/clusterfuzz +[ClusterFuzzLite]: https://google.github.io/clusterfuzzlite/ + +Currently, OSS-Fuzz supports C/C++, Rust, Go, Python and Java/JVM code. Other +languages supported by [LLVM] may work too. OSS-Fuzz supports fuzzing x86_64 +and i386 builds. + +[LLVM]: https://llvm.org + + +## Project history +OSS-Fuzz was launched in 2016 in response to the +[Heartbleed] vulnerability, discovered in [OpenSSL], one of the +most popular open source projects for encrypting web traffic. The vulnerability +had the potential to affect almost every internet user, yet was caused by a +relatively simple memory buffer overflow bug that could have been detected by +fuzzing—that is, by running the code on randomized inputs to intentionally cause +unexpected behaviors or crashes. At the time, though, fuzzing +was not widely used and was cumbersome for developers, requiring extensive +manual effort. + +Google created OSS-Fuzz to fill this gap: it's a free service that runs fuzzers +for open source projects and privately alerts developers to the bugs detected. +Since its launch, OSS-Fuzz has become a critical service for the open source +community, growing beyond C/C++ to +detect problems in memory-safe languages such as Go, Rust, and Python. + +[Heartbleed]: https://heartbleed.com/ +[OpenSSL]: https://www.openssl.org/ + +## Learn more about fuzzing + +This documentation describes how to use OSS-Fuzz service for your open source +project. To learn more about fuzzing in general, we recommend reading [libFuzzer +tutorial] and the other docs in [google/fuzzing] repository. These and some +other resources are listed on the [useful links] page. + +[google/fuzzing]: https://github.com/google/fuzzing/tree/master/docs +[libFuzzer tutorial]: https://github.com/google/fuzzing/blob/master/tutorial/libFuzzerTutorial.md +[useful links]: {{ site.baseurl }}/reference/useful-links/#tutorials + +## Trophies +As of August 2023, OSS-Fuzz has helped identify and fix over [10,000] vulnerabilities and [36,000] bugs across [1,000] projects. + +[10,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug-Security%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[36,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[1,000]: https://github.com/google/oss-fuzz/tree/master/projects diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/new_project_guide.md b/local-test-curl-delta-01/fuzz-tooling/docs/new_project_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..782486ad5a1106991e279f137c62340e0c369942 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/new_project_guide.md @@ -0,0 +1 @@ +This page has moved [here](https://google.github.io/oss-fuzz/getting-started/new-project-guide/) diff --git a/local-test-curl-delta-01/fuzz-tooling/docs/reproducing.md b/local-test-curl-delta-01/fuzz-tooling/docs/reproducing.md new file mode 100644 index 0000000000000000000000000000000000000000..77c79dfe2062a0d12628944692b01825cd5b69d3 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/docs/reproducing.md @@ -0,0 +1 @@ +This page has moved [here](https://google.github.io/oss-fuzz/advanced-topics/reproducing) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/.dockerignore b/local-test-curl-delta-01/fuzz-tooling/infra/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..c786533425754418b7e2256ae37c7624ff9eee11 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/.dockerignore @@ -0,0 +1,9 @@ +cifuzz/test_data/* + +# Copied from .gitignore. +.vscode/ +*.pyc +build +*~ +.DS_Store +*.swp \ No newline at end of file diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/MAINTAINERS.csv b/local-test-curl-delta-01/fuzz-tooling/infra/MAINTAINERS.csv new file mode 100644 index 0000000000000000000000000000000000000000..803827d833b91cfb3ad80f356737dded20dfa17b --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/MAINTAINERS.csv @@ -0,0 +1,7 @@ +Name,Email,Github Username +Adam Korcz,adam@adalogics.com,AdamKorcz +David Korczynski,david@adalogics.com,DavidKorczynski +Dongge Liu,donggeliu@google.com,Alan32Liu +Holly Gong,gongh@google.com,hogo6002 +Jonathan Metzman,metzman@google.com,jonathanmetzman +Oliver Chang,ochang@google.com,oliverchang \ No newline at end of file diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/README.md b/local-test-curl-delta-01/fuzz-tooling/infra/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eff007eeaafa8c47b2ddb18cbd6a2fa44bb2c48a --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/README.md @@ -0,0 +1,23 @@ +# infra +> OSS-Fuzz project infrastructure + +Core infrastructure: +* [`base-images`](base-images/) - docker images for building fuzz targets & corresponding jenkins + pipeline. + +Continuous Integration infrastructure: + +* [`ci`](ci/) - script to build projects in CI. + +## helper.py +> script to automate common docker operations + +| Command | Description | +|---------|------------- +| `generate` | Generates skeleton files for a new project | +| `build_image` | Builds a docker image for a given project | +| `build_fuzzers` | Builds fuzz targets for a given project | +| `run_fuzzer` | Runs a fuzz target in a docker container | +| `coverage` | Runs fuzz target(s) in a docker container and generates a code coverage report. See [Code Coverage doc](https://google.github.io/oss-fuzz/advanced-topics/code-coverage/) | +| `reproduce` | Runs a testcase to reproduce a crash | +| `shell` | Starts a shell inside the docker image for a project | diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc b/local-test-curl-delta-01/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccfaddb7f0fd7ee3a0d944593a4a8cef7cdc8248 Binary files /dev/null and b/local-test-curl-delta-01/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc differ diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/base-images/README.md b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e155e2cb91f146dcac565bc60705d01b8ac74c98 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/README.md @@ -0,0 +1,6 @@ +Building all infra images: + +```bash +# run from project root +infra/base-images/all.sh +``` diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/base-images/aixcc_build_all.sh b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/aixcc_build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed8eee86385559020055682e668aee685f68ad12 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/aixcc_build_all.sh @@ -0,0 +1,59 @@ +#!/bin/bash -eux + +if [ "$1" = "--cache-from" ]; then + PULL_CACHE=1 + shift + CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes + shift +elif [ "$1" = "--cache-to" ]; then + PUSH_CACHE=1 + shift + CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes + shift +fi + +ARG_TAG="$1" +shift + +BASE_IMAGES=( + "ghcr.io/aixcc-finals/base-image infra/base-images/base-image" + "ghcr.io/aixcc-finals/base-clang infra/base-images/base-clang" + "ghcr.io/aixcc-finals/base-builder infra/base-images/base-builder" + "ghcr.io/aixcc-finals/base-builder-go infra/base-images/base-builder-go" + "ghcr.io/aixcc-finals/base-builder-jvm infra/base-images/base-builder-jvm" + "ghcr.io/aixcc-finals/base-builder-python infra/base-images/base-builder-python" + "ghcr.io/aixcc-finals/base-builder-rust infra/base-images/base-builder-rust" + "ghcr.io/aixcc-finals/base-builder-ruby infra/base-images/base-builder-ruby" + "ghcr.io/aixcc-finals/base-builder-swift infra/base-images/base-builder-swift" + "ghcr.io/aixcc-finals/base-runner infra/base-images/base-runner" + "ghcr.io/aixcc-finals/base-runner-debug infra/base-images/base-runner-debug" +) + +for tuple in "${BASE_IMAGES[@]}"; do + read -r image path <<< "$tuple" + + if [ "${PULL_CACHE+x}" ]; then + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + elif [ "${PUSH_CACHE+x}" ]; then + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \ + --cache-to=type=registry,ref="${image}:${CACHE_TAG}",mode=max \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + else + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + fi + +done + diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/base-images/all.sh b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/all.sh new file mode 100644 index 0000000000000000000000000000000000000000..75b806bbef6800e0f98c2682571aacf06f701071 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/base-images/all.sh @@ -0,0 +1,28 @@ +#!/bin/bash -eux +# Copyright 2016 Google Inc. +# +# 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. +# +################################################################################ + +docker build --pull -t ghcr.io/aixcc-finals/base-image "$@" infra/base-images/base-image +docker build -t ghcr.io/aixcc-finals/base-clang "$@" infra/base-images/base-clang +docker build -t ghcr.io/aixcc-finals/base-builder "$@" infra/base-images/base-builder +docker build -t ghcr.io/aixcc-finals/base-builder-go "$@" infra/base-images/base-builder-go +docker build -t ghcr.io/aixcc-finals/base-builder-jvm "$@" infra/base-images/base-builder-jvm +docker build -t ghcr.io/aixcc-finals/base-builder-python "$@" infra/base-images/base-builder-python +docker build -t ghcr.io/aixcc-finals/base-builder-rust "$@" infra/base-images/base-builder-rust +docker build -t ghcr.io/aixcc-finals/base-builder-ruby "$@" infra/base-images/base-builder-ruby +docker build -t ghcr.io/aixcc-finals/base-builder-swift "$@" infra/base-images/base-builder-swift +docker build -t ghcr.io/aixcc-finals/base-runner "$@" infra/base-images/base-runner +docker build -t ghcr.io/aixcc-finals/base-runner-debug "$@" infra/base-images/base-runner-debug diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/bisector.py b/local-test-curl-delta-01/fuzz-tooling/infra/bisector.py new file mode 100644 index 0000000000000000000000000000000000000000..21333afdf96cb21c9f57bc6ed7f62a8569112949 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/bisector.py @@ -0,0 +1,318 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Uses bisection to determine which commit a bug was introduced and fixed. +This module takes a high and a low commit SHA, a repo name, and a bug. +The module bisects the high and low commit SHA searching for the location +where the bug was introduced. It also looks for where the bug was fixed. +This is done with the following steps: + + + NOTE: Needs to be run from root of the OSS-Fuzz source checkout. + + Typical usage example: + python3 infra/bisector.py + --old_commit 1e403e9259a1abedf108ab86f711ba52c907226d + --new_commit f79be4f2330f4b89ea2f42e1c44ca998c59a0c0f + --fuzz_target rules_fuzzer + --project_name yara + --testcase infra/yara_testcase + --sanitizer address +""" + +import argparse +import collections +import logging +import os +import sys +import tempfile + +import build_specified_commit +import helper +import repo_manager +import utils + +Result = collections.namedtuple('Result', ['repo_url', 'commit']) + +START_MARKERS = [ + '==ERROR', + '==WARNING', +] + +END_MARKERS = [ + 'SUMMARY:', +] + +DEDUP_TOKEN_MARKER = 'DEDUP_TOKEN:' + + +class BisectError(Exception): + """Bisection error.""" + + def __init__(self, message, repo_url): + super().__init__(message) + self.repo_url = repo_url + + +def main(): + """Finds the commit SHA where an error was initally introduced.""" + logging.getLogger().setLevel(logging.INFO) + utils.chdir_to_root() + parser = argparse.ArgumentParser( + description='git bisection for finding introduction of bugs') + + parser.add_argument('--project_name', + help='The name of the project where the bug occurred.', + required=True) + parser.add_argument('--new_commit', + help='The newest commit SHA to be bisected.', + required=True) + parser.add_argument('--old_commit', + help='The oldest commit SHA to be bisected.', + required=True) + parser.add_argument('--fuzz_target', + help='The name of the fuzzer to be built.', + required=True) + parser.add_argument('--test_case_path', + help='The path to test case.', + required=True) + parser.add_argument('--engine', + help='The default is "libfuzzer".', + default='libfuzzer') + parser.add_argument('--sanitizer', + default='address', + help='The default is "address".') + parser.add_argument('--type', + choices=['regressed', 'fixed'], + help='The bisection type.', + required=True) + parser.add_argument('--architecture', default='x86_64') + args = parser.parse_args() + + build_data = build_specified_commit.BuildData(project_name=args.project_name, + engine=args.engine, + sanitizer=args.sanitizer, + architecture=args.architecture) + + result = bisect(args.type, args.old_commit, args.new_commit, + args.test_case_path, args.fuzz_target, build_data) + if not result.commit: + logging.error('No error was found in commit range %s:%s', args.old_commit, + args.new_commit) + return 1 + if result.commit == args.old_commit: + logging.error( + 'Bisection Error: Both the first and the last commits in' + 'the given range have the same behavior, bisection is not possible. ') + return 1 + if args.type == 'regressed': + print('Error was introduced at commit %s' % result.commit) + elif args.type == 'fixed': + print('Error was fixed at commit %s' % result.commit) + return 0 + + +def _get_dedup_token(output): + """Get dedup token.""" + for line in output.splitlines(): + token_location = line.find(DEDUP_TOKEN_MARKER) + if token_location == -1: + continue + + return line[token_location + len(DEDUP_TOKEN_MARKER):].strip() + + return None + + +def _check_for_crash(project_name, fuzz_target, testcase_path): + """Check for crash.""" + + def docker_run(args, **kwargs): + del kwargs + command = ['docker', 'run', '--rm', '--privileged'] + if sys.stdin.isatty(): + command.append('-i') + + return utils.execute(command + args) + + logging.info('Checking for crash') + out, err, return_code = helper.reproduce_impl( + project=helper.Project(project_name), + fuzzer_name=fuzz_target, + valgrind=False, + env_to_add=[], + fuzzer_args=[], + testcase_path=testcase_path, + run_function=docker_run, + err_result=(None, None, None)) + if return_code is None: + return None + + logging.info('stdout =\n%s', out) + logging.info('stderr =\n%s', err) + + # pylint: disable=unsupported-membership-test + has_start_marker = any( + marker in out or marker in err for marker in START_MARKERS) + has_end_marker = any(marker in out or marker in err for marker in END_MARKERS) + if not has_start_marker or not has_end_marker: + return None + + return _get_dedup_token(out + err) + + +# pylint: disable=too-many-locals +# pylint: disable=too-many-arguments +# pylint: disable=too-many-statements +def _bisect(bisect_type, old_commit, new_commit, testcase_path, fuzz_target, + build_data): + """Perform the bisect.""" + # pylint: disable=too-many-branches + base_builder_repo = build_specified_commit.load_base_builder_repo() + + with tempfile.TemporaryDirectory() as tmp_dir: + repo_url, repo_path = build_specified_commit.detect_main_repo( + build_data.project_name, commit=new_commit) + if not repo_url or not repo_path: + raise ValueError('Main git repo can not be determined.') + + if old_commit == new_commit: + raise BisectError('old_commit is the same as new_commit', repo_url) + + # Copy /src from the built Docker container to ensure all dependencies + # exist. This will be mounted when running them. + host_src_dir = build_specified_commit.copy_src_from_docker( + build_data.project_name, tmp_dir) + + bisect_repo_manager = repo_manager.RepoManager( + os.path.join(host_src_dir, os.path.basename(repo_path))) + bisect_repo_manager.fetch_all_remotes() + + commit_list = bisect_repo_manager.get_commit_list(new_commit, old_commit) + + old_idx = len(commit_list) - 1 + new_idx = 0 + logging.info('Testing against new_commit (%s)', commit_list[new_idx]) + if not build_specified_commit.build_fuzzers_from_commit( + commit_list[new_idx], + bisect_repo_manager, + host_src_dir, + build_data, + base_builder_repo=base_builder_repo): + raise BisectError('Failed to build new_commit', repo_url) + + if bisect_type == 'fixed': + should_crash = False + elif bisect_type == 'regressed': + should_crash = True + else: + raise BisectError('Invalid bisect type ' + bisect_type, repo_url) + + expected_error = _check_for_crash(build_data.project_name, fuzz_target, + testcase_path) + logging.info('new_commit result = %s', expected_error) + + if not should_crash and expected_error: + logging.warning('new_commit crashed but not shouldn\'t. ' + 'Continuing to see if stack changes.') + + range_valid = False + for _ in range(2): + logging.info('Testing against old_commit (%s)', commit_list[old_idx]) + if not build_specified_commit.build_fuzzers_from_commit( + commit_list[old_idx], + bisect_repo_manager, + host_src_dir, + build_data, + base_builder_repo=base_builder_repo): + raise BisectError('Failed to build old_commit', repo_url) + + if _check_for_crash(build_data.project_name, fuzz_target, + testcase_path) == expected_error: + logging.warning('old_commit %s had same result as new_commit %s', + old_commit, new_commit) + # Try again on an slightly older commit. + old_commit = bisect_repo_manager.get_parent(old_commit, 64) + if not old_commit: + break + + commit_list = bisect_repo_manager.get_commit_list( + new_commit, old_commit) + old_idx = len(commit_list) - 1 + continue + + range_valid = True + break + + if not range_valid: + raise BisectError('old_commit had same result as new_commit', repo_url) + + while old_idx - new_idx > 1: + curr_idx = (old_idx + new_idx) // 2 + logging.info('Testing against %s (idx=%d)', commit_list[curr_idx], + curr_idx) + if not build_specified_commit.build_fuzzers_from_commit( + commit_list[curr_idx], + bisect_repo_manager, + host_src_dir, + build_data, + base_builder_repo=base_builder_repo): + # Treat build failures as if we couldn't repo. + # TODO(ochang): retry nearby commits? + old_idx = curr_idx + continue + + current_error = _check_for_crash(build_data.project_name, fuzz_target, + testcase_path) + logging.info('Current result = %s', current_error) + if expected_error == current_error: + new_idx = curr_idx + else: + old_idx = curr_idx + return Result(repo_url, commit_list[new_idx]) + + +# pylint: disable=too-many-locals +# pylint: disable=too-many-arguments +def bisect(bisect_type, old_commit, new_commit, testcase_path, fuzz_target, + build_data): + """From a commit range, this function caluclates which introduced a + specific error from a fuzz testcase_path. + + Args: + bisect_type: The type of the bisect ('regressed' or 'fixed'). + old_commit: The oldest commit in the error regression range. + new_commit: The newest commit in the error regression range. + testcase_path: The file path of the test case that triggers the error + fuzz_target: The name of the fuzzer to be tested. + build_data: a class holding all of the input parameters for bisection. + + Returns: + The commit SHA that introduced the error or None. + + Raises: + ValueError: when a repo url can't be determine from the project. + """ + try: + return _bisect(bisect_type, old_commit, new_commit, testcase_path, + fuzz_target, build_data) + finally: + # Clean up projects/ as _bisect may have modified it. + oss_fuzz_repo_manager = repo_manager.RepoManager(helper.OSS_FUZZ_DIR) + oss_fuzz_repo_manager.git(['reset', 'projects']) + oss_fuzz_repo_manager.git(['checkout', 'projects']) + oss_fuzz_repo_manager.git(['clean', '-fxd', 'projects']) + + +if __name__ == '__main__': + main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/bisector_test.py b/local-test-curl-delta-01/fuzz-tooling/infra/bisector_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d93ac323980a19b308029e08a3a49d3ec650e749 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/bisector_test.py @@ -0,0 +1,70 @@ +# Copyright 2019 Google LLC +# +# 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 perepo_managerissions and +# limitations under the License. +"""Test the functionality of bisection module: +1) Test a known case where an error appears in a regression range. +2) Bisect can handle incorrect inputs. + +IMPORTANT: This test needs to be run with root privileges. +""" + +import os +import unittest + +import bisector +import build_specified_commit +import test_repos + +# Necessary because __file__ changes with os.chdir +TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__)) + + +@unittest.skip('Test is too long to be run with presubmit.') +class BisectIntegrationTests(unittest.TestCase): + """Class to test the functionality of bisection method.""" + + BISECT_TYPE = 'regressed' + + def test_bisect_invalid_repo(self): + """Test the bisection method on a project that does not exist.""" + test_repo = test_repos.INVALID_REPO + build_data = build_specified_commit.BuildData( + project_name=test_repo.project_name, + engine='libfuzzer', + sanitizer='address', + architecture='x86_64') + with self.assertRaises(ValueError): + bisector.bisect(self.BISECT_TYPE, test_repo.old_commit, + test_repo.new_commit, test_repo.testcase_path, + test_repo.fuzz_target, build_data) + + def test_bisect(self): + """Test the bisect method on example projects.""" + for test_repo in test_repos.TEST_REPOS: + if test_repo.new_commit: + build_data = build_specified_commit.BuildData( + project_name=test_repo.project_name, + engine='libfuzzer', + sanitizer='address', + architecture='x86_64') + result = bisector.bisect(self.BISECT_TYPE, test_repo.old_commit, + test_repo.new_commit, test_repo.testcase_path, + test_repo.fuzz_target, build_data) + self.assertEqual(result.commit, test_repo.intro_commit) + + +if __name__ == '__main__': + # Change to oss-fuzz main directory so helper.py runs correctly. + if os.getcwd() != os.path.dirname(TEST_DIR_PATH): + os.chdir(os.path.dirname(TEST_DIR_PATH)) + unittest.main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/build_fuzzers.Dockerfile b/local-test-curl-delta-01/fuzz-tooling/infra/build_fuzzers.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..be53f720f7c00e3aea27ce03b1baaf9b08b35f25 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/build_fuzzers.Dockerfile @@ -0,0 +1,31 @@ +# Copyright 2020 Google LLC +# +# 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. +# +################################################################################ +# Docker image to run fuzzers for CIFuzz (the run_fuzzers action on GitHub +# actions). + +FROM ghcr.io/aixcc-finals/cifuzz-base + +# Python file to execute when the docker container starts up +# We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var, +# just expand to '/opt/oss-fuzz'. +ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/build_fuzzers_entrypoint.py"] + +WORKDIR ${OSS_FUZZ_ROOT}/infra + +# Update infra source code. +ADD . ${OSS_FUZZ_ROOT}/infra + +RUN python3 -m pip install -r ${OSS_FUZZ_ROOT}/infra/cifuzz/requirements.txt \ No newline at end of file diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit.py b/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit.py new file mode 100644 index 0000000000000000000000000000000000000000..f1ad21866095ef5becb11623a11272b2dc13cce7 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit.py @@ -0,0 +1,410 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Module to build a image from a specific commit, branch or pull request. + +This module is allows each of the OSS Fuzz projects fuzzers to be built +from a specific point in time. This feature can be used for implementations +like continuious integration fuzzing and bisection to find errors +""" +import argparse +import bisect +import datetime +import os +import collections +import json +import logging +import re +import shutil +import tempfile + +import helper +import repo_manager +import retry +import utils + +BuildData = collections.namedtuple( + 'BuildData', ['project_name', 'engine', 'sanitizer', 'architecture']) + +_GIT_DIR_MARKER = 'gitdir: ' +_IMAGE_BUILD_TRIES = 3 + + +class BaseBuilderRepo: + """Repo of base-builder images.""" + + def __init__(self): + self.timestamps = [] + self.digests = [] + + def add_digest(self, timestamp, digest): + """Add a digest.""" + self.timestamps.append(timestamp) + self.digests.append(digest) + + def find_digest(self, timestamp): + """Find the latest image before the given timestamp.""" + index = bisect.bisect_right(self.timestamps, timestamp) + if index > 0: + return self.digests[index - 1] + + logging.error('Failed to find suitable base-builder.') + return None + + +def _replace_gitdir(src_dir, file_path): + """Replace gitdir with a relative path.""" + with open(file_path) as handle: + lines = handle.readlines() + + new_lines = [] + for line in lines: + if line.startswith(_GIT_DIR_MARKER): + absolute_path = line[len(_GIT_DIR_MARKER):].strip() + if not os.path.isabs(absolute_path): + # Already relative. + return + + current_dir = os.path.dirname(file_path) + # Rebase to /src rather than the host src dir. + base_dir = current_dir.replace(src_dir, '/src') + relative_path = os.path.relpath(absolute_path, base_dir) + logging.info('Replacing absolute submodule gitdir from %s to %s', + absolute_path, relative_path) + + line = _GIT_DIR_MARKER + relative_path + + new_lines.append(line) + + with open(file_path, 'w') as handle: + handle.write(''.join(new_lines)) + + +def _make_gitdirs_relative(src_dir): + """Make gitdirs relative.""" + for root_dir, _, files in os.walk(src_dir): + for filename in files: + if filename != '.git': + continue + + file_path = os.path.join(root_dir, filename) + _replace_gitdir(src_dir, file_path) + + +def _replace_base_builder_digest(dockerfile_path, digest): + """Replace the base-builder digest in a Dockerfile.""" + with open(dockerfile_path) as handle: + lines = handle.readlines() + + new_lines = [] + for line in lines: + if line.strip().startswith('FROM'): + line = 'FROM ghcr.io/aixcc-finals/base-builder@' + digest + '\n' + + new_lines.append(line) + + with open(dockerfile_path, 'w') as handle: + handle.write(''.join(new_lines)) + + +def copy_src_from_docker(project_name, host_dir): + """Copy /src from docker to the host.""" + # Copy /src to host. + image_name = 'gcr.io/oss-fuzz/' + project_name + src_dir = os.path.join(host_dir, 'src') + if os.path.exists(src_dir): + shutil.rmtree(src_dir, ignore_errors=True) + + docker_args = [ + '-v', + host_dir + ':/out', + image_name, + 'cp', + '-r', + '-p', + '/src', + '/out', + ] + helper.docker_run(docker_args) + + # Submodules can have gitdir entries which point to absolute paths. Make them + # relative, as otherwise we can't do operations on the checkout on the host. + _make_gitdirs_relative(src_dir) + return src_dir + + +@retry.wrap(_IMAGE_BUILD_TRIES, 2) +def _build_image_with_retries(project_name): + """Build image with retries.""" + return helper.build_image_impl(helper.Project(project_name)) + + +def get_required_post_checkout_steps(dockerfile_path): + """Get required post checkout steps (best effort).""" + + checkout_pattern = re.compile(r'\s*RUN\s*(git|svn|hg)') + + # If the build.sh is copied from upstream, we need to copy it again after + # changing the revision to ensure correct building. + post_run_pattern = re.compile(r'\s*RUN\s*(.*build\.sh.*(\$SRC|/src).*)') + + with open(dockerfile_path) as handle: + lines = handle.readlines() + + subsequent_run_cmds = [] + for i, line in enumerate(lines): + if checkout_pattern.match(line): + subsequent_run_cmds = [] + continue + + match = post_run_pattern.match(line) + if match: + workdir = helper.workdir_from_lines(lines[:i]) + command = match.group(1) + subsequent_run_cmds.append((workdir, command)) + + return subsequent_run_cmds + + +# pylint: disable=too-many-locals +def build_fuzzers_from_commit(commit, + build_repo_manager, + host_src_path, + build_data, + base_builder_repo=None): + """Builds a OSS-Fuzz fuzzer at a specific commit SHA. + + Args: + commit: The commit SHA to build the fuzzers at. + build_repo_manager: The OSS-Fuzz project's repo manager to be built at. + build_data: A struct containing project build information. + base_builder_repo: A BaseBuilderRepo. + Returns: + 0 on successful build or error code on failure. + """ + oss_fuzz_repo_manager = repo_manager.RepoManager(helper.OSS_FUZZ_DIR) + num_retry = 1 + + def cleanup(): + # Re-copy /src for a clean checkout every time. + copy_src_from_docker(build_data.project_name, + os.path.dirname(host_src_path)) + build_repo_manager.fetch_all_remotes() + + projects_dir = os.path.join('projects', build_data.project_name) + dockerfile_path = os.path.join(projects_dir, 'Dockerfile') + + for i in range(num_retry + 1): + build_repo_manager.checkout_commit(commit, clean=False) + + post_checkout_steps = get_required_post_checkout_steps(dockerfile_path) + for workdir, post_checkout_step in post_checkout_steps: + logging.info('Running post-checkout step `%s` in %s.', post_checkout_step, + workdir) + helper.docker_run([ + '-w', + workdir, + '-v', + host_src_path + ':' + '/src', + 'gcr.io/oss-fuzz/' + build_data.project_name, + '/bin/bash', + '-c', + post_checkout_step, + ]) + + project = helper.Project(build_data.project_name) + result = helper.build_fuzzers_impl(project=project, + clean=True, + engine=build_data.engine, + sanitizer=build_data.sanitizer, + architecture=build_data.architecture, + env_to_add=None, + source_path=host_src_path, + mount_path='/src') + if result or i == num_retry: + break + + # Retry with an OSS-Fuzz builder container that's closer to the project + # commit date. + commit_date = build_repo_manager.commit_date(commit) + + # Find first change in the projects/ directory before the project + # commit date. + oss_fuzz_commit, _, _ = oss_fuzz_repo_manager.git([ + 'log', '--before=' + commit_date.isoformat(), '-n1', '--format=%H', + projects_dir + ], + check_result=True) + oss_fuzz_commit = oss_fuzz_commit.strip() + if not oss_fuzz_commit: + logging.info( + 'Could not find first OSS-Fuzz commit prior to upstream commit. ' + 'Falling back to oldest integration commit.') + + # Find the oldest commit. + oss_fuzz_commit, _, _ = oss_fuzz_repo_manager.git( + ['log', '--reverse', '--format=%H', projects_dir], check_result=True) + + oss_fuzz_commit = oss_fuzz_commit.splitlines()[0].strip() + + if not oss_fuzz_commit: + logging.error('Failed to get oldest integration commit.') + break + + logging.info('Build failed. Retrying on earlier OSS-Fuzz commit %s.', + oss_fuzz_commit) + + # Check out projects/ dir to the commit that was found. + oss_fuzz_repo_manager.git(['checkout', oss_fuzz_commit, projects_dir], + check_result=True) + + # Also use the closest base-builder we can find. + if base_builder_repo: + base_builder_digest = base_builder_repo.find_digest(commit_date) + if not base_builder_digest: + return False + + logging.info('Using base-builder with digest %s.', base_builder_digest) + _replace_base_builder_digest(dockerfile_path, base_builder_digest) + + # Rebuild image and re-copy src dir since things in /src could have changed. + if not _build_image_with_retries(build_data.project_name): + logging.error('Failed to rebuild image.') + return False + + cleanup() + + cleanup() + return result + + +def detect_main_repo(project_name, repo_name=None, commit=None): + """Checks a docker image for the main repo of an OSS-Fuzz project. + + Note: The default is to use the repo name to detect the main repo. + + Args: + project_name: The name of the oss-fuzz project. + repo_name: The name of the main repo in an OSS-Fuzz project. + commit: A commit SHA that is associated with the main repo. + + Returns: + A tuple containing (the repo's origin, the repo's path). + """ + + if not repo_name and not commit: + logging.error( + 'Error: can not detect main repo without a repo_name or a commit.') + return None, None + if repo_name and commit: + logging.info( + 'Both repo name and commit specific. Using repo name for detection.') + + # Change to oss-fuzz main directory so helper.py runs correctly. + utils.chdir_to_root() + if not _build_image_with_retries(project_name): + logging.error('Error: building %s image failed.', project_name) + return None, None + docker_image_name = 'gcr.io/oss-fuzz/' + project_name + command_to_run = [ + 'docker', 'run', '--rm', '-t', docker_image_name, 'python3', + os.path.join('/opt', 'cifuzz', 'detect_repo.py') + ] + if repo_name: + command_to_run.extend(['--repo_name', repo_name]) + else: + command_to_run.extend(['--example_commit', commit]) + out, _, _ = utils.execute(command_to_run) + match = re.search(r'\bDetected repo: ([^ ]+) ([^ ]+)', out.rstrip()) + if match and match.group(1) and match.group(2): + return match.group(1), match.group(2) + + logging.error('Failed to detect repo:\n%s', out) + return None, None + + +def load_base_builder_repo(): + """Get base-image digests.""" + gcloud_path = shutil.which('gcloud') + if not gcloud_path: + logging.warning('gcloud not found in PATH.') + return None + + result, _, _ = utils.execute([ + gcloud_path, + 'container', + 'images', + 'list-tags', + 'ghcr.io/aixcc-finals/base-builder', + '--format=json', + '--sort-by=timestamp', + ], + check_result=True) + result = json.loads(result) + + repo = BaseBuilderRepo() + for image in result: + timestamp = datetime.datetime.fromisoformat( + image['timestamp']['datetime']).astimezone(datetime.timezone.utc) + repo.add_digest(timestamp, image['digest']) + + return repo + + +def main(): + """Main function.""" + logging.getLogger().setLevel(logging.INFO) + + parser = argparse.ArgumentParser( + description='Build fuzzers at a specific commit') + parser.add_argument('--project_name', + help='The name of the project where the bug occurred.', + required=True) + parser.add_argument('--commit', + help='The newest commit SHA to be bisected.', + required=True) + parser.add_argument('--engine', + help='The default is "libfuzzer".', + default='libfuzzer') + parser.add_argument('--sanitizer', + default='address', + help='The default is "address".') + parser.add_argument('--architecture', default='x86_64') + + args = parser.parse_args() + + repo_url, repo_path = detect_main_repo(args.project_name, commit=args.commit) + + if not repo_url or not repo_path: + raise ValueError('Main git repo can not be determined.') + + with tempfile.TemporaryDirectory() as tmp_dir: + host_src_dir = copy_src_from_docker(args.project_name, tmp_dir) + build_repo_manager = repo_manager.RepoManager( + os.path.join(host_src_dir, os.path.basename(repo_path))) + base_builder_repo = load_base_builder_repo() + + build_data = BuildData(project_name=args.project_name, + engine=args.engine, + sanitizer=args.sanitizer, + architecture=args.architecture) + if not build_fuzzers_from_commit(args.commit, + build_repo_manager, + host_src_dir, + build_data, + base_builder_repo=base_builder_repo): + raise RuntimeError('Failed to build.') + + +if __name__ == '__main__': + main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit_test.py b/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit_test.py new file mode 100644 index 0000000000000000000000000000000000000000..00f50947f711e03cdb5190284808b069eab99864 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/build_specified_commit_test.py @@ -0,0 +1,126 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Test the functionality of the build image from commit module. +The will consist of the following functional tests: + 1. The inference of the main repo for a specific project. + 2. The building of a projects fuzzers from a specific commit. + +""" +import os +import tempfile +import unittest + +import build_specified_commit +import helper +import repo_manager +import test_repos + +# necessary because __file__ changes with os.chdir +TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__)) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class BuildImageIntegrationTest(unittest.TestCase): + """Tests if an image can be built from different states e.g. a commit.""" + + @unittest.skip('Test is failing (spuriously?).') + def test_build_fuzzers_from_commit(self): + """Tests if the fuzzers can build at a specified commit. + + This is done by using a known regression range for a specific test case. + The old commit should show the error when its fuzzers run and the new one + should not. + """ + with tempfile.TemporaryDirectory() as tmp_dir: + test_repo = test_repos.TEST_REPOS[1] + self.assertTrue(helper.build_image_impl(test_repo.project_name)) + host_src_dir = build_specified_commit.copy_src_from_docker( + test_repo.project_name, tmp_dir) + + test_repo_manager = repo_manager.clone_repo_and_get_manager( + test_repo.git_url, host_src_dir, test_repo.oss_repo_name) + build_data = build_specified_commit.BuildData( + sanitizer='address', + architecture='x86_64', + engine='libfuzzer', + project_name=test_repo.project_name) + + build_specified_commit.build_fuzzers_from_commit(test_repo.old_commit, + test_repo_manager, + host_src_dir, build_data) + project = helper.Project(test_repo.project_name) + old_result = helper.reproduce_impl(project=project, + fuzzer_name=test_repo.fuzz_target, + valgrind=False, + env_to_add=[], + fuzzer_args=[], + testcase_path=test_repo.testcase_path) + build_specified_commit.build_fuzzers_from_commit(test_repo.project_name, + test_repo_manager, + host_src_dir, build_data) + new_result = helper.reproduce_impl(project=project, + fuzzer_name=test_repo.fuzz_target, + valgrind=False, + env_to_add=[], + fuzzer_args=[], + testcase_path=test_repo.testcase_path) + self.assertNotEqual(new_result, old_result) + + def test_detect_main_repo_from_commit(self): + """Test the detect main repo function from build specific commit module.""" + # TODO(metzman): Fix these tests so they don't randomly break because of + # changes in the outside world. + for example_repo in test_repos.TEST_REPOS: + if example_repo.new_commit: + # TODO(metzman): This function calls _build_image_with_retries which + # has a long delay (30 seconds). Figure out how to make this quicker. + repo_origin, repo_name = build_specified_commit.detect_main_repo( + example_repo.project_name, commit=example_repo.new_commit) + self.assertEqual(repo_origin, example_repo.git_url) + self.assertEqual(repo_name, + os.path.join('/src', example_repo.oss_repo_name)) + + repo_origin, repo_name = build_specified_commit.detect_main_repo( + test_repos.INVALID_REPO.project_name, + test_repos.INVALID_REPO.new_commit) + self.assertIsNone(repo_origin) + self.assertIsNone(repo_name) + + def test_detect_main_repo_from_name(self): + """Test the detect main repo function from build specific commit module.""" + for example_repo in test_repos.TEST_REPOS: + if example_repo.project_name == 'gonids': + # It's unclear how this test ever passed, but we can't infer the repo + # because gonids doesn't really check it out, it uses "go get". + continue + repo_origin, repo_name = build_specified_commit.detect_main_repo( + example_repo.project_name, repo_name=example_repo.git_repo_name) + self.assertEqual(repo_origin, example_repo.git_url) + self.assertEqual( + repo_name, + os.path.join(example_repo.image_location, example_repo.oss_repo_name)) + + repo_origin, repo_name = build_specified_commit.detect_main_repo( + test_repos.INVALID_REPO.project_name, + test_repos.INVALID_REPO.oss_repo_name) + self.assertIsNone(repo_origin) + self.assertIsNone(repo_name) + + +if __name__ == '__main__': + # Change to oss-fuzz main directory so helper.py runs correctly. + if os.getcwd() != os.path.dirname(TEST_DIR_PATH): + os.chdir(os.path.dirname(TEST_DIR_PATH)) + unittest.main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/ci/requirements.txt b/local-test-curl-delta-01/fuzz-tooling/infra/ci/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..303274fd5fbec5d190a3baa80dd449f579a2b5a9 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/ci/requirements.txt @@ -0,0 +1,9 @@ +# Requirements for submitting code changes to infra/ (needed by presubmit.py). +parameterized==0.7.4 +pyfakefs==4.5.6 +pylint==2.5.3 +pytest==7.1.2 +pytest-xdist==2.5.0 +PyYAML==6.0 +requests==2.31.0 +yapf==0.32.0 diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build-images.sh b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build-images.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3d94c1f4cf29c3943d6cce7a06a2dba38af580e --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build-images.sh @@ -0,0 +1,34 @@ +#! /bin/bash -eux +# Copyright 2021 Google LLC +# +# 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. + +# Script for building the docker images for cifuzz. + +CIFUZZ_DIR=$(dirname "$0") +CIFUZZ_DIR=$(realpath $CIFUZZ_DIR) +INFRA_DIR=$(realpath $CIFUZZ_DIR/..) +OSS_FUZZ_ROOT=$(realpath $INFRA_DIR/..) + +# Build cifuzz-base. +docker build --tag ghcr.io/aixcc-finals/cifuzz-base --file $CIFUZZ_DIR/cifuzz-base/Dockerfile $OSS_FUZZ_ROOT + +# Build run-fuzzers and build-fuzzers images. +docker build \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers-test:v1 \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 \ + --file $INFRA_DIR/build_fuzzers.Dockerfile $INFRA_DIR +docker build \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers-test:v1 \ + --file $INFRA_DIR/run_fuzzers.Dockerfile $INFRA_DIR diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5bec6b5573cc7720f5031bc7d50de944320f81 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py @@ -0,0 +1,60 @@ +# Copyright 2020 Google LLC +# +# 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. +"""Builds a specific OSS-Fuzz project's fuzzers for CI tools.""" +import logging +import sys + +import build_fuzzers +import logs +import config_utils + +# pylint: disable=c-extension-no-member +# pylint gets confused because of the relative import of cifuzz. + +logs.init() + + +def build_fuzzers_entrypoint(): + """Builds OSS-Fuzz project's fuzzers for CI tools.""" + config = config_utils.BuildFuzzersConfig() + + if config.dry_run: + # Sets the default return code on error to success. + returncode = 0 + else: + # The default return code when an error occurs. + returncode = 1 + + if not build_fuzzers.build_fuzzers(config): + logging.error('Error building fuzzers for (commit: %s, pr_ref: %s).', + config.git_sha, config.pr_ref) + return returncode + + return 0 + + +def main(): + """Builds OSS-Fuzz project's fuzzers for CI tools. + + Note: The resulting fuzz target binaries of this build are placed in + the directory: ${GITHUB_WORKSPACE}/out + + Returns: + 0 on success or nonzero on failure. + """ + return build_fuzzers_entrypoint() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..b36fc78dec9ab35b045aa6b42b790e1904a98e67 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py @@ -0,0 +1,385 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Module for interacting with the ClusterFuzz deployment.""" +import logging +import os +import sys +import urllib.error +import urllib.request + +import config_utils +import continuous_integration +import filestore_utils +import http_utils +import get_coverage +import repo_manager + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + + +class BaseClusterFuzzDeployment: + """Base class for ClusterFuzz deployments.""" + + def __init__(self, config, workspace): + self.config = config + self.workspace = workspace + self.ci_system = continuous_integration.get_ci(config) + + def download_latest_build(self): + """Downloads the latest build from ClusterFuzz. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + raise NotImplementedError('Child class must implement method.') + + def upload_build(self, commit): + """Uploads the build with the given commit sha to the filestore.""" + raise NotImplementedError('Child class must implement method.') + + def download_corpus(self, target_name, corpus_dir): + """Downloads the corpus for |target_name| from ClusterFuzz to |corpus_dir|. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + raise NotImplementedError('Child class must implement method.') + + def upload_crashes(self): + """Uploads crashes in |crashes_dir| to filestore.""" + raise NotImplementedError('Child class must implement method.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Uploads the corpus for |target_name| to filestore.""" + raise NotImplementedError('Child class must implement method.') + + def upload_coverage(self): + """Uploads the coverage report to the filestore.""" + raise NotImplementedError('Child class must implement method.') + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + raise NotImplementedError('Child class must implement method.') + + +def _make_empty_dir_if_nonexistent(path): + """Makes an empty directory at |path| if it does not exist.""" + os.makedirs(path, exist_ok=True) + + +class ClusterFuzzLite(BaseClusterFuzzDeployment): + """Class representing a deployment of ClusterFuzzLite.""" + + COVERAGE_NAME = 'latest' + LATEST_BUILD_WINDOW = 3 + + def __init__(self, config, workspace): + super().__init__(config, workspace) + self.filestore = filestore_utils.get_filestore(self.config) + + def download_latest_build(self): + if os.path.exists(self.workspace.clusterfuzz_build): + # This path is necessary because download_latest_build can be called + # multiple times.That is the case because it is called only when we need + # to see if a bug is novel, i.e. until we want to check a bug is novel we + # don't want to waste time calling this, but therefore this method can be + # called if multiple bugs are found. + return self.workspace.clusterfuzz_build + + repo_dir = self.ci_system.repo_dir + if not repo_dir: + raise RuntimeError('Repo checkout does not exist.') + + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build) + repo = repo_manager.RepoManager(repo_dir) + + diff_base = self.ci_system.get_diff_base() + if not diff_base: + diff_base = 'HEAD^' + + # Builds are stored by commit, so try the latest |LATEST_BUILD_WINDOW| + # commits before the current diff base. + # TODO(ochang): If API usage becomes an issue, this can be optimized by the + # filestore accepting a list of filenames to try. + try: + # TODO(metzman): Why do we default to 'origin', we should avoid going down + # this path entirely and not need to catch an exception. + commit_list = repo.get_commit_list(diff_base, + limit=self.LATEST_BUILD_WINDOW) + except ValueError as error: + logging.error('Can\'t get commit list: %s', error) + return None + + for old_commit in commit_list: + logging.info('Trying to downloading previous build %s.', old_commit) + build_name = self._get_build_name(old_commit) + try: + if self.filestore.download_build(build_name, + self.workspace.clusterfuzz_build): + logging.info('Done downloading previous build.') + return self.workspace.clusterfuzz_build + + logging.info('Build for %s does not exist.', old_commit) + except Exception as err: # pylint: disable=broad-except + logging.error('Could not download build for %s because of: %s', + old_commit, err) + + return None + + def download_corpus(self, target_name, corpus_dir): + _make_empty_dir_if_nonexistent(corpus_dir) + logging.info('Downloading corpus for %s to %s.', target_name, corpus_dir) + corpus_name = self._get_corpus_name(target_name) + try: + self.filestore.download_corpus(corpus_name, corpus_dir) + logging.info('Done downloading corpus. Contains %d elements.', + len(os.listdir(corpus_dir))) + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to download corpus for target: %s. Error: %s', + target_name, str(err)) + return corpus_dir + + def _get_build_name(self, name): + return f'{self.config.sanitizer}-{name}' + + def _get_corpus_name(self, target_name): # pylint: disable=no-self-use + """Returns the name of the corpus artifact.""" + return target_name + + def upload_corpus(self, target_name, corpus_dir, replace=False): + """Upload the corpus produced by |target_name|.""" + logging.info('Uploading corpus in %s for %s.', corpus_dir, target_name) + name = self._get_corpus_name(target_name) + try: + self.filestore.upload_corpus(name, corpus_dir, replace=replace) + logging.info('Done uploading corpus.') + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload corpus for target: %s. Error: %s.', + target_name, err) + + def upload_build(self, commit): + """Upload the build produced by CIFuzz as the latest build.""" + logging.info('Uploading latest build in %s.', self.workspace.out) + build_name = self._get_build_name(commit) + try: + result = self.filestore.upload_build(build_name, self.workspace.out) + logging.info('Done uploading latest build.') + return result + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload latest build: %s. Error: %s', + self.workspace.out, err) + + def upload_crashes(self): + """Uploads crashes.""" + artifact_dirs = os.listdir(self.workspace.artifacts) + if not artifact_dirs: + logging.info('No crashes in %s. Not uploading.', self.workspace.artifacts) + return + + for crash_target in artifact_dirs: + artifact_dir = os.path.join(self.workspace.artifacts, crash_target) + if not os.path.isdir(artifact_dir): + logging.warning('%s is not an expected artifact directory, skipping.', + crash_target) + continue + + logging.info('Uploading crashes in %s.', artifact_dir) + try: + self.filestore.upload_crashes(crash_target, artifact_dir) + logging.info('Done uploading crashes.') + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload crashes. Error: %s', err) + + def upload_coverage(self): + """Uploads the coverage report to the filestore.""" + self.filestore.upload_coverage(self.COVERAGE_NAME, + self.workspace.coverage_report) + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_coverage) + try: + if not self.filestore.download_coverage( + self.COVERAGE_NAME, self.workspace.clusterfuzz_coverage): + logging.error('Could not download coverage.') + return None + return get_coverage.FilesystemCoverage( + repo_path, self.workspace.clusterfuzz_coverage) + except Exception as err: # pylint: disable=broad-except + logging.error('Could not get coverage: %s.', err) + return None + + +class OSSFuzz(BaseClusterFuzzDeployment): + """The OSS-Fuzz ClusterFuzz deployment.""" + + # Location of clusterfuzz builds on GCS. + CLUSTERFUZZ_BUILDS = 'clusterfuzz-builds' + + # Zip file name containing the corpus. + CORPUS_ZIP_NAME = 'public.zip' + + def get_latest_build_name(self): + """Gets the name of the latest OSS-Fuzz build of a project. + + Returns: + A string with the latest build version or None. + """ + version_file = ( + f'{self.config.oss_fuzz_project_name}-{self.config.sanitizer}' + '-latest.version') + version_url = utils.url_join(utils.GCS_BASE_URL, self.CLUSTERFUZZ_BUILDS, + self.config.oss_fuzz_project_name, + version_file) + try: + response = urllib.request.urlopen(version_url) + except urllib.error.HTTPError: + logging.error('Error getting latest build version for %s from: %s.', + self.config.oss_fuzz_project_name, version_url) + return None + return response.read().decode() + + def download_latest_build(self): + """Downloads the latest OSS-Fuzz build from GCS. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + if os.path.exists(self.workspace.clusterfuzz_build): + # This function can be called multiple times, don't download the build + # again. + return self.workspace.clusterfuzz_build + + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build) + + latest_build_name = self.get_latest_build_name() + if not latest_build_name: + return None + + logging.info('Downloading latest build.') + oss_fuzz_build_url = utils.url_join(utils.GCS_BASE_URL, + self.CLUSTERFUZZ_BUILDS, + self.config.oss_fuzz_project_name, + latest_build_name) + if http_utils.download_and_unpack_zip(oss_fuzz_build_url, + self.workspace.clusterfuzz_build): + logging.info('Done downloading latest build.') + return self.workspace.clusterfuzz_build + + return None + + def upload_build(self, commit): # pylint: disable=no-self-use + """Noop Implementation of upload_build.""" + logging.info('Not uploading latest build because on OSS-Fuzz.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Noop Implementation of upload_corpus.""" + logging.info('Not uploading corpus because on OSS-Fuzz.') + + def upload_crashes(self): # pylint: disable=no-self-use + """Noop Implementation of upload_crashes.""" + logging.info('Not uploading crashes because on OSS-Fuzz.') + + def download_corpus(self, target_name, corpus_dir): + """Downloads the latest OSS-Fuzz corpus for the target. + + Returns: + The local path to to corpus or None if download failed. + """ + _make_empty_dir_if_nonexistent(corpus_dir) + project_qualified_fuzz_target_name = target_name + qualified_name_prefix = self.config.oss_fuzz_project_name + '_' + if not target_name.startswith(qualified_name_prefix): + project_qualified_fuzz_target_name = qualified_name_prefix + target_name + + corpus_url = (f'{utils.GCS_BASE_URL}{self.config.oss_fuzz_project_name}' + '-backup.clusterfuzz-external.appspot.com/corpus/' + f'libFuzzer/{project_qualified_fuzz_target_name}/' + f'{self.CORPUS_ZIP_NAME}') + logging.info('Downloading corpus from OSS-Fuzz: %s', corpus_url) + + if not http_utils.download_and_unpack_zip(corpus_url, corpus_dir): + logging.warning('Failed to download corpus for %s.', target_name) + return corpus_dir + + def upload_coverage(self): + """Noop Implementation of upload_coverage_report.""" + logging.info('Not uploading coverage report because on OSS-Fuzz.') + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + try: + return get_coverage.OSSFuzzCoverage(repo_path, + self.config.oss_fuzz_project_name) + except get_coverage.CoverageError: + return None + + +class NoClusterFuzzDeployment(BaseClusterFuzzDeployment): + """ClusterFuzzDeployment implementation used when there is no deployment of + ClusterFuzz to use.""" + + def upload_build(self, commit): # pylint: disable=no-self-use + """Noop Implementation of upload_build.""" + logging.info('Not uploading latest build because no ClusterFuzz ' + 'deployment.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Noop Implementation of upload_corpus.""" + logging.info('Not uploading corpus because no ClusterFuzz deployment.') + + def upload_crashes(self): # pylint: disable=no-self-use + """Noop Implementation of upload_crashes.""" + logging.info('Not uploading crashes because no ClusterFuzz deployment.') + + def download_corpus(self, target_name, corpus_dir): + """Noop Implementation of download_corpus.""" + logging.info('Not downloading corpus because no ClusterFuzz deployment.') + return _make_empty_dir_if_nonexistent(corpus_dir) + + def download_latest_build(self): # pylint: disable=no-self-use + """Noop Implementation of download_latest_build.""" + logging.info( + 'Not downloading latest build because no ClusterFuzz deployment.') + + def upload_coverage(self): + """Noop Implementation of upload_coverage.""" + logging.info( + 'Not uploading coverage report because no ClusterFuzz deployment.') + + def get_coverage(self, repo_path): + """Noop Implementation of get_coverage.""" + logging.info( + 'Not getting project coverage because no ClusterFuzz deployment.') + + +_PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING = { + config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI: OSSFuzz, + config_utils.BaseConfig.Platform.INTERNAL_GITHUB: OSSFuzz, + config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI: ClusterFuzzLite, + config_utils.BaseConfig.Platform.EXTERNAL_GITHUB: ClusterFuzzLite, +} + + +def get_clusterfuzz_deployment(config, workspace): + """Returns object reprsenting deployment of ClusterFuzz used by |config|.""" + deployment_cls = _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING[config.platform] + if config.no_clusterfuzz_deployment: + logging.info('Overriding ClusterFuzzDeployment. Using None.') + deployment_cls = NoClusterFuzzDeployment + result = deployment_cls(config, workspace) + logging.info('ClusterFuzzDeployment: %s.', result) + return result diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/requirements.txt b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d09da56ada1ec32208bf7a667598cf6ba940be65 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/requirements.txt @@ -0,0 +1,4 @@ +clusterfuzz==2.5.9 +requests==2.28.0 +protobuf==3.20.2 +gsutil==5.20 diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils.py b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf2dd7e2da113ec3b179fcb3e0d319ed75c26e8 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils.py @@ -0,0 +1,251 @@ +# Copyright 2023 Google LLC +# +# 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. +"""Module for outputting SARIF data.""" +import copy +import json +import logging +import os + +from clusterfuzz import stacktraces + +SARIF_RULES = [ + { + 'id': 'no-crashes', + 'shortDescription': { + 'text': 'Don\'t crash' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'heap-use-after-free', + 'shortDescription': { + 'text': 'Use of a heap-object after it has been freed.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'heap-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a heap buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/122.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a stack buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'global-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a global buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-use-after-return', + 'shortDescription': { + 'text': + 'A stack-based variable has been used after the function returned.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-use-after-scope', + 'shortDescription': { + 'text': + 'A stack-based variable has been used outside of the scope in which it exists.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'initialization-order-fiasco', + 'shortDescription': { + 'text': 'Problem with order of initialization of global objects.' + }, + 'helpUri': 'https://isocpp.org/wiki/faq/ctors#static-init-order', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': + 'direct-leak', + 'shortDescription': { + 'text': 'Memory is leaked.' + }, + 'helpUri': + 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': + 'indirect-leak', + 'shortDescription': { + 'text': 'Memory is leaked.' + }, + 'helpUri': + 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer', + 'properties': { + 'category': 'Crashes' + } + }, +] +SARIF_DATA = { + 'version': + '2.1.0', + '$schema': + 'http://json.schemastore.org/sarif-2.1.0-rtm.4', + 'runs': [{ + 'tool': { + 'driver': { + 'name': 'ClusterFuzzLite/CIFuzz', + 'informationUri': 'https://google.github.io/clusterfuzzlite/', + 'rules': SARIF_RULES, + } + }, + 'results': [] + }] +} + +SRC_ROOT = '/src/' + + +def redact_src_path(src_path): + """Redact the src path so that it can be reported to users.""" + src_path = os.path.normpath(src_path) + if src_path.startswith(SRC_ROOT): + src_path = src_path[len(SRC_ROOT):] + + src_path = os.sep.join(src_path.split(os.sep)[1:]) + return src_path + + +def get_error_frame(crash_info): + """Returns the stackframe where the error occurred.""" + if not crash_info.crash_state: + return None + state = crash_info.crash_state.split('\n')[0] + logging.info('state: %s frames %s, %s', state, crash_info.frames, + [f.function_name for f in crash_info.frames[0]]) + + for crash_frames in crash_info.frames: + for frame in crash_frames: + # TODO(metzman): Do something less fragile here. + if frame.function_name is None: + continue + if state in frame.function_name: + return frame + return None + + +def get_error_source_info(crash_info): + """Returns the filename and the line where the bug occurred.""" + frame = get_error_frame(crash_info) + if not frame: + return (None, 1) + try: + return redact_src_path(frame.filename), int(frame.fileline or 1) + except TypeError: + return (None, 1) + + +def get_rule_index(crash_type): + """Returns the rule index describe the rule that |crash_type| ran afoul of.""" + # Don't include "READ" or "WRITE" or number of bytes. + crash_type = crash_type.replace('\n', ' ').split(' ')[0].lower() + logging.info('crash_type: %s.', crash_type) + for idx, rule in enumerate(SARIF_RULES): + if rule['id'] == crash_type: + logging.info('Rule index: %d.', idx) + return idx + + return get_rule_index('no-crashes') + + +def get_sarif_data(stacktrace, target_path): + """Returns a description of the crash in SARIF.""" + data = copy.deepcopy(SARIF_DATA) + if stacktrace is None: + return data + + fuzz_target = os.path.basename(target_path) + stack_parser = stacktraces.StackParser(fuzz_target=fuzz_target, + symbolized=True, + detect_ooms_and_hangs=True, + include_ubsan=True) + crash_info = stack_parser.parse(stacktrace) + error_source_info = get_error_source_info(crash_info) + rule_idx = get_rule_index(crash_info.crash_type) + rule_id = SARIF_RULES[rule_idx]['id'] + uri = error_source_info[0] + + result = { + 'level': 'error', + 'message': { + 'text': crash_info.crash_type + }, + 'locations': [{ + 'physicalLocation': { + 'artifactLocation': { + 'uri': uri, + 'index': 0 + }, + 'region': { + 'startLine': error_source_info[1], + # We don't have this granualarity fuzzing. + 'startColumn': 1, + } + } + }], + 'ruleId': rule_id, + 'ruleIndex': rule_idx + } + if uri: + data['runs'][0]['results'].append(result) + return data + + +def write_stacktrace_to_sarif(stacktrace, target_path, workspace): + """Writes a description of the crash in stacktrace to a SARIF file.""" + data = get_sarif_data(stacktrace, target_path) + if not os.path.exists(workspace.sarif): + os.makedirs(workspace.sarif) + with open(os.path.join(workspace.sarif, 'results.sarif'), 'w') as file_handle: + file_handle.write(json.dumps(data)) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/constants.py b/local-test-curl-delta-01/fuzz-tooling/infra/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9b40d1fc3f1130c2ee3c03f45b6d759fd74d05 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/constants.py @@ -0,0 +1,49 @@ +# Copyright 2021 Google LLC +# +# 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. +# +################################################################################ +"""Constants for OSS-Fuzz.""" + +DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH = '.clusterfuzzlite' + +DEFAULT_LANGUAGE = 'c++' +DEFAULT_SANITIZER = 'address' +DEFAULT_ARCHITECTURE = 'x86_64' +DEFAULT_ENGINE = 'libfuzzer' +LANGUAGES = [ + 'c', + 'c++', + 'go', + 'javascript', + 'jvm', + 'python', + 'rust', + 'swift', + 'ruby', +] +LANGUAGES_WITH_COVERAGE_SUPPORT = [ + 'c', 'c++', 'go', 'jvm', 'python', 'rust', 'swift', 'javascript', 'ruby' +] +SANITIZERS = [ + 'address', + 'none', + 'memory', + 'undefined', + 'thread', + 'coverage', + 'introspector', + 'hwaddress', +] +ARCHITECTURES = ['i386', 'x86_64', 'aarch64'] +ENGINES = ['libfuzzer', 'afl', 'honggfuzz', 'centipede', 'none', 'wycheproof'] diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/helper.py b/local-test-curl-delta-01/fuzz-tooling/infra/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..0aefe880791ec4193cedf5fb5986c94a711e9dfc --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/helper.py @@ -0,0 +1,1810 @@ +#!/usr/bin/env python +# Copyright 2016 Google Inc. +# +# 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. +# +################################################################################ +"""Helper script for OSS-Fuzz users. Can do common tasks like building +projects/fuzzers, running them etc.""" + +from __future__ import print_function +from multiprocessing.dummy import Pool as ThreadPool +import argparse +import datetime +import errno +import logging +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile + +import constants +import templates + +OSS_FUZZ_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +BUILD_DIR = os.path.join(OSS_FUZZ_DIR, 'build') + +BASE_IMAGE_TAG = ':v1.2.1' # no tag for latest + +BASE_RUNNER_IMAGE = f'ghcr.io/aixcc-finals/base-runner{BASE_IMAGE_TAG}' + +BASE_IMAGES = { + 'generic': [ + f'ghcr.io/aixcc-finals/base-image{BASE_IMAGE_TAG}', + f'ghcr.io/aixcc-finals/base-clang{BASE_IMAGE_TAG}', + f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}', + BASE_RUNNER_IMAGE, + f'ghcr.io/aixcc-finals/base-runner-debug{BASE_IMAGE_TAG}', + ], + 'go': [f'ghcr.io/aixcc-finals/base-builder-go{BASE_IMAGE_TAG}'], + 'javascript': [f'ghcr.io/aixcc-finals/base-builder-javascript{BASE_IMAGE_TAG}'], + 'jvm': [f'ghcr.io/aixcc-finals/base-builder-jvm{BASE_IMAGE_TAG}'], + 'python': [f'ghcr.io/aixcc-finals/base-builder-python{BASE_IMAGE_TAG}'], + 'rust': [f'ghcr.io/aixcc-finals/base-builder-rust{BASE_IMAGE_TAG}'], + 'ruby': [f'ghcr.io/aixcc-finals/base-builder-ruby{BASE_IMAGE_TAG}'], + 'swift': [f'ghcr.io/aixcc-finals/base-builder-swift{BASE_IMAGE_TAG}'], +} + +VALID_PROJECT_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$') +MAX_PROJECT_NAME_LENGTH = 26 + +CORPUS_URL_FORMAT = ( + 'gs://{project_name}-corpus.clusterfuzz-external.appspot.com/libFuzzer/' + '{fuzz_target}/') +CORPUS_BACKUP_URL_FORMAT = ( + 'gs://{project_name}-backup.clusterfuzz-external.appspot.com/corpus/' + 'libFuzzer/{fuzz_target}/') + +HTTPS_CORPUS_BACKUP_URL_FORMAT = ( + 'https://storage.googleapis.com/{project_name}-backup.clusterfuzz-external' + '.appspot.com/corpus/libFuzzer/{fuzz_target}/public.zip') + +LANGUAGE_REGEX = re.compile(r'[^\s]+') +PROJECT_LANGUAGE_REGEX = re.compile(r'\s*language\s*:\s*([^\s]+)') + +WORKDIR_REGEX = re.compile(r'\s*WORKDIR\s*([^\s]+)') + +# Regex to match special chars in project name. +SPECIAL_CHARS_REGEX = re.compile('[^a-zA-Z0-9_-]') + +LANGUAGE_TO_BASE_BUILDER_IMAGE = { + 'c': 'base-builder', + 'c++': 'base-builder', + 'go': 'base-builder-go', + 'javascript': 'base-builder-javascript', + 'jvm': 'base-builder-jvm', + 'python': 'base-builder-python', + 'ruby': 'base-builder-ruby', + 'rust': 'base-builder-rust', + 'swift': 'base-builder-swift' +} +ARM_BUILDER_NAME = 'oss-fuzz-buildx-builder' + +CLUSTERFUZZLITE_ENGINE = 'libfuzzer' +CLUSTERFUZZLITE_ARCHITECTURE = 'x86_64' +CLUSTERFUZZLITE_FILESTORE_DIR = 'filestore' +CLUSTERFUZZLITE_DOCKER_IMAGE = 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers' + +logger = logging.getLogger(__name__) + +if sys.version_info[0] >= 3: + raw_input = input # pylint: disable=invalid-name + +# pylint: disable=too-many-lines + + +class Project: + """Class representing a project that is in OSS-Fuzz or an external project + (ClusterFuzzLite user).""" + + def __init__( + self, + project_name_or_path, + is_external=False, + build_integration_path=constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH): + self.is_external = is_external + if self.is_external: + self.path = os.path.abspath(project_name_or_path) + self.name = os.path.basename(self.path) + self.build_integration_path = os.path.join(self.path, + build_integration_path) + else: + self.name = project_name_or_path + self.path = os.path.join(OSS_FUZZ_DIR, 'projects', self.name) + self.build_integration_path = self.path + + @property + def dockerfile_path(self): + """Returns path to the project Dockerfile.""" + return os.path.join(self.build_integration_path, 'Dockerfile') + + @property + def language(self): + """Returns project language.""" + project_yaml_path = os.path.join(self.build_integration_path, + 'project.yaml') + if not os.path.exists(project_yaml_path): + logger.warning('No project.yaml. Assuming c++.') + return constants.DEFAULT_LANGUAGE + + with open(project_yaml_path) as file_handle: + content = file_handle.read() + for line in content.splitlines(): + match = PROJECT_LANGUAGE_REGEX.match(line) + if match: + return match.group(1) + + logger.warning('Language not specified in project.yaml. Assuming c++.') + return constants.DEFAULT_LANGUAGE + + @property + def coverage_extra_args(self): + """Returns project coverage extra args.""" + project_yaml_path = os.path.join(self.build_integration_path, + 'project.yaml') + if not os.path.exists(project_yaml_path): + logger.warning('project.yaml not found: %s.', project_yaml_path) + return '' + + with open(project_yaml_path) as file_handle: + content = file_handle.read() + + coverage_flags = '' + read_coverage_extra_args = False + # Pass the yaml file and extract the value of the coverage_extra_args key. + # This is naive yaml parsing and we do not handle comments at this point. + for line in content.splitlines(): + if read_coverage_extra_args: + # Break reading coverage args if a new yaml key is defined. + if len(line) > 0 and line[0] != ' ': + break + coverage_flags += line + if 'coverage_extra_args' in line: + read_coverage_extra_args = True + # Include the first line only if it's not a multi-line value. + if 'coverage_extra_args: >' not in line: + coverage_flags += line.replace('coverage_extra_args: ', '') + return coverage_flags + + @property + def out(self): + """Returns the out dir for the project. Creates it if needed.""" + return _get_out_dir(self.name) + + @property + def work(self): + """Returns the out dir for the project. Creates it if needed.""" + return _get_project_build_subdir(self.name, 'work') + + @property + def corpus(self): + """Returns the out dir for the project. Creates it if needed.""" + return _get_project_build_subdir(self.name, 'corpus') + + +def main(): # pylint: disable=too-many-branches,too-many-return-statements + """Gets subcommand from program arguments and does it. Returns 0 on success 1 + on error.""" + logging.basicConfig(level=logging.INFO) + parser = get_parser() + args = parse_args(parser) + + # Need to do this before chdir. + # TODO(https://github.com/google/oss-fuzz/issues/6758): Get rid of chdir. + if hasattr(args, 'testcase_path'): + args.testcase_path = _get_absolute_path(args.testcase_path) + # Note: this has to happen after parse_args above as parse_args needs to know + # the original CWD for external projects. + os.chdir(OSS_FUZZ_DIR) + if not os.path.exists(BUILD_DIR): + os.mkdir(BUILD_DIR) + + # We have different default values for `sanitizer` depending on the `engine`. + # Some commands do not have `sanitizer` argument, so `hasattr` is necessary. + if hasattr(args, 'sanitizer') and not args.sanitizer: + if args.project.language == 'javascript': + args.sanitizer = 'none' + else: + args.sanitizer = constants.DEFAULT_SANITIZER + + if args.command == 'generate': + result = generate(args) + elif args.command == 'build_image': + result = build_image(args) + elif args.command == 'build_fuzzers': + result = build_fuzzers(args) + elif args.command == 'fuzzbench_build_fuzzers': + result = fuzzbench_build_fuzzers(args) + elif args.command == 'fuzzbench_run_fuzzer': + result = fuzzbench_run_fuzzer(args) + elif args.command == 'fuzzbench_measure': + result = fuzzbench_measure(args) + elif args.command == 'check_build': + result = check_build(args) + elif args.command == 'download_corpora': + result = download_corpora(args) + elif args.command == 'run_fuzzer': + result = run_fuzzer(args) + elif args.command == 'coverage': + result = coverage(args) + elif args.command == 'introspector': + result = introspector(args) + elif args.command == 'reproduce': + result = reproduce(args) + if args.propagate_exit_codes: + return result + elif args.command == 'shell': + result = shell(args) + elif args.command == 'pull_images': + result = pull_images() + elif args.command == 'run_clusterfuzzlite': + result = run_clusterfuzzlite(args) + else: + # Print help string if no arguments provided. + parser.print_help() + result = False + return bool_to_retcode(result) + + +def bool_to_retcode(boolean): + """Returns 0 if |boolean| is Truthy, 0 is the standard return code for a + successful process execution. Returns 1 otherwise, indicating the process + failed.""" + return 0 if boolean else 1 + + +def parse_args(parser, args=None): + """Parses |args| using |parser| and returns parsed args. Also changes + |args.build_integration_path| to have correct default behavior.""" + # Use default argument None for args so that in production, argparse does its + # normal behavior, but unittesting is easier. + parsed_args = parser.parse_args(args) + project = getattr(parsed_args, 'project', None) + if not project: + return parsed_args + + # Use hacky method for extracting attributes so that ShellTest works. + # TODO(metzman): Fix this. + is_external = getattr(parsed_args, 'external', False) + parsed_args.project = Project(parsed_args.project, is_external) + return parsed_args + + +def _add_external_project_args(parser): + parser.add_argument( + '--external', + help='Is project external?', + default=False, + action='store_true', + ) + + +def get_parser(): # pylint: disable=too-many-statements,too-many-locals + """Returns an argparse parser.""" + parser = argparse.ArgumentParser('helper.py', description='oss-fuzz helpers') + subparsers = parser.add_subparsers(dest='command') + + generate_parser = subparsers.add_parser( + 'generate', help='Generate files for new project.') + generate_parser.add_argument('project') + generate_parser.add_argument('--language', + default=constants.DEFAULT_LANGUAGE, + choices=LANGUAGE_TO_BASE_BUILDER_IMAGE.keys(), + help='Project language.') + _add_external_project_args(generate_parser) + + build_image_parser = subparsers.add_parser('build_image', + help='Build an image.') + build_image_parser.add_argument('project') + build_image_parser.add_argument('--pull', + action='store_true', + help='Pull latest base image.') + _add_architecture_args(build_image_parser) + build_image_parser.add_argument('--cache', + action='store_true', + default=False, + help='Use docker cache when building image.') + build_image_parser.add_argument('--no-pull', + action='store_true', + help='Do not pull latest base image.') + build_image_parser.add_argument('--docker_image_tag', + dest='docker_image_tag', + default='latest', + help='docker image build tag' + 'default: latest') + _add_external_project_args(build_image_parser) + + build_fuzzers_parser = subparsers.add_parser( + 'build_fuzzers', help='Build fuzzers for a project.') + _add_architecture_args(build_fuzzers_parser) + _add_engine_args(build_fuzzers_parser) + _add_sanitizer_args(build_fuzzers_parser) + _add_environment_args(build_fuzzers_parser) + _add_external_project_args(build_fuzzers_parser) + build_fuzzers_parser.add_argument('project') + build_fuzzers_parser.add_argument('source_path', + help='path of local source', + nargs='?') + build_fuzzers_parser.add_argument('--mount_path', + dest='mount_path', + help='path to mount local source in ' + '(defaults to WORKDIR)') + build_fuzzers_parser.add_argument('--clean', + dest='clean', + action='store_true', + help='clean existing artifacts.') + build_fuzzers_parser.add_argument('--no-clean', + dest='clean', + action='store_false', + help='do not clean existing artifacts ' + '(default).') + build_fuzzers_parser.add_argument('--docker_image_tag', + dest='docker_image_tag', + default='latest', + help='docker image build tag' + 'default: latest') + build_fuzzers_parser.set_defaults(clean=False) + + fuzzbench_build_fuzzers_parser = subparsers.add_parser( + 'fuzzbench_build_fuzzers') + _add_architecture_args(fuzzbench_build_fuzzers_parser) + fuzzbench_build_fuzzers_parser.add_argument('--engine') + _add_sanitizer_args(fuzzbench_build_fuzzers_parser) + _add_environment_args(fuzzbench_build_fuzzers_parser) + _add_external_project_args(fuzzbench_build_fuzzers_parser) + fuzzbench_build_fuzzers_parser.add_argument('project') + check_build_parser = subparsers.add_parser( + 'check_build', help='Checks that fuzzers execute without errors.') + _add_architecture_args(check_build_parser) + _add_engine_args(check_build_parser, choices=constants.ENGINES) + _add_sanitizer_args(check_build_parser, choices=constants.SANITIZERS) + _add_environment_args(check_build_parser) + check_build_parser.add_argument('project', + help='name of the project or path (external)') + check_build_parser.add_argument('fuzzer_name', + help='name of the fuzzer', + nargs='?') + _add_external_project_args(check_build_parser) + + run_fuzzer_parser = subparsers.add_parser( + 'run_fuzzer', help='Run a fuzzer in the emulated fuzzing environment.') + _add_architecture_args(run_fuzzer_parser) + _add_engine_args(run_fuzzer_parser) + _add_sanitizer_args(run_fuzzer_parser) + _add_environment_args(run_fuzzer_parser) + _add_external_project_args(run_fuzzer_parser) + run_fuzzer_parser.add_argument( + '--corpus-dir', help='directory to store corpus for the fuzz target') + run_fuzzer_parser.add_argument('project', + help='name of the project or path (external)') + run_fuzzer_parser.add_argument('fuzzer_name', help='name of the fuzzer') + run_fuzzer_parser.add_argument('fuzzer_args', + help='arguments to pass to the fuzzer', + nargs='*') + + fuzzbench_run_fuzzer_parser = subparsers.add_parser('fuzzbench_run_fuzzer') + _add_architecture_args(fuzzbench_run_fuzzer_parser) + fuzzbench_run_fuzzer_parser.add_argument('--engine') + _add_sanitizer_args(fuzzbench_run_fuzzer_parser) + _add_environment_args(fuzzbench_run_fuzzer_parser) + _add_external_project_args(fuzzbench_run_fuzzer_parser) + fuzzbench_run_fuzzer_parser.add_argument( + '--corpus-dir', help='directory to store corpus for the fuzz target') + fuzzbench_run_fuzzer_parser.add_argument( + 'project', help='name of the project or path (external)') + fuzzbench_run_fuzzer_parser.add_argument('fuzzer_name', + help='name of the fuzzer') + fuzzbench_run_fuzzer_parser.add_argument( + 'fuzzer_args', help='arguments to pass to the fuzzer', nargs='*') + + fuzzbench_measure_parser = subparsers.add_parser('fuzzbench_measure') + fuzzbench_measure_parser.add_argument( + 'project', help='name of the project or path (external)') + fuzzbench_measure_parser.add_argument('engine_name', + help='name of the fuzzer') + fuzzbench_measure_parser.add_argument('fuzz_target_name', + help='name of the fuzzer') + + coverage_parser = subparsers.add_parser( + 'coverage', help='Generate code coverage report for the project.') + coverage_parser.add_argument('--no-corpus-download', + action='store_true', + help='do not download corpus backup from ' + 'OSS-Fuzz; use corpus located in ' + 'build/corpus///') + coverage_parser.add_argument('--no-serve', + action='store_true', + help='do not serve a local HTTP server.') + coverage_parser.add_argument('--port', + default='8008', + help='specify port for' + ' a local HTTP server rendering coverage report') + coverage_parser.add_argument('--fuzz-target', + help='specify name of a fuzz ' + 'target to be run for generating coverage ' + 'report') + coverage_parser.add_argument('--corpus-dir', + help='specify location of corpus' + ' to be used (requires --fuzz-target argument)') + coverage_parser.add_argument('--public', + action='store_true', + help='if set, will download public ' + 'corpus using wget') + coverage_parser.add_argument('project', + help='name of the project or path (external)') + coverage_parser.add_argument('extra_args', + help='additional arguments to ' + 'pass to llvm-cov utility.', + nargs='*') + _add_external_project_args(coverage_parser) + _add_architecture_args(coverage_parser) + + introspector_parser = subparsers.add_parser( + 'introspector', + help='Run a complete end-to-end run of ' + 'fuzz introspector. This involves (1) ' + 'building the fuzzers with ASAN; (2) ' + 'running all fuzzers; (3) building ' + 'fuzzers with coverge; (4) extracting ' + 'coverage; (5) building fuzzers using ' + 'introspector') + introspector_parser.add_argument('project', help='name of the project') + introspector_parser.add_argument('--seconds', + help='number of seconds to run fuzzers', + default=10) + introspector_parser.add_argument('source_path', + help='path of local source', + nargs='?') + introspector_parser.add_argument( + '--public-corpora', + help='if specified, will use public corpora for code coverage', + default=False, + action='store_true') + introspector_parser.add_argument( + '--private-corpora', + help='if specified, will use private corpora', + default=False, + action='store_true') + + download_corpora_parser = subparsers.add_parser( + 'download_corpora', help='Download all corpora for a project.') + download_corpora_parser.add_argument('--fuzz-target', + nargs='+', + help='specify name of a fuzz target') + download_corpora_parser.add_argument('--public', + action='store_true', + help='if set, will download public ' + 'corpus using wget') + download_corpora_parser.add_argument( + 'project', help='name of the project or path (external)') + + reproduce_parser = subparsers.add_parser('reproduce', + help='Reproduce a crash.') + reproduce_parser.add_argument('--valgrind', + action='store_true', + help='run with valgrind') + reproduce_parser.add_argument('--propagate_exit_codes', + action='store_true', + default=False, + help='return underlying exit codes instead of True/False.') + reproduce_parser.add_argument('--not_privileged', + dest='privileged', + action='store_false', + default=True, + help='reproduce without running docker in privileged mode.') + reproduce_parser.add_argument('--err_result', + help='exit code override for missing harness / fuzz targets ' + '(default err_result = 1).', + type=int) + reproduce_parser.add_argument('--timeout', + help='timeout for reproduce subprocess ' + '(default: None).', + default=None, + type=int) + reproduce_parser.add_argument('project', + help='name of the project or path (external)') + reproduce_parser.add_argument('fuzzer_name', help='name of the fuzzer') + reproduce_parser.add_argument('testcase_path', help='path of local testcase') + reproduce_parser.add_argument('fuzzer_args', + help='arguments to pass to the fuzzer', + nargs='*') + _add_environment_args(reproduce_parser) + _add_external_project_args(reproduce_parser) + _add_architecture_args(reproduce_parser) + + shell_parser = subparsers.add_parser( + 'shell', help='Run /bin/bash within the builder container.') + shell_parser.add_argument('project', + help='name of the project or path (external)') + shell_parser.add_argument('source_path', + help='path of local source', + nargs='?') + shell_parser.add_argument('--docker_image_tag', + dest='docker_image_tag', + default='latest', + help='docker image build tag' + 'default: latest') + _add_architecture_args(shell_parser) + _add_engine_args(shell_parser) + _add_sanitizer_args(shell_parser) + _add_environment_args(shell_parser) + _add_external_project_args(shell_parser) + + run_clusterfuzzlite_parser = subparsers.add_parser( + 'run_clusterfuzzlite', help='Run ClusterFuzzLite on a project.') + _add_sanitizer_args(run_clusterfuzzlite_parser) + _add_environment_args(run_clusterfuzzlite_parser) + run_clusterfuzzlite_parser.add_argument('project') + run_clusterfuzzlite_parser.add_argument('--clean', + dest='clean', + action='store_true', + help='clean existing artifacts.') + run_clusterfuzzlite_parser.add_argument( + '--no-clean', + dest='clean', + action='store_false', + help='do not clean existing artifacts ' + '(default).') + run_clusterfuzzlite_parser.add_argument('--branch', + default='master', + required=True) + _add_external_project_args(run_clusterfuzzlite_parser) + run_clusterfuzzlite_parser.set_defaults(clean=False) + + subparsers.add_parser('pull_images', help='Pull base images.') + return parser + + +def is_base_image(image_name): + """Checks if the image name is a base image.""" + return os.path.exists(os.path.join('infra', 'base-images', image_name)) + + +def check_project_exists(project): + """Checks if a project exists.""" + if os.path.exists(project.path): + return True + + if project.is_external: + descriptive_project_name = project.path + else: + descriptive_project_name = project.name + + logger.error('"%s" does not exist.', descriptive_project_name) + return False + + +def _check_fuzzer_exists(project, fuzzer_name, architecture='x86_64'): + """Checks if a fuzzer exists.""" + platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64' + command = ['docker', 'run', '--rm', '--platform', platform] + command.extend(['-v', '%s:/out' % project.out]) + command.append(BASE_RUNNER_IMAGE) + + command.extend(['/bin/bash', '-c', 'test -f /out/%s' % fuzzer_name]) + + try: + subprocess.check_call(command) + except subprocess.CalledProcessError: + logger.error('%s does not seem to exist. Please run build_fuzzers first.', + fuzzer_name) + return False + + return True + + +def _normalized_name(name): + """Return normalized name with special chars like slash, colon, etc normalized + to hyphen(-). This is important as otherwise these chars break local and cloud + storage paths.""" + return SPECIAL_CHARS_REGEX.sub('-', name).strip('-') + + +def _get_absolute_path(path): + """Returns absolute path with user expansion.""" + return os.path.abspath(os.path.expanduser(path)) + + +def _get_command_string(command): + """Returns a shell escaped command string.""" + return ' '.join(shlex.quote(part) for part in command) + + +def _get_project_build_subdir(project, subdir_name): + """Creates the |subdir_name| subdirectory of the |project| subdirectory in + |BUILD_DIR| and returns its path.""" + directory = os.path.join(BUILD_DIR, subdir_name, project) + os.makedirs(directory, exist_ok=True) + + return directory + + +def _get_out_dir(project=''): + """Creates and returns path to /out directory for the given project (if + specified).""" + return _get_project_build_subdir(project, 'out') + + +def _add_architecture_args(parser, choices=None): + """Adds common architecture args.""" + if choices is None: + choices = constants.ARCHITECTURES + parser.add_argument('--architecture', + default=constants.DEFAULT_ARCHITECTURE, + choices=choices) + + +def _add_engine_args(parser, choices=None): + """Adds common engine args.""" + if choices is None: + choices = constants.ENGINES + parser.add_argument('--engine', + default=constants.DEFAULT_ENGINE, + choices=choices) + + +def _add_sanitizer_args(parser, choices=None): + """Adds common sanitizer args.""" + if choices is None: + choices = constants.SANITIZERS + parser.add_argument('--sanitizer', + default=None, + choices=choices, + help='the default is "address"') + + +def _add_environment_args(parser): + """Adds common environment args.""" + parser.add_argument('-e', + action='append', + help="set environment variable e.g. VAR=value") + + +def build_image_impl(project, cache=True, pull=False, + architecture='x86_64', + docker_image_tag='latest'): + """Builds image.""" + image_name = project.name + + if is_base_image(image_name): + image_project = 'aixcc-finals' + docker_build_dir = os.path.join(OSS_FUZZ_DIR, 'infra', 'base-images', + image_name) + dockerfile_path = os.path.join(docker_build_dir, 'Dockerfile') + image_name = 'ghcr.io/%s/%s%s' % (image_project, image_name, BASE_IMAGE_TAG) + else: + if not check_project_exists(project): + return False + dockerfile_path = project.dockerfile_path + docker_build_dir = project.path + image_project = 'aixcc-afc' + image_name = '%s/%s:%s' % (image_project, image_name, docker_image_tag) + + if pull and not pull_images(project.language): + return False + + build_args = [] + if architecture == 'aarch64': + build_args += [ + 'buildx', + 'build', + '--platform', + 'linux/arm64', + '--progress', + 'plain', + '--load', + ] + if not cache: + build_args.append('--no-cache') + + build_args += ['-t', image_name, '--file', dockerfile_path] + build_args.append(docker_build_dir) + + if architecture == 'aarch64': + command = ['docker'] + build_args + subprocess.check_call(command) + return True + return docker_build(build_args) + + +def _env_to_docker_args(env_list): + """Turns envirnoment variable list into docker arguments.""" + return sum([['-e', v] for v in env_list], []) + + +def workdir_from_lines(lines, default='/src'): + """Gets the WORKDIR from the given lines.""" + for line in reversed(lines): # reversed to get last WORKDIR. + match = re.match(WORKDIR_REGEX, line) + if match: + workdir = match.group(1) + workdir = workdir.replace('$SRC', '/src') + + if not os.path.isabs(workdir): + workdir = os.path.join('/src', workdir) + + return os.path.normpath(workdir) + + return default + + +def _workdir_from_dockerfile(project): + """Parses WORKDIR from the Dockerfile for the given project.""" + with open(project.dockerfile_path) as file_handle: + lines = file_handle.readlines() + + return workdir_from_lines(lines, default=os.path.join('/src', project.name)) + + +def prepare_aarch64_emulation(): + """Run some necessary commands to use buildx to build AArch64 targets using + QEMU emulation on an x86_64 host.""" + subprocess.check_call( + ['docker', 'buildx', 'create', '--name', ARM_BUILDER_NAME]) + subprocess.check_call(['docker', 'buildx', 'use', ARM_BUILDER_NAME]) + + +def docker_run(run_args, print_output=True, architecture='x86_64', propagate_exit_codes=False, privileged=True, timeout=None): + """Calls `docker run`.""" + platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64' + + if privileged: + command = [ + 'docker', 'run', '--privileged', '--shm-size=2g', '--platform', platform + ] + else: + command = [ + 'docker', 'run', '--shm-size=2g', '--platform', platform + ] + + if os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME'): + command.append('--name') + command.append(os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME')) + else: + command.append('--rm') + + # Support environments with a TTY. + if sys.stdin.isatty(): + command.append('-i') + + command.extend(run_args) + + logger.info('Running: %s.', _get_command_string(command)) + stdout = None + if not print_output: + stdout = open(os.devnull, 'w') + + exit_code = 0 + + try: + subprocess.check_call(command, stdout=stdout, stderr=subprocess.STDOUT, + timeout=timeout) + except subprocess.CalledProcessError as e: + print(f'subprocess command returned a non-zero exit status: {e.returncode}') + exit_code = e.returncode + except subprocess.TimeoutExpired: + print(f'subprocess command timed out: {timeout=}') + exit_code = 124 + + return exit_code if propagate_exit_codes else exit_code == 0 + + +def docker_build(build_args): + """Calls `docker build`.""" + command = ['docker', 'build'] + command.extend(build_args) + logger.info('Running: %s.', _get_command_string(command)) + + try: + subprocess.check_call(command) + except subprocess.CalledProcessError: + logger.error('Docker build failed.') + return False + + return True + + +def docker_pull(image): + """Call `docker pull`.""" + command = ['docker', 'pull', image] + logger.info('Running: %s', _get_command_string(command)) + + try: + subprocess.check_call(command) + except subprocess.CalledProcessError: + logger.error('Docker pull failed.') + return False + + return True + + +def build_image(args): + """Builds docker image.""" + if args.pull and args.no_pull: + logger.error('Incompatible arguments --pull and --no-pull.') + return False + + if args.pull: + pull = True + elif args.no_pull: + pull = False + else: + y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ') + pull = y_or_n.lower() == 'y' + + if pull: + logger.info('Pulling latest base images...') + else: + logger.info('Using cached base images...') + + # If build_image is called explicitly, don't use cache. + if build_image_impl(args.project, + cache=args.cache, + pull=pull, + architecture=args.architecture, + docker_image_tag=args.docker_image_tag): + return True + + return False + + +def build_fuzzers_impl( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches + project, + clean, + engine, + sanitizer, + architecture, + env_to_add, + source_path, + mount_path=None, + child_dir='', + build_project_image=True, + docker_image_tag='latest'): + """Builds fuzzers.""" + if build_project_image and not build_image_impl(project, + architecture=architecture, + docker_image_tag=docker_image_tag): + return False + + docker_image = f'aixcc-afc/{project.name}:{docker_image_tag}' + + project_out = os.path.join(project.out, child_dir) + if clean: + logger.info('Cleaning existing build artifacts.') + + # Clean old and possibly conflicting artifacts in project's out directory. + docker_run([ + '-v', f'{project_out}:/out', '-t', f'{docker_image}', + '/bin/bash', '-c', 'rm -rf /out/*' + ], + architecture=architecture) + + docker_run([ + '-v', + '%s:/work' % project.work, '-t', + f'{docker_image}', '/bin/bash', '-c', 'rm -rf /work/*' + ], + architecture=architecture) + + else: + logger.info('Keeping existing build artifacts as-is (if any).') + env = [ + 'FUZZING_ENGINE=' + engine, + 'SANITIZER=' + sanitizer, + 'ARCHITECTURE=' + architecture, + 'PROJECT_NAME=' + project.name, + 'HELPER=True', + ] + + _add_oss_fuzz_ci_if_needed(env) + + if project.language: + env.append('FUZZING_LANGUAGE=' + project.language) + + if env_to_add: + env += env_to_add + + command = _env_to_docker_args(env) + if source_path: + workdir = _workdir_from_dockerfile(project) + stateless_path = mount_path if mount_path else workdir + + if stateless_path == '/src': + logger.error('Cannot mount local source targeting "/src".') + return False + + command += [ + '-v', + '%s:%s:ro' % (_get_absolute_path(source_path), '/local-source-mount'), + ] + + command += [ + '-v', f'{project_out}:/out', '-v', f'{project.work}:/work', + f'{docker_image}' + ] + + if sys.stdin.isatty(): + command.insert(-1, '-t') + + if source_path: + default_cmd = 'compile' + command += [ + '/bin/bash', + '-c', + f'pushd $SRC && rm -rf {stateless_path} && cp -r /local-source-mount {stateless_path} && popd && {default_cmd}' + ] + + result = docker_run(command, architecture=architecture) + if not result: + logger.error('Building fuzzers failed.') + return False + + return True + + +def run_clusterfuzzlite(args): + """Runs ClusterFuzzLite on a local repo.""" + if not os.path.exists(CLUSTERFUZZLITE_FILESTORE_DIR): + os.mkdir(CLUSTERFUZZLITE_FILESTORE_DIR) + + try: + with tempfile.TemporaryDirectory() as workspace: + + if args.external: + project_src_path = os.path.join(workspace, args.project.name) + shutil.copytree(args.project.path, project_src_path) + + build_command = [ + '--tag', 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers', '--file', + 'infra/run_fuzzers.Dockerfile', 'infra' + ] + if not docker_build(build_command): + return False + filestore_path = os.path.abspath(CLUSTERFUZZLITE_FILESTORE_DIR) + docker_run_command = [] + if args.external: + docker_run_command += [ + '-e', + f'PROJECT_SRC_PATH={project_src_path}', + ] + else: + docker_run_command += [ + '-e', + f'OSS_FUZZ_PROJECT_NAME={args.project.name}', + ] + docker_run_command += [ + '-v', + f'{filestore_path}:{filestore_path}', + '-v', + f'{workspace}:{workspace}', + '-e', + f'FILESTORE_ROOT_DIR={filestore_path}', + '-e', + f'WORKSPACE={workspace}', + '-e', + f'REPOSITORY={args.project.name}', + '-e', + 'CFL_PLATFORM=standalone', + '--entrypoint', + '', + '-v', + '/var/run/docker.sock:/var/run/docker.sock', + CLUSTERFUZZLITE_DOCKER_IMAGE, + 'python3', + '/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py', + ] + return docker_run(docker_run_command) + + except PermissionError as error: + logger.error('PermissionError: %s.', error) + # Tempfile can't delete the workspace because of a permissions issue. This + # is because docker creates files in the workspace that are owned by root + # but this process is probably being run as another user. Use a docker image + # to delete the temp directory (workspace) so that we have permission. + docker_run([ + '-v', f'{workspace}:{workspace}', '--entrypoint', '', + CLUSTERFUZZLITE_DOCKER_IMAGE, 'rm', '-rf', + os.path.join(workspace, '*') + ]) + return False + + +def build_fuzzers(args): + """Builds fuzzers.""" + if args.engine == 'centipede' and args.sanitizer != 'none': + # Centipede always requires separate binaries for sanitizers: + # An unsanitized binary, which Centipede requires for fuzzing. + # A sanitized binary, placed in the child directory. + sanitized_binary_directories = ( + ('none', ''), + (args.sanitizer, f'__centipede_{args.sanitizer}'), + ) + else: + # Generally, a fuzzer only needs one sanitized binary in the default dir. + sanitized_binary_directories = ((args.sanitizer, ''),) + return all( + build_fuzzers_impl(args.project, + args.clean, + args.engine, + sanitizer, + args.architecture, + args.e, + args.source_path, + mount_path=args.mount_path, + child_dir=child_dir, + docker_image_tag=args.docker_image_tag) + for sanitizer, child_dir in sanitized_binary_directories) + + +def fuzzbench_build_fuzzers(args): + """Builds fuzz targets with an arbitrary fuzzer from FuzzBench.""" + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_dir = os.path.abspath(tmp_dir) + fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench') + subprocess.run([ + 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1', + fuzzbench_path + ], + check=True) + env = [ + f'FUZZBENCH_PATH={fuzzbench_path}', 'OSS_FUZZ_ON_DEMAND=1', + f'PROJECT={args.project.name}' + ] + tag = f'aixcc-afc/{args.project.name}' + subprocess.run([ + 'docker', 'tag', 'ghcr.io/aixcc-finals/base-builder-fuzzbench', + f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}' + ], + check=True) + build_image_impl(args.project) + assert docker_build([ + '--tag', tag, '--build-arg', f'parent_image={tag}', '--file', + os.path.join(fuzzbench_path, 'fuzzers', args.engine, + 'builder.Dockerfile'), + os.path.join(fuzzbench_path, 'fuzzers', args.engine) + ]) + + return build_fuzzers_impl(args.project, + False, + args.engine, + args.sanitizer, + args.architecture, + env, + source_path=fuzzbench_path, + mount_path=fuzzbench_path, + build_project_image=False) + + +def _add_oss_fuzz_ci_if_needed(env): + """Adds value of |OSS_FUZZ_CI| environment variable to |env| if it is set.""" + oss_fuzz_ci = os.getenv('OSS_FUZZ_CI') + if oss_fuzz_ci: + env.append('OSS_FUZZ_CI=' + oss_fuzz_ci) + + +def check_build(args): + """Checks that fuzzers in the container execute without errors.""" + if not check_project_exists(args.project): + return False + + if (args.fuzzer_name and not _check_fuzzer_exists( + args.project, args.fuzzer_name, args.architecture)): + return False + + env = [ + 'FUZZING_ENGINE=' + args.engine, + 'SANITIZER=' + args.sanitizer, + 'ARCHITECTURE=' + args.architecture, + 'FUZZING_LANGUAGE=' + args.project.language, + 'HELPER=True', + ] + _add_oss_fuzz_ci_if_needed(env) + if args.e: + env += args.e + + run_args = _env_to_docker_args(env) + [ + '-v', f'{args.project.out}:/out', '-t', BASE_RUNNER_IMAGE + ] + + if args.fuzzer_name: + run_args += ['test_one.py', args.fuzzer_name] + else: + run_args.append('test_all.py') + + result = docker_run(run_args, architecture=args.architecture) + if result: + logger.info('Check build passed.') + else: + logger.error('Check build failed.') + + return result + + +def _get_fuzz_targets(project): + """Returns names of fuzz targest build in the project's /out directory.""" + fuzz_targets = [] + for name in os.listdir(project.out): + if name.startswith('afl-'): + continue + if name == 'centipede': + continue + if name.startswith('jazzer_'): + continue + if name == 'llvm-symbolizer': + continue + + path = os.path.join(project.out, name) + # Python and JVM fuzz targets are only executable for the root user, so + # we can't use os.access. + if os.path.isfile(path) and (os.stat(path).st_mode & 0o111): + fuzz_targets.append(name) + + return fuzz_targets + + +def _get_latest_corpus(project, fuzz_target, base_corpus_dir): + """Downloads the latest corpus for the given fuzz target.""" + corpus_dir = os.path.join(base_corpus_dir, fuzz_target) + os.makedirs(corpus_dir, exist_ok=True) + + if not fuzz_target.startswith(project.name + '_'): + fuzz_target = '%s_%s' % (project.name, fuzz_target) + + # Normalise fuzz target name. + fuzz_target = _normalized_name(fuzz_target) + + corpus_backup_url = CORPUS_BACKUP_URL_FORMAT.format(project_name=project.name, + fuzz_target=fuzz_target) + command = ['gsutil', 'ls', corpus_backup_url] + + # Don't capture stderr. We want it to print in real time, in case gsutil is + # asking for two-factor authentication. + corpus_listing = subprocess.Popen(command, stdout=subprocess.PIPE) + output, _ = corpus_listing.communicate() + + # Some fuzz targets (e.g. new ones) may not have corpus yet, just skip those. + if corpus_listing.returncode: + logger.warning('Corpus for %s not found:\n', fuzz_target) + return + + if output: + latest_backup_url = output.splitlines()[-1] + archive_path = corpus_dir + '.zip' + command = ['gsutil', '-q', 'cp', latest_backup_url, archive_path] + subprocess.check_call(command) + + command = ['unzip', '-q', '-o', archive_path, '-d', corpus_dir] + subprocess.check_call(command) + os.remove(archive_path) + else: + # Sync the working corpus copy if a minimized backup is not available. + corpus_url = CORPUS_URL_FORMAT.format(project_name=project.name, + fuzz_target=fuzz_target) + command = ['gsutil', '-m', '-q', 'rsync', '-R', corpus_url, corpus_dir] + subprocess.check_call(command) + + +def _get_latest_public_corpus(args, fuzzer): + """Downloads the public corpus""" + target_corpus_dir = "build/corpus/%s" % args.project.name + if not os.path.isdir(target_corpus_dir): + os.makedirs(target_corpus_dir) + + target_zip = os.path.join(target_corpus_dir, fuzzer + ".zip") + + project_qualified_fuzz_target_name = fuzzer + qualified_name_prefix = args.project.name + '_' + if not fuzzer.startswith(qualified_name_prefix): + project_qualified_fuzz_target_name = qualified_name_prefix + fuzzer + + download_url = HTTPS_CORPUS_BACKUP_URL_FORMAT.format( + project_name=args.project.name, + fuzz_target=project_qualified_fuzz_target_name) + + cmd = ['wget', download_url, '-O', target_zip] + try: + with open(os.devnull, 'w') as stdout: + subprocess.check_call(cmd, stdout=stdout) + except OSError: + logger.error('Failed to download corpus') + + target_fuzzer_dir = os.path.join(target_corpus_dir, fuzzer) + if not os.path.isdir(target_fuzzer_dir): + os.mkdir(target_fuzzer_dir) + + target_corpus_dir = os.path.join(target_corpus_dir, fuzzer) + try: + with open(os.devnull, 'w') as stdout: + subprocess.check_call( + ['unzip', '-q', '-o', target_zip, '-d', target_fuzzer_dir], + stdout=stdout) + except OSError: + logger.error('Failed to unzip corpus') + + # Remove the downloaded zip + os.remove(target_zip) + return True + + +def download_corpora(args): + """Downloads most recent corpora from GCS for the given project.""" + if not check_project_exists(args.project): + return False + + if args.public: + logger.info("Downloading public corpus") + try: + with open(os.devnull, 'w') as stdout: + subprocess.check_call(['wget', '--version'], stdout=stdout) + except OSError: + logger.error('wget not found') + return False + else: + try: + with open(os.devnull, 'w') as stdout: + subprocess.check_call(['gsutil', '--version'], stdout=stdout) + except OSError: + logger.error('gsutil not found. Please install it from ' + 'https://cloud.google.com/storage/docs/gsutil_install') + return False + + if args.fuzz_target: + fuzz_targets = args.fuzz_target + else: + fuzz_targets = _get_fuzz_targets(args.project) + + if not fuzz_targets: + logger.error( + 'Fuzz targets not found. Please build project first ' + '(python3 infra/helper.py build_fuzzers %s) so that download_corpora ' + 'can automatically identify targets.', args.project.name) + return False + + corpus_dir = args.project.corpus + + def _download_for_single_target(fuzz_target): + try: + if args.public: + _get_latest_public_corpus(args, fuzz_target) + else: + _get_latest_corpus(args.project, fuzz_target, corpus_dir) + return True + except Exception as error: # pylint:disable=broad-except + logger.error('Corpus download for %s failed: %s.', fuzz_target, + str(error)) + return False + + logger.info('Downloading corpora for %s project to %s.', args.project.name, + corpus_dir) + thread_pool = ThreadPool() + return all(thread_pool.map(_download_for_single_target, fuzz_targets)) + + +def coverage(args): # pylint: disable=too-many-branches + """Generates code coverage using clang source based code coverage.""" + if args.corpus_dir and not args.fuzz_target: + logger.error( + '--corpus-dir requires specifying a particular fuzz target using ' + '--fuzz-target') + return False + + if not check_project_exists(args.project): + return False + + if args.project.language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT: + logger.error( + 'Project is written in %s, coverage for it is not supported yet.', + args.project.language) + return False + + if (not args.no_corpus_download and not args.corpus_dir and + not args.project.is_external): + if not download_corpora(args): + return False + + extra_cov_args = ( + f'{args.project.coverage_extra_args.strip()} {" ".join(args.extra_args)}') + env = [ + 'FUZZING_ENGINE=libfuzzer', + 'HELPER=True', + 'FUZZING_LANGUAGE=%s' % args.project.language, + 'PROJECT=%s' % args.project.name, + 'SANITIZER=coverage', + 'COVERAGE_EXTRA_ARGS=%s' % extra_cov_args, + 'ARCHITECTURE=' + args.architecture, + ] + + if not args.no_serve: + env.append(f'HTTP_PORT={args.port}') + + run_args = _env_to_docker_args(env) + + if args.port: + run_args.extend([ + '-p', + '%s:%s' % (args.port, args.port), + ]) + + if args.corpus_dir: + if not os.path.exists(args.corpus_dir): + logger.error('The path provided in --corpus-dir argument does not ' + 'exist.') + return False + corpus_dir = os.path.realpath(args.corpus_dir) + run_args.extend(['-v', '%s:/corpus/%s' % (corpus_dir, args.fuzz_target)]) + else: + run_args.extend(['-v', '%s:/corpus' % args.project.corpus]) + + run_args.extend([ + '-v', + '%s:/out' % args.project.out, + '-t', + BASE_RUNNER_IMAGE, + ]) + + run_args.append('coverage') + if args.fuzz_target: + run_args.append(args.fuzz_target) + + result = docker_run(run_args, architecture=args.architecture) + if result: + logger.info('Successfully generated clang code coverage report.') + else: + logger.error('Failed to generate clang code coverage report.') + + return result + + +def _introspector_prepare_corpus(args): + """Helper function for introspector runs to generate corpora.""" + parser = get_parser() + # Generate corpus, either by downloading or running fuzzers. + if args.private_corpora or args.public_corpora: + corpora_command = ['download_corpora'] + if args.public_corpora: + corpora_command.append('--public') + corpora_command.append(args.project.name) + if not download_corpora(parse_args(parser, corpora_command)): + logger.error('Failed to download corpora') + return False + else: + fuzzer_targets = _get_fuzz_targets(args.project) + for fuzzer_name in fuzzer_targets: + # Make a corpus directory. + fuzzer_corpus_dir = args.project.corpus + f'/{fuzzer_name}' + if not os.path.isdir(fuzzer_corpus_dir): + os.makedirs(fuzzer_corpus_dir) + run_fuzzer_command = [ + 'run_fuzzer', '--sanitizer', 'address', '--corpus-dir', + fuzzer_corpus_dir, args.project.name, fuzzer_name + ] + + parsed_args = parse_args(parser, run_fuzzer_command) + parsed_args.fuzzer_args = [ + f'-max_total_time={args.seconds}', '-detect_leaks=0' + ] + # Continue even if run command fails, because we do not have 100% + # accuracy in fuzz target detection, i.e. we might try to run something + # that is not a target. + run_fuzzer(parsed_args) + return True + + +def introspector(args): + """Runs a complete end-to-end run of introspector.""" + parser = get_parser() + + args_to_append = [] + if args.source_path: + args_to_append.append(_get_absolute_path(args.source_path)) + + # Build fuzzers with ASAN. + build_fuzzers_command = [ + 'build_fuzzers', '--sanitizer=address', args.project.name + ] + args_to_append + if not build_fuzzers(parse_args(parser, build_fuzzers_command)): + logger.error('Failed to build project with ASAN') + return False + + if not _introspector_prepare_corpus(args): + return False + + # Build code coverage. + build_fuzzers_command = [ + 'build_fuzzers', '--sanitizer=coverage', args.project.name + ] + args_to_append + if not build_fuzzers(parse_args(parser, build_fuzzers_command)): + logger.error('Failed to build project with coverage instrumentation') + return False + + # Collect coverage. + coverage_command = [ + 'coverage', '--no-corpus-download', '--port', '', args.project.name + ] + if not coverage(parse_args(parser, coverage_command)): + logger.error('Failed to extract coverage') + return False + + # Build introspector. + build_fuzzers_command = [ + 'build_fuzzers', '--sanitizer=introspector', args.project.name + ] + args_to_append + if not build_fuzzers(parse_args(parser, build_fuzzers_command)): + logger.error('Failed to build project with introspector') + return False + + introspector_dst = os.path.join(args.project.out, + "introspector-report/inspector") + shutil.rmtree(introspector_dst, ignore_errors=True) + shutil.copytree(os.path.join(args.project.out, "inspector"), introspector_dst) + + # Copy the coverage reports into the introspector report. + dst_cov_report = os.path.join(introspector_dst, "covreport") + shutil.copytree(os.path.join(args.project.out, "report"), dst_cov_report) + + # Copy per-target coverage reports + src_target_cov_report = os.path.join(args.project.out, "report_target") + for target_cov_dir in os.listdir(src_target_cov_report): + dst_target_cov_report = os.path.join(dst_cov_report, target_cov_dir) + shutil.copytree(os.path.join(src_target_cov_report, target_cov_dir), + dst_target_cov_report) + + logger.info('Introspector run complete. Report in %s', introspector_dst) + logger.info( + 'To browse the report, run: `python3 -m http.server 8008 --directory %s`' + 'and navigate to localhost:8008/fuzz_report.html in your browser', + introspector_dst) + return True + + +def run_fuzzer(args): + """Runs a fuzzer in the container.""" + if not check_project_exists(args.project): + return False + + if not _check_fuzzer_exists(args.project, args.fuzzer_name, + args.architecture): + return False + + env = [ + 'FUZZING_ENGINE=' + args.engine, + 'SANITIZER=' + args.sanitizer, + 'RUN_FUZZER_MODE=interactive', + 'HELPER=True', + ] + + if args.e: + env += args.e + + run_args = _env_to_docker_args(env) + + if args.corpus_dir: + if not os.path.exists(args.corpus_dir): + logger.error('The path provided in --corpus-dir argument does not exist') + return False + corpus_dir = os.path.realpath(args.corpus_dir) + run_args.extend([ + '-v', + '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir, + fuzzer=args.fuzzer_name) + ]) + + run_args.extend([ + '-v', + '%s:/out' % args.project.out, + '-t', + BASE_RUNNER_IMAGE, + 'run_fuzzer', + args.fuzzer_name, + ] + args.fuzzer_args) + + return docker_run(run_args, architecture=args.architecture) + + +def fuzzbench_run_fuzzer(args): + """Runs a fuzz target built by fuzzbench in the container.""" + if not check_project_exists(args.project): + return False + + env = [ + 'FUZZING_ENGINE=' + args.engine, + 'SANITIZER=' + args.sanitizer, + 'RUN_FUZZER_MODE=interactive', + 'HELPER=True', + f'FUZZ_TARGET={args.fuzzer_name}', + f'BENCHMARK={args.project.name}', + 'TRIAL_ID=1', + 'EXPERIMENT_TYPE=bug', + ] + + if args.e: + env += args.e + + run_args = _env_to_docker_args(env) + + if args.corpus_dir: + if not os.path.exists(args.corpus_dir): + logger.error('The path provided in --corpus-dir argument does not exist') + return False + corpus_dir = os.path.realpath(args.corpus_dir) + run_args.extend([ + '-v', + '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir, + fuzzer=args.fuzzer_name) + ]) + + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_dir = os.path.abspath(tmp_dir) + fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench') + subprocess.run([ + 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1', + fuzzbench_path + ], + check=True) + run_args.extend([ + '-v', + f'{args.project.out}:/out', + '-v', + f'{fuzzbench_path}:{fuzzbench_path}', + '-e', + f'FUZZBENCH_PATH={fuzzbench_path}', + f'aixcc-afc/{args.project.name}', + 'fuzzbench_run_fuzzer', + args.fuzzer_name, + ] + args.fuzzer_args) + + return docker_run(run_args, architecture=args.architecture) + + +def fuzzbench_measure(args): + """Measure results from fuzzing with fuzzbench.""" + if not check_project_exists(args.project): + return False + + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_dir = os.path.abspath(tmp_dir) + fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench') + subprocess.run([ + 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1', + fuzzbench_path + ], + check=True) + run_args = [ + '-v', f'{args.project.out}:/out', '-v', + f'{fuzzbench_path}:{fuzzbench_path}', '-e', + f'FUZZBENCH_PATH={fuzzbench_path}', '-e', 'EXPERIMENT_TYPE=bug', '-e', + f'FUZZ_TARGET={args.fuzz_target_name}', '-e', + f'FUZZER={args.engine_name}', '-e', f'BENCHMARK={args.project.name}', + f'aixcc-afc/{args.project.name}', 'fuzzbench_measure' + ] + + return docker_run(run_args, 'x86_64') + + +def reproduce(args): + """Reproduces a specific test case from a specific project.""" + return reproduce_impl(args.project, args.fuzzer_name, args.valgrind, args.e, + args.fuzzer_args, args.testcase_path, args.architecture, + args.propagate_exit_codes, args.err_result, + privileged=args.privileged, timeout=args.timeout) + + +def reproduce_impl( # pylint: disable=too-many-arguments + project, + fuzzer_name, + valgrind, + env_to_add, + fuzzer_args, + testcase_path, + architecture='x86_64', + propagate_exit_codes=False, + err_result=1, + run_function=docker_run, + privileged=True, + timeout=None): + """Reproduces a testcase in the container.""" + + if not check_project_exists(project): + return err_result if propagate_exit_codes else False + + if not _check_fuzzer_exists(project, fuzzer_name, architecture): + return err_result if propagate_exit_codes else False + + debugger = '' + env = ['HELPER=True', 'ARCHITECTURE=' + architecture] + image_name = 'base-runner' + + if valgrind: + debugger = 'valgrind --tool=memcheck --track-origins=yes --leak-check=full' + + if debugger: + image_name = 'base-runner-debug' + env += ['DEBUGGER=' + debugger] + + if env_to_add: + env += env_to_add + + run_args = _env_to_docker_args(env) + [ + '-v', + '%s:/out' % project.out, + '-v', + '%s:/testcase' % _get_absolute_path(testcase_path), + '-t', + 'ghcr.io/aixcc-finals/%s%s' % (image_name, BASE_IMAGE_TAG), + 'reproduce', + fuzzer_name, + '-runs=100', + ] + fuzzer_args + + return run_function(run_args, architecture=architecture, propagate_exit_codes=propagate_exit_codes, privileged=privileged, timeout=timeout) + + +def _validate_project_name(project_name): + """Validates |project_name| is a valid OSS-Fuzz project name.""" + if len(project_name) > MAX_PROJECT_NAME_LENGTH: + logger.error( + 'Project name needs to be less than or equal to %d characters.', + MAX_PROJECT_NAME_LENGTH) + return False + + if not VALID_PROJECT_NAME_REGEX.match(project_name): + logger.info('Invalid project name: %s.', project_name) + return False + + return True + + +def _validate_language(language): + if not LANGUAGE_REGEX.match(language): + logger.error('Invalid project language %s.', language) + return False + + return True + + +def _create_build_integration_directory(directory): + """Returns True on successful creation of a build integration directory. + Suitable for OSS-Fuzz and external projects.""" + try: + os.makedirs(directory) + except OSError as error: + if error.errno != errno.EEXIST: + raise + logger.error('%s already exists.', directory) + return False + return True + + +def _template_project_file(filename, template, template_args, directory): + """Templates |template| using |template_args| and writes the result to + |directory|/|filename|. Sets the file to executable if |filename| is + build.sh.""" + file_path = os.path.join(directory, filename) + with open(file_path, 'w') as file_handle: + file_handle.write(template % template_args) + + if filename == 'build.sh': + os.chmod(file_path, 0o755) + + +def generate(args): + """Generates empty project files.""" + return _generate_impl(args.project, args.language) + + +def _get_current_datetime(): + """Returns this year. Needed for mocking.""" + return datetime.datetime.now() + + +def _base_builder_from_language(language): + """Returns the base builder for the specified language.""" + return LANGUAGE_TO_BASE_BUILDER_IMAGE[language] + + +def _generate_impl(project, language): + """Implementation of generate(). Useful for testing.""" + if project.is_external: + # External project. + project_templates = templates.EXTERNAL_TEMPLATES + else: + # Internal project. + if not _validate_project_name(project.name): + return False + project_templates = templates.TEMPLATES + + if not _validate_language(language): + return False + + directory = project.build_integration_path + if not _create_build_integration_directory(directory): + return False + + logger.info('Writing new files to: %s.', directory) + + template_args = { + 'project_name': project.name, + 'base_builder': _base_builder_from_language(language), + 'language': language, + 'year': _get_current_datetime().year + } + for filename, template in project_templates.items(): + _template_project_file(filename, template, template_args, directory) + return True + + +def shell(args): + """Runs a shell within a docker image.""" + if not build_image_impl(args.project): + return False + + env = [ + 'FUZZING_ENGINE=' + args.engine, + 'SANITIZER=' + args.sanitizer, + 'ARCHITECTURE=' + args.architecture, + 'HELPER=True', + ] + + if args.project.name != 'base-runner-debug': + env.append('FUZZING_LANGUAGE=' + args.project.language) + + if args.e: + env += args.e + + if is_base_image(args.project.name): + image_project = 'aixcc-finals' + project_full = 'ghcr.io/%s/%s%s' % (image_project, args.project.name, BASE_IMAGE_TAG) + out_dir = _get_out_dir() + else: + image_project = 'aixcc-afc' + project_full = '%s/%s:%s' % (image_project, args.project.name, args.docker_image_tag) + out_dir = args.project.out + + run_args = _env_to_docker_args(env) + if args.source_path: + workdir = _workdir_from_dockerfile(args.project) + run_args.extend([ + '-v', + '%s:%s' % (_get_absolute_path(args.source_path), workdir), + ]) + + + run_args.extend([ + '-v', + '%s:/out' % out_dir, '-v', + '%s:/work' % args.project.work, '-t', + '%s' % (project_full), '/bin/bash' + ]) + + docker_run(run_args, architecture=args.architecture) + return True + + +def pull_images(language=None): + """Pulls base images used to build projects in language lang (or all if lang + is None).""" + for base_image_lang, base_images in BASE_IMAGES.items(): + if (language is None or base_image_lang == 'generic' or + base_image_lang == language): + for base_image in base_images: + if not docker_pull(base_image): + return False + + return True + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/helper_test.py b/local-test-curl-delta-01/fuzz-tooling/infra/helper_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3172103998f11ba3113ba25ff4faf9b3775539 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/helper_test.py @@ -0,0 +1,239 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Tests for helper.py""" + +import datetime +import os +import tempfile +import unittest +from unittest import mock + +from pyfakefs import fake_filesystem_unittest + +import constants +import helper +import templates + +# pylint: disable=no-self-use,protected-access + + +class ShellTest(unittest.TestCase): + """Tests 'shell' command.""" + + @mock.patch('helper.docker_run') + @mock.patch('helper.build_image_impl') + def test_base_runner_debug(self, _, __): + """Tests that shell base-runner-debug works as intended.""" + image_name = 'base-runner-debug' + unparsed_args = ['shell', image_name] + parser = helper.get_parser() + args = helper.parse_args(parser, unparsed_args) + args.sanitizer = 'address' + result = helper.shell(args) + self.assertTrue(result) + + +class BuildImageImplTest(unittest.TestCase): + """Tests for build_image_impl.""" + + @mock.patch('helper.docker_build') + def test_no_cache(self, mock_docker_build): + """Tests that cache=False is handled properly.""" + image_name = 'base-image' + helper.build_image_impl(helper.Project(image_name), cache=False) + self.assertIn('--no-cache', mock_docker_build.call_args_list[0][0][0]) + + @mock.patch('helper.docker_build') + @mock.patch('helper.pull_images') + def test_pull(self, mock_pull_images, _): + """Tests that pull=True is handled properly.""" + image_name = 'base-image' + project = helper.Project(image_name, is_external=True) + self.assertTrue(helper.build_image_impl(project, pull=True)) + mock_pull_images.assert_called_with('c++') + + @mock.patch('helper.docker_build') + def test_base_image(self, mock_docker_build): + """Tests that build_image_impl works as intended with a base-image.""" + image_name = 'base-image' + self.assertTrue(helper.build_image_impl(helper.Project(image_name))) + build_dir = os.path.join(helper.OSS_FUZZ_DIR, + 'infra/base-images/base-image') + mock_docker_build.assert_called_with([ + '-t', 'ghcr.io/aixcc-finals/base-image', '--file', + os.path.join(build_dir, 'Dockerfile'), build_dir + ]) + + @mock.patch('helper.docker_build') + def test_oss_fuzz_project(self, mock_docker_build): + """Tests that build_image_impl works as intended with an OSS-Fuzz + project.""" + project_name = 'example' + self.assertTrue(helper.build_image_impl(helper.Project(project_name))) + build_dir = os.path.join(helper.OSS_FUZZ_DIR, 'projects', project_name) + mock_docker_build.assert_called_with([ + '-t', 'gcr.io/oss-fuzz/example', '--file', + os.path.join(build_dir, 'Dockerfile'), build_dir + ]) + + @mock.patch('helper.docker_build') + def test_external_project(self, mock_docker_build): + """Tests that build_image_impl works as intended with a non-OSS-Fuzz + project.""" + with tempfile.TemporaryDirectory() as temp_dir: + project_src_path = os.path.join(temp_dir, 'example') + os.mkdir(project_src_path) + build_integration_path = 'build-integration' + project = helper.Project(project_src_path, + is_external=True, + build_integration_path=build_integration_path) + self.assertTrue(helper.build_image_impl(project)) + mock_docker_build.assert_called_with([ + '-t', 'gcr.io/oss-fuzz/example', '--file', + os.path.join(project_src_path, build_integration_path, 'Dockerfile'), + project_src_path + ]) + + +class GenerateImplTest(fake_filesystem_unittest.TestCase): + """Tests for _generate_impl.""" + PROJECT_NAME = 'newfakeproject' + PROJECT_LANGUAGE = 'python' + + def setUp(self): + self.maxDiff = None # pylint: disable=invalid-name + self.setUpPyfakefs() + self.fs.add_real_directory(helper.OSS_FUZZ_DIR) + + def _verify_templated_files(self, template_dict, directory, language): + template_args = { + 'project_name': self.PROJECT_NAME, + 'year': 2021, + 'base_builder': helper._base_builder_from_language(language), + 'language': language, + } + for filename, template in template_dict.items(): + file_path = os.path.join(directory, filename) + with open(file_path, 'r') as file_handle: + contents = file_handle.read() + self.assertEqual(contents, template % template_args) + + @mock.patch('helper._get_current_datetime', + return_value=datetime.datetime(year=2021, month=1, day=1)) + def test_generate_oss_fuzz_project(self, _): + """Tests that the correct files are generated for an OSS-Fuzz project.""" + helper._generate_impl(helper.Project(self.PROJECT_NAME), + self.PROJECT_LANGUAGE) + self._verify_templated_files( + templates.TEMPLATES, + os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.PROJECT_NAME), + self.PROJECT_LANGUAGE) + + def test_generate_external_project(self): + """Tests that the correct files are generated for a non-OSS-Fuzz project.""" + build_integration_path = '/newfakeproject/build-integration' + helper._generate_impl( + helper.Project('/newfakeproject/', + is_external=True, + build_integration_path=build_integration_path), + self.PROJECT_LANGUAGE) + self._verify_templated_files(templates.EXTERNAL_TEMPLATES, + build_integration_path, self.PROJECT_LANGUAGE) + + @mock.patch('helper._get_current_datetime', + return_value=datetime.datetime(year=2021, month=1, day=1)) + def test_generate_swift_project(self, _): + """Tests that the swift project uses the correct base image.""" + helper._generate_impl(helper.Project(self.PROJECT_NAME), 'swift') + self._verify_templated_files( + templates.TEMPLATES, + os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.PROJECT_NAME), + 'swift') + + +class ProjectTest(fake_filesystem_unittest.TestCase): + """Tests for Project class.""" + + def setUp(self): + self.project_name = 'project' + self.internal_project = helper.Project(self.project_name) + self.external_project_path = os.path.join('/path', 'to', self.project_name) + self.external_project = helper.Project(self.external_project_path, + is_external=True) + self.setUpPyfakefs() + + def test_init_external_project(self): + """Tests __init__ method for external projects.""" + self.assertEqual(self.external_project.name, self.project_name) + self.assertEqual(self.external_project.path, self.external_project_path) + self.assertEqual( + self.external_project.build_integration_path, + os.path.join(self.external_project_path, + constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH)) + + def test_init_internal_project(self): + """Tests __init__ method for internal projects.""" + self.assertEqual(self.internal_project.name, self.project_name) + path = os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.project_name) + self.assertEqual(self.internal_project.path, path) + self.assertEqual(self.internal_project.build_integration_path, path) + + def test_dockerfile_path_internal_project(self): + """Tests that dockerfile_path works as intended.""" + self.assertEqual( + self.internal_project.dockerfile_path, + os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.project_name, + 'Dockerfile')) + + def test_dockerfile_path_external_project(self): + """Tests that dockerfile_path works as intended.""" + self.assertEqual( + self.external_project.dockerfile_path, + os.path.join(self.external_project_path, + constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH, + 'Dockerfile')) + + def test_out(self): + """Tests that out works as intended.""" + out_dir = self.internal_project.out + self.assertEqual( + out_dir, + os.path.join(helper.OSS_FUZZ_DIR, 'build', 'out', self.project_name)) + self.assertTrue(os.path.exists(out_dir)) + + def test_work(self): + """Tests that work works as intended.""" + work_dir = self.internal_project.work + self.assertEqual( + work_dir, + os.path.join(helper.OSS_FUZZ_DIR, 'build', 'work', self.project_name)) + self.assertTrue(os.path.exists(work_dir)) + + def test_corpus(self): + """Tests that corpus works as intended.""" + corpus_dir = self.internal_project.corpus + self.assertEqual( + corpus_dir, + os.path.join(helper.OSS_FUZZ_DIR, 'build', 'corpus', self.project_name)) + self.assertTrue(os.path.exists(corpus_dir)) + + def test_language_internal_project(self): + """Tests that language works as intended for an internal project.""" + project_yaml_path = os.path.join(self.internal_project.path, 'project.yaml') + self.fs.create_file(project_yaml_path, contents='language: python') + self.assertEqual(self.internal_project.language, 'python') + + def test_language_external_project(self): + """Tests that language works as intended for an external project.""" + self.assertEqual(self.external_project.language, 'c++') diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/manifest.py b/local-test-curl-delta-01/fuzz-tooling/infra/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..acb3b8d995aeeb4617b36c9862a7bcdb85992081 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/manifest.py @@ -0,0 +1,61 @@ +#! /usr/bin/env python3 +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Script for pushing manifest files to docker that point to AMD64 and ARM +images.""" +import logging +import subprocess +import sys + + +def push_manifest(image): + """Pushes a manifest file in place of |image| for ARM and AMD64 versions of + that image.""" + subprocess.run(['docker', 'pull', image], check=True) + amd64_image = f'{image}:manifest-amd64' + subprocess.run(['docker', 'tag', image, amd64_image], check=True) + subprocess.run(['docker', 'push', amd64_image], check=True) + + arm_version = f'{image}-testing-arm' + subprocess.run(['docker', 'pull', arm_version], check=True) + arm64_image = f'{image}:manifest-arm64v8' + subprocess.run(['docker', 'tag', arm_version, arm64_image], check=True) + + subprocess.run([ + 'docker', 'manifest', 'create', image, '--amend', arm64_image, '--amend', + amd64_image + ], + check=True) + subprocess.run(['docker', 'manifest', 'push', image], check=True) + return True + + +def main(): + """Sets up manifests for base-builder and base-runner so they can be used for + ARM builds.""" + logging.info('Doing simple gcloud command to ensure 2FA passes. ' + 'Otherwise docker push fails.') + subprocess.run(['gcloud', 'projects', 'list', '--limit=1'], check=True) + + images = [ + 'ghcr.io/aixcc-finals/base-builder', 'ghcr.io/aixcc-finals/base-runner' + ] + results = [push_manifest(image) for image in images] + return 0 if all(results) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/pr_helper.py b/local-test-curl-delta-01/fuzz-tooling/infra/pr_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..4d93b24a5d2f05d85570ec2d10fad5480596c2e2 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/pr_helper.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python +# Copyright 2023 Google LLC +# +# 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. +# +################################################################################ +"""Adds comments for PR to provide more information for approvers.""" +import base64 +import json +import os +import subprocess + +import requests +import yaml + +OWNER = 'google' +REPO = 'oss-fuzz' +GITHUB_URL = 'https://github.com/' +GITHUB_NONREF_URL = f'https://www.github.com/{OWNER}/{REPO}' # Github URL that doesn't send emails on linked issues. +API_URL = 'https://api.github.com' +BASE_URL = f'{API_URL}/repos/{OWNER}/{REPO}' +BRANCH = 'master' +CRITICALITY_SCORE_PATH = '/home/runner/go/bin/criticality_score' +COMMITS_LIMIT = 50 # Only process the most recent 50 commits. + + +def get_criticality_score(repo_url): + """Gets the criticality score of the project.""" + # Criticality score does not support repo url ends with '.git' + if repo_url.endswith('.git'): + repo_url = repo_url[:-4] + report = subprocess.run([ + CRITICALITY_SCORE_PATH, '--format', 'json', + '-gcp-project-id=clusterfuzz-external', '-depsdev-disable', repo_url + ], + capture_output=True, + text=True) + + try: + report_dict = json.loads(report.stdout) + except: + print(f'Criticality score failed with stdout: {report.stdout}') + print(f'Criticality score failed with stderr: {report.stderr}') + return 'N/A' + return report_dict.get('default_score', 'N/A') + + +def is_known_contributor(content, email): + """Checks if the author is in the contact list.""" + return (email == content.get('primary_contact') or + email in content.get('vendor_ccs', []) or + email in content.get('auto_ccs', [])) + + +def save_env(message, is_ready_for_merge, is_internal=False): + """Saves the outputs as environment variables.""" + with open(os.environ['GITHUB_ENV'], 'a') as github_env: + github_env.write(f'MESSAGE={message}\n') + github_env.write(f'IS_READY_FOR_MERGE={is_ready_for_merge}\n') + github_env.write(f'IS_INTERNAL={is_internal}') + + +def main(): + """Verifies if a PR is ready to merge.""" + github = GithubHandler() + + # Bypasses PRs of the internal members. + if github.is_author_internal_member(): + save_env(None, None, True) + return + + message = '' + is_ready_for_merge = True + pr_author = github.get_pr_author() + # Gets all modified projects path. + projects_path = github.get_projects_path() + verified, email = github.get_author_email() + + for project_path in projects_path: + project_url = f'{GITHUB_URL}/{OWNER}/{REPO}/tree/{BRANCH}/{project_path}' + content_dict = github.get_project_yaml(project_path) + + # Gets information for the new integrating project. + if not content_dict: + is_ready_for_merge = False + new_project = github.get_integrated_project_info() + repo_url = new_project.get('main_repo') + if repo_url is None: + message += (f'{pr_author} is integrating a new project, ' + 'but the `main_repo` is missing. ' + 'The criticality score cannot be computed.
') + else: + message += (f'{pr_author} is integrating a new project:
' + f'- Main repo: {repo_url}
- Criticality score: ' + f'{get_criticality_score(repo_url)}
') + continue + + # Checks if the author is in the contact list. + if email: + if is_known_contributor(content_dict, email): + # Checks if the email is verified. + verified_marker = ' (verified)' if verified else '' + message += ( + f'{pr_author}{verified_marker} is either the primary contact or ' + f'is in the CCs list of [{project_path}]({project_url}).
') + if verified: + continue + + # Checks the previous commits. + commit_sha = github.has_author_modified_project(project_path) + if commit_sha is None: + history_message = '' + contributors = github.get_past_contributors(project_path) + if contributors: + history_message = 'The past contributors are: ' + history_message += ', '.join(contributors) + message += ( + f'{pr_author} is a new contributor to ' + f'[{project_path}]({project_url}). The PR must be approved by known ' + f'contributors before it can be merged. {history_message}
') + is_ready_for_merge = False + continue + + # If the previous commit is not associated with a pull request. + pr_message = (f'{pr_author} has previously contributed to ' + f'[{project_path}]({project_url}). The previous commit was ' + f'{GITHUB_NONREF_URL}/commit/{commit_sha}
') + + previous_pr_number = github.get_pull_request_number(commit_sha) + if previous_pr_number is not None: + pr_message = (f'{pr_author} has previously contributed to ' + f'[{project_path}]({project_url}). ' + f'The previous PR was [#{previous_pr_number}]' + f'({GITHUB_NONREF_URL}/pull/{previous_pr_number})
') + message += pr_message + + save_env(message, is_ready_for_merge, False) + + +class GithubHandler: + """Github requests handler.""" + + def __init__(self): + self._pr_author = os.environ['PRAUTHOR'] + self._token = os.environ['GITHUBTOKEN'] + self._pr_number = os.environ['PRNUMBER'] + self._headers = { + 'Authorization': f'Bearer {self._token}', + 'X-GitHub-Api-Version': '2022-11-28' + } + self._maintainers = set() + os.environ['GITHUB_AUTH_TOKEN'] = self._token + + def get_pr_author(self): + """Gets the pr author user name.""" + return self._pr_author + + def get_projects_path(self): + """Gets the current project path.""" + response = requests.get(f'{BASE_URL}/pulls/{self._pr_number}/files', + headers=self._headers) + if not response.ok: + return [] + + projects_path = set() + for file in response.json(): + file_path = file['filename'] + dir_path = file_path.split(os.sep) + if len(dir_path) > 1 and dir_path[0] == 'projects': + projects_path.add(os.sep.join(dir_path[0:2])) + return list(projects_path) + + def get_author_email(self): + """Retrieves the author's email address for a pull request, + including non-public emails.""" + user_response = requests.get(f'{API_URL}/users/{self._pr_author}') + if user_response.ok: + email = user_response.json()['email'] + if email: + return True, email + + commits_response = requests.get( + f'{BASE_URL}/pulls/{self._pr_number}/commits', headers=self._headers) + if not commits_response.ok: + return False, None + email = commits_response.json()[0]['commit']['author']['email'] + verified = commits_response.json()[0]['commit']['verification']['verified'] + return verified, email + + def get_project_yaml(self, project_path): + """Gets the project yaml file.""" + contents_url = f'{BASE_URL}/contents/{project_path}/project.yaml' + return self.get_yaml_file_content(contents_url) + + def get_yaml_file_content(self, contents_url): + """Gets yaml file content.""" + response = requests.get(contents_url, headers=self._headers) + if not response.ok: + return {} + content = base64.b64decode(response.json()['content']).decode('UTF-8') + return yaml.safe_load(content) + + def get_integrated_project_info(self): + """Gets the new integrated project.""" + response = requests.get(f'{BASE_URL}/pulls/{self._pr_number}/files', + headers=self._headers) + + for file in response.json(): + file_path = file['filename'] + if 'project.yaml' in file_path: + return self.get_yaml_file_content(file['contents_url']) + + return {} + + def get_pull_request_number(self, commit): + """Gets the pull request number.""" + pr_response = requests.get(f'{BASE_URL}/commits/{commit}/pulls', + headers=self._headers) + if not pr_response.ok: + return None + return pr_response.json()[0]['number'] + + def get_past_contributors(self, project_path): + """Returns a list of past contributors of a certain project.""" + commits_response = requests.get(f'{BASE_URL}/commits?path={project_path}', + headers=self._headers) + + if not commits_response.ok: + return [] + commits = commits_response.json() + contributors: dict[str, bool] = {} + for i, commit in enumerate(commits): + if i >= COMMITS_LIMIT: + break + + if not commit['author'] or not commit['commit']: + continue + + login = commit['author']['login'] + verified = commit['commit']['verification']['verified'] + if login in self._maintainers: + continue + if login not in contributors: + contributors[login] = verified + if verified: + # Override previous verification bit. + contributors[login] = True + + all_contributors = [] + for login, verified in contributors.items(): + login_verify = login if verified else f'{login} (unverified)' + all_contributors.append(login_verify) + + return all_contributors + + def get_maintainers(self): + """Get a list of internal members.""" + if self._maintainers: + return self._maintainers + + response = requests.get(f'{BASE_URL}/contents/infra/MAINTAINERS.csv', + headers=self._headers) + if not response.ok: + return self._maintainers + + maintainers_file = base64.b64decode( + response.json()['content']).decode('UTF-8') + for line in maintainers_file.split(os.linesep): + self._maintainers.add(line.split(',')[2]) + return self._maintainers + + def is_author_internal_member(self): + """Returns if the author is an internal member.""" + return self._pr_author in self.get_maintainers() + + def has_author_modified_project(self, project_path): + """Checks if the author has modified this project before.""" + commits_response = requests.get( + f'{BASE_URL}/commits?path={project_path}&author={self._pr_author}', + headers=self._headers) + + if not commits_response.ok or not commits_response.json(): + return None + + commit = commits_response.json()[0] + return commit['sha'] + + +if __name__ == '__main__': + main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/presubmit.py b/local-test-curl-delta-01/fuzz-tooling/infra/presubmit.py new file mode 100644 index 0000000000000000000000000000000000000000..41633fa256a73518f09fcf8ad8f9e40c7ad845c7 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/presubmit.py @@ -0,0 +1,549 @@ +#!/usr/bin/env python3 +# Copyright 2020 Google LLC +# +# 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. +# +################################################################################ +"""Checks code for common issues before submitting.""" + +import argparse +import os +import re +import subprocess +import sys +import unittest +import yaml + +import constants + +_SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +VALID_PROJECT_REGEX_STR = '^[a-z0-9_-]+$' +VALID_PROJECT_REGEX = re.compile(VALID_PROJECT_REGEX_STR) + + +def _is_project_file(actual_path, expected_filename): + """Returns True if actual_path's name is |expected_filename| and is a file + that exists and is in in projects/.""" + if os.path.basename(actual_path) != expected_filename: + return False + + if os.path.basename(os.path.dirname( + os.path.dirname(actual_path))) != 'projects': + return False + + return os.path.exists(actual_path) + + +# TODO: Check for -fsanitize=fuzzer in files as well. + + +def _check_one_lib_fuzzing_engine(build_sh_file): + """Returns False if |build_sh_file| contains -lFuzzingEngine. + This is deprecated behavior. $LIB_FUZZING_ENGINE should be used instead + so that -fsanitize=fuzzer is used.""" + if not _is_project_file(build_sh_file, 'build.sh'): + return True + + with open(build_sh_file) as build_sh: + build_sh_lines = build_sh.readlines() + for line_num, line in enumerate(build_sh_lines): + uncommented_code = line.split('#')[0] + if '-lFuzzingEngine' in uncommented_code: + print('Error: build.sh contains deprecated "-lFuzzingEngine" on line: ' + f'{line_num}. Please use "$LIB_FUZZING_ENGINE" instead.') + return False + return True + + +def check_lib_fuzzing_engine(paths): + """Calls _check_one_lib_fuzzing_engine on each path in |paths|. Returns True + if the result of every call is True.""" + return all(_check_one_lib_fuzzing_engine(path) for path in paths) + + +class ProjectYamlChecker: + """Checks for a project.yaml file.""" + + # Sections in a project.yaml and the constant values that they are allowed + # to have. + SECTIONS_AND_CONSTANTS = { + 'sanitizers': constants.SANITIZERS, + 'architectures': constants.ARCHITECTURES, + 'fuzzing_engines': constants.ENGINES, + } + + # Note: this list must be updated when we allow new sections. + VALID_SECTION_NAMES = [ + 'architectures', + 'auto_ccs', + 'blackbox', + 'builds_per_day', + 'coverage_extra_args', + 'disabled', + 'fuzzing_engines', + 'help_url', + 'homepage', + 'language', + 'labels', # For internal use only, hard to lint as it uses fuzzer names. + 'main_repo', + 'primary_contact', + 'run_tests', + 'sanitizers', + 'selective_unpack', + 'vendor_ccs', + 'view_restrictions', + 'file_github_issue', + ] + + REQUIRED_SECTIONS = ['main_repo'] + + def __init__(self, filename): + self.filename = filename + with open(filename) as file_handle: + self.data = yaml.safe_load(file_handle) + + self.success = True + + def do_checks(self): + """Does all project.yaml checks. Returns True if they pass.""" + if self.is_disabled(): + return True + + checks = [ + self.check_project_yaml_constants, + self.check_required_sections, + self.check_valid_section_names, + self.check_valid_emails, + self.check_valid_language, + self.check_valid_project_name, + ] + for check_function in checks: + check_function() + return self.success + + def is_disabled(self): + """Returns True if this project is disabled.""" + return self.data.get('disabled', False) + + def error(self, message): + """Prints an error message and sets self.success to False.""" + self.success = False + print(f'Error in {self.filename}: {message}') + + def check_valid_project_name(self): + """Checks that the project has a valid name.""" + banned_names = ['google', 'g00gle'] + project_name = os.path.basename(os.path.dirname(self.filename)) + for banned_name in banned_names: + if banned_name in project_name: + self.error('Projects can\'t have \'google\' in the name.') + if not VALID_PROJECT_REGEX.match(project_name): + self.error(f'Projects must conform to regex {VALID_PROJECT_REGEX_STR}') + + def check_project_yaml_constants(self): + """Returns True if certain sections only have certain constant values.""" + for section, allowed_constants in self.SECTIONS_AND_CONSTANTS.items(): + if section not in self.data: + continue + actual_constants = self.data[section] + allowed_constants_str = ', '.join(allowed_constants) + for constant in actual_constants: + if isinstance(constant, str): + if constant not in allowed_constants: + self.error(f'{constant} (in {section} section) is not a valid ' + f'constant ({allowed_constants_str}).') + elif isinstance(constant, dict): + # The only alternative value allowed is the experimental flag, i.e. + # `constant == {'memory': {'experimental': True}}`. Do not check the + # experimental flag, but assert that the sanitizer is a valid one. + if (len(constant.keys()) > 1 or + list(constant.keys())[0] not in allowed_constants): + self.error(f'Not allowed value in the project.yaml: {constant}') + else: + self.error(f'Not allowed value in the project.yaml: {constant}') + + def check_valid_section_names(self): + """Returns True if all section names are valid.""" + for name in self.data: + if name not in self.VALID_SECTION_NAMES: + self.error( + f'{name} is not a valid section name ({self.VALID_SECTION_NAMES})') + + def check_required_sections(self): + """Returns True if all required sections are in |self.data|.""" + for section in self.REQUIRED_SECTIONS: + if section not in self.data: + self.error(f'{section} section is missing.') + + def check_valid_emails(self): + """Returns True if emails are valid looking..""" + # Get email addresses. + email_addresses = [] + primary_contact = self.data.get('primary_contact') + if primary_contact: + email_addresses.append(primary_contact) + auto_ccs = self.data.get('auto_ccs') + if auto_ccs: + email_addresses.extend(auto_ccs) + + # Check that email addresses seem normal. + for email_address in email_addresses: + if '@' not in email_address or '.' not in email_address: + self.error(f'{email_address} is an invalid email address.') + + def check_valid_language(self): + """Returns True if the language is specified and valid.""" + language = self.data.get('language') + if not language: + self.error('Missing "language" attribute in project.yaml.') + elif language not in constants.LANGUAGES: + self.error( + f'"language: {language}" is not supported ({constants.LANGUAGES}).') + + +def _check_one_project_yaml(project_yaml_filename): + """Does checks on the project.yaml file. Returns True on success.""" + if _is_project_file(project_yaml_filename, 'project.yml'): + print(project_yaml_filename, 'must be named project.yaml.') + return False + + if not _is_project_file(project_yaml_filename, 'project.yaml'): + return True + + checker = ProjectYamlChecker(project_yaml_filename) + return checker.do_checks() + + +def check_project_yaml(paths): + """Calls _check_one_project_yaml on each path in |paths|. Returns True if the + result of every call is True.""" + return all([_check_one_project_yaml(path) for path in paths]) + + +def _check_one_seed_corpus(path): + """Returns False and prints error if |path| is a seed corpus.""" + if os.path.basename(os.path.dirname(os.path.dirname(path))) != 'projects': + return True + + if os.path.splitext(path)[1] == '.zip': + print('Don\'t commit seed corpora into the ClusterFuzz repo,' + 'they bloat it forever.') + return False + + return True + + +def check_seed_corpus(paths): + """Calls _check_one_seed_corpus on each path in |paths|. Returns True if the + result of every call is True.""" + return all([_check_one_seed_corpus(path) for path in paths]) + + +def _check_one_apt_update(path): + """Checks that a Dockerfile uses apt-update before apt-install""" + if os.path.basename(os.path.dirname(os.path.dirname(path))) != 'projects': + return True + + if os.path.basename(path) != 'Dockerfile': + return True + + with open(path, 'r') as file: + dockerfile = file.read() + if 'RUN apt install' in dockerfile or 'RUN apt-get install' in dockerfile: + print('Please add an "apt-get update" before "apt-get install". ' + 'Otherwise, a cached and outdated RUN layer may lead to install ' + 'failures in file %s.' % str(path)) + return False + + return True + + +def check_apt_update(paths): + """Checks that all Dockerfile use apt-update before apt-install""" + return all([_check_one_apt_update(path) for path in paths]) + + +def do_checks(changed_files): + """Runs all presubmit checks. Returns False if any fails.""" + checks = [ + check_license, + yapf, + check_project_yaml, + check_lib_fuzzing_engine, + check_seed_corpus, + check_apt_update, + ] + # Use a list comprehension here and in other cases where we use all() so that + # we don't quit early on failure. This is more user-friendly since the more + # errors we spit out at once, the less frequently the less check-fix-check + # cycles they need to do. + return all([check(changed_files) for check in checks]) + + +_CHECK_LICENSE_FILENAMES = ['Dockerfile'] +_CHECK_LICENSE_EXTENSIONS = [ + '.bash', + '.c', + '.cc', + '.cpp', + '.css', + '.Dockerfile', + '.go', + '.h', + '.htm', + '.html', + '.java', + '.js', + '.proto', + '.py', + '.rs', + '.sh', + '.ts', +] +THIRD_PARTY_DIR_NAME = 'third_party' + +_LICENSE_STRING = 'http://www.apache.org/licenses/LICENSE-2.0' + + +def check_license(paths): + """Validates license header.""" + if not paths: + return True + + success = True + for path in paths: + path_parts = str(path).split(os.sep) + if any(path_part == THIRD_PARTY_DIR_NAME for path_part in path_parts): + continue + filename = os.path.basename(path) + extension = os.path.splitext(path)[1] + if (filename not in _CHECK_LICENSE_FILENAMES and + extension not in _CHECK_LICENSE_EXTENSIONS): + continue + + with open(path) as file_handle: + if _LICENSE_STRING not in file_handle.read(): + print('Missing license header in file %s.' % str(path)) + success = False + + return success + + +def bool_to_returncode(success): + """Returns 0 if |success|. Otherwise returns 1.""" + if success: + print('Success.') + return 0 + + print('Failed.') + return 1 + + +def is_nonfuzzer_python(path): + """Returns True if |path| ends in .py.""" + return os.path.splitext(path)[1] == '.py' and '/projects/' not in path + + +def lint(_=None): + """Runs python's linter on infra. Returns False if it fails linting.""" + + # Use --score no to make linting quieter. + command = ['python3', '-m', 'pylint', '--score', 'no', '-j', '0', 'infra'] + returncode = subprocess.run(command, check=False).returncode + return returncode == 0 + + +def yapf(paths, validate=True): + """Does yapf on |path| if it is Python file. Only validates format if + |validate|. Otherwise, formats the file. Returns False if validation or + formatting fails.""" + paths = [path for path in paths if is_nonfuzzer_python(path)] + if not paths: + return True + + validate_argument = '-d' if validate else '-i' + command = ['yapf', validate_argument, '-p'] + command.extend(paths) + + returncode = subprocess.run(command, check=False).returncode + return returncode == 0 + + +def get_changed_files(): + """Returns a list of absolute paths of files changed in this git branch.""" + branch_commit_hash = subprocess.check_output( + ['git', 'merge-base', 'HEAD', 'origin/HEAD']).strip().decode() + + diff_commands = [ + # Return list of modified files in the commits on this branch. + ['git', 'diff', '--name-only', branch_commit_hash + '..'], + # Return list of modified files from uncommitted changes. + ['git', 'diff', '--name-only'] + ] + + changed_files = set() + for command in diff_commands: + file_paths = subprocess.check_output(command).decode().splitlines() + for file_path in file_paths: + if not os.path.isfile(file_path): + continue + changed_files.add(file_path) + print(f'Changed files: {" ".join(changed_files)}') + return [os.path.abspath(f) for f in changed_files] + + +def run_build_tests(): + """Runs build tests because they can't be run in parallel.""" + suite_list = [ + unittest.TestLoader().discover(os.path.join(_SRC_ROOT, 'infra', 'build'), + pattern='*_test.py'), + ] + suite = unittest.TestSuite(suite_list) + print('Running build tests.') + result = unittest.TextTestRunner().run(suite) + return not result.failures and not result.errors + + +def run_nonbuild_tests(parallel): + """Runs all tests but build tests. Does them in parallel if |parallel|. The + reason why we exclude build tests is because they use an emulator that + prevents them from being used in parallel.""" + # We look for all project directories because otherwise pytest won't run tests + # that are not in valid modules (e.g. "base-images"). + relevant_dirs = set() + all_files = get_all_files() + for file_path in all_files: + directory = os.path.dirname(file_path) + relevant_dirs.add(directory) + + # Use ignore-glob because ignore doesn't seem to work properly with the way we + # pass directories to pytest. + command = [ + 'pytest', + '--ignore-glob=infra/build/*', + '--ignore-glob=projects/*', + ] + if parallel: + command.extend(['-n', 'auto']) + command += list(relevant_dirs) + print('Running non-build tests.') + + # TODO(metzman): Get rid of this once config_utils stops using it. + env = os.environ.copy() + env['CIFUZZ_TEST'] = '1' + + return subprocess.run(command, check=False, env=env).returncode == 0 + + +def run_tests(_=None, parallel=False, build_tests=True, nonbuild_tests=True): + """Runs all unit tests.""" + build_success = True + nonbuild_success = True + if nonbuild_tests: + nonbuild_success = run_nonbuild_tests(parallel) + else: + print('Skipping nonbuild tests as specified.') + + if build_tests: + build_success = run_build_tests() + else: + print('Skipping build tests as specified.') + + return nonbuild_success and build_success + + +def run_systemsan_tests(_=None): + """Runs SystemSan unit tests.""" + command = ['make', 'test'] + return subprocess.run(command, + cwd='infra/experimental/SystemSan', + check=False).returncode == 0 + + +def get_all_files(): + """Returns a list of absolute paths of files in this repo.""" + get_all_files_command = ['git', 'ls-files'] + output = subprocess.check_output(get_all_files_command).decode().splitlines() + return [os.path.abspath(path) for path in output if os.path.isfile(path)] + + +def main(): + """Check changes on a branch for common issues before submitting.""" + # Get program arguments. + parser = argparse.ArgumentParser(description='Presubmit script for oss-fuzz.') + parser.add_argument( + 'command', + choices=['format', 'lint', 'license', 'infra-tests', 'systemsan-tests'], + nargs='?') + parser.add_argument('-a', + '--all-files', + action='store_true', + help='Run presubmit check(s) on all files', + default=False) + parser.add_argument('-p', + '--parallel', + action='store_true', + help='Run tests in parallel.', + default=False) + parser.add_argument('-s', + '--skip-build-tests', + action='store_true', + help='Skip build tests which are slow and must run ' + 'sequentially.', + default=False) + parser.add_argument('-n', + '--skip-nonbuild-tests', + action='store_true', + help='Only do build tests.', + default=False) + args = parser.parse_args() + + if args.all_files: + relevant_files = get_all_files() + else: + relevant_files = get_changed_files() + + os.chdir(_SRC_ROOT) + + # Do one specific check if the user asked for it. + if args.command == 'format': + success = yapf(relevant_files, False) + return bool_to_returncode(success) + + if args.command == 'lint': + success = lint() + return bool_to_returncode(success) + + if args.command == 'license': + success = check_license(relevant_files) + return bool_to_returncode(success) + + if args.command == 'infra-tests': + success = run_tests(relevant_files, + parallel=args.parallel, + build_tests=(not args.skip_build_tests), + nonbuild_tests=(not args.skip_nonbuild_tests)) + return bool_to_returncode(success) + + if args.command == 'systemsan-tests': + success = run_systemsan_tests(relevant_files) + return bool_to_returncode(success) + + # Do all the checks (but no tests). + success = do_checks(relevant_files) + + return bool_to_returncode(success) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/pytest.ini b/local-test-curl-delta-01/fuzz-tooling/infra/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..2a10272e26592f4f8bdea82c1675c767b4488dec --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +python_files = *_test.py +log_cli = true \ No newline at end of file diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager.py b/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..8e86f25482c1539a557b2b751855f7ea1c5872f0 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager.py @@ -0,0 +1,272 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Class to manage a git repository via python. + +This class is to be used to implement git commands over +a python API and manage the current state of the git repo. + + Typical usage example: + + r_man = RepoManager('https://github.com/google/oss-fuzz.git') + r_man.checkout('5668cc422c2c92d38a370545d3591039fb5bb8d4') +""" +import datetime +import logging +import os +import shutil + +import urllib.parse + +import utils + + +class RepoManager: + """Repo manager.""" + + def __init__(self, repo_dir): + self.repo_dir = repo_dir + + def _is_git_repo(self): + """Test if the current repo dir is a git repo or not. + + Returns: + True if the current repo_dir is a valid git repo. + """ + git_path = os.path.join(self.repo_dir, '.git') + return os.path.isdir(git_path) + + def git(self, cmd, check_result=False): + """Run a git command. + + Args: + command: The git command as a list to be run. + check_result: Should an exception be thrown on failed command. + + Returns: + stdout, stderr, error code. + """ + return utils.execute(['git'] + cmd, + location=self.repo_dir, + check_result=check_result) + + def commit_exists(self, commit): + """Checks to see if a commit exists in the project repo. + + Args: + commit: The commit SHA you are checking. + + Returns: + True if the commit exits in the project. + """ + if not commit.rstrip(): + return False + + _, _, err_code = self.git(['cat-file', '-e', commit]) + return not err_code + + def commit_date(self, commit): + """Get the date of a commit. + + Args: + commit: The commit hash. + + Returns: + A datetime representing the date of the commit. + """ + out, _, _ = self.git(['show', '-s', '--format=%ct', commit], + check_result=True) + return datetime.datetime.fromtimestamp(int(out), tz=datetime.timezone.utc) + + def get_git_diff(self, base='origin...'): + """Gets a list of files that have changed from the repo head. + + Returns: + A list of changed file paths or None on Error. + """ + self.fetch_unshallow() + # Add '--' so that git knows we aren't talking about files. + command = ['diff', '--name-only', base, '--'] + out, err_msg, err_code = self.git(command) + if err_code: + logging.error('Git diff failed with error message %s.', err_msg) + return None + if not out: + logging.error('No diff was found.') + return None + return [line for line in out.splitlines() if line] + + def get_current_commit(self): + """Gets the current commit SHA of the repo. + + Returns: + The current active commit SHA. + """ + out, _, _ = self.git(['rev-parse', 'HEAD'], check_result=True) + return out.strip() + + def get_parent(self, commit, count): + """Gets the count'th parent of the given commit. + + Returns: + The parent commit SHA. + """ + self.fetch_unshallow() + out, _, err_code = self.git(['rev-parse', commit + '~' + str(count)], + check_result=False) + if err_code: + return None + + return out.strip() + + def fetch_all_remotes(self): + """Fetch all remotes for checkouts that track a single branch.""" + self.git([ + 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*' + ], + check_result=True) + self.git(['remote', 'update'], check_result=True) + + def get_commit_list(self, newest_commit, oldest_commit=None, limit=None): + """Gets the list of commits(inclusive) between the old and new commits. + + Args: + newest_commit: The newest commit to be in the list. + oldest_commit: The (optional) oldest commit to be in the list. + + Returns: + The list of commit SHAs from newest to oldest. + + Raises: + ValueError: When either the oldest or newest commit does not exist. + RuntimeError: When there is an error getting the commit list. + """ + self.fetch_unshallow() + if oldest_commit and not self.commit_exists(oldest_commit): + raise ValueError('The oldest commit %s does not exist' % oldest_commit) + if not self.commit_exists(newest_commit): + raise ValueError('The newest commit %s does not exist' % newest_commit) + if oldest_commit == newest_commit: + return [oldest_commit] + + if oldest_commit: + commit_range = oldest_commit + '..' + newest_commit + else: + commit_range = newest_commit + + limit_args = [] + if limit: + limit_args.append(f'--max-count={limit}') + + out, _, err_code = self.git(['rev-list', commit_range] + limit_args) + commits = out.split('\n') + commits = [commit for commit in commits if commit] + if err_code or not commits: + raise RuntimeError('Error getting commit list between %s and %s ' % + (oldest_commit, newest_commit)) + + # Make sure result is inclusive + if oldest_commit: + commits.append(oldest_commit) + return commits + + def fetch_branch(self, branch): + """Fetches a remote branch from origin.""" + return self.git( + ['fetch', 'origin', '{branch}:{branch}'.format(branch=branch)]) + + def fetch_unshallow(self): + """Gets the current git repository history.""" + shallow_file = os.path.join(self.repo_dir, '.git', 'shallow') + if os.path.exists(shallow_file): + _, err, err_code = self.git(['fetch', '--unshallow'], check_result=False) + if err_code: + logging.error('Unshallow returned non-zero code: %s', err) + + def checkout_pr(self, pr_ref): + """Checks out a remote pull request. + + Args: + pr_ref: The pull request reference to be checked out. + """ + self.fetch_unshallow() + self.git(['fetch', 'origin', pr_ref], check_result=True) + self.git(['checkout', '-f', 'FETCH_HEAD'], check_result=True) + self.git(['submodule', 'update', '-f', '--init', '--recursive'], + check_result=True) + + def checkout_commit(self, commit, clean=True): + """Checks out a specific commit from the repo. + + Args: + commit: The commit SHA to be checked out. + + Raises: + RuntimeError: when checkout is not successful. + ValueError: when commit does not exist. + """ + self.fetch_unshallow() + if not self.commit_exists(commit): + raise ValueError('Commit %s does not exist in current branch' % commit) + self.git(['checkout', '-f', commit], check_result=True) + self.git(['submodule', 'update', '-f', '--init', '--recursive'], + check_result=True) + if clean: + self.git(['clean', '-fxd'], check_result=True) + if self.get_current_commit() != commit: + raise RuntimeError('Error checking out commit %s' % commit) + + def remove_repo(self): + """Removes the git repo from disk.""" + if os.path.isdir(self.repo_dir): + shutil.rmtree(self.repo_dir) + + +def clone_repo_and_get_manager(repo_url, + base_dir, + repo_name=None, + username=None, + password=None): + """Clones a repo and constructs a repo manager class. + + Args: + repo_url: The github url needed to clone. + base_dir: The full file-path where the git repo is located. + repo_name: The name of the directory the repo is cloned to. + """ + if repo_name is None: + repo_name = os.path.basename(repo_url).replace('.git', '') + repo_dir = os.path.join(base_dir, repo_name) + manager = RepoManager(repo_dir) + + if not os.path.exists(repo_dir): + _clone(repo_url, base_dir, repo_name, username=username, password=password) + + return manager + + +def _clone(repo_url, base_dir, repo_name, username=None, password=None): + """Creates a clone of the repo in the specified directory. + + Raises: + ValueError: when the repo is not able to be cloned. + """ + if username and password: + parsed_url = urllib.parse.urlparse(repo_url) + new_netloc = f'{username}:{password}@{parsed_url.netloc}' + repo_url = urllib.parse.urlunparse(parsed_url._replace(netloc=new_netloc)) + + utils.execute(['git', 'clone', repo_url, repo_name], + location=base_dir, + check_result=True, + log_command=not password) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager_test.py b/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfa64d0f41f40ab3024e58ec45ccd3ae81dbfac --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/repo_manager_test.py @@ -0,0 +1,201 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Test the functionality of the RepoManager class.""" + +import contextlib +import os +import tempfile +import unittest +from unittest import mock + +import repo_manager +import utils + +# pylint: disable=protected-access + +OSS_FUZZ_REPO_URL = 'https://github.com/google/oss-fuzz' + + +@contextlib.contextmanager +def get_oss_fuzz_repo(): + """Clones a temporary copy of the OSS-Fuzz repo. Returns the path to the + repo.""" + repo_name = 'oss-fuzz' + with tempfile.TemporaryDirectory() as tmp_dir: + repo_manager._clone(OSS_FUZZ_REPO_URL, tmp_dir, repo_name) + yield os.path.join(tmp_dir, repo_name) + + +class CloneTest(unittest.TestCase): + """Tests the _clone function.""" + + @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') + def test_clone_valid_repo_integration(self): + """Integration test that tests the correct location of the git repo.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + git_path = os.path.join(oss_fuzz_repo, '.git') + self.assertTrue(os.path.isdir(git_path)) + + def test_clone_invalid_repo(self): + """Tests that cloning an invalid repo will fail.""" + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(RuntimeError): + repo_manager._clone('https://github.com/oss-fuzz-not-real.git', tmp_dir, + 'oss-fuzz') + + @mock.patch('utils.execute') + def test_clone_with_username(self, mock_execute): # pylint: disable=no-self-use + """Test clone with username.""" + repo_manager._clone('https://github.com/fake/repo.git', + '/', + 'name', + username='user', + password='password') + mock_execute.assert_called_once_with([ + 'git', 'clone', 'https://user:password@github.com/fake/repo.git', 'name' + ], + location='/', + check_result=True, + log_command=False) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class RepoManagerCheckoutTest(unittest.TestCase): + """Tests the checkout functionality of RepoManager.""" + + def test_checkout_valid_commit(self): + """Tests that the git checkout command works.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + commit_to_test = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b' + repo_man.checkout_commit(commit_to_test) + self.assertEqual(commit_to_test, repo_man.get_current_commit()) + + def test_checkout_invalid_commit(self): + """Tests that the git checkout invalid commit fails.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + with self.assertRaises(ValueError): + repo_man.checkout_commit(' ') + with self.assertRaises(ValueError): + repo_man.checkout_commit('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') + with self.assertRaises(ValueError): + repo_man.checkout_commit('not-a-valid-commit') + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class RepoManagerGetCommitListTest(unittest.TestCase): + """Tests the get_commit_list method of RepoManager.""" + + def test_get_valid_commit_list(self): + """Tests an accurate commit list can be retrieved from the repo manager.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b' + new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463' + commit_list = [ + 'fa662173bfeb3ba08d2e84cefc363be11e6c8463', + '17035317a44fa89d22fe6846d868d4bf57def78b', + '97dee00a3c4ce95071c3e061592f5fd577dea886', + '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b' + ] + result_list = repo_man.get_commit_list(new_commit, old_commit) + self.assertListEqual(commit_list, result_list) + + def test_get_invalid_commit_list(self): + """Tests that the proper errors are thrown when invalid commits are + passed to get_commit_list.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b' + new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463' + with self.assertRaises(ValueError): + repo_man.get_commit_list('fakecommit', new_commit) + with self.assertRaises(ValueError): + repo_man.get_commit_list(new_commit, 'fakecommit') + with self.assertRaises(RuntimeError): + repo_man.get_commit_list(old_commit, new_commit) # pylint: disable=arguments-out-of-order + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class GitDiffTest(unittest.TestCase): + """Tests get_git_diff.""" + + def test_diff_exists(self): + """Tests that a real diff is returned when a valid repo manager exists.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + with mock.patch.object(utils, + 'execute', + return_value=('test.py\ndiff.py', None, 0)): + diff = repo_man.get_git_diff() + self.assertCountEqual(diff, ['test.py', 'diff.py']) + + def test_diff_empty(self): + """Tests that None is returned when there is no difference between repos.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + with mock.patch.object(utils, 'execute', return_value=('', None, 0)): + diff = repo_man.get_git_diff() + self.assertIsNone(diff) + + def test_error_on_command(self): + """Tests that None is returned when the command errors out.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + with mock.patch.object(utils, + 'execute', + return_value=('', 'Test error.', 1)): + diff = repo_man.get_git_diff() + self.assertIsNone(diff) + + def test_diff_no_change(self): + """Tests that None is returned when there is no difference between repos.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + diff = repo_man.get_git_diff() + self.assertIsNone(diff) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class CheckoutPrIntegrationTest(unittest.TestCase): + """Does Integration tests on the checkout_pr method of RepoManager.""" + + def test_pull_request_exists(self): + """Tests that a diff is returned when a valid PR is checked out.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + repo_man.checkout_pr('refs/pull/3415/merge') + diff = repo_man.get_git_diff() + self.assertCountEqual(diff, ['README.md']) + + def test_checkout_invalid_pull_request(self): + """Tests that the git checkout invalid pull request fails.""" + with get_oss_fuzz_repo() as oss_fuzz_repo: + repo_man = repo_manager.RepoManager(oss_fuzz_repo) + with self.assertRaises(RuntimeError): + repo_man.checkout_pr(' ') + with self.assertRaises(RuntimeError): + repo_man.checkout_pr('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') + with self.assertRaises(RuntimeError): + repo_man.checkout_pr('not/a/valid/pr') + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/retry.py b/local-test-curl-delta-01/fuzz-tooling/infra/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6d54b8d00d081b672a7cbb9f998b5b92c624ce --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/retry.py @@ -0,0 +1,106 @@ +# Copyright 2020 Google LLC +# +# 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. +"""Retry decorator. Copied from ClusterFuzz source.""" + +import functools +import inspect +import logging +import sys +import time + +# pylint: disable=too-many-arguments,broad-except + + +def sleep(seconds): + """Invoke time.sleep. This is to avoid the flakiness of time.sleep. See: + crbug.com/770375""" + time.sleep(seconds) + + +def get_delay(num_try, delay, backoff): + """Compute backoff delay.""" + return delay * (backoff**(num_try - 1)) + + +def wrap(retries, + delay, + backoff=2, + exception_type=Exception, + retry_on_false=False): + """Retry decorator for a function.""" + + assert delay > 0 + assert backoff >= 1 + assert retries >= 0 + + def decorator(func): + """Decorator for the given function.""" + tries = retries + 1 + is_generator = inspect.isgeneratorfunction(func) + function_with_type = func.__qualname__ + if is_generator: + function_with_type += ' (generator)' + + def handle_retry(num_try, exception=None): + """Handle retry.""" + if (exception is None or + isinstance(exception, exception_type)) and num_try < tries: + logging.info('Retrying on %s failed with %s. Retrying again.', + function_with_type, + sys.exc_info()[1]) + sleep(get_delay(num_try, delay, backoff)) + return True + + logging.error('Retrying on %s failed with %s. Raise.', function_with_type, + sys.exc_info()[1]) + return False + + @functools.wraps(func) + def _wrapper(*args, **kwargs): + """Regular function wrapper.""" + for num_try in range(1, tries + 1): + try: + result = func(*args, **kwargs) + if retry_on_false and not result: + if not handle_retry(num_try): + return result + + continue + return result + except Exception as error: + if not handle_retry(num_try, exception=error): + raise + + @functools.wraps(func) + def _generator_wrapper(*args, **kwargs): + """Generator function wrapper.""" + # This argument is not applicable for generator functions. + assert not retry_on_false + already_yielded_element_count = 0 + for num_try in range(1, tries + 1): + try: + for index, result in enumerate(func(*args, **kwargs)): + if index >= already_yielded_element_count: + yield result + already_yielded_element_count += 1 + break + except Exception as error: + if not handle_retry(num_try, exception=error): + raise + + if is_generator: + return _generator_wrapper + return _wrapper + + return decorator diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/run_fuzzers.Dockerfile b/local-test-curl-delta-01/fuzz-tooling/infra/run_fuzzers.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..81accee186d02b6871e3da841e5e73740ff0c8d4 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/run_fuzzers.Dockerfile @@ -0,0 +1,31 @@ +# Copyright 2020 Google LLC +# +# 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. +# +################################################################################ +# Docker image for running fuzzers on CIFuzz (the run_fuzzers action on GitHub +# actions). + +FROM ghcr.io/aixcc-finals/cifuzz-base + +# Python file to execute when the docker container starts up. +# We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var, +# just expand to '/opt/oss-fuzz'. +ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/run_fuzzers_entrypoint.py"] + +WORKDIR ${OSS_FUZZ_ROOT}/infra + +# Copy infra source code. +ADD . ${OSS_FUZZ_ROOT}/infra + +RUN python3 -m pip install -r ${OSS_FUZZ_ROOT}/infra/cifuzz/requirements.txt diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/templates.py b/local-test-curl-delta-01/fuzz-tooling/infra/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..ed5819683c1b7ca673b09174558394851f6cb04f --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/templates.py @@ -0,0 +1,119 @@ +# Copyright 2016 Google Inc. +# +# 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. +# +################################################################################ +"""Templates for OSS-Fuzz project files.""" + +PROJECT_YAML_TEMPLATE = """\ +homepage: "" +language: %(language)s +primary_contact: "" +main_repo: "https://path/to/main/repo.git" +file_github_issue: true +""" + +DOCKER_TEMPLATE = """\ +# Copyright %(year)d Google LLC +# +# 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. +# +################################################################################ + +FROM ghcr.io/aixcc-finals/%(base_builder)s +RUN apt-get update && apt-get install -y make autoconf automake libtool +RUN git clone --depth 1 %(project_name)s # or use other version control +WORKDIR %(project_name)s +COPY build.sh $SRC/ +""" + +EXTERNAL_DOCKER_TEMPLATE = """\ +FROM ghcr.io/aixcc-finals/%(base_builder)s:v1 +RUN apt-get update && apt-get install -y make autoconf automake libtool +COPY . $SRC/%(project_name)s +WORKDIR %(project_name)s +COPY .clusterfuzzlite/build.sh $SRC/ +""" + +BUILD_TEMPLATE = """\ +#!/bin/bash -eu +# Copyright %(year)d Google LLC +# +# 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. +# +################################################################################ + +# build project +# e.g. +# ./autogen.sh +# ./configure +# make -j$(nproc) all + +# build fuzzers +# e.g. +# $CXX $CXXFLAGS -std=c++11 -Iinclude \\ +# /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\ +# $LIB_FUZZING_ENGINE /path/to/library.a +""" + +EXTERNAL_BUILD_TEMPLATE = """\ +#!/bin/bash -eu + +# build project +# e.g. +# ./autogen.sh +# ./configure +# make -j$(nproc) all + +# build fuzzers +# e.g. +# $CXX $CXXFLAGS -std=c++11 -Iinclude \\ +# /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\ +# $LIB_FUZZING_ENGINE /path/to/library.a +""" + +EXTERNAL_PROJECT_YAML_TEMPLATE = """\ +language: %(language)s +""" + +TEMPLATES = { + 'build.sh': BUILD_TEMPLATE, + 'Dockerfile': DOCKER_TEMPLATE, + 'project.yaml': PROJECT_YAML_TEMPLATE +} + +EXTERNAL_TEMPLATES = { + 'build.sh': EXTERNAL_BUILD_TEMPLATE, + 'Dockerfile': EXTERNAL_DOCKER_TEMPLATE, + 'project.yaml': EXTERNAL_PROJECT_YAML_TEMPLATE +} diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/test b/local-test-curl-delta-01/fuzz-tooling/infra/test new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/test @@ -0,0 +1 @@ + diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/test_repos.py b/local-test-curl-delta-01/fuzz-tooling/infra/test_repos.py new file mode 100644 index 0000000000000000000000000000000000000000..389876864b59e7ec46f76f8311c323c22f763e74 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/test_repos.py @@ -0,0 +1,84 @@ +# Copyright 2020 Google LLC +# +# 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 module contains a list of test repository's used in unit/integration +tests. + +Note: If you notice tests failing for unexpected reasons, make sure the data +in the test repos are correct. This is because the test repos are dynamic and +may change. + +Note: This should be removed when a better method of testing is established. +""" + +import collections +import os + +ExampleRepo = collections.namedtuple('ExampleRepo', [ + 'project_name', 'oss_repo_name', 'git_repo_name', 'image_location', + 'git_url', 'new_commit', 'old_commit', 'intro_commit', 'fuzz_target', + 'testcase_path' +]) + +TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), + 'testcases') + +# WARNING: Tests are dependent upon the following repos existing and the +# specified commits existing. +# TODO(metzman): Fix this problem. +# TODO(metzman): The testcases got deleted here because the test that used them +# was skipped. Probably worth deleting the test. +TEST_REPOS = [ + ExampleRepo(project_name='curl', + oss_repo_name='curl', + git_repo_name='curl', + image_location='/src', + git_url='https://github.com/curl/curl.git', + old_commit='df26f5f9c36e19cd503c0e462e9f72ad37b84c82', + new_commit='dda418266c99ceab368d723facb52069cbb9c8d5', + intro_commit='df26f5f9c36e19cd503c0e462e9f72ad37b84c82', + fuzz_target='curl_fuzzer_ftp', + testcase_path=os.path.join(TEST_DIR_PATH, 'curl_test_data')), + ExampleRepo(project_name='libarchive', + oss_repo_name='libarchive', + git_repo_name='libarchive', + image_location='/src', + git_url='https://github.com/libarchive/libarchive.git', + old_commit='5bd2a9b6658a3a6efa20bb9ad75bd39a44d71da6', + new_commit='458e49358f17ec58d65ab1c45cf299baaf3c98d1', + intro_commit='840266712006de5e737f8052db920dfea2be4260', + fuzz_target='libarchive_fuzzer', + testcase_path=os.path.join(TEST_DIR_PATH, + 'libarchive_test_data')), + ExampleRepo(project_name='gonids', + oss_repo_name='gonids', + git_repo_name='gonids', + image_location='/root/go/src/github.com/google/', + git_url='https://github.com/google/gonids', + old_commit='', + new_commit='', + intro_commit='', + fuzz_target='', + testcase_path='') +] + +INVALID_REPO = ExampleRepo(project_name='notaproj', + oss_repo_name='notarepo', + git_repo_name='notarepo', + git_url='invalid.git', + image_location='/src', + old_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + new_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + intro_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + fuzz_target='NONEFUZZER', + testcase_path='not/a/path') diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/tools/hold_back_images.py b/local-test-curl-delta-01/fuzz-tooling/infra/tools/hold_back_images.py new file mode 100644 index 0000000000000000000000000000000000000000..659eb5debc28f0bbfbfcd34d863c88571b89c9f5 --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/tools/hold_back_images.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Script for pinning builder images for projects that break on upgrades. Works +with projects that use language builders.""" +import argparse +import logging +import os +import re +import sys +import subprocess + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) +PROJECTS_DIR = os.path.join(ROOT_DIR, 'projects') + +IMAGE_DIGEST_REGEX = re.compile(r'\[(.+)\]\n') +FROM_LINE_REGEX = re.compile( + r'FROM (ghcr.io\/aixcc-finals\/base-builder[\-a-z0-9]*)(\@?.*)') + + +def get_latest_docker_image_digest(image): + """Returns a pinnable version of the latest |image|. This version will have a + SHA.""" + subprocess.run(['docker', 'pull', image], check=True) + subprocess.run(['docker', 'pull', image], stdout=subprocess.PIPE, check=True) + + command = [ + 'docker', 'image', 'inspect', '--format', '{{.RepoDigests}}', image + ] + output = subprocess.run(command, check=True, + stdout=subprocess.PIPE).stdout.decode('utf-8') + return IMAGE_DIGEST_REGEX.match(output).groups(1)[0] + + +def get_args(): + """Returns parsed arguments.""" + parser = argparse.ArgumentParser(sys.argv[0], + description='Hold back builder images.') + parser.add_argument('projects', help='Projects.', nargs='+') + + parser.add_argument('--hold-image-digest', + required=False, + nargs='?', + default=None, + help='Image to hold on to.') + + parser.add_argument('--update-held', + action='store_true', + default=False, + help='Update held images.') + + parser.add_argument('--issue-number', + required=False, + nargs='?', + default=None, + help='Issue to reference.') + + args = parser.parse_args() + return args + + +def get_hold_image_digest(line, hold_image_digest, update_held): + """Returns the image digest for the |line| we want to pin. If the image is + already pinned then it is only updated if |update_held. If |hold_image_digest + is specified then it is returned, otherwise the latest pinnable version is + returned.""" + matches = FROM_LINE_REGEX.match(line).groups() + if matches[1] and not update_held: + return None, False + initial_image = matches[0] + if hold_image_digest: + return hold_image_digest, True + return get_latest_docker_image_digest(initial_image), True + + +def hold_image(project, hold_image_digest, update_held, issue_number): + """Rewrites the Dockerfile of |project| to pin the base-builder image on + upgrade.""" + dockerfile_path = os.path.join(PROJECTS_DIR, project, 'Dockerfile') + with open(dockerfile_path, 'r') as dockerfile_handle: + dockerfile = dockerfile_handle.readlines() + for idx, line in enumerate(dockerfile[:]): + if not line.startswith('FROM ghcr.io/aixcc-finals/base-builder'): + continue + + hold_image_digest, should_hold = get_hold_image_digest( + line.strip(), hold_image_digest, update_held) + if not should_hold: + logging.error('Not holding back %s.', project) + break + dockerfile[idx] = f'FROM {hold_image_digest}\n' + if issue_number: + comment = ('# Held back because of github.com/google/oss-fuzz/pull/' + f'{issue_number}\n# Please fix failure and upgrade.\n') + dockerfile.insert(idx, comment) + break + else: + # This path is taken when we don't break out of the loop. + assert None, f'Could not find FROM line in {project}' + dockerfile = ''.join(dockerfile) + with open(dockerfile_path, 'w') as dockerfile_handle: + dockerfile_handle.write(dockerfile) + + +def main(): + """Script for pinning builder images for projects that break on upgrades.""" + args = get_args() + for project in args.projects: + hold_image(project, args.hold_image_digest, args.update_held, + args.issue_number) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/uploader/Dockerfile b/local-test-curl-delta-01/fuzz-tooling/infra/uploader/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..814678833ec765fbb06bc21300b67ad5e6e1668f --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/uploader/Dockerfile @@ -0,0 +1,7 @@ +from ubuntu:16.04 + +RUN apt-get update && apt-get upgrade -y +RUN apt-get install -y curl + +ENTRYPOINT ["curl", "--retry", "5", "-X", "PUT", "-T"] + diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/utils.py b/local-test-curl-delta-01/fuzz-tooling/infra/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..661a773e74b4ee4518bf489989ed05ac866b712a --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/utils.py @@ -0,0 +1,205 @@ +# Copyright 2020 Google LLC +# +# 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. +"""Utilities for OSS-Fuzz infrastructure.""" + +import logging +import os +import posixpath +import re +import shlex +import stat +import subprocess +import sys + +import helper + +ALLOWED_FUZZ_TARGET_EXTENSIONS = ['', '.exe'] +FUZZ_TARGET_SEARCH_STRING = 'LLVMFuzzerTestOneInput' +VALID_TARGET_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$') +BLOCKLISTED_TARGET_NAME_REGEX = re.compile(r'^(jazzer_driver.*)$') + +# Location of google cloud storage for latest OSS-Fuzz builds. +GCS_BASE_URL = 'https://storage.googleapis.com/' + + +def chdir_to_root(): + """Changes cwd to OSS-Fuzz root directory.""" + # Change to oss-fuzz main directory so helper.py runs correctly. + if os.getcwd() != helper.OSS_FUZZ_DIR: + os.chdir(helper.OSS_FUZZ_DIR) + + +def command_to_string(command): + """Returns the stringfied version of |command| a list representing a binary to + run and arguments to pass to it or a string representing a binary to run.""" + if isinstance(command, str): + return command + return shlex.join(command) + + +def execute(command, + env=None, + location=None, + check_result=False, + log_command=True): + """Runs a shell command in the specified directory location. + + Args: + command: The command as a list to be run. + env: (optional) an environment to pass to Popen to run the command in. + location (optional): The directory to run command in. + check_result (optional): Should an exception be thrown on failure. + + Returns: + stdout, stderr, returncode. + + Raises: + RuntimeError: running a command resulted in an error. + """ + + if not location: + location = os.getcwd() + process = subprocess.Popen(command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=location, + env=env) + out, err = process.communicate() + out = out.decode('utf-8', errors='ignore') + err = err.decode('utf-8', errors='ignore') + + if log_command: + command_str = command_to_string(command) + display_err = err + else: + command_str = 'redacted' + display_err = 'redacted' + + if err: + logging.debug('Stderr of command "%s" is: %s.', command_str, display_err) + if check_result and process.returncode: + raise RuntimeError('Executing command "{0}" failed with error: {1}.'.format( + command_str, display_err)) + return out, err, process.returncode + + +def get_fuzz_targets(path): + """Gets fuzz targets in a directory. + + Args: + path: A path to search for fuzz targets in. + + Returns: + A list of paths to fuzzers or an empty list if None. + """ + if not os.path.exists(path): + return [] + fuzz_target_paths = [] + for root, _, fuzzers in os.walk(path): + for fuzzer in fuzzers: + file_path = os.path.join(root, fuzzer) + if is_fuzz_target_local(file_path): + fuzz_target_paths.append(file_path) + + return fuzz_target_paths + + +def get_container_name(): + """Gets the name of the current docker container you are in. + + Returns: + Container name or None if not in a container. + """ + result = subprocess.run( # pylint: disable=subprocess-run-check + ['systemd-detect-virt', '-c'], + stdout=subprocess.PIPE).stdout + if b'docker' not in result: + return None + with open('/etc/hostname') as file_handle: + return file_handle.read().strip() + + +def is_executable(file_path): + """Returns True if |file_path| is an exectuable.""" + return os.path.exists(file_path) and os.access(file_path, os.X_OK) + + +def is_fuzz_target_local(file_path): + """Returns whether |file_path| is a fuzz target binary (local path). + Copied from clusterfuzz src/python/bot/fuzzers/utils.py + with slight modifications. + """ + # pylint: disable=too-many-return-statements + filename, file_extension = os.path.splitext(os.path.basename(file_path)) + if not VALID_TARGET_NAME_REGEX.match(filename): + # Check fuzz target has a valid name (without any special chars). + return False + + if BLOCKLISTED_TARGET_NAME_REGEX.match(filename): + # Check fuzz target an explicitly disallowed name (e.g. binaries used for + # jazzer-based targets). + return False + + if file_extension not in ALLOWED_FUZZ_TARGET_EXTENSIONS: + # Ignore files with disallowed extensions (to prevent opening e.g. .zips). + return False + + if not is_executable(file_path): + return False + + if filename.endswith('_fuzzer'): + return True + + if os.path.exists(file_path) and not stat.S_ISREG(os.stat(file_path).st_mode): + return False + + with open(file_path, 'rb') as file_handle: + return file_handle.read().find(FUZZ_TARGET_SEARCH_STRING.encode()) != -1 + + +def binary_print(string): + """Prints string. Can print a binary string.""" + if isinstance(string, bytes): + string += b'\n' + else: + string += '\n' + sys.stdout.buffer.write(string) + sys.stdout.flush() + + +def url_join(*url_parts): + """Joins URLs together using the POSIX join method. + + Args: + url_parts: Sections of a URL to be joined. + + Returns: + Joined URL. + """ + return posixpath.join(*url_parts) + + +def gs_url_to_https(url): + """Converts |url| from a GCS URL (beginning with 'gs://') to an HTTPS one.""" + return url_join(GCS_BASE_URL, remove_prefix(url, 'gs://')) + + +def remove_prefix(string, prefix): + """Returns |string| without the leading substring |prefix|.""" + # Match behavior of removeprefix from python3.9: + # https://www.python.org/dev/peps/pep-0616/ + if string.startswith(prefix): + return string[len(prefix):] + + return string diff --git a/local-test-curl-delta-01/fuzz-tooling/infra/utils_test.py b/local-test-curl-delta-01/fuzz-tooling/infra/utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7fbc90323af958c2d9fdcbe5d7889b84f0db2b --- /dev/null +++ b/local-test-curl-delta-01/fuzz-tooling/infra/utils_test.py @@ -0,0 +1,151 @@ +# Copyright 2020 Google LLC +# +# 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. +"""Tests the functionality of the utils module's functions""" + +import os +import tempfile +import unittest +from unittest import mock + +import utils +import helper + +EXAMPLE_PROJECT = 'example' + +TEST_OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'cifuzz', 'test_data', 'build-out') + + +class IsFuzzTargetLocalTest(unittest.TestCase): + """Tests the is_fuzz_target_local function.""" + + def test_invalid_filepath(self): + """Tests the function with an invalid file path.""" + is_local = utils.is_fuzz_target_local('not/a/real/file') + self.assertFalse(is_local) + is_local = utils.is_fuzz_target_local('') + self.assertFalse(is_local) + is_local = utils.is_fuzz_target_local(' ') + self.assertFalse(is_local) + + def test_valid_filepath(self): + """Checks is_fuzz_target_local function with a valid filepath.""" + + is_local = utils.is_fuzz_target_local( + os.path.join(TEST_OUT_DIR, 'example_crash_fuzzer')) + self.assertTrue(is_local) + is_local = utils.is_fuzz_target_local(TEST_OUT_DIR) + self.assertFalse(is_local) + + +class GetFuzzTargetsTest(unittest.TestCase): + """Tests the get_fuzz_targets function.""" + + def test_valid_filepath(self): + """Tests that fuzz targets can be retrieved once the fuzzers are built.""" + fuzz_targets = utils.get_fuzz_targets(TEST_OUT_DIR) + crash_fuzzer_path = os.path.join(TEST_OUT_DIR, 'example_crash_fuzzer') + nocrash_fuzzer_path = os.path.join(TEST_OUT_DIR, 'example_nocrash_fuzzer') + self.assertCountEqual(fuzz_targets, + [crash_fuzzer_path, nocrash_fuzzer_path]) + + # Testing on a arbitrary directory with no fuzz targets in it. + fuzz_targets = utils.get_fuzz_targets( + os.path.join(helper.OSS_FUZZ_DIR, 'infra', 'travis')) + self.assertFalse(fuzz_targets) + + def test_invalid_filepath(self): + """Tests what get_fuzz_targets return when invalid filepath is used.""" + fuzz_targets = utils.get_fuzz_targets('not/a/valid/file/path') + self.assertFalse(fuzz_targets) + + +class ExecuteTest(unittest.TestCase): + """Tests the execute function.""" + + def test_valid_command(self): + """Tests that execute can produce valid output.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out, err, err_code = utils.execute(['ls', '.'], + location=tmp_dir, + check_result=False) + self.assertEqual(err_code, 0) + self.assertEqual(err, '') + self.assertEqual(out, '') + out, err, err_code = utils.execute(['mkdir', 'tmp'], + location=tmp_dir, + check_result=False) + self.assertEqual(err_code, 0) + self.assertEqual(err, '') + self.assertEqual(out, '') + out, err, err_code = utils.execute(['ls', '.'], + location=tmp_dir, + check_result=False) + self.assertEqual(err_code, 0) + self.assertEqual(err, '') + self.assertEqual(out, 'tmp\n') + + def test_error_command(self): + """Tests that execute can correctly surface errors.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out, err, err_code = utils.execute(['ls', 'notarealdir'], + location=tmp_dir, + check_result=False) + self.assertEqual(err_code, 2) + self.assertIsNotNone(err) + self.assertEqual(out, '') + with self.assertRaises(RuntimeError): + out, err, err_code = utils.execute(['ls', 'notarealdir'], + location=tmp_dir, + check_result=True) + + +class BinaryPrintTest(unittest.TestCase): + """Tests for utils.binary_print.""" + + @unittest.skip('Causes spurious failures because of side-effects.') + def test_string(self): # pylint: disable=no-self-use + """Tests that utils.binary_print can print a regular string.""" + # Should execute without raising any exceptions. + with mock.patch('sys.stdout.buffer.write') as mock_write: + utils.binary_print('hello') + mock_write.assert_called_with('hello\n') + + @unittest.skip('Causes spurious failures because of side-effects.') + def test_binary_string(self): # pylint: disable=no-self-use + """Tests that utils.binary_print can print a bianry string.""" + # Should execute without raising any exceptions. + with mock.patch('sys.stdout.buffer.write') as mock_write: + utils.binary_print(b'hello') + mock_write.assert_called_with(b'hello\n') + + +class CommandToStringTest(unittest.TestCase): + """Tests for command_to_string.""" + + def test_string(self): + """Tests that command_to_string returns the argument passed to it when it is + passed a string.""" + command = 'command' + self.assertEqual(utils.command_to_string(command), command) + + def test_list(self): + """Tests that command_to_string returns the correct stringwhen it is passed + a list.""" + command = ['command', 'arg1', 'arg2'] + self.assertEqual(utils.command_to_string(command), 'command arg1 arg2') + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.c new file mode 100644 index 0000000000000000000000000000000000000000..0f8a1156738014a505aeb6266f474c1a86d0abfe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.c @@ -0,0 +1,323 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Display Update Virtual Channel Extension + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "disp_main.h" +#include "../disp_common.h" + +typedef struct +{ + GENERIC_DYNVC_PLUGIN base; + + DispClientContext* context; + UINT32 MaxNumMonitors; + UINT32 MaxMonitorAreaFactorA; + UINT32 MaxMonitorAreaFactorB; +} DISP_PLUGIN; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +disp_send_display_control_monitor_layout_pdu(GENERIC_CHANNEL_CALLBACK* callback, UINT32 NumMonitors, + const DISPLAY_CONTROL_MONITOR_LAYOUT* Monitors) +{ + UINT status = 0; + wStream* s = NULL; + DISP_PLUGIN* disp = NULL; + UINT32 MonitorLayoutSize = 0; + DISPLAY_CONTROL_HEADER header = { 0 }; + + WINPR_ASSERT(callback); + WINPR_ASSERT(Monitors || (NumMonitors == 0)); + + disp = (DISP_PLUGIN*)callback->plugin; + WINPR_ASSERT(disp); + + MonitorLayoutSize = DISPLAY_CONTROL_MONITOR_LAYOUT_SIZE; + header.length = 8 + 8 + (NumMonitors * MonitorLayoutSize); + header.type = DISPLAY_CONTROL_PDU_TYPE_MONITOR_LAYOUT; + + s = Stream_New(NULL, header.length); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if ((status = disp_write_header(s, &header))) + { + WLog_ERR(TAG, "Failed to write header with error %" PRIu32 "!", status); + goto out; + } + + if (NumMonitors > disp->MaxNumMonitors) + NumMonitors = disp->MaxNumMonitors; + + Stream_Write_UINT32(s, MonitorLayoutSize); /* MonitorLayoutSize (4 bytes) */ + Stream_Write_UINT32(s, NumMonitors); /* NumMonitors (4 bytes) */ + WLog_DBG(TAG, "NumMonitors=%" PRIu32 "", NumMonitors); + + for (UINT32 index = 0; index < NumMonitors; index++) + { + DISPLAY_CONTROL_MONITOR_LAYOUT current = Monitors[index]; + current.Width -= (current.Width % 2); + + if (current.Width < 200) + current.Width = 200; + + if (current.Width > 8192) + current.Width = 8192; + + if (current.Width % 2) + current.Width++; + + if (current.Height < 200) + current.Height = 200; + + if (current.Height > 8192) + current.Height = 8192; + + Stream_Write_UINT32(s, current.Flags); /* Flags (4 bytes) */ + Stream_Write_INT32(s, current.Left); /* Left (4 bytes) */ + Stream_Write_INT32(s, current.Top); /* Top (4 bytes) */ + Stream_Write_UINT32(s, current.Width); /* Width (4 bytes) */ + Stream_Write_UINT32(s, current.Height); /* Height (4 bytes) */ + Stream_Write_UINT32(s, current.PhysicalWidth); /* PhysicalWidth (4 bytes) */ + Stream_Write_UINT32(s, current.PhysicalHeight); /* PhysicalHeight (4 bytes) */ + Stream_Write_UINT32(s, current.Orientation); /* Orientation (4 bytes) */ + Stream_Write_UINT32(s, current.DesktopScaleFactor); /* DesktopScaleFactor (4 bytes) */ + Stream_Write_UINT32(s, current.DeviceScaleFactor); /* DeviceScaleFactor (4 bytes) */ + WLog_DBG(TAG, + "\t%" PRIu32 " : Flags: 0x%08" PRIX32 " Left/Top: (%" PRId32 ",%" PRId32 + ") W/H=%" PRIu32 "x%" PRIu32 ")", + index, current.Flags, current.Left, current.Top, current.Width, current.Height); + WLog_DBG(TAG, + "\t PhysicalWidth: %" PRIu32 " PhysicalHeight: %" PRIu32 " Orientation: %" PRIu32 + "", + current.PhysicalWidth, current.PhysicalHeight, current.Orientation); + } + +out: + Stream_SealLength(s); + status = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s), + NULL); + Stream_Free(s, TRUE); + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_recv_display_control_caps_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + DISP_PLUGIN* disp = NULL; + DispClientContext* context = NULL; + UINT ret = CHANNEL_RC_OK; + + WINPR_ASSERT(callback); + WINPR_ASSERT(s); + + disp = (DISP_PLUGIN*)callback->plugin; + WINPR_ASSERT(disp); + + context = disp->context; + WINPR_ASSERT(context); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 12)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, disp->MaxNumMonitors); /* MaxNumMonitors (4 bytes) */ + Stream_Read_UINT32(s, disp->MaxMonitorAreaFactorA); /* MaxMonitorAreaFactorA (4 bytes) */ + Stream_Read_UINT32(s, disp->MaxMonitorAreaFactorB); /* MaxMonitorAreaFactorB (4 bytes) */ + + if (context->DisplayControlCaps) + ret = context->DisplayControlCaps(context, disp->MaxNumMonitors, + disp->MaxMonitorAreaFactorA, disp->MaxMonitorAreaFactorB); + + return ret; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_recv_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT32 error = 0; + DISPLAY_CONTROL_HEADER header = { 0 }; + + WINPR_ASSERT(callback); + WINPR_ASSERT(s); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return ERROR_INVALID_DATA; + + if ((error = disp_read_header(s, &header))) + { + WLog_ERR(TAG, "disp_read_header failed with error %" PRIu32 "!", error); + return error; + } + + if (!Stream_EnsureRemainingCapacity(s, header.length)) + { + WLog_ERR(TAG, "not enough remaining data"); + return ERROR_INVALID_DATA; + } + + switch (header.type) + { + case DISPLAY_CONTROL_PDU_TYPE_CAPS: + return disp_recv_display_control_caps_pdu(callback, s); + + default: + WLog_ERR(TAG, "Type %" PRIu32 " not recognized!", header.type); + return ERROR_INTERNAL_ERROR; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + return disp_recv_pdu(callback, data); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + free(pChannelCallback); + return CHANNEL_RC_OK; +} + +/** + * Channel Client Interface + */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_send_monitor_layout(DispClientContext* context, UINT32 NumMonitors, + DISPLAY_CONTROL_MONITOR_LAYOUT* Monitors) +{ + DISP_PLUGIN* disp = NULL; + GENERIC_CHANNEL_CALLBACK* callback = NULL; + + WINPR_ASSERT(context); + + disp = (DISP_PLUGIN*)context->handle; + WINPR_ASSERT(disp); + + callback = disp->base.listener_callback->channel_callback; + + return disp_send_display_control_monitor_layout_pdu(callback, NumMonitors, Monitors); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT disp_plugin_initialize(GENERIC_DYNVC_PLUGIN* base, rdpContext* rcontext, + rdpSettings* settings) +{ + DispClientContext* context = NULL; + DISP_PLUGIN* disp = (DISP_PLUGIN*)base; + + WINPR_ASSERT(disp); + disp->MaxNumMonitors = 16; + disp->MaxMonitorAreaFactorA = 8192; + disp->MaxMonitorAreaFactorB = 8192; + + context = (DispClientContext*)calloc(1, sizeof(DispClientContext)); + if (!context) + { + WLog_Print(base->log, WLOG_ERROR, "unable to allocate DispClientContext"); + return CHANNEL_RC_NO_MEMORY; + } + + context->handle = (void*)disp; + context->SendMonitorLayout = disp_send_monitor_layout; + + disp->base.iface.pInterface = disp->context = context; + + return CHANNEL_RC_OK; +} + +static void disp_plugin_terminated(GENERIC_DYNVC_PLUGIN* base) +{ + DISP_PLUGIN* disp = (DISP_PLUGIN*)base; + + WINPR_ASSERT(disp); + + free(disp->context); +} + +static const IWTSVirtualChannelCallback disp_callbacks = { disp_on_data_received, NULL, /* Open */ + disp_on_close, NULL }; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE disp_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + return freerdp_generic_DVCPluginEntry(pEntryPoints, TAG, DISP_DVC_CHANNEL_NAME, + sizeof(DISP_PLUGIN), sizeof(GENERIC_CHANNEL_CALLBACK), + &disp_callbacks, disp_plugin_initialize, + disp_plugin_terminated); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.h new file mode 100644 index 0000000000000000000000000000000000000000..d5ce4467942524a83260e9ff7c2b218fcb74486c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/client/disp_main.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Display Update Virtual Channel Extension + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_DISP_CLIENT_MAIN_H +#define FREERDP_CHANNEL_DISP_CLIENT_MAIN_H + +#include + +#include +#include +#include +#include + +#include + +#define TAG CHANNELS_TAG("disp.client") + +#endif /* FREERDP_CHANNEL_DISP_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e39f886e805503571553c6b8c0ae23ef2049240a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/CMakeLists.txt @@ -0,0 +1,25 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2019 Kobi Mizrachi +# +# 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. + +define_channel_server("disp") + +set(${MODULE_PREFIX}_SRCS disp_main.c disp_main.h ../disp_common.c ../disp_common.h) + +set(${MODULE_PREFIX}_LIBS freerdp) +include_directories(..) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/disp_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/disp_main.h new file mode 100644 index 0000000000000000000000000000000000000000..920a5087153e1e4ea7fe05fdd75b9b15dd4f695f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/disp/server/disp_main.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * RDPEDISP Virtual Channel Extension + * + * Copyright 2019 Kobi Mizrachi + * + * 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 FREERDP_CHANNEL_DISP_SERVER_MAIN_H +#define FREERDP_CHANNEL_DISP_SERVER_MAIN_H + +#include + +struct s_disp_server_private +{ + BOOL isReady; + wStream* input_stream; + HANDLE channelEvent; + HANDLE thread; + HANDLE stopEvent; + DWORD SessionId; + + void* disp_channel; +}; + +#endif /* FREERDP_CHANNEL_DISP_SERVER_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/client/drdynvc_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/client/drdynvc_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d4df8435ce9601fadd05f8c32737886523c68aaf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/client/drdynvc_main.c @@ -0,0 +1,2059 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Dynamic Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include + +#include "drdynvc_main.h" + +#define TAG CHANNELS_TAG("drdynvc.client") + +static void dvcman_channel_free(DVCMAN_CHANNEL* channel); +static UINT dvcman_channel_close(DVCMAN_CHANNEL* channel, BOOL perRequest, BOOL fromHashTableFn); +static void dvcman_free(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr); +static UINT drdynvc_write_data(drdynvcPlugin* drdynvc, UINT32 ChannelId, const BYTE* data, + UINT32 dataSize, BOOL* close); +static UINT drdynvc_send(drdynvcPlugin* drdynvc, wStream* s); + +static void dvcman_wtslistener_free(DVCMAN_LISTENER* listener) +{ + if (listener) + free(listener->channel_name); + free(listener); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_get_configuration(IWTSListener* pListener, void** ppPropertyBag) +{ + WINPR_ASSERT(ppPropertyBag); + WINPR_UNUSED(pListener); + *ppPropertyBag = NULL; + return ERROR_INTERNAL_ERROR; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_create_listener(IWTSVirtualChannelManager* pChannelMgr, + const char* pszChannelName, ULONG ulFlags, + IWTSListenerCallback* pListenerCallback, + IWTSListener** ppListener) +{ + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + DVCMAN_LISTENER* listener = NULL; + + WINPR_ASSERT(dvcman); + WLog_DBG(TAG, "create_listener: %" PRIuz ".%s.", HashTable_Count(dvcman->listeners) + 1, + pszChannelName); + listener = (DVCMAN_LISTENER*)calloc(1, sizeof(DVCMAN_LISTENER)); + + if (!listener) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + listener->iface.GetConfiguration = dvcman_get_configuration; + listener->iface.pInterface = NULL; + listener->dvcman = dvcman; + listener->channel_name = _strdup(pszChannelName); + + if (!listener->channel_name) + { + WLog_ERR(TAG, "_strdup failed!"); + dvcman_wtslistener_free(listener); + return CHANNEL_RC_NO_MEMORY; + } + + listener->flags = ulFlags; + listener->listener_callback = pListenerCallback; + + if (ppListener) + *ppListener = (IWTSListener*)listener; + + if (!HashTable_Insert(dvcman->listeners, listener->channel_name, listener)) + { + dvcman_wtslistener_free(listener); + return ERROR_INTERNAL_ERROR; + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership of listener + return CHANNEL_RC_OK; +} + +static UINT dvcman_destroy_listener(IWTSVirtualChannelManager* pChannelMgr, IWTSListener* pListener) +{ + DVCMAN_LISTENER* listener = (DVCMAN_LISTENER*)pListener; + + WINPR_UNUSED(pChannelMgr); + + if (listener) + { + DVCMAN* dvcman = listener->dvcman; + if (dvcman) + HashTable_Remove(dvcman->listeners, listener->channel_name); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_register_plugin(IDRDYNVC_ENTRY_POINTS* pEntryPoints, const char* name, + IWTSPlugin* pPlugin) +{ + WINPR_ASSERT(pEntryPoints); + DVCMAN* dvcman = ((DVCMAN_ENTRY_POINTS*)pEntryPoints)->dvcman; + + WINPR_ASSERT(dvcman); + if (!ArrayList_Append(dvcman->plugin_names, name)) + return ERROR_INTERNAL_ERROR; + if (!ArrayList_Append(dvcman->plugins, pPlugin)) + return ERROR_INTERNAL_ERROR; + + WLog_DBG(TAG, "register_plugin: num_plugins %" PRIuz, ArrayList_Count(dvcman->plugins)); + return CHANNEL_RC_OK; +} + +static IWTSPlugin* dvcman_get_plugin(IDRDYNVC_ENTRY_POINTS* pEntryPoints, const char* name) +{ + IWTSPlugin* plugin = NULL; + size_t nc = 0; + size_t pc = 0; + WINPR_ASSERT(pEntryPoints); + DVCMAN* dvcman = ((DVCMAN_ENTRY_POINTS*)pEntryPoints)->dvcman; + if (!dvcman || !pEntryPoints || !name) + return NULL; + + nc = ArrayList_Count(dvcman->plugin_names); + pc = ArrayList_Count(dvcman->plugins); + if (nc != pc) + return NULL; + + ArrayList_Lock(dvcman->plugin_names); + ArrayList_Lock(dvcman->plugins); + for (size_t i = 0; i < pc; i++) + { + const char* cur = ArrayList_GetItem(dvcman->plugin_names, i); + if (strcmp(cur, name) == 0) + { + plugin = ArrayList_GetItem(dvcman->plugins, i); + break; + } + } + ArrayList_Unlock(dvcman->plugin_names); + ArrayList_Unlock(dvcman->plugins); + return plugin; +} + +static const ADDIN_ARGV* dvcman_get_plugin_data(IDRDYNVC_ENTRY_POINTS* pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + return ((DVCMAN_ENTRY_POINTS*)pEntryPoints)->args; +} + +static rdpContext* dvcman_get_rdp_context(IDRDYNVC_ENTRY_POINTS* pEntryPoints) +{ + DVCMAN_ENTRY_POINTS* entry = (DVCMAN_ENTRY_POINTS*)pEntryPoints; + WINPR_ASSERT(entry); + return entry->context; +} + +static rdpSettings* dvcman_get_rdp_settings(IDRDYNVC_ENTRY_POINTS* pEntryPoints) +{ + rdpContext* context = dvcman_get_rdp_context(pEntryPoints); + WINPR_ASSERT(context); + + return context->settings; +} + +static UINT32 dvcman_get_channel_id(IWTSVirtualChannel* channel) +{ + DVCMAN_CHANNEL* dvc = (DVCMAN_CHANNEL*)channel; + WINPR_ASSERT(dvc); + return dvc->channel_id; +} + +static const char* dvcman_get_channel_name(IWTSVirtualChannel* channel) +{ + DVCMAN_CHANNEL* dvc = (DVCMAN_CHANNEL*)channel; + WINPR_ASSERT(dvc); + return dvc->channel_name; +} + +static DVCMAN_CHANNEL* dvcman_get_channel_by_id(IWTSVirtualChannelManager* pChannelMgr, + UINT32 ChannelId, BOOL doRef) +{ + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + DVCMAN_CHANNEL* dvcChannel = NULL; + + WINPR_ASSERT(dvcman); + HashTable_Lock(dvcman->channelsById); + dvcChannel = HashTable_GetItemValue(dvcman->channelsById, &ChannelId); + if (dvcChannel) + { + if (doRef) + InterlockedIncrement(&dvcChannel->refCounter); + } + + HashTable_Unlock(dvcman->channelsById); + return dvcChannel; +} + +static IWTSVirtualChannel* dvcman_find_channel_by_id(IWTSVirtualChannelManager* pChannelMgr, + UINT32 ChannelId) +{ + DVCMAN_CHANNEL* channel = dvcman_get_channel_by_id(pChannelMgr, ChannelId, FALSE); + if (!channel) + return NULL; + + return &channel->iface; +} + +static void dvcman_plugin_terminate(void* plugin) +{ + IWTSPlugin* pPlugin = plugin; + + WINPR_ASSERT(pPlugin); + UINT error = IFCALLRESULT(CHANNEL_RC_OK, pPlugin->Terminated, pPlugin); + if (error != CHANNEL_RC_OK) + WLog_ERR(TAG, "Terminated failed with error %" PRIu32 "!", error); +} + +static void wts_listener_free(void* arg) +{ + DVCMAN_LISTENER* listener = (DVCMAN_LISTENER*)arg; + dvcman_wtslistener_free(listener); +} + +static BOOL channelIdMatch(const void* k1, const void* k2) +{ + WINPR_ASSERT(k1); + WINPR_ASSERT(k2); + return *((const UINT32*)k1) == *((const UINT32*)k2); +} + +static UINT32 channelIdHash(const void* id) +{ + WINPR_ASSERT(id); + return *((const UINT32*)id); +} + +static void channelByIdCleanerFn(void* value) +{ + DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*)value; + if (channel) + { + dvcman_channel_close(channel, FALSE, TRUE); + dvcman_channel_free(channel); + } +} + +static IWTSVirtualChannelManager* dvcman_new(drdynvcPlugin* plugin) +{ + wObject* obj = NULL; + DVCMAN* dvcman = (DVCMAN*)calloc(1, sizeof(DVCMAN)); + + if (!dvcman) + return NULL; + + dvcman->iface.CreateListener = dvcman_create_listener; + dvcman->iface.DestroyListener = dvcman_destroy_listener; + dvcman->iface.FindChannelById = dvcman_find_channel_by_id; + dvcman->iface.GetChannelId = dvcman_get_channel_id; + dvcman->iface.GetChannelName = dvcman_get_channel_name; + dvcman->drdynvc = plugin; + dvcman->channelsById = HashTable_New(TRUE); + + if (!dvcman->channelsById) + goto fail; + + HashTable_SetHashFunction(dvcman->channelsById, channelIdHash); + obj = HashTable_KeyObject(dvcman->channelsById); + WINPR_ASSERT(obj); + obj->fnObjectEquals = channelIdMatch; + + obj = HashTable_ValueObject(dvcman->channelsById); + WINPR_ASSERT(obj); + obj->fnObjectFree = channelByIdCleanerFn; + + dvcman->pool = StreamPool_New(TRUE, 10); + if (!dvcman->pool) + goto fail; + + dvcman->listeners = HashTable_New(TRUE); + if (!dvcman->listeners) + goto fail; + HashTable_SetHashFunction(dvcman->listeners, HashTable_StringHash); + + obj = HashTable_KeyObject(dvcman->listeners); + obj->fnObjectEquals = HashTable_StringCompare; + + obj = HashTable_ValueObject(dvcman->listeners); + obj->fnObjectFree = wts_listener_free; + + dvcman->plugin_names = ArrayList_New(TRUE); + if (!dvcman->plugin_names) + goto fail; + obj = ArrayList_Object(dvcman->plugin_names); + obj->fnObjectNew = winpr_ObjectStringClone; + obj->fnObjectFree = winpr_ObjectStringFree; + + dvcman->plugins = ArrayList_New(TRUE); + if (!dvcman->plugins) + goto fail; + obj = ArrayList_Object(dvcman->plugins); + obj->fnObjectFree = dvcman_plugin_terminate; + return &dvcman->iface; +fail: + dvcman_free(plugin, &dvcman->iface); + return NULL; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_load_addin(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr, + const ADDIN_ARGV* args, rdpContext* context) +{ + WINPR_ASSERT(drdynvc); + WINPR_ASSERT(pChannelMgr); + WINPR_ASSERT(args); + WINPR_ASSERT(context); + + WLog_Print(drdynvc->log, WLOG_INFO, "Loading Dynamic Virtual Channel %s", args->argv[0]); + + PVIRTUALCHANNELENTRY pvce = + freerdp_load_channel_addin_entry(args->argv[0], NULL, NULL, FREERDP_ADDIN_CHANNEL_DYNAMIC); + PDVC_PLUGIN_ENTRY pDVCPluginEntry = WINPR_FUNC_PTR_CAST(pvce, PDVC_PLUGIN_ENTRY); + + if (pDVCPluginEntry) + { + DVCMAN_ENTRY_POINTS entryPoints = { 0 }; + + entryPoints.iface.RegisterPlugin = dvcman_register_plugin; + entryPoints.iface.GetPlugin = dvcman_get_plugin; + entryPoints.iface.GetPluginData = dvcman_get_plugin_data; + entryPoints.iface.GetRdpSettings = dvcman_get_rdp_settings; + entryPoints.iface.GetRdpContext = dvcman_get_rdp_context; + entryPoints.dvcman = (DVCMAN*)pChannelMgr; + entryPoints.args = args; + entryPoints.context = context; + return pDVCPluginEntry(&entryPoints.iface); + } + + return ERROR_INVALID_FUNCTION; +} + +static void dvcman_channel_free(DVCMAN_CHANNEL* channel) +{ + if (!channel) + return; + + if (channel->dvc_data) + Stream_Release(channel->dvc_data); + + DeleteCriticalSection(&(channel->lock)); + free(channel->channel_name); + free(channel); +} + +static void dvcman_channel_unref(DVCMAN_CHANNEL* channel) +{ + WINPR_ASSERT(channel); + if (InterlockedDecrement(&channel->refCounter)) + return; + + DVCMAN* dvcman = channel->dvcman; + if (dvcman) + HashTable_Remove(dvcman->channelsById, &channel->channel_id); +} + +static UINT dvcchannel_send_close(DVCMAN_CHANNEL* channel) +{ + WINPR_ASSERT(channel); + DVCMAN* dvcman = channel->dvcman; + drdynvcPlugin* drdynvc = dvcman->drdynvc; + wStream* s = StreamPool_Take(dvcman->pool, 5); + + if (!s) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT8(s, (CLOSE_REQUEST_PDU << 4) | 0x02); + Stream_Write_UINT32(s, channel->channel_id); + return drdynvc_send(drdynvc, s); +} + +static void check_open_close_receive(DVCMAN_CHANNEL* channel) +{ + WINPR_ASSERT(channel); + + IWTSVirtualChannelCallback* cb = channel->channel_callback; + const char* name = channel->channel_name; + const UINT32 id = channel->channel_id; + + WINPR_ASSERT(cb); + if (cb->OnOpen || cb->OnClose) + { + if (!cb->OnOpen || !cb->OnClose) + WLog_WARN(TAG, "{%s:%" PRIu32 "} OnOpen=%p, OnClose=%p", name, id, cb->OnOpen, + cb->OnClose); + } +} + +static UINT dvcman_call_on_receive(DVCMAN_CHANNEL* channel, wStream* data) +{ + WINPR_ASSERT(channel); + WINPR_ASSERT(data); + + IWTSVirtualChannelCallback* cb = channel->channel_callback; + WINPR_ASSERT(cb); + + check_open_close_receive(channel); + WINPR_ASSERT(cb->OnDataReceived); + return cb->OnDataReceived(cb, data); +} + +static UINT dvcman_channel_close(DVCMAN_CHANNEL* channel, BOOL perRequest, BOOL fromHashTableFn) +{ + UINT error = CHANNEL_RC_OK; + DrdynvcClientContext* context = NULL; + + WINPR_ASSERT(channel); + switch (channel->state) + { + case DVC_CHANNEL_INIT: + break; + case DVC_CHANNEL_RUNNING: + if (channel->dvcman) + { + drdynvcPlugin* drdynvc = channel->dvcman->drdynvc; + WINPR_ASSERT(drdynvc); + context = drdynvc->context; + if (perRequest) + WLog_Print(drdynvc->log, WLOG_DEBUG, "sending close confirm for '%s'", + channel->channel_name); + + error = dvcchannel_send_close(channel); + if (error != CHANNEL_RC_OK) + { + const char* msg = "error when sending close confirm for '%s'"; + if (perRequest) + msg = "error when sending closeRequest for '%s'"; + + WLog_Print(drdynvc->log, WLOG_DEBUG, msg, channel->channel_name); + } + } + + channel->state = DVC_CHANNEL_CLOSED; + + IWTSVirtualChannelCallback* cb = channel->channel_callback; + if (cb) + { + check_open_close_receive(channel); + IFCALL(cb->OnClose, cb); + } + + channel->channel_callback = NULL; + + if (channel->dvcman && channel->dvcman->drdynvc) + { + if (context) + { + IFCALLRET(context->OnChannelDisconnected, error, context, channel->channel_name, + channel->pInterface); + } + } + + if (!fromHashTableFn) + dvcman_channel_unref(channel); + break; + case DVC_CHANNEL_CLOSED: + break; + default: + break; + } + + return error; +} + +static DVCMAN_CHANNEL* dvcman_channel_new(drdynvcPlugin* drdynvc, + IWTSVirtualChannelManager* pChannelMgr, UINT32 ChannelId, + const char* ChannelName) +{ + DVCMAN_CHANNEL* channel = NULL; + + WINPR_ASSERT(drdynvc); + WINPR_ASSERT(pChannelMgr); + channel = (DVCMAN_CHANNEL*)calloc(1, sizeof(DVCMAN_CHANNEL)); + + if (!channel) + return NULL; + + channel->dvcman = (DVCMAN*)pChannelMgr; + channel->channel_id = ChannelId; + channel->refCounter = 1; + channel->state = DVC_CHANNEL_INIT; + channel->channel_name = _strdup(ChannelName); + + if (!channel->channel_name) + goto fail; + + if (!InitializeCriticalSectionEx(&(channel->lock), 0, 0)) + goto fail; + + return channel; +fail: + dvcman_channel_free(channel); + return NULL; +} + +static void dvcman_clear(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr) +{ + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + + WINPR_ASSERT(dvcman); + WINPR_UNUSED(drdynvc); + + HashTable_Clear(dvcman->channelsById); + ArrayList_Clear(dvcman->plugins); + ArrayList_Clear(dvcman->plugin_names); + HashTable_Clear(dvcman->listeners); +} +static void dvcman_free(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr) +{ + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + + WINPR_ASSERT(dvcman); + WINPR_UNUSED(drdynvc); + + HashTable_Free(dvcman->channelsById); + ArrayList_Free(dvcman->plugins); + ArrayList_Free(dvcman->plugin_names); + HashTable_Free(dvcman->listeners); + + StreamPool_Free(dvcman->pool); + free(dvcman); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_init(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr) +{ + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(dvcman); + ArrayList_Lock(dvcman->plugins); + for (size_t i = 0; i < ArrayList_Count(dvcman->plugins); i++) + { + IWTSPlugin* pPlugin = ArrayList_GetItem(dvcman->plugins, i); + + error = IFCALLRESULT(CHANNEL_RC_OK, pPlugin->Initialize, pPlugin, pChannelMgr); + if (error != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "Initialize failed with error %" PRIu32 "!", + error); + goto fail; + } + } + +fail: + ArrayList_Unlock(dvcman->plugins); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_write_channel(IWTSVirtualChannel* pChannel, ULONG cbSize, const BYTE* pBuffer, + void* pReserved) +{ + BOOL close = FALSE; + UINT status = 0; + DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*)pChannel; + + WINPR_UNUSED(pReserved); + if (!channel || !channel->dvcman) + return CHANNEL_RC_BAD_CHANNEL; + + EnterCriticalSection(&(channel->lock)); + status = + drdynvc_write_data(channel->dvcman->drdynvc, channel->channel_id, pBuffer, cbSize, &close); + LeaveCriticalSection(&(channel->lock)); + /* Close delayed, it removes the channel struct */ + if (close) + dvcman_channel_close(channel, FALSE, FALSE); + + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_close_channel_iface(IWTSVirtualChannel* pChannel) +{ + DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*)pChannel; + + if (!channel) + return CHANNEL_RC_BAD_CHANNEL; + + WLog_DBG(TAG, "close_channel_iface: id=%" PRIu32 "", channel->channel_id); + return dvcman_channel_close(channel, FALSE, FALSE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static DVCMAN_CHANNEL* dvcman_create_channel(drdynvcPlugin* drdynvc, + IWTSVirtualChannelManager* pChannelMgr, + UINT32 ChannelId, const char* ChannelName, UINT* res) +{ + BOOL bAccept = 0; + DVCMAN_CHANNEL* channel = NULL; + DrdynvcClientContext* context = NULL; + DVCMAN* dvcman = (DVCMAN*)pChannelMgr; + DVCMAN_LISTENER* listener = NULL; + IWTSVirtualChannelCallback* pCallback = NULL; + + WINPR_ASSERT(dvcman); + WINPR_ASSERT(res); + + HashTable_Lock(dvcman->listeners); + listener = (DVCMAN_LISTENER*)HashTable_GetItemValue(dvcman->listeners, ChannelName); + if (!listener) + { + *res = ERROR_NOT_FOUND; + goto out; + } + + channel = dvcman_get_channel_by_id(pChannelMgr, ChannelId, FALSE); + if (channel) + { + switch (channel->state) + { + case DVC_CHANNEL_RUNNING: + WLog_Print(drdynvc->log, WLOG_ERROR, + "Protocol error: Duplicated ChannelId %" PRIu32 " (%s)!", ChannelId, + ChannelName); + *res = CHANNEL_RC_ALREADY_OPEN; + goto out; + + case DVC_CHANNEL_CLOSED: + case DVC_CHANNEL_INIT: + default: + WLog_Print(drdynvc->log, WLOG_ERROR, "not expecting a createChannel from state %d", + channel->state); + *res = CHANNEL_RC_INITIALIZATION_ERROR; + goto out; + } + } + else + { + if (!(channel = dvcman_channel_new(drdynvc, pChannelMgr, ChannelId, ChannelName))) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_channel_new failed!"); + *res = CHANNEL_RC_NO_MEMORY; + goto out; + } + } + + if (!HashTable_Insert(dvcman->channelsById, &channel->channel_id, channel)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "unable to register channel in our channel list"); + *res = ERROR_INTERNAL_ERROR; + dvcman_channel_free(channel); + channel = NULL; + goto out; + } + + channel->iface.Write = dvcman_write_channel; + channel->iface.Close = dvcman_close_channel_iface; + bAccept = TRUE; + + *res = listener->listener_callback->OnNewChannelConnection( + listener->listener_callback, &channel->iface, NULL, &bAccept, &pCallback); + + if (*res != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, + "OnNewChannelConnection failed with error %" PRIu32 "!", *res); + *res = ERROR_INTERNAL_ERROR; + dvcman_channel_unref(channel); + goto out; + } + + if (!bAccept) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "OnNewChannelConnection returned with bAccept FALSE!"); + *res = ERROR_INTERNAL_ERROR; + dvcman_channel_unref(channel); + channel = NULL; + goto out; + } + + WLog_Print(drdynvc->log, WLOG_DEBUG, "listener %s created new channel %" PRIu32 "", + listener->channel_name, channel->channel_id); + channel->state = DVC_CHANNEL_RUNNING; + channel->channel_callback = pCallback; + channel->pInterface = listener->iface.pInterface; + context = dvcman->drdynvc->context; + + IFCALLRET(context->OnChannelConnected, *res, context, ChannelName, listener->iface.pInterface); + if (*res != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, + "context.OnChannelConnected failed with error %" PRIu32 "", *res); + } + +out: + HashTable_Unlock(dvcman->listeners); + + return channel; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_open_channel(drdynvcPlugin* drdynvc, DVCMAN_CHANNEL* channel) +{ + IWTSVirtualChannelCallback* pCallback = NULL; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(drdynvc); + WINPR_ASSERT(channel); + if (channel->state == DVC_CHANNEL_RUNNING) + { + pCallback = channel->channel_callback; + + if (pCallback->OnOpen) + { + check_open_close_receive(channel); + error = pCallback->OnOpen(pCallback); + if (error) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "OnOpen failed with error %" PRIu32 "!", + error); + goto out; + } + } + + WLog_Print(drdynvc->log, WLOG_DEBUG, "open_channel: ChannelId %" PRIu32 "", + channel->channel_id); + } + +out: + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_receive_channel_data_first(DVCMAN_CHANNEL* channel, UINT32 length) +{ + WINPR_ASSERT(channel); + WINPR_ASSERT(channel->dvcman); + if (channel->dvc_data) + Stream_Release(channel->dvc_data); + + channel->dvc_data = StreamPool_Take(channel->dvcman->pool, length); + + if (!channel->dvc_data) + { + drdynvcPlugin* drdynvc = channel->dvcman->drdynvc; + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + channel->dvc_data_length = length; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT dvcman_receive_channel_data(DVCMAN_CHANNEL* channel, wStream* data, + UINT32 ThreadingFlags) +{ + UINT status = CHANNEL_RC_OK; + size_t dataSize = Stream_GetRemainingLength(data); + + WINPR_ASSERT(channel); + WINPR_ASSERT(channel->dvcman); + if (channel->dvc_data) + { + drdynvcPlugin* drdynvc = channel->dvcman->drdynvc; + + /* Fragmented data */ + if (Stream_GetPosition(channel->dvc_data) + dataSize > channel->dvc_data_length) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!"); + Stream_Release(channel->dvc_data); + channel->dvc_data = NULL; + status = ERROR_INVALID_DATA; + goto out; + } + + Stream_Copy(data, channel->dvc_data, dataSize); + + if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length) + { + Stream_SealLength(channel->dvc_data); + Stream_SetPosition(channel->dvc_data, 0); + + status = dvcman_call_on_receive(channel, channel->dvc_data); + Stream_Release(channel->dvc_data); + channel->dvc_data = NULL; + } + } + else + status = dvcman_call_on_receive(channel, data); + +out: + return status; +} + +static UINT8 drdynvc_write_variable_uint(wStream* s, UINT32 val) +{ + UINT8 cb = 0; + + if (val <= 0xFF) + { + cb = 0; + Stream_Write_UINT8(s, (UINT8)val); + } + else if (val <= 0xFFFF) + { + cb = 1; + Stream_Write_UINT16(s, (UINT16)val); + } + else + { + cb = 2; + Stream_Write_UINT32(s, val); + } + + return cb; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_send(drdynvcPlugin* drdynvc, wStream* s) +{ + UINT status = 0; + + if (!drdynvc) + status = CHANNEL_RC_BAD_CHANNEL_HANDLE; + else + { + WINPR_ASSERT(drdynvc->channelEntryPoints.pVirtualChannelWriteEx); + status = drdynvc->channelEntryPoints.pVirtualChannelWriteEx( + drdynvc->InitHandle, drdynvc->OpenHandle, Stream_Buffer(s), + (UINT32)Stream_GetPosition(s), s); + } + + switch (status) + { + case CHANNEL_RC_OK: + return CHANNEL_RC_OK; + + case CHANNEL_RC_NOT_CONNECTED: + Stream_Release(s); + return CHANNEL_RC_OK; + + case CHANNEL_RC_BAD_CHANNEL_HANDLE: + Stream_Release(s); + WLog_ERR(TAG, "VirtualChannelWriteEx failed with CHANNEL_RC_BAD_CHANNEL_HANDLE"); + return status; + + default: + Stream_Release(s); + WLog_Print(drdynvc->log, WLOG_ERROR, + "VirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + return status; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_write_data(drdynvcPlugin* drdynvc, UINT32 ChannelId, const BYTE* data, + UINT32 dataSize, BOOL* close) +{ + wStream* data_out = NULL; + size_t pos = 0; + UINT8 cbChId = 0; + UINT8 cbLen = 0; + unsigned long chunkLength = 0; + UINT status = CHANNEL_RC_BAD_INIT_HANDLE; + DVCMAN* dvcman = NULL; + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + dvcman = (DVCMAN*)drdynvc->channel_mgr; + WINPR_ASSERT(dvcman); + + WLog_Print(drdynvc->log, WLOG_TRACE, "write_data: ChannelId=%" PRIu32 " size=%" PRIu32 "", + ChannelId, dataSize); + data_out = StreamPool_Take(dvcman->pool, CHANNEL_CHUNK_LENGTH); + + if (!data_out) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_SetPosition(data_out, 1); + cbChId = drdynvc_write_variable_uint(data_out, ChannelId); + pos = Stream_GetPosition(data_out); + + if (dataSize == 0) + { + /* TODO: shall treat that case with write(0) that do a close */ + *close = TRUE; + Stream_Release(data_out); + } + else if (dataSize <= CHANNEL_CHUNK_LENGTH - pos) + { + Stream_SetPosition(data_out, 0); + Stream_Write_UINT8(data_out, (DATA_PDU << 4) | cbChId); + Stream_SetPosition(data_out, pos); + Stream_Write(data_out, data, dataSize); + status = drdynvc_send(drdynvc, data_out); + } + else + { + /* Fragment the data */ + cbLen = drdynvc_write_variable_uint(data_out, dataSize); + pos = Stream_GetPosition(data_out); + Stream_SetPosition(data_out, 0); + + const INT32 pdu = (DATA_FIRST_PDU << 4) | cbChId | (cbLen << 2); + Stream_Write_UINT8(data_out, WINPR_ASSERTING_INT_CAST(UINT8, pdu)); + Stream_SetPosition(data_out, pos); + chunkLength = CHANNEL_CHUNK_LENGTH - pos; + Stream_Write(data_out, data, chunkLength); + data += chunkLength; + dataSize -= chunkLength; + status = drdynvc_send(drdynvc, data_out); + + while (status == CHANNEL_RC_OK && dataSize > 0) + { + data_out = StreamPool_Take(dvcman->pool, CHANNEL_CHUNK_LENGTH); + + if (!data_out) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_SetPosition(data_out, 1); + cbChId = drdynvc_write_variable_uint(data_out, ChannelId); + pos = Stream_GetPosition(data_out); + Stream_SetPosition(data_out, 0); + Stream_Write_UINT8(data_out, (DATA_PDU << 4) | cbChId); + Stream_SetPosition(data_out, pos); + chunkLength = dataSize; + + if (chunkLength > CHANNEL_CHUNK_LENGTH - pos) + chunkLength = CHANNEL_CHUNK_LENGTH - pos; + + Stream_Write(data_out, data, chunkLength); + data += chunkLength; + dataSize -= chunkLength; + status = drdynvc_send(drdynvc, data_out); + } + } + + if (status != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + return status; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_send_capability_response(drdynvcPlugin* drdynvc) +{ + UINT status = 0; + wStream* s = NULL; + DVCMAN* dvcman = NULL; + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + dvcman = (DVCMAN*)drdynvc->channel_mgr; + WINPR_ASSERT(dvcman); + + WLog_Print(drdynvc->log, WLOG_TRACE, "capability_response"); + s = StreamPool_Take(dvcman->pool, 4); + + if (!s) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_Ndrdynvc_write_variable_uintew failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, 0x0050); /* Cmd+Sp+cbChId+Pad. Note: MSTSC sends 0x005c */ + Stream_Write_UINT16(s, drdynvc->version); + status = drdynvc_send(drdynvc, s); + + if (status != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + } + + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_process_capability_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, + wStream* s) +{ + UINT status = 0; + + if (!drdynvc) + return CHANNEL_RC_BAD_INIT_HANDLE; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 3)) + return ERROR_INVALID_DATA; + + WLog_Print(drdynvc->log, WLOG_TRACE, "capability_request Sp=%d cbChId=%d", Sp, cbChId); + Stream_Seek(s, 1); /* pad */ + Stream_Read_UINT16(s, drdynvc->version); + + /* RDP8 servers offer version 3, though Microsoft forgot to document it + * in their early documents. It behaves the same as version 2. + */ + if ((drdynvc->version == 2) || (drdynvc->version == 3)) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, drdynvc->PriorityCharge0); + Stream_Read_UINT16(s, drdynvc->PriorityCharge1); + Stream_Read_UINT16(s, drdynvc->PriorityCharge2); + Stream_Read_UINT16(s, drdynvc->PriorityCharge3); + } + + status = drdynvc_send_capability_response(drdynvc); + drdynvc->state = DRDYNVC_STATE_READY; + return status; +} + +static UINT32 drdynvc_cblen_to_bytes(int cbLen) +{ + switch (cbLen) + { + case 0: + return 1; + + case 1: + return 2; + + default: + return 4; + } +} + +static UINT32 drdynvc_read_variable_uint(wStream* s, int cbLen) +{ + UINT32 val = 0; + + switch (cbLen) + { + case 0: + Stream_Read_UINT8(s, val); + break; + + case 1: + Stream_Read_UINT16(s, val); + break; + + default: + Stream_Read_UINT32(s, val); + break; + } + + return val; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, UINT8 Sp, UINT8 cbChId, + wStream* s) +{ + UINT status = 0; + wStream* data_out = NULL; + UINT channel_status = 0; + DVCMAN* dvcman = NULL; + DVCMAN_CHANNEL* channel = NULL; + INT32 retStatus = 0; + + WINPR_UNUSED(Sp); + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + dvcman = (DVCMAN*)drdynvc->channel_mgr; + WINPR_ASSERT(dvcman); + + if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES) + { + /** + * For some reason the server does not always send the + * capabilities pdu as it should. When this happens, + * send a capabilities response. + */ + drdynvc->version = 3; + + if ((status = drdynvc_send_capability_response(drdynvc))) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!"); + return status; + } + + drdynvc->state = DRDYNVC_STATE_READY; + } + + if (!Stream_CheckAndLogRequiredLength(TAG, s, drdynvc_cblen_to_bytes(cbChId))) + return ERROR_INVALID_DATA; + + const UINT32 ChannelId = drdynvc_read_variable_uint(s, cbChId); + const size_t pos = Stream_GetPosition(s); + const char* name = Stream_ConstPointer(s); + const size_t length = Stream_GetRemainingLength(s); + + if (strnlen(name, length) >= length) + return ERROR_INVALID_DATA; + + WLog_Print(drdynvc->log, WLOG_DEBUG, + "process_create_request: ChannelId=%" PRIu32 " ChannelName=%s", ChannelId, name); + + data_out = StreamPool_Take(dvcman->pool, pos + 4); + if (!data_out) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT8(data_out, (CREATE_REQUEST_PDU << 4) | cbChId); + Stream_SetPosition(s, 1); + Stream_Copy(s, data_out, pos - 1); + + channel = + dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId, name, &channel_status); + switch (channel_status) + { + case CHANNEL_RC_OK: + WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created"); + retStatus = 0; + break; + case CHANNEL_RC_NO_MEMORY: + WLog_Print(drdynvc->log, WLOG_DEBUG, "not enough memory for channel creation"); + retStatus = STATUS_NO_MEMORY; + break; + case ERROR_NOT_FOUND: + WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener for '%s'", name); + retStatus = STATUS_NOT_FOUND; /* same code used by mstsc, STATUS_UNSUCCESSFUL */ + break; + default: + WLog_Print(drdynvc->log, WLOG_DEBUG, "channel creation error"); + retStatus = STATUS_UNSUCCESSFUL; /* same code used by mstsc, STATUS_UNSUCCESSFUL */ + break; + } + Stream_Write_INT32(data_out, retStatus); + + status = drdynvc_send(drdynvc, data_out); + if (status != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + dvcman_channel_unref(channel); + return status; + } + + if (channel_status == CHANNEL_RC_OK) + { + if ((status = dvcman_open_channel(drdynvc, channel))) + { + WLog_Print(drdynvc->log, WLOG_ERROR, + "dvcman_open_channel failed with error %" PRIu32 "!", status); + return status; + } + } + + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s, + UINT32 ThreadingFlags) +{ + UINT status = CHANNEL_RC_OK; + UINT32 Length = 0; + UINT32 ChannelId = 0; + DVCMAN_CHANNEL* channel = NULL; + + WINPR_ASSERT(drdynvc); + if (!Stream_CheckAndLogRequiredLength( + TAG, s, drdynvc_cblen_to_bytes(cbChId) + drdynvc_cblen_to_bytes(Sp))) + return ERROR_INVALID_DATA; + + ChannelId = drdynvc_read_variable_uint(s, cbChId); + Length = drdynvc_read_variable_uint(s, Sp); + WLog_Print(drdynvc->log, WLOG_TRACE, + "process_data_first: Sp=%d cbChId=%d, ChannelId=%" PRIu32 " Length=%" PRIu32 "", Sp, + cbChId, ChannelId, Length); + + channel = dvcman_get_channel_by_id(drdynvc->channel_mgr, ChannelId, TRUE); + if (!channel) + { + /** + * Windows Server 2012 R2 can send some messages over + * Microsoft::Windows::RDS::Geometry::v08.01 even if the dynamic virtual channel wasn't + * registered on our side. Ignoring it works. + */ + WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %" PRIu32 " not found!", ChannelId); + return CHANNEL_RC_OK; + } + + if (channel->state != DVC_CHANNEL_RUNNING) + goto out; + + status = dvcman_receive_channel_data_first(channel, Length); + + if (status == CHANNEL_RC_OK) + status = dvcman_receive_channel_data(channel, s, ThreadingFlags); + + if (status != CHANNEL_RC_OK) + status = dvcman_channel_close(channel, FALSE, FALSE); + +out: + dvcman_channel_unref(channel); + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s, + UINT32 ThreadingFlags) +{ + UINT32 ChannelId = 0; + DVCMAN_CHANNEL* channel = NULL; + UINT status = CHANNEL_RC_OK; + + WINPR_ASSERT(drdynvc); + if (!Stream_CheckAndLogRequiredLength(TAG, s, drdynvc_cblen_to_bytes(cbChId))) + return ERROR_INVALID_DATA; + + ChannelId = drdynvc_read_variable_uint(s, cbChId); + WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%" PRIu32 "", Sp, + cbChId, ChannelId); + + channel = dvcman_get_channel_by_id(drdynvc->channel_mgr, ChannelId, TRUE); + if (!channel) + { + /** + * Windows Server 2012 R2 can send some messages over + * Microsoft::Windows::RDS::Geometry::v08.01 even if the dynamic virtual channel wasn't + * registered on our side. Ignoring it works. + */ + WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %" PRIu32 " not found!", ChannelId); + return CHANNEL_RC_OK; + } + + if (channel->state != DVC_CHANNEL_RUNNING) + goto out; + + status = dvcman_receive_channel_data(channel, s, ThreadingFlags); + if (status != CHANNEL_RC_OK) + status = dvcman_channel_close(channel, FALSE, FALSE); + +out: + dvcman_channel_unref(channel); + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) +{ + UINT32 ChannelId = 0; + DVCMAN_CHANNEL* channel = NULL; + + WINPR_ASSERT(drdynvc); + if (!Stream_CheckAndLogRequiredLength(TAG, s, drdynvc_cblen_to_bytes(cbChId))) + return ERROR_INVALID_DATA; + + ChannelId = drdynvc_read_variable_uint(s, cbChId); + WLog_Print(drdynvc->log, WLOG_DEBUG, + "process_close_request: Sp=%d cbChId=%d, ChannelId=%" PRIu32 "", Sp, cbChId, + ChannelId); + + channel = dvcman_get_channel_by_id(drdynvc->channel_mgr, ChannelId, TRUE); + if (!channel) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_request channel %" PRIu32 " not present", + ChannelId); + return CHANNEL_RC_OK; + } + + dvcman_channel_close(channel, TRUE, FALSE); + dvcman_channel_unref(channel); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_order_recv(drdynvcPlugin* drdynvc, wStream* s, UINT32 ThreadingFlags) +{ + UINT8 value = 0; + + WINPR_ASSERT(drdynvc); + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, value); + const UINT8 Cmd = (value & 0xf0) >> 4; + const UINT8 Sp = (value & 0x0c) >> 2; + const UINT8 cbChId = (value & 0x03) >> 0; + WLog_Print(drdynvc->log, WLOG_TRACE, "order_recv: Cmd=%s, Sp=%" PRIu8 " cbChId=%" PRIu8, + drdynvc_get_packet_type(Cmd), Sp, cbChId); + + switch (Cmd) + { + case CAPABILITY_REQUEST_PDU: + return drdynvc_process_capability_request(drdynvc, Sp, cbChId, s); + + case CREATE_REQUEST_PDU: + return drdynvc_process_create_request(drdynvc, Sp, cbChId, s); + + case DATA_FIRST_PDU: + return drdynvc_process_data_first(drdynvc, Sp, cbChId, s, ThreadingFlags); + + case DATA_PDU: + return drdynvc_process_data(drdynvc, Sp, cbChId, s, ThreadingFlags); + + case CLOSE_REQUEST_PDU: + return drdynvc_process_close_request(drdynvc, Sp, cbChId, s); + + default: + WLog_Print(drdynvc->log, WLOG_ERROR, "unknown drdynvc cmd 0x%x", Cmd); + return ERROR_INTERNAL_ERROR; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + wStream* data_in = NULL; + + WINPR_ASSERT(drdynvc); + if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) + { + return CHANNEL_RC_OK; + } + + if (dataFlags & CHANNEL_FLAG_FIRST) + { + DVCMAN* mgr = (DVCMAN*)drdynvc->channel_mgr; + if (drdynvc->data_in) + Stream_Release(drdynvc->data_in); + + drdynvc->data_in = StreamPool_Take(mgr->pool, totalLength); + } + + if (!(data_in = drdynvc->data_in)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "StreamPool_Take failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); + Stream_Release(drdynvc->data_in); + drdynvc->data_in = NULL; + return ERROR_INTERNAL_ERROR; + } + + Stream_Write(data_in, pData, dataLength); + + if (dataFlags & CHANNEL_FLAG_LAST) + { + const size_t cap = Stream_Capacity(data_in); + const size_t pos = Stream_GetPosition(data_in); + if (cap < pos) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); + return ERROR_INVALID_DATA; + } + + drdynvc->data_in = NULL; + Stream_SealLength(data_in); + Stream_SetPosition(data_in, 0); + + if (drdynvc->async) + { + if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*)data_in, NULL)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + } + else + { + UINT error = drdynvc_order_recv(drdynvc, data_in, TRUE); + Stream_Release(data_in); + + if (error) + { + WLog_Print(drdynvc->log, WLOG_WARN, + "drdynvc_order_recv failed with error %" PRIu32 "!", error); + } + } + } + + return CHANNEL_RC_OK; +} + +static void VCAPITYPE drdynvc_virtual_channel_open_event_ex(LPVOID lpUserParam, DWORD openHandle, + UINT event, LPVOID pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + UINT error = CHANNEL_RC_OK; + drdynvcPlugin* drdynvc = (drdynvcPlugin*)lpUserParam; + + WINPR_ASSERT(drdynvc); + switch (event) + { + case CHANNEL_EVENT_DATA_RECEIVED: + if (!drdynvc || (drdynvc->OpenHandle != openHandle)) + { + WLog_ERR(TAG, "drdynvc_virtual_channel_open_event: error no match"); + return; + } + if ((error = drdynvc_virtual_channel_event_data_received(drdynvc, pData, dataLength, + totalLength, dataFlags))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_data_received failed with error %" PRIu32 + "", + error); + + break; + + case CHANNEL_EVENT_WRITE_CANCELLED: + case CHANNEL_EVENT_WRITE_COMPLETE: + { + wStream* s = (wStream*)pData; + Stream_Release(s); + } + break; + + case CHANNEL_EVENT_USER: + break; + default: + break; + } + + if (error && drdynvc && drdynvc->rdpcontext) + setChannelError(drdynvc->rdpcontext, error, + "drdynvc_virtual_channel_open_event reported an error"); +} + +static DWORD WINAPI drdynvc_virtual_channel_client_thread(LPVOID arg) +{ + /* TODO: rewrite this */ + wStream* data = NULL; + wMessage message = { 0 }; + UINT error = CHANNEL_RC_OK; + drdynvcPlugin* drdynvc = (drdynvcPlugin*)arg; + + if (!drdynvc) + { + ExitThread((DWORD)CHANNEL_RC_BAD_CHANNEL_HANDLE); + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + } + + while (1) + { + if (!MessageQueue_Wait(drdynvc->queue)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Wait failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (!MessageQueue_Peek(drdynvc->queue, &message, TRUE)) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Peek failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (message.id == WMQ_QUIT) + break; + + if (message.id == 0) + { + UINT32 ThreadingFlags = TRUE; + data = (wStream*)message.wParam; + + if ((error = drdynvc_order_recv(drdynvc, data, ThreadingFlags))) + { + WLog_Print(drdynvc->log, WLOG_WARN, + "drdynvc_order_recv failed with error %" PRIu32 "!", error); + } + + Stream_Release(data); + } + } + + { + /* Disconnect remaining dynamic channels that the server did not. + * This is required to properly shut down channels by calling the appropriate + * event handlers. */ + DVCMAN* drdynvcMgr = (DVCMAN*)drdynvc->channel_mgr; + + HashTable_Clear(drdynvcMgr->channelsById); + } + + if (error && drdynvc->rdpcontext) + setChannelError(drdynvc->rdpcontext, error, + "drdynvc_virtual_channel_client_thread reported an error"); + + ExitThread((DWORD)error); + return error; +} + +static void drdynvc_queue_object_free(void* obj) +{ + wStream* s = NULL; + wMessage* msg = (wMessage*)obj; + + if (!msg || (msg->id != 0)) + return; + + s = (wStream*)msg->wParam; + + if (s) + Stream_Release(s); +} + +static UINT drdynvc_virtual_channel_event_initialized(drdynvcPlugin* drdynvc, LPVOID pData, + UINT32 dataLength) +{ + wObject* obj = NULL; + WINPR_UNUSED(pData); + WINPR_UNUSED(dataLength); + + if (!drdynvc) + goto error; + + drdynvc->queue = MessageQueue_New(NULL); + + if (!drdynvc->queue) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_New failed!"); + goto error; + } + + obj = MessageQueue_Object(drdynvc->queue); + obj->fnObjectFree = drdynvc_queue_object_free; + drdynvc->channel_mgr = dvcman_new(drdynvc); + + if (!drdynvc->channel_mgr) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_new failed!"); + goto error; + } + + return CHANNEL_RC_OK; +error: + return ERROR_INTERNAL_ERROR; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_virtual_channel_event_connected(drdynvcPlugin* drdynvc, LPVOID pData, + UINT32 dataLength) +{ + UINT error = 0; + UINT32 status = 0; + rdpSettings* settings = NULL; + + WINPR_ASSERT(drdynvc); + WINPR_UNUSED(pData); + WINPR_UNUSED(dataLength); + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + WINPR_ASSERT(drdynvc->channelEntryPoints.pVirtualChannelOpenEx); + status = drdynvc->channelEntryPoints.pVirtualChannelOpenEx( + drdynvc->InitHandle, &drdynvc->OpenHandle, drdynvc->channelDef.name, + drdynvc_virtual_channel_open_event_ex); + + if (status != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "pVirtualChannelOpen failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + return status; + } + + WINPR_ASSERT(drdynvc->rdpcontext); + settings = drdynvc->rdpcontext->settings; + WINPR_ASSERT(settings); + + for (UINT32 index = 0; + index < freerdp_settings_get_uint32(settings, FreeRDP_DynamicChannelCount); index++) + { + const ADDIN_ARGV* args = + freerdp_settings_get_pointer_array(settings, FreeRDP_DynamicChannelArray, index); + error = dvcman_load_addin(drdynvc, drdynvc->channel_mgr, args, drdynvc->rdpcontext); + + if (CHANNEL_RC_OK != error) + goto error; + } + + if ((error = dvcman_init(drdynvc, drdynvc->channel_mgr))) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_init failed with error %" PRIu32 "!", error); + goto error; + } + + drdynvc->state = DRDYNVC_STATE_CAPABILITIES; + + if (drdynvc->async) + { + if (!(drdynvc->thread = CreateThread(NULL, 0, drdynvc_virtual_channel_client_thread, + (void*)drdynvc, 0, NULL))) + { + error = ERROR_INTERNAL_ERROR; + WLog_Print(drdynvc->log, WLOG_ERROR, "CreateThread failed!"); + goto error; + } + + if (!SetThreadPriority(drdynvc->thread, THREAD_PRIORITY_HIGHEST)) + WLog_Print(drdynvc->log, WLOG_WARN, "SetThreadPriority failed, ignoring."); + } + +error: + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_virtual_channel_event_disconnected(drdynvcPlugin* drdynvc) +{ + UINT status = 0; + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + if (drdynvc->OpenHandle == 0) + return CHANNEL_RC_OK; + + if (drdynvc->queue) + { + if (!MessageQueue_PostQuit(drdynvc->queue, 0)) + { + status = GetLastError(); + WLog_Print(drdynvc->log, WLOG_ERROR, + "MessageQueue_PostQuit failed with error %" PRIu32 "", status); + return status; + } + } + + if (drdynvc->thread) + { + if (WaitForSingleObject(drdynvc->thread, INFINITE) != WAIT_OBJECT_0) + { + status = GetLastError(); + WLog_Print(drdynvc->log, WLOG_ERROR, + "WaitForSingleObject failed with error %" PRIu32 "", status); + return status; + } + + (void)CloseHandle(drdynvc->thread); + drdynvc->thread = NULL; + } + else + { + { + /* Disconnect remaining dynamic channels that the server did not. + * This is required to properly shut down channels by calling the appropriate + * event handlers. */ + DVCMAN* drdynvcMgr = (DVCMAN*)drdynvc->channel_mgr; + + HashTable_Clear(drdynvcMgr->channelsById); + } + } + + WINPR_ASSERT(drdynvc->channelEntryPoints.pVirtualChannelCloseEx); + status = drdynvc->channelEntryPoints.pVirtualChannelCloseEx(drdynvc->InitHandle, + drdynvc->OpenHandle); + + if (status != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "pVirtualChannelClose failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + } + + dvcman_clear(drdynvc, drdynvc->channel_mgr); + if (drdynvc->queue) + MessageQueue_Clear(drdynvc->queue); + drdynvc->OpenHandle = 0; + + if (drdynvc->data_in) + { + Stream_Release(drdynvc->data_in); + drdynvc->data_in = NULL; + } + + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_virtual_channel_event_terminated(drdynvcPlugin* drdynvc) +{ + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + MessageQueue_Free(drdynvc->queue); + drdynvc->queue = NULL; + + if (drdynvc->channel_mgr) + { + dvcman_free(drdynvc, drdynvc->channel_mgr); + drdynvc->channel_mgr = NULL; + } + drdynvc->InitHandle = 0; + free(drdynvc->context); + free(drdynvc); + return CHANNEL_RC_OK; +} + +static UINT drdynvc_virtual_channel_event_attached(drdynvcPlugin* drdynvc) +{ + UINT error = CHANNEL_RC_OK; + DVCMAN* dvcman = NULL; + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + dvcman = (DVCMAN*)drdynvc->channel_mgr; + + if (!dvcman) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + ArrayList_Lock(dvcman->plugins); + for (size_t i = 0; i < ArrayList_Count(dvcman->plugins); i++) + { + IWTSPlugin* pPlugin = ArrayList_GetItem(dvcman->plugins, i); + + error = IFCALLRESULT(CHANNEL_RC_OK, pPlugin->Attached, pPlugin); + if (error != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "Attach failed with error %" PRIu32 "!", error); + goto fail; + } + } + +fail: + ArrayList_Unlock(dvcman->plugins); + return error; +} + +static UINT drdynvc_virtual_channel_event_detached(drdynvcPlugin* drdynvc) +{ + UINT error = CHANNEL_RC_OK; + DVCMAN* dvcman = NULL; + + if (!drdynvc) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + dvcman = (DVCMAN*)drdynvc->channel_mgr; + + if (!dvcman) + return CHANNEL_RC_BAD_CHANNEL_HANDLE; + + ArrayList_Lock(dvcman->plugins); + for (size_t i = 0; i < ArrayList_Count(dvcman->plugins); i++) + { + IWTSPlugin* pPlugin = ArrayList_GetItem(dvcman->plugins, i); + + error = IFCALLRESULT(CHANNEL_RC_OK, pPlugin->Detached, pPlugin); + if (error != CHANNEL_RC_OK) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "Detach failed with error %" PRIu32 "!", error); + goto fail; + } + } + +fail: + ArrayList_Unlock(dvcman->plugins); + + return error; +} + +static VOID VCAPITYPE drdynvc_virtual_channel_init_event_ex(LPVOID lpUserParam, LPVOID pInitHandle, + UINT event, LPVOID pData, + UINT dataLength) +{ + UINT error = CHANNEL_RC_OK; + drdynvcPlugin* drdynvc = (drdynvcPlugin*)lpUserParam; + + if (!drdynvc || (drdynvc->InitHandle != pInitHandle)) + { + WLog_ERR(TAG, "drdynvc_virtual_channel_init_event: error no match"); + return; + } + + switch (event) + { + case CHANNEL_EVENT_INITIALIZED: + error = drdynvc_virtual_channel_event_initialized(drdynvc, pData, dataLength); + break; + case CHANNEL_EVENT_CONNECTED: + if ((error = drdynvc_virtual_channel_event_connected(drdynvc, pData, dataLength))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_connected failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_DISCONNECTED: + if ((error = drdynvc_virtual_channel_event_disconnected(drdynvc))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_disconnected failed with error %" PRIu32 + "", + error); + + break; + + case CHANNEL_EVENT_TERMINATED: + if ((error = drdynvc_virtual_channel_event_terminated(drdynvc))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_terminated failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_ATTACHED: + if ((error = drdynvc_virtual_channel_event_attached(drdynvc))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_attached failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_DETACHED: + if ((error = drdynvc_virtual_channel_event_detached(drdynvc))) + WLog_Print(drdynvc->log, WLOG_ERROR, + "drdynvc_virtual_channel_event_detached failed with error %" PRIu32 "", + error); + + break; + + default: + break; + } + + if (error && drdynvc->rdpcontext) + setChannelError(drdynvc->rdpcontext, error, + "drdynvc_virtual_channel_init_event_ex reported an error"); +} + +/** + * Channel Client Interface + */ + +static int drdynvc_get_version(DrdynvcClientContext* context) +{ + WINPR_ASSERT(context); + drdynvcPlugin* drdynvc = (drdynvcPlugin*)context->handle; + WINPR_ASSERT(drdynvc); + return drdynvc->version; +} + +/* drdynvc is always built-in */ +#define VirtualChannelEntryEx drdynvc_VirtualChannelEntryEx + +FREERDP_ENTRY_POINT(BOOL VCAPITYPE VirtualChannelEntryEx(PCHANNEL_ENTRY_POINTS_EX pEntryPoints, + PVOID pInitHandle)) +{ + UINT rc = 0; + drdynvcPlugin* drdynvc = NULL; + DrdynvcClientContext* context = NULL; + CHANNEL_ENTRY_POINTS_FREERDP_EX* pEntryPointsEx = NULL; + drdynvc = (drdynvcPlugin*)calloc(1, sizeof(drdynvcPlugin)); + + WINPR_ASSERT(pEntryPoints); + if (!drdynvc) + { + WLog_ERR(TAG, "calloc failed!"); + return FALSE; + } + + drdynvc->channelDef.options = + CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | CHANNEL_OPTION_COMPRESS_RDP; + (void)sprintf_s(drdynvc->channelDef.name, ARRAYSIZE(drdynvc->channelDef.name), + DRDYNVC_SVC_CHANNEL_NAME); + drdynvc->state = DRDYNVC_STATE_INITIAL; + pEntryPointsEx = (CHANNEL_ENTRY_POINTS_FREERDP_EX*)pEntryPoints; + + if ((pEntryPointsEx->cbSize >= sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)) && + (pEntryPointsEx->MagicNumber == FREERDP_CHANNEL_MAGIC_NUMBER)) + { + context = (DrdynvcClientContext*)calloc(1, sizeof(DrdynvcClientContext)); + + if (!context) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "calloc failed!"); + free(drdynvc); + return FALSE; + } + + context->handle = (void*)drdynvc; + context->custom = NULL; + drdynvc->context = context; + context->GetVersion = drdynvc_get_version; + drdynvc->rdpcontext = pEntryPointsEx->context; + if (!freerdp_settings_get_bool(drdynvc->rdpcontext->settings, + FreeRDP_TransportDumpReplay) && + !freerdp_settings_get_bool(drdynvc->rdpcontext->settings, + FreeRDP_SynchronousDynamicChannels)) + drdynvc->async = TRUE; + } + + drdynvc->log = WLog_Get(TAG); + WLog_Print(drdynvc->log, WLOG_DEBUG, "VirtualChannelEntryEx"); + CopyMemory(&(drdynvc->channelEntryPoints), pEntryPoints, + sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)); + drdynvc->InitHandle = pInitHandle; + + WINPR_ASSERT(drdynvc->channelEntryPoints.pVirtualChannelInitEx); + rc = drdynvc->channelEntryPoints.pVirtualChannelInitEx( + drdynvc, context, pInitHandle, &drdynvc->channelDef, 1, VIRTUAL_CHANNEL_VERSION_WIN2000, + drdynvc_virtual_channel_init_event_ex); + + if (CHANNEL_RC_OK != rc) + { + WLog_Print(drdynvc->log, WLOG_ERROR, "pVirtualChannelInit failed with %s [%08" PRIX32 "]", + WTSErrorToString(rc), rc); + free(drdynvc->context); + free(drdynvc); + return FALSE; + } + + drdynvc->channelEntryPoints.pInterface = context; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..bea05db57359660cacd4a83a737eb37f89402217 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/CMakeLists.txt @@ -0,0 +1,23 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("drdynvc") + +set(${MODULE_PREFIX}_SRCS drdynvc_main.c drdynvc_main.h) + +set(${MODULE_PREFIX}_LIBS freerdp) +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/drdynvc_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/drdynvc_main.c new file mode 100644 index 0000000000000000000000000000000000000000..aa089c4a4f147625db95a5dfc5f0a199b05158f4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drdynvc/server/drdynvc_main.c @@ -0,0 +1,204 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Dynamic Virtual Channel Extension + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include +#include +#include + +#include "drdynvc_main.h" + +#define TAG CHANNELS_TAG("drdynvc.server") + +static DWORD WINAPI drdynvc_server_thread(LPVOID arg) +{ +#if 0 + wStream* s; + DWORD status; + DWORD nCount; + void* buffer; + HANDLE events[8]; + HANDLE ChannelEvent; + DWORD BytesReturned; + DrdynvcServerContext* context; + UINT error = ERROR_INTERNAL_ERROR; + context = (DrdynvcServerContext*) arg; + buffer = NULL; + BytesReturned = 0; + ChannelEvent = NULL; + + s = Stream_New(NULL, 4096); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + ExitThread((DWORD) CHANNEL_RC_NO_MEMORY); + return CHANNEL_RC_NO_MEMORY; + } + + if (WTSVirtualChannelQuery(context->priv->ChannelHandle, WTSVirtualEventHandle, + &buffer, &BytesReturned) == TRUE) + { + if (BytesReturned == sizeof(HANDLE)) + CopyMemory(&ChannelEvent, buffer, sizeof(HANDLE)); + + WTSFreeMemory(buffer); + } + + nCount = 0; + events[nCount++] = ChannelEvent; + events[nCount++] = context->priv->StopEvent; + + while (1) + { + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (WaitForSingleObject(context->priv->StopEvent, 0) == WAIT_OBJECT_0) + { + error = CHANNEL_RC_OK; + break; + } + + if (!WTSVirtualChannelRead(context->priv->ChannelHandle, 0, NULL, 0, + &BytesReturned)) + { + WLog_ERR(TAG, "WTSVirtualChannelRead failed!"); + break; + } + + if (BytesReturned < 1) + continue; + + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + break; + } + + if (!WTSVirtualChannelRead(context->priv->ChannelHandle, 0, + Stream_BufferAs(s, char), Stream_Capacity(s), &BytesReturned)) + { + WLog_ERR(TAG, "WTSVirtualChannelRead failed!"); + break; + } + } + + Stream_Free(s, TRUE); + ExitThread((DWORD) error); +#endif + // WTF ... this code only reads data into the stream until there is no more memory + ExitThread(0); + return 0; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_server_start(DrdynvcServerContext* context) +{ + context->priv->ChannelHandle = + WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, DRDYNVC_SVC_CHANNEL_NAME); + + if (!context->priv->ChannelHandle) + { + WLog_ERR(TAG, "WTSVirtualChannelOpen failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if (!(context->priv->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + WLog_ERR(TAG, "CreateEvent failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (!(context->priv->Thread = + CreateThread(NULL, 0, drdynvc_server_thread, (void*)context, 0, NULL))) + { + WLog_ERR(TAG, "CreateThread failed!"); + (void)CloseHandle(context->priv->StopEvent); + context->priv->StopEvent = NULL; + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drdynvc_server_stop(DrdynvcServerContext* context) +{ + UINT error = 0; + (void)SetEvent(context->priv->StopEvent); + + if (WaitForSingleObject(context->priv->Thread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error); + return error; + } + + (void)CloseHandle(context->priv->Thread); + return CHANNEL_RC_OK; +} + +DrdynvcServerContext* drdynvc_server_context_new(HANDLE vcm) +{ + DrdynvcServerContext* context = NULL; + context = (DrdynvcServerContext*)calloc(1, sizeof(DrdynvcServerContext)); + + if (context) + { + context->vcm = vcm; + context->Start = drdynvc_server_start; + context->Stop = drdynvc_server_stop; + context->priv = (DrdynvcServerPrivate*)calloc(1, sizeof(DrdynvcServerPrivate)); + + if (!context->priv) + { + WLog_ERR(TAG, "calloc failed!"); + free(context); + return NULL; + } + } + else + { + WLog_ERR(TAG, "calloc failed!"); + } + + return context; +} + +void drdynvc_server_context_free(DrdynvcServerContext* context) +{ + if (context) + { + free(context->priv); + free(context); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4e239823bce8b0a5b28a38d179925e6ca85177fa --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/CMakeLists.txt @@ -0,0 +1,23 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client("drive") + +set(${MODULE_PREFIX}_SRCS drive_file.c drive_file.h drive_main.c) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DeviceServiceEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.c b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.c new file mode 100644 index 0000000000000000000000000000000000000000..319c86360cb4b66e450490949634d12cbbf286f4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.c @@ -0,0 +1,1018 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * File System Virtual Channel + * + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2010-2011 Vic Lee + * Copyright 2012 Gerald Richter + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Inuvika Inc. + * Copyright 2016 David PHAM-VAN + * Copyright 2017 Armin Novak + * Copyright 2017 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 + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "drive_file.h" + +#ifdef WITH_DEBUG_RDPDR +#define DEBUG_WSTR(msg, wstr) \ + do \ + { \ + char lpstr[1024] = { 0 }; \ + (void)ConvertWCharToUtf8(wstr, lpstr, ARRAYSIZE(lpstr)); \ + WLog_DBG(TAG, msg, lpstr); \ + } while (0) +#else +#define DEBUG_WSTR(msg, wstr) \ + do \ + { \ + } while (0) +#endif + +static BOOL drive_file_fix_path(WCHAR* path, size_t length) +{ + if ((length == 0) || (length > UINT32_MAX)) + return FALSE; + + WINPR_ASSERT(path); + + for (size_t i = 0; i < length; i++) + { + if (path[i] == L'\\') + path[i] = L'/'; + } + +#ifdef WIN32 + + if ((length == 3) && (path[1] == L':') && (path[2] == L'/')) + return FALSE; + +#else + + if ((length == 1) && (path[0] == L'/')) + return FALSE; + +#endif + + if ((length > 0) && (path[length - 1] == L'/')) + path[length - 1] = L'\0'; + + return TRUE; +} + +static BOOL contains_dotdot(const WCHAR* path, size_t base_length, size_t path_length) +{ + WCHAR dotdotbuffer[6] = { 0 }; + const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer)); + const WCHAR* tst = path; + + if (path_length < 2) + return FALSE; + + do + { + tst = _wcsstr(tst, dotdot); + if (!tst) + return FALSE; + + /* Filter .. sequences in file or directory names */ + if ((base_length == 0) || (*(tst - 1) == L'/') || (*(tst - 1) == L'\\')) + { + if (tst + 2 < path + path_length) + { + if ((tst[2] == '/') || (tst[2] == '\\')) + return TRUE; + } + } + tst += 2; + } while (TRUE); + + return FALSE; +} + +static WCHAR* drive_file_combine_fullpath(const WCHAR* base_path, const WCHAR* path, + size_t PathWCharLength) +{ + BOOL ok = FALSE; + WCHAR* fullpath = NULL; + + if (!base_path || (!path && (PathWCharLength > 0))) + goto fail; + + const size_t base_path_length = _wcsnlen(base_path, MAX_PATH); + const size_t length = base_path_length + PathWCharLength + 1; + fullpath = (WCHAR*)calloc(length, sizeof(WCHAR)); + + if (!fullpath) + goto fail; + + CopyMemory(fullpath, base_path, base_path_length * sizeof(WCHAR)); + if (path) + CopyMemory(&fullpath[base_path_length], path, PathWCharLength * sizeof(WCHAR)); + + if (!drive_file_fix_path(fullpath, length)) + goto fail; + + /* Ensure the path does not contain sequences like '..' */ + if (contains_dotdot(&fullpath[base_path_length], base_path_length, PathWCharLength)) + { + char abuffer[MAX_PATH] = { 0 }; + (void)ConvertWCharToUtf8(&fullpath[base_path_length], abuffer, ARRAYSIZE(abuffer)); + + WLog_WARN(TAG, "[rdpdr] received invalid file path '%s' from server, aborting!", + &abuffer[base_path_length]); + goto fail; + } + + ok = TRUE; +fail: + if (!ok) + { + free(fullpath); + fullpath = NULL; + } + return fullpath; +} + +static BOOL drive_file_set_fullpath(DRIVE_FILE* file, const WCHAR* fullpath) +{ + if (!file || !fullpath) + return FALSE; + + const size_t len = _wcslen(fullpath); + free(file->fullpath); + file->fullpath = NULL; + + if (len == 0) + return TRUE; + + file->fullpath = _wcsdup(fullpath); + if (!file->fullpath) + return FALSE; + + const WCHAR sep[] = { PathGetSeparatorW(PATH_STYLE_NATIVE), '\0' }; + WCHAR* filename = _wcsrchr(file->fullpath, *sep); + if (filename && _wcsncmp(filename, sep, ARRAYSIZE(sep)) == 0) + *filename = '\0'; + + return TRUE; +} + +static BOOL drive_file_init(DRIVE_FILE* file) +{ + UINT CreateDisposition = 0; + DWORD dwAttr = GetFileAttributesW(file->fullpath); + + if (dwAttr != INVALID_FILE_ATTRIBUTES) + { + /* The file exists */ + file->is_dir = (dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0; + + if (file->is_dir) + { + if (file->CreateDisposition == FILE_CREATE) + { + SetLastError(ERROR_ALREADY_EXISTS); + return FALSE; + } + + if (file->CreateOptions & FILE_NON_DIRECTORY_FILE) + { + SetLastError(ERROR_ACCESS_DENIED); + return FALSE; + } + + return TRUE; + } + else + { + if (file->CreateOptions & FILE_DIRECTORY_FILE) + { + SetLastError(ERROR_DIRECTORY); + return FALSE; + } + } + } + else + { + file->is_dir = ((file->CreateOptions & FILE_DIRECTORY_FILE) ? TRUE : FALSE); + + if (file->is_dir) + { + /* Should only create the directory if the disposition allows for it */ + if ((file->CreateDisposition == FILE_OPEN_IF) || + (file->CreateDisposition == FILE_CREATE)) + { + if (CreateDirectoryW(file->fullpath, NULL) != 0) + { + return TRUE; + } + } + + SetLastError(ERROR_FILE_NOT_FOUND); + return FALSE; + } + } + + if (file->file_handle == INVALID_HANDLE_VALUE) + { + switch (file->CreateDisposition) + { + case FILE_SUPERSEDE: /* If the file already exists, replace it with the given file. If + it does not, create the given file. */ + CreateDisposition = CREATE_ALWAYS; + break; + + case FILE_OPEN: /* If the file already exists, open it instead of creating a new file. + If it does not, fail the request and do not create a new file. */ + CreateDisposition = OPEN_EXISTING; + break; + + case FILE_CREATE: /* If the file already exists, fail the request and do not create or + open the given file. If it does not, create the given file. */ + CreateDisposition = CREATE_NEW; + break; + + case FILE_OPEN_IF: /* If the file already exists, open it. If it does not, create the + given file. */ + CreateDisposition = OPEN_ALWAYS; + break; + + case FILE_OVERWRITE: /* If the file already exists, open it and overwrite it. If it does + not, fail the request. */ + CreateDisposition = TRUNCATE_EXISTING; + break; + + case FILE_OVERWRITE_IF: /* If the file already exists, open it and overwrite it. If it + does not, create the given file. */ + CreateDisposition = CREATE_ALWAYS; + break; + + default: + break; + } + +#ifndef WIN32 + file->SharedAccess = 0; +#endif + file->file_handle = CreateFileW(file->fullpath, file->DesiredAccess, file->SharedAccess, + NULL, CreateDisposition, file->FileAttributes, NULL); + } + +#ifdef WIN32 + if (file->file_handle == INVALID_HANDLE_VALUE) + { + /* Get the error message, if any. */ + DWORD errorMessageID = GetLastError(); + + if (errorMessageID != 0) + { + LPSTR messageBuffer = NULL; + size_t size = + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&messageBuffer, 0, NULL); + WLog_ERR(TAG, "Error in drive_file_init: %s %s", messageBuffer, file->fullpath); + /* Free the buffer. */ + LocalFree(messageBuffer); + /* restore original error code */ + SetLastError(errorMessageID); + } + } +#endif + + return file->file_handle != INVALID_HANDLE_VALUE; +} + +DRIVE_FILE* drive_file_new(const WCHAR* base_path, const WCHAR* path, UINT32 PathWCharLength, + UINT32 id, UINT32 DesiredAccess, UINT32 CreateDisposition, + UINT32 CreateOptions, UINT32 FileAttributes, UINT32 SharedAccess) +{ + if (!base_path || (!path && (PathWCharLength > 0))) + return NULL; + + DRIVE_FILE* file = (DRIVE_FILE*)calloc(1, sizeof(DRIVE_FILE)); + + if (!file) + { + WLog_ERR(TAG, "calloc failed!"); + return NULL; + } + + file->file_handle = INVALID_HANDLE_VALUE; + file->find_handle = INVALID_HANDLE_VALUE; + file->id = id; + file->basepath = base_path; + file->FileAttributes = FileAttributes; + file->DesiredAccess = DesiredAccess; + file->CreateDisposition = CreateDisposition; + file->CreateOptions = CreateOptions; + file->SharedAccess = SharedAccess; + + WCHAR* p = drive_file_combine_fullpath(base_path, path, PathWCharLength); + (void)drive_file_set_fullpath(file, p); + free(p); + + if (!drive_file_init(file)) + { + DWORD lastError = GetLastError(); + drive_file_free(file); + SetLastError(lastError); + return NULL; + } + + return file; +} + +BOOL drive_file_free(DRIVE_FILE* file) +{ + BOOL rc = FALSE; + + if (!file) + return FALSE; + + if (file->file_handle != INVALID_HANDLE_VALUE) + { + (void)CloseHandle(file->file_handle); + file->file_handle = INVALID_HANDLE_VALUE; + } + + if (file->find_handle != INVALID_HANDLE_VALUE) + { + FindClose(file->find_handle); + file->find_handle = INVALID_HANDLE_VALUE; + } + + if (file->delete_pending) + { + if (file->is_dir) + { + if (!winpr_RemoveDirectory_RecursiveW(file->fullpath)) + goto fail; + } + else if (!DeleteFileW(file->fullpath)) + goto fail; + } + + rc = TRUE; +fail: + DEBUG_WSTR("Free %s", file->fullpath); + free(file->fullpath); + free(file); + return rc; +} + +BOOL drive_file_seek(DRIVE_FILE* file, UINT64 Offset) +{ + LARGE_INTEGER loffset = { 0 }; + + if (!file) + return FALSE; + + if (Offset > INT64_MAX) + return FALSE; + + loffset.QuadPart = (LONGLONG)Offset; + return SetFilePointerEx(file->file_handle, loffset, NULL, FILE_BEGIN); +} + +BOOL drive_file_read(DRIVE_FILE* file, BYTE* buffer, UINT32* Length) +{ + DWORD read = 0; + + if (!file || !buffer || !Length) + return FALSE; + + DEBUG_WSTR("Read file %s", file->fullpath); + + if (ReadFile(file->file_handle, buffer, *Length, &read, NULL)) + { + *Length = read; + return TRUE; + } + + return FALSE; +} + +BOOL drive_file_write(DRIVE_FILE* file, const BYTE* buffer, UINT32 Length) +{ + DWORD written = 0; + + if (!file || !buffer) + return FALSE; + + DEBUG_WSTR("Write file %s", file->fullpath); + + while (Length > 0) + { + if (!WriteFile(file->file_handle, buffer, Length, &written, NULL)) + return FALSE; + + Length -= written; + buffer += written; + } + + return TRUE; +} + +static BOOL drive_file_query_from_handle_information(const DRIVE_FILE* file, + const BY_HANDLE_FILE_INFORMATION* info, + UINT32 FsInformationClass, wStream* output) +{ + switch (FsInformationClass) + { + case FileBasicInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232094.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 36)) + return FALSE; + + Stream_Write_UINT32(output, 36); /* Length */ + Stream_Write_UINT32(output, info->ftCreationTime.dwLowDateTime); /* CreationTime */ + Stream_Write_UINT32(output, info->ftCreationTime.dwHighDateTime); /* CreationTime */ + Stream_Write_UINT32(output, info->ftLastAccessTime.dwLowDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, info->ftLastAccessTime.dwHighDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, info->ftLastWriteTime.dwLowDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, info->ftLastWriteTime.dwHighDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, info->ftLastWriteTime.dwLowDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, info->ftLastWriteTime.dwHighDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, info->dwFileAttributes); /* FileAttributes */ + /* Reserved(4), MUST NOT be added! */ + break; + + case FileStandardInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232088.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 22)) + return FALSE; + + Stream_Write_UINT32(output, 22); /* Length */ + Stream_Write_UINT32(output, info->nFileSizeLow); /* AllocationSize */ + Stream_Write_UINT32(output, info->nFileSizeHigh); /* AllocationSize */ + Stream_Write_UINT32(output, info->nFileSizeLow); /* EndOfFile */ + Stream_Write_UINT32(output, info->nFileSizeHigh); /* EndOfFile */ + Stream_Write_UINT32(output, info->nNumberOfLinks); /* NumberOfLinks */ + Stream_Write_UINT8(output, file->delete_pending ? 1 : 0); /* DeletePending */ + Stream_Write_UINT8(output, info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY + ? TRUE + : FALSE); /* Directory */ + /* Reserved(2), MUST NOT be added! */ + break; + + case FileAttributeTagInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232093.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 8)) + return FALSE; + + Stream_Write_UINT32(output, 8); /* Length */ + Stream_Write_UINT32(output, info->dwFileAttributes); /* FileAttributes */ + Stream_Write_UINT32(output, 0); /* ReparseTag */ + break; + + default: + /* Unhandled FsInformationClass */ + return FALSE; + } + + return TRUE; +} + +static BOOL drive_file_query_from_attributes(const DRIVE_FILE* file, + const WIN32_FILE_ATTRIBUTE_DATA* attrib, + UINT32 FsInformationClass, wStream* output) +{ + switch (FsInformationClass) + { + case FileBasicInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232094.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 36)) + return FALSE; + + Stream_Write_UINT32(output, 36); /* Length */ + Stream_Write_UINT32(output, attrib->ftCreationTime.dwLowDateTime); /* CreationTime */ + Stream_Write_UINT32(output, attrib->ftCreationTime.dwHighDateTime); /* CreationTime */ + Stream_Write_UINT32(output, + attrib->ftLastAccessTime.dwLowDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, + attrib->ftLastAccessTime.dwHighDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, attrib->ftLastWriteTime.dwLowDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, attrib->ftLastWriteTime.dwHighDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, attrib->ftLastWriteTime.dwLowDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, attrib->ftLastWriteTime.dwHighDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, attrib->dwFileAttributes); /* FileAttributes */ + /* Reserved(4), MUST NOT be added! */ + break; + + case FileStandardInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232088.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 22)) + return FALSE; + + Stream_Write_UINT32(output, 22); /* Length */ + Stream_Write_UINT32(output, attrib->nFileSizeLow); /* AllocationSize */ + Stream_Write_UINT32(output, attrib->nFileSizeHigh); /* AllocationSize */ + Stream_Write_UINT32(output, attrib->nFileSizeLow); /* EndOfFile */ + Stream_Write_UINT32(output, attrib->nFileSizeHigh); /* EndOfFile */ + Stream_Write_UINT32(output, 0); /* NumberOfLinks */ + Stream_Write_UINT8(output, file->delete_pending ? 1 : 0); /* DeletePending */ + Stream_Write_UINT8(output, attrib->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY + ? TRUE + : FALSE); /* Directory */ + /* Reserved(2), MUST NOT be added! */ + break; + + case FileAttributeTagInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232093.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 8)) + return FALSE; + + Stream_Write_UINT32(output, 8); /* Length */ + Stream_Write_UINT32(output, attrib->dwFileAttributes); /* FileAttributes */ + Stream_Write_UINT32(output, 0); /* ReparseTag */ + break; + + default: + /* Unhandled FsInformationClass */ + return FALSE; + } + + return TRUE; +} + +BOOL drive_file_query_information(DRIVE_FILE* file, UINT32 FsInformationClass, wStream* output) +{ + BY_HANDLE_FILE_INFORMATION fileInformation = { 0 }; + BOOL status = 0; + HANDLE hFile = NULL; + + if (!file || !output) + return FALSE; + + hFile = CreateFileW(file->fullpath, 0, FILE_SHARE_DELETE, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile != INVALID_HANDLE_VALUE) + { + status = GetFileInformationByHandle(hFile, &fileInformation); + (void)CloseHandle(hFile); + if (!status) + goto out_fail; + + if (!drive_file_query_from_handle_information(file, &fileInformation, FsInformationClass, + output)) + goto out_fail; + + return TRUE; + } + + /* If we failed before (i.e. if information for a drive is queried) fall back to + * GetFileAttributesExW */ + WIN32_FILE_ATTRIBUTE_DATA fileAttributes = { 0 }; + if (!GetFileAttributesExW(file->fullpath, GetFileExInfoStandard, &fileAttributes)) + goto out_fail; + + if (!drive_file_query_from_attributes(file, &fileAttributes, FsInformationClass, output)) + goto out_fail; + + return TRUE; +out_fail: + Stream_Write_UINT32(output, 0); /* Length */ + return FALSE; +} + +BOOL drive_file_set_information(DRIVE_FILE* file, UINT32 FsInformationClass, UINT32 Length, + wStream* input) +{ + INT64 size = 0; + ULARGE_INTEGER liCreationTime = { 0 }; + ULARGE_INTEGER liLastAccessTime = { 0 }; + ULARGE_INTEGER liLastWriteTime = { 0 }; + ULARGE_INTEGER liChangeTime = { 0 }; + FILETIME ftCreationTime; + FILETIME ftLastAccessTime; + FILETIME ftLastWriteTime; + FILETIME* pftCreationTime = NULL; + FILETIME* pftLastAccessTime = NULL; + FILETIME* pftLastWriteTime = NULL; + UINT32 FileAttributes = 0; + UINT32 FileNameLength = 0; + LARGE_INTEGER liSize = { 0 }; + UINT8 delete_pending = 0; + UINT8 ReplaceIfExists = 0; + DWORD attr = 0; + + if (!file || !input) + return FALSE; + + switch (FsInformationClass) + { + case FileBasicInformation: + if (!Stream_CheckAndLogRequiredLength(TAG, input, 36)) + return FALSE; + + /* http://msdn.microsoft.com/en-us/library/cc232094.aspx */ + Stream_Read_UINT64(input, liCreationTime.QuadPart); + Stream_Read_UINT64(input, liLastAccessTime.QuadPart); + Stream_Read_UINT64(input, liLastWriteTime.QuadPart); + Stream_Read_UINT64(input, liChangeTime.QuadPart); + Stream_Read_UINT32(input, FileAttributes); + + if (!PathFileExistsW(file->fullpath)) + return FALSE; + + if (file->file_handle == INVALID_HANDLE_VALUE) + { + WLog_ERR(TAG, "Unable to set file time %s (%" PRId32 ")", file->fullpath, + GetLastError()); + return FALSE; + } + + if (liCreationTime.QuadPart != 0) + { + ftCreationTime.dwHighDateTime = liCreationTime.u.HighPart; + ftCreationTime.dwLowDateTime = liCreationTime.u.LowPart; + pftCreationTime = &ftCreationTime; + } + + if (liLastAccessTime.QuadPart != 0) + { + ftLastAccessTime.dwHighDateTime = liLastAccessTime.u.HighPart; + ftLastAccessTime.dwLowDateTime = liLastAccessTime.u.LowPart; + pftLastAccessTime = &ftLastAccessTime; + } + + if (liLastWriteTime.QuadPart != 0) + { + ftLastWriteTime.dwHighDateTime = liLastWriteTime.u.HighPart; + ftLastWriteTime.dwLowDateTime = liLastWriteTime.u.LowPart; + pftLastWriteTime = &ftLastWriteTime; + } + + if (liChangeTime.QuadPart != 0 && liChangeTime.QuadPart > liLastWriteTime.QuadPart) + { + ftLastWriteTime.dwHighDateTime = liChangeTime.u.HighPart; + ftLastWriteTime.dwLowDateTime = liChangeTime.u.LowPart; + pftLastWriteTime = &ftLastWriteTime; + } + + DEBUG_WSTR("SetFileTime %s", file->fullpath); + + SetFileAttributesW(file->fullpath, FileAttributes); + if (!SetFileTime(file->file_handle, pftCreationTime, pftLastAccessTime, + pftLastWriteTime)) + { + WLog_ERR(TAG, "Unable to set file time to %s", file->fullpath); + return FALSE; + } + + break; + + case FileEndOfFileInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232067.aspx */ + case FileAllocationInformation: + if (!Stream_CheckAndLogRequiredLength(TAG, input, 8)) + return FALSE; + + /* http://msdn.microsoft.com/en-us/library/cc232076.aspx */ + Stream_Read_INT64(input, size); + + if (file->file_handle == INVALID_HANDLE_VALUE) + { + WLog_ERR(TAG, "Unable to truncate %s to %" PRId64 " (%" PRId32 ")", file->fullpath, + size, GetLastError()); + return FALSE; + } + + liSize.QuadPart = size; + + if (!SetFilePointerEx(file->file_handle, liSize, NULL, FILE_BEGIN)) + { + WLog_ERR(TAG, "Unable to truncate %s to %" PRId64 " (%" PRId32 ")", file->fullpath, + size, GetLastError()); + return FALSE; + } + + DEBUG_WSTR("Truncate %s", file->fullpath); + + if (SetEndOfFile(file->file_handle) == 0) + { + WLog_ERR(TAG, "Unable to truncate %s to %" PRId64 " (%" PRId32 ")", file->fullpath, + size, GetLastError()); + return FALSE; + } + + break; + + case FileDispositionInformation: + + /* http://msdn.microsoft.com/en-us/library/cc232098.aspx */ + /* http://msdn.microsoft.com/en-us/library/cc241371.aspx */ + if (file->is_dir && !PathIsDirectoryEmptyW(file->fullpath)) + break; /* TODO: SetLastError ??? */ + + if (Length) + { + if (!Stream_CheckAndLogRequiredLength(TAG, input, 1)) + return FALSE; + + Stream_Read_UINT8(input, delete_pending); + } + else + delete_pending = 1; + + if (delete_pending) + { + DEBUG_WSTR("SetDeletePending %s", file->fullpath); + attr = GetFileAttributesW(file->fullpath); + + if (attr & FILE_ATTRIBUTE_READONLY) + { + SetLastError(ERROR_ACCESS_DENIED); + return FALSE; + } + } + + file->delete_pending = delete_pending; + break; + + case FileRenameInformation: + { + if (!Stream_CheckAndLogRequiredLength(TAG, input, 6)) + return FALSE; + + /* http://msdn.microsoft.com/en-us/library/cc232085.aspx */ + Stream_Read_UINT8(input, ReplaceIfExists); + Stream_Seek_UINT8(input); /* RootDirectory */ + Stream_Read_UINT32(input, FileNameLength); + + if (!Stream_CheckAndLogRequiredLength(TAG, input, FileNameLength)) + return FALSE; + + WCHAR* fullpath = drive_file_combine_fullpath( + file->basepath, Stream_ConstPointer(input), FileNameLength / sizeof(WCHAR)); + + if (!fullpath) + return FALSE; + +#ifdef _WIN32 + + if (file->file_handle != INVALID_HANDLE_VALUE) + { + (void)CloseHandle(file->file_handle); + file->file_handle = INVALID_HANDLE_VALUE; + } + +#endif + DEBUG_WSTR("MoveFileExW %s", file->fullpath); + + if (MoveFileExW(file->fullpath, fullpath, + MOVEFILE_COPY_ALLOWED | + (ReplaceIfExists ? MOVEFILE_REPLACE_EXISTING : 0))) + { + const BOOL rc = drive_file_set_fullpath(file, fullpath); + free(fullpath); + if (!rc) + return FALSE; + } + else + { + free(fullpath); + return FALSE; + } + +#ifdef _WIN32 + drive_file_init(file); +#endif + } + break; + + default: + return FALSE; + } + + return TRUE; +} + +static BOOL drive_file_query_dir_info(DRIVE_FILE* file, wStream* output, size_t length) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(output); + + /* http://msdn.microsoft.com/en-us/library/cc232097.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 64 + length)) + return FALSE; + + if (length > UINT32_MAX - 64) + return FALSE; + + Stream_Write_UINT32(output, (UINT32)(64 + length)); /* Length */ + Stream_Write_UINT32(output, 0); /* NextEntryOffset */ + Stream_Write_UINT32(output, 0); /* FileIndex */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwLowDateTime); /* CreationTime */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwHighDateTime); /* CreationTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwLowDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwHighDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.dwFileAttributes); /* FileAttributes */ + Stream_Write_UINT32(output, (UINT32)length); /* FileNameLength */ + Stream_Write(output, file->find_data.cFileName, length); + return TRUE; +} + +static BOOL drive_file_query_full_dir_info(DRIVE_FILE* file, wStream* output, size_t length) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(output); + /* http://msdn.microsoft.com/en-us/library/cc232068.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 68 + length)) + return FALSE; + + if (length > UINT32_MAX - 68) + return FALSE; + + Stream_Write_UINT32(output, (UINT32)(68 + length)); /* Length */ + Stream_Write_UINT32(output, 0); /* NextEntryOffset */ + Stream_Write_UINT32(output, 0); /* FileIndex */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwLowDateTime); /* CreationTime */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwHighDateTime); /* CreationTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwLowDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwHighDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.dwFileAttributes); /* FileAttributes */ + Stream_Write_UINT32(output, (UINT32)length); /* FileNameLength */ + Stream_Write_UINT32(output, 0); /* EaSize */ + Stream_Write(output, file->find_data.cFileName, length); + return TRUE; +} + +static BOOL drive_file_query_both_dir_info(DRIVE_FILE* file, wStream* output, size_t length) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(output); + /* http://msdn.microsoft.com/en-us/library/cc232095.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 93 + length)) + return FALSE; + + if (length > UINT32_MAX - 93) + return FALSE; + + Stream_Write_UINT32(output, (UINT32)(93 + length)); /* Length */ + Stream_Write_UINT32(output, 0); /* NextEntryOffset */ + Stream_Write_UINT32(output, 0); /* FileIndex */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwLowDateTime); /* CreationTime */ + Stream_Write_UINT32(output, file->find_data.ftCreationTime.dwHighDateTime); /* CreationTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwLowDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, + file->find_data.ftLastAccessTime.dwHighDateTime); /* LastAccessTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* LastWriteTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwLowDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.ftLastWriteTime.dwHighDateTime); /* ChangeTime */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* EndOfFile */ + Stream_Write_UINT32(output, file->find_data.nFileSizeLow); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.nFileSizeHigh); /* AllocationSize */ + Stream_Write_UINT32(output, file->find_data.dwFileAttributes); /* FileAttributes */ + Stream_Write_UINT32(output, (UINT32)length); /* FileNameLength */ + Stream_Write_UINT32(output, 0); /* EaSize */ + Stream_Write_UINT8(output, 0); /* ShortNameLength */ + /* Reserved(1), MUST NOT be added! */ + Stream_Zero(output, 24); /* ShortName */ + Stream_Write(output, file->find_data.cFileName, length); + return TRUE; +} + +static BOOL drive_file_query_names_info(DRIVE_FILE* file, wStream* output, size_t length) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(output); + /* http://msdn.microsoft.com/en-us/library/cc232077.aspx */ + if (!Stream_EnsureRemainingCapacity(output, 4 + 12 + length)) + return FALSE; + + if (length > UINT32_MAX - 12) + return FALSE; + + Stream_Write_UINT32(output, (UINT32)(12 + length)); /* Length */ + Stream_Write_UINT32(output, 0); /* NextEntryOffset */ + Stream_Write_UINT32(output, 0); /* FileIndex */ + Stream_Write_UINT32(output, (UINT32)length); /* FileNameLength */ + Stream_Write(output, file->find_data.cFileName, length); + return TRUE; +} + +BOOL drive_file_query_directory(DRIVE_FILE* file, UINT32 FsInformationClass, BYTE InitialQuery, + const WCHAR* path, UINT32 PathWCharLength, wStream* output) +{ + BOOL rc = FALSE; + size_t length = 0; + WCHAR* ent_path = NULL; + + if (!file || !path || !output) + return FALSE; + + if (InitialQuery != 0) + { + /* release search handle */ + if (file->find_handle != INVALID_HANDLE_VALUE) + FindClose(file->find_handle); + + ent_path = drive_file_combine_fullpath(file->basepath, path, PathWCharLength); + /* open new search handle and retrieve the first entry */ + file->find_handle = FindFirstFileW(ent_path, &file->find_data); + free(ent_path); + + if (file->find_handle == INVALID_HANDLE_VALUE) + goto out_fail; + } + else if (!FindNextFileW(file->find_handle, &file->find_data)) + goto out_fail; + + length = _wcslen(file->find_data.cFileName) * 2; + + switch (FsInformationClass) + { + case FileDirectoryInformation: + rc = drive_file_query_dir_info(file, output, length); + break; + + case FileFullDirectoryInformation: + rc = drive_file_query_full_dir_info(file, output, length); + break; + + case FileBothDirectoryInformation: + rc = drive_file_query_both_dir_info(file, output, length); + break; + + case FileNamesInformation: + rc = drive_file_query_names_info(file, output, length); + break; + + default: + WLog_ERR(TAG, "unhandled FsInformationClass %" PRIu32, FsInformationClass); + /* Unhandled FsInformationClass */ + goto out_fail; + } + +out_fail: + if (!rc) + { + Stream_Write_UINT32(output, 0); /* Length */ + Stream_Write_UINT8(output, 0); /* Padding */ + } + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.h b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.h new file mode 100644 index 0000000000000000000000000000000000000000..761295b6576bf09d432a043bc44a33e329eb770a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_file.h @@ -0,0 +1,67 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * File System Virtual Channel + * + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2010-2011 Vic Lee + * Copyright 2012 Gerald Richter + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Inuvika Inc. + * Copyright 2016 David PHAM-VAN + * + * 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 FREERDP_CHANNEL_DRIVE_CLIENT_FILE_H +#define FREERDP_CHANNEL_DRIVE_CLIENT_FILE_H + +#include +#include +#include + +#define TAG CHANNELS_TAG("drive.client") + +typedef struct +{ + UINT32 id; + BOOL is_dir; + HANDLE file_handle; + HANDLE find_handle; + WIN32_FIND_DATAW find_data; + const WCHAR* basepath; + WCHAR* fullpath; + BOOL delete_pending; + UINT32 FileAttributes; + UINT32 SharedAccess; + UINT32 DesiredAccess; + UINT32 CreateDisposition; + UINT32 CreateOptions; +} DRIVE_FILE; + +DRIVE_FILE* drive_file_new(const WCHAR* base_path, const WCHAR* path, UINT32 PathWCharLength, + UINT32 id, UINT32 DesiredAccess, UINT32 CreateDisposition, + UINT32 CreateOptions, UINT32 FileAttributes, UINT32 SharedAccess); +BOOL drive_file_free(DRIVE_FILE* file); + +BOOL drive_file_open(DRIVE_FILE* file); +BOOL drive_file_seek(DRIVE_FILE* file, UINT64 Offset); +BOOL drive_file_read(DRIVE_FILE* file, BYTE* buffer, UINT32* Length); +BOOL drive_file_write(DRIVE_FILE* file, const BYTE* buffer, UINT32 Length); +BOOL drive_file_query_information(DRIVE_FILE* file, UINT32 FsInformationClass, wStream* output); +BOOL drive_file_set_information(DRIVE_FILE* file, UINT32 FsInformationClass, UINT32 Length, + wStream* input); +BOOL drive_file_query_directory(DRIVE_FILE* file, UINT32 FsInformationClass, BYTE InitialQuery, + const WCHAR* path, UINT32 PathWCharLength, wStream* output); + +#endif /* FREERDP_CHANNEL_DRIVE_FILE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_main.c new file mode 100644 index 0000000000000000000000000000000000000000..817178248606aec8767e8512de7703e15cb53a2b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/drive/client/drive_main.c @@ -0,0 +1,1153 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * File System Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "drive_file.h" + +typedef struct +{ + DEVICE device; + + WCHAR* path; + BOOL automount; + UINT32 PathLength; + wListDictionary* files; + + HANDLE thread; + BOOL async; + wMessageQueue* IrpQueue; + + DEVMAN* devman; + + rdpContext* rdpcontext; +} DRIVE_DEVICE; + +static NTSTATUS drive_map_windows_err(DWORD fs_errno) +{ + NTSTATUS rc = 0; + + /* try to return NTSTATUS version of error code */ + + switch (fs_errno) + { + case STATUS_SUCCESS: + rc = STATUS_SUCCESS; + break; + + case ERROR_ACCESS_DENIED: + case ERROR_SHARING_VIOLATION: + rc = STATUS_ACCESS_DENIED; + break; + + case ERROR_FILE_NOT_FOUND: + rc = STATUS_NO_SUCH_FILE; + break; + + case ERROR_BUSY_DRIVE: + rc = STATUS_DEVICE_BUSY; + break; + + case ERROR_INVALID_DRIVE: + rc = STATUS_NO_SUCH_DEVICE; + break; + + case ERROR_NOT_READY: + rc = STATUS_NO_SUCH_DEVICE; + break; + + case ERROR_FILE_EXISTS: + case ERROR_ALREADY_EXISTS: + rc = STATUS_OBJECT_NAME_COLLISION; + break; + + case ERROR_INVALID_NAME: + rc = STATUS_NO_SUCH_FILE; + break; + + case ERROR_INVALID_HANDLE: + rc = STATUS_INVALID_HANDLE; + break; + + case ERROR_NO_MORE_FILES: + rc = STATUS_NO_MORE_FILES; + break; + + case ERROR_DIRECTORY: + rc = STATUS_NOT_A_DIRECTORY; + break; + + case ERROR_PATH_NOT_FOUND: + rc = STATUS_OBJECT_PATH_NOT_FOUND; + break; + + default: + rc = STATUS_UNSUCCESSFUL; + WLog_ERR(TAG, "Error code not found: %" PRIu32 "", fs_errno); + break; + } + + return rc; +} + +static DRIVE_FILE* drive_get_file_by_id(DRIVE_DEVICE* drive, UINT32 id) +{ + DRIVE_FILE* file = NULL; + void* key = (void*)(size_t)id; + + if (!drive) + return NULL; + + file = (DRIVE_FILE*)ListDictionary_GetItemValue(drive->files, key); + return file; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_create(DRIVE_DEVICE* drive, IRP* irp) +{ + UINT32 FileId = 0; + DRIVE_FILE* file = NULL; + BYTE Information = 0; + UINT32 FileAttributes = 0; + UINT32 SharedAccess = 0; + UINT32 DesiredAccess = 0; + UINT32 CreateDisposition = 0; + UINT32 CreateOptions = 0; + UINT32 PathLength = 0; + UINT64 allocationSize = 0; + const WCHAR* path = NULL; + + if (!drive || !irp || !irp->devman || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 6 * 4 + 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, DesiredAccess); + Stream_Read_UINT64(irp->input, allocationSize); + Stream_Read_UINT32(irp->input, FileAttributes); + Stream_Read_UINT32(irp->input, SharedAccess); + Stream_Read_UINT32(irp->input, CreateDisposition); + Stream_Read_UINT32(irp->input, CreateOptions); + Stream_Read_UINT32(irp->input, PathLength); + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, PathLength)) + return ERROR_INVALID_DATA; + + path = Stream_ConstPointer(irp->input); + FileId = irp->devman->id_sequence++; + file = drive_file_new(drive->path, path, PathLength / sizeof(WCHAR), FileId, DesiredAccess, + CreateDisposition, CreateOptions, FileAttributes, SharedAccess); + + if (!file) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + FileId = 0; + Information = 0; + } + else + { + void* key = (void*)(size_t)file->id; + + if (!ListDictionary_Add(drive->files, key, file)) + { + WLog_ERR(TAG, "ListDictionary_Add failed!"); + return ERROR_INTERNAL_ERROR; + } + + switch (CreateDisposition) + { + case FILE_SUPERSEDE: + case FILE_OPEN: + case FILE_CREATE: + case FILE_OVERWRITE: + Information = FILE_SUPERSEDED; + break; + + case FILE_OPEN_IF: + Information = FILE_OPENED; + break; + + case FILE_OVERWRITE_IF: + Information = FILE_OVERWRITTEN; + break; + + default: + Information = 0; + break; + } + } + + Stream_Write_UINT32(irp->output, FileId); + Stream_Write_UINT8(irp->output, Information); + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_close(DRIVE_DEVICE* drive, IRP* irp) +{ + void* key = NULL; + DRIVE_FILE* file = NULL; + + if (!drive || !irp || !irp->Complete || !irp->output) + return ERROR_INVALID_PARAMETER; + + file = drive_get_file_by_id(drive, irp->FileId); + key = (void*)(size_t)irp->FileId; + + if (!file) + irp->IoStatus = STATUS_UNSUCCESSFUL; + else + { + ListDictionary_Take(drive->files, key); + + if (drive_file_free(file)) + irp->IoStatus = STATUS_SUCCESS; + else + irp->IoStatus = drive_map_windows_err(GetLastError()); + } + + Stream_Zero(irp->output, 5); /* Padding(5) */ + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_read(DRIVE_DEVICE* drive, IRP* irp) +{ + DRIVE_FILE* file = NULL; + UINT32 Length = 0; + UINT64 Offset = 0; + + if (!drive || !irp || !irp->output || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 12)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, Length); + Stream_Read_UINT64(irp->input, Offset); + file = drive_get_file_by_id(drive, irp->FileId); + + if (!file) + { + irp->IoStatus = STATUS_UNSUCCESSFUL; + Length = 0; + } + else if (!drive_file_seek(file, Offset)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + Length = 0; + } + + if (!Stream_EnsureRemainingCapacity(irp->output, Length + 4)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return ERROR_INTERNAL_ERROR; + } + else if (Length == 0) + Stream_Write_UINT32(irp->output, 0); + else + { + BYTE* buffer = Stream_PointerAs(irp->output, BYTE) + sizeof(UINT32); + + if (!drive_file_read(file, buffer, &Length)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + Stream_Write_UINT32(irp->output, 0); + } + else + { + Stream_Write_UINT32(irp->output, Length); + Stream_Seek(irp->output, Length); + } + } + + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_write(DRIVE_DEVICE* drive, IRP* irp) +{ + DRIVE_FILE* file = NULL; + UINT32 Length = 0; + UINT64 Offset = 0; + + if (!drive || !irp || !irp->input || !irp->output || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, Length); + Stream_Read_UINT64(irp->input, Offset); + Stream_Seek(irp->input, 20); /* Padding */ + const void* ptr = Stream_ConstPointer(irp->input); + if (!Stream_SafeSeek(irp->input, Length)) + return ERROR_INVALID_DATA; + file = drive_get_file_by_id(drive, irp->FileId); + + if (!file) + { + irp->IoStatus = STATUS_UNSUCCESSFUL; + Length = 0; + } + else if (!drive_file_seek(file, Offset)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + Length = 0; + } + else if (!drive_file_write(file, ptr, Length)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + Length = 0; + } + + Stream_Write_UINT32(irp->output, Length); + Stream_Write_UINT8(irp->output, 0); /* Padding */ + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_query_information(DRIVE_DEVICE* drive, IRP* irp) +{ + DRIVE_FILE* file = NULL; + UINT32 FsInformationClass = 0; + + if (!drive || !irp || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, FsInformationClass); + file = drive_get_file_by_id(drive, irp->FileId); + + if (!file) + { + irp->IoStatus = STATUS_UNSUCCESSFUL; + } + else if (!drive_file_query_information(file, FsInformationClass, irp->output)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + } + + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_set_information(DRIVE_DEVICE* drive, IRP* irp) +{ + DRIVE_FILE* file = NULL; + UINT32 FsInformationClass = 0; + UINT32 Length = 0; + + if (!drive || !irp || !irp->Complete || !irp->input || !irp->output) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, FsInformationClass); + Stream_Read_UINT32(irp->input, Length); + Stream_Seek(irp->input, 24); /* Padding */ + file = drive_get_file_by_id(drive, irp->FileId); + + if (!file) + { + irp->IoStatus = STATUS_UNSUCCESSFUL; + } + else if (!drive_file_set_information(file, FsInformationClass, Length, irp->input)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + } + + if (file && file->is_dir && !PathIsDirectoryEmptyW(file->fullpath)) + irp->IoStatus = STATUS_DIRECTORY_NOT_EMPTY; + + Stream_Write_UINT32(irp->output, Length); + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_query_volume_information(DRIVE_DEVICE* drive, IRP* irp) +{ + UINT32 FsInformationClass = 0; + wStream* output = NULL; + DWORD lpSectorsPerCluster = 0; + DWORD lpBytesPerSector = 0; + DWORD lpNumberOfFreeClusters = 0; + DWORD lpTotalNumberOfClusters = 0; + WIN32_FILE_ATTRIBUTE_DATA wfad = { 0 }; + WCHAR LabelBuffer[32] = { 0 }; + + if (!drive || !irp) + return ERROR_INVALID_PARAMETER; + + output = irp->output; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, FsInformationClass); + GetDiskFreeSpaceW(drive->path, &lpSectorsPerCluster, &lpBytesPerSector, &lpNumberOfFreeClusters, + &lpTotalNumberOfClusters); + + switch (FsInformationClass) + { + case FileFsVolumeInformation: + { + /* http://msdn.microsoft.com/en-us/library/cc232108.aspx */ + const WCHAR* volumeLabel = + InitializeConstWCharFromUtf8("FREERDP", LabelBuffer, ARRAYSIZE(LabelBuffer)); + const size_t volumeLabelLen = (_wcslen(volumeLabel) + 1) * sizeof(WCHAR); + const size_t length = 17ul + volumeLabelLen; + + if ((length > UINT32_MAX) || (volumeLabelLen > UINT32_MAX)) + return CHANNEL_RC_NO_BUFFER; + + Stream_Write_UINT32(output, (UINT32)length); /* Length */ + + if (!Stream_EnsureRemainingCapacity(output, length)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + GetFileAttributesExW(drive->path, GetFileExInfoStandard, &wfad); + Stream_Write_UINT32(output, wfad.ftCreationTime.dwLowDateTime); /* VolumeCreationTime */ + Stream_Write_UINT32(output, + wfad.ftCreationTime.dwHighDateTime); /* VolumeCreationTime */ + Stream_Write_UINT32(output, lpNumberOfFreeClusters & 0xffff); /* VolumeSerialNumber */ + Stream_Write_UINT32(output, (UINT32)volumeLabelLen); /* VolumeLabelLength */ + Stream_Write_UINT8(output, 0); /* SupportsObjects */ + /* Reserved(1), MUST NOT be added! */ + Stream_Write(output, volumeLabel, volumeLabelLen); /* VolumeLabel (Unicode) */ + } + break; + + case FileFsSizeInformation: + /* http://msdn.microsoft.com/en-us/library/cc232107.aspx */ + Stream_Write_UINT32(output, 24); /* Length */ + + if (!Stream_EnsureRemainingCapacity(output, 24)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */ + Stream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */ + Stream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */ + Stream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */ + break; + + case FileFsAttributeInformation: + { + /* http://msdn.microsoft.com/en-us/library/cc232101.aspx */ + const WCHAR* diskType = + InitializeConstWCharFromUtf8("FAT32", LabelBuffer, ARRAYSIZE(LabelBuffer)); + const size_t diskTypeLen = (_wcslen(diskType) + 1) * sizeof(WCHAR); + const size_t length = 12ul + diskTypeLen; + + if ((length > UINT32_MAX) || (diskTypeLen > UINT32_MAX)) + return CHANNEL_RC_NO_BUFFER; + + Stream_Write_UINT32(output, (UINT32)length); /* Length */ + + if (!Stream_EnsureRemainingCapacity(output, length)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT32(output, FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES | + FILE_UNICODE_ON_DISK); /* FileSystemAttributes */ + Stream_Write_UINT32(output, MAX_PATH); /* MaximumComponentNameLength */ + Stream_Write_UINT32(output, (UINT32)diskTypeLen); /* FileSystemNameLength */ + Stream_Write(output, diskType, diskTypeLen); /* FileSystemName (Unicode) */ + } + break; + + case FileFsFullSizeInformation: + /* http://msdn.microsoft.com/en-us/library/cc232104.aspx */ + Stream_Write_UINT32(output, 32); /* Length */ + + if (!Stream_EnsureRemainingCapacity(output, 32)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */ + Stream_Write_UINT64(output, + lpNumberOfFreeClusters); /* CallerAvailableAllocationUnits */ + Stream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */ + Stream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */ + Stream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */ + break; + + case FileFsDeviceInformation: + /* http://msdn.microsoft.com/en-us/library/cc232109.aspx */ + Stream_Write_UINT32(output, 8); /* Length */ + + if (!Stream_EnsureRemainingCapacity(output, 8)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT32(output, FILE_DEVICE_DISK); /* DeviceType */ + Stream_Write_UINT32(output, 0); /* Characteristics */ + break; + + default: + irp->IoStatus = STATUS_UNSUCCESSFUL; + Stream_Write_UINT32(output, 0); /* Length */ + break; + } + + return irp->Complete(irp); +} + +/* http://msdn.microsoft.com/en-us/library/cc241518.aspx */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_silent_ignore(DRIVE_DEVICE* drive, IRP* irp) +{ + UINT32 FsInformationClass = 0; + + if (!drive || !irp || !irp->output || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, FsInformationClass); + Stream_Write_UINT32(irp->output, 0); /* Length */ + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_query_directory(DRIVE_DEVICE* drive, IRP* irp) +{ + const WCHAR* path = NULL; + DRIVE_FILE* file = NULL; + BYTE InitialQuery = 0; + UINT32 PathLength = 0; + UINT32 FsInformationClass = 0; + + if (!drive || !irp || !irp->Complete) + return ERROR_INVALID_PARAMETER; + + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(irp->input, FsInformationClass); + Stream_Read_UINT8(irp->input, InitialQuery); + Stream_Read_UINT32(irp->input, PathLength); + Stream_Seek(irp->input, 23); /* Padding */ + path = Stream_ConstPointer(irp->input); + if (!Stream_CheckAndLogRequiredLength(TAG, irp->input, PathLength)) + return ERROR_INVALID_DATA; + + file = drive_get_file_by_id(drive, irp->FileId); + + if (file == NULL) + { + irp->IoStatus = STATUS_UNSUCCESSFUL; + Stream_Write_UINT32(irp->output, 0); /* Length */ + } + else if (!drive_file_query_directory(file, FsInformationClass, InitialQuery, path, + PathLength / sizeof(WCHAR), irp->output)) + { + irp->IoStatus = drive_map_windows_err(GetLastError()); + } + + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_directory_control(DRIVE_DEVICE* drive, IRP* irp) +{ + if (!drive || !irp) + return ERROR_INVALID_PARAMETER; + + switch (irp->MinorFunction) + { + case IRP_MN_QUERY_DIRECTORY: + return drive_process_irp_query_directory(drive, irp); + + case IRP_MN_NOTIFY_CHANGE_DIRECTORY: /* TODO */ + return irp->Discard(irp); + + default: + irp->IoStatus = STATUS_NOT_SUPPORTED; + Stream_Write_UINT32(irp->output, 0); /* Length */ + return irp->Complete(irp); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp_device_control(DRIVE_DEVICE* drive, IRP* irp) +{ + if (!drive || !irp) + return ERROR_INVALID_PARAMETER; + + Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */ + return irp->Complete(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_process_irp(DRIVE_DEVICE* drive, IRP* irp) +{ + UINT error = 0; + + if (!drive || !irp) + return ERROR_INVALID_PARAMETER; + + irp->IoStatus = STATUS_SUCCESS; + + switch (irp->MajorFunction) + { + case IRP_MJ_CREATE: + error = drive_process_irp_create(drive, irp); + break; + + case IRP_MJ_CLOSE: + error = drive_process_irp_close(drive, irp); + break; + + case IRP_MJ_READ: + error = drive_process_irp_read(drive, irp); + break; + + case IRP_MJ_WRITE: + error = drive_process_irp_write(drive, irp); + break; + + case IRP_MJ_QUERY_INFORMATION: + error = drive_process_irp_query_information(drive, irp); + break; + + case IRP_MJ_SET_INFORMATION: + error = drive_process_irp_set_information(drive, irp); + break; + + case IRP_MJ_QUERY_VOLUME_INFORMATION: + error = drive_process_irp_query_volume_information(drive, irp); + break; + + case IRP_MJ_LOCK_CONTROL: + error = drive_process_irp_silent_ignore(drive, irp); + break; + + case IRP_MJ_DIRECTORY_CONTROL: + error = drive_process_irp_directory_control(drive, irp); + break; + + case IRP_MJ_DEVICE_CONTROL: + error = drive_process_irp_device_control(drive, irp); + break; + + default: + irp->IoStatus = STATUS_NOT_SUPPORTED; + error = irp->Complete(irp); + break; + } + + return error; +} + +static BOOL drive_poll_run(DRIVE_DEVICE* drive, IRP* irp) +{ + WINPR_ASSERT(drive); + + if (irp) + { + const UINT error = drive_process_irp(drive, irp); + if (error) + { + WLog_ERR(TAG, "drive_process_irp failed with error %" PRIu32 "!", error); + return FALSE; + } + } + + return TRUE; +} + +static DWORD WINAPI drive_thread_func(LPVOID arg) +{ + DRIVE_DEVICE* drive = (DRIVE_DEVICE*)arg; + UINT error = CHANNEL_RC_OK; + + if (!drive) + { + error = ERROR_INVALID_PARAMETER; + goto fail; + } + + while (1) + { + if (!MessageQueue_Wait(drive->IrpQueue)) + { + WLog_ERR(TAG, "MessageQueue_Wait failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (MessageQueue_Size(drive->IrpQueue) < 1) + continue; + + wMessage message = { 0 }; + if (!MessageQueue_Peek(drive->IrpQueue, &message, TRUE)) + { + WLog_ERR(TAG, "MessageQueue_Peek failed!"); + continue; + } + + if (message.id == WMQ_QUIT) + break; + + IRP* irp = (IRP*)message.wParam; + if (!drive_poll_run(drive, irp)) + break; + } + +fail: + + if (error && drive && drive->rdpcontext) + setChannelError(drive->rdpcontext, error, "drive_thread_func reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_irp_request(DEVICE* device, IRP* irp) +{ + DRIVE_DEVICE* drive = (DRIVE_DEVICE*)device; + + if (!drive) + return ERROR_INVALID_PARAMETER; + + if (drive->async) + { + if (!MessageQueue_Post(drive->IrpQueue, NULL, 0, (void*)irp, NULL)) + { + WLog_ERR(TAG, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + } + else + { + if (!drive_poll_run(drive, irp)) + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +static UINT drive_free_int(DRIVE_DEVICE* drive) +{ + UINT error = CHANNEL_RC_OK; + + if (!drive) + return ERROR_INVALID_PARAMETER; + + (void)CloseHandle(drive->thread); + ListDictionary_Free(drive->files); + MessageQueue_Free(drive->IrpQueue); + Stream_Free(drive->device.data, TRUE); + free(drive->path); + free(drive); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_free(DEVICE* device) +{ + DRIVE_DEVICE* drive = (DRIVE_DEVICE*)device; + UINT error = CHANNEL_RC_OK; + + if (!drive) + return ERROR_INVALID_PARAMETER; + + if (MessageQueue_PostQuit(drive->IrpQueue, 0) && + (WaitForSingleObject(drive->thread, INFINITE) == WAIT_FAILED)) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); + return error; + } + + return drive_free_int(drive); +} + +/** + * Helper function used for freeing list dictionary value object + */ +static void drive_file_objfree(void* obj) +{ + drive_file_free((DRIVE_FILE*)obj); +} + +static void drive_message_free(void* obj) +{ + wMessage* msg = obj; + if (!msg) + return; + if (msg->id != 0) + return; + + IRP* irp = (IRP*)msg->wParam; + if (!irp) + return; + WINPR_ASSERT(irp->Discard); + irp->Discard(irp); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_register_drive_path(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, const char* name, + const char* path, BOOL automount) +{ + size_t length = 0; + DRIVE_DEVICE* drive = NULL; + UINT error = ERROR_INTERNAL_ERROR; + + if (!pEntryPoints || !name || !path) + { + WLog_ERR(TAG, "[%s] Invalid parameters: pEntryPoints=%p, name=%p, path=%p", pEntryPoints, + name, path); + return ERROR_INVALID_PARAMETER; + } + + if (name[0] && path[0]) + { + size_t pathLength = strnlen(path, MAX_PATH); + drive = (DRIVE_DEVICE*)calloc(1, sizeof(DRIVE_DEVICE)); + + if (!drive) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + drive->device.type = RDPDR_DTYP_FILESYSTEM; + drive->device.IRPRequest = drive_irp_request; + drive->device.Free = drive_free; + drive->rdpcontext = pEntryPoints->rdpcontext; + drive->automount = automount; + length = strlen(name); + drive->device.data = Stream_New(NULL, length + 1); + + if (!drive->device.data) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out_error; + } + + for (size_t i = 0; i < length; i++) + { + /* Filter 2.2.1.3 Device Announce Header (DEVICE_ANNOUNCE) forbidden symbols */ + switch (name[i]) + { + case ':': + case '<': + case '>': + case '\"': + case '/': + case '\\': + case '|': + case ' ': + Stream_Write_UINT8(drive->device.data, '_'); + break; + default: + Stream_Write_UINT8(drive->device.data, (BYTE)name[i]); + break; + } + } + Stream_Write_UINT8(drive->device.data, '\0'); + + drive->device.name = Stream_BufferAs(drive->device.data, char); + if (!drive->device.name) + goto out_error; + + if ((pathLength > 1) && (path[pathLength - 1] == '/')) + pathLength--; + + drive->path = ConvertUtf8NToWCharAlloc(path, pathLength, NULL); + if (!drive->path) + { + error = CHANNEL_RC_NO_MEMORY; + goto out_error; + } + + drive->files = ListDictionary_New(TRUE); + + if (!drive->files) + { + WLog_ERR(TAG, "ListDictionary_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out_error; + } + + ListDictionary_ValueObject(drive->files)->fnObjectFree = drive_file_objfree; + drive->IrpQueue = MessageQueue_New(NULL); + + if (!drive->IrpQueue) + { + WLog_ERR(TAG, "ListDictionary_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out_error; + } + + wObject* obj = MessageQueue_Object(drive->IrpQueue); + WINPR_ASSERT(obj); + obj->fnObjectFree = drive_message_free; + + if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)drive))) + { + WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error); + goto out_error; + } + + drive->async = !freerdp_settings_get_bool(drive->rdpcontext->settings, + FreeRDP_SynchronousStaticChannels); + if (drive->async) + { + if (!(drive->thread = + CreateThread(NULL, 0, drive_thread_func, drive, CREATE_SUSPENDED, NULL))) + { + WLog_ERR(TAG, "CreateThread failed!"); + goto out_error; + } + + ResumeThread(drive->thread); + } + } + + return CHANNEL_RC_OK; +out_error: + drive_free_int(drive); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT( + UINT VCAPITYPE drive_DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)) +{ + RDPDR_DRIVE* drive = NULL; + UINT error = 0; +#ifdef WIN32 + int len; + char devlist[512], buf[512]; + char* bufdup; + char* devdup; +#endif + + WINPR_ASSERT(pEntryPoints); + + drive = (RDPDR_DRIVE*)pEntryPoints->device; + WINPR_ASSERT(drive); + +#ifndef WIN32 + if (strcmp(drive->Path, "*") == 0) + { + /* all drives */ + free(drive->Path); + drive->Path = _strdup("/"); + + if (!drive->Path) + { + WLog_ERR(TAG, "_strdup failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + else if (strcmp(drive->Path, "%") == 0) + { + free(drive->Path); + drive->Path = GetKnownPath(KNOWN_PATH_HOME); + + if (!drive->Path) + { + WLog_ERR(TAG, "_strdup failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + + error = + drive_register_drive_path(pEntryPoints, drive->device.Name, drive->Path, drive->automount); +#else + /* Special case: path[0] == '*' -> export all drives */ + /* Special case: path[0] == '%' -> user home dir */ + if (strcmp(drive->Path, "%") == 0) + { + GetEnvironmentVariableA("USERPROFILE", buf, sizeof(buf)); + PathCchAddBackslashA(buf, sizeof(buf)); + free(drive->Path); + drive->Path = _strdup(buf); + + if (!drive->Path) + { + WLog_ERR(TAG, "_strdup failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + error = drive_register_drive_path(pEntryPoints, drive->device.Name, drive->Path, + drive->automount); + } + else if (strcmp(drive->Path, "*") == 0) + { + /* Enumerate all devices: */ + GetLogicalDriveStringsA(sizeof(devlist) - 1, devlist); + + for (size_t i = 0;; i++) + { + char* dev = &devlist[i * 4]; + if (!*dev) + break; + if (*dev > 'B') + { + /* Suppress disk drives A and B to avoid pesty messages */ + len = sprintf_s(buf, sizeof(buf) - 4, "%s", drive->device.Name); + buf[len] = '_'; + buf[len + 1] = dev[0]; + buf[len + 2] = 0; + buf[len + 3] = 0; + + if (!(bufdup = _strdup(buf))) + { + WLog_ERR(TAG, "_strdup failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if (!(devdup = _strdup(dev))) + { + WLog_ERR(TAG, "_strdup failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if ((error = drive_register_drive_path(pEntryPoints, bufdup, devdup, TRUE))) + { + break; + } + } + } + } + else + { + error = drive_register_drive_path(pEntryPoints, drive->device.Name, drive->Path, + drive->automount); + } + +#endif + return error; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/echo/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/echo/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b894fb06aba28ecd3847a20d1e7adcc776b69555 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/echo/server/CMakeLists.txt @@ -0,0 +1,23 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("echo") + +set(${MODULE_PREFIX}_SRCS echo_main.c) + +set(${MODULE_PREFIX}_LIBS freerdp) +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4bc27e200f4098e63eb1a5a6b32cf7a90f9b9ac8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client("encomsp") + +include_directories(..) + +set(${MODULE_PREFIX}_SRCS encomsp_main.c encomsp_main.h) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntryEx") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.c new file mode 100644 index 0000000000000000000000000000000000000000..54a25149ebfa03b1403dda849bb893c645653b14 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.c @@ -0,0 +1,1304 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Multiparty Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include + +#include +#include +#include + +#include "encomsp_main.h" + +struct encomsp_plugin +{ + CHANNEL_DEF channelDef; + CHANNEL_ENTRY_POINTS_FREERDP_EX channelEntryPoints; + + EncomspClientContext* context; + + HANDLE thread; + wStream* data_in; + void* InitHandle; + DWORD OpenHandle; + wMessageQueue* queue; + rdpContext* rdpcontext; +}; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_read_header(wStream* s, ENCOMSP_ORDER_HEADER* header) +{ + WINPR_ASSERT(header); + if (!Stream_CheckAndLogRequiredLength(TAG, s, ENCOMSP_ORDER_HEADER_SIZE)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, header->Type); /* Type (2 bytes) */ + Stream_Read_UINT16(s, header->Length); /* Length (2 bytes) */ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_write_header(wStream* s, const ENCOMSP_ORDER_HEADER* header) +{ + WINPR_ASSERT(header); + Stream_Write_UINT16(s, header->Type); /* Type (2 bytes) */ + Stream_Write_UINT16(s, header->Length); /* Length (2 bytes) */ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_read_unicode_string(wStream* s, ENCOMSP_UNICODE_STRING* str) +{ + WINPR_ASSERT(str); + const ENCOMSP_UNICODE_STRING empty = { 0 }; + *str = empty; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 2)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, str->cchString); /* cchString (2 bytes) */ + + if (str->cchString > 1024) + { + WLog_ERR(TAG, "cchString was %" PRIu16 " but has to be < 1025!", str->cchString); + return ERROR_INVALID_DATA; + } + + if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, str->cchString, sizeof(WCHAR))) + return ERROR_INVALID_DATA; + + Stream_Read(s, &(str->wString), (sizeof(WCHAR) * str->cchString)); /* String (variable) */ + return CHANNEL_RC_OK; +} + +static EncomspClientContext* encomsp_get_client_interface(encomspPlugin* encomsp) +{ + WINPR_ASSERT(encomsp); + return (EncomspClientContext*)encomsp->channelEntryPoints.pInterface; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_virtual_channel_write(encomspPlugin* encomsp, wStream* s) +{ + if (!encomsp) + { + Stream_Free(s, TRUE); + return ERROR_INVALID_HANDLE; + } + +#if 0 + WLog_INFO(TAG, "EncomspWrite (%"PRIuz")", Stream_Length(s)); + winpr_HexDump(Stream_Buffer(s), Stream_Length(s)); +#endif + const UINT status = encomsp->channelEntryPoints.pVirtualChannelWriteEx( + encomsp->InitHandle, encomsp->OpenHandle, Stream_Buffer(s), (UINT32)Stream_Length(s), s); + + if (status != CHANNEL_RC_OK) + { + Stream_Free(s, TRUE); + WLog_ERR(TAG, "VirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + } + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_filter_updated_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_FILTER_UPDATED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + WINPR_ASSERT(header); + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, pdu.Flags); /* Flags (1 byte) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->FilterUpdated, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->FilterUpdated failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_application_created_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_APPLICATION_CREATED_PDU pdu = { 0 }; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 6)) + return ERROR_INVALID_DATA; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + Stream_Read_UINT16(s, pdu.Flags); /* Flags (2 bytes) */ + Stream_Read_UINT32(s, pdu.AppId); /* AppId (4 bytes) */ + + UINT error = encomsp_read_unicode_string(s, &(pdu.Name)); + if (error != CHANNEL_RC_OK) + { + WLog_ERR(TAG, "encomsp_read_unicode_string failed with error %" PRIu32 "", error); + return error; + } + + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ApplicationCreated, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ApplicationCreated failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_application_removed_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_APPLICATION_REMOVED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, pdu.AppId); /* AppId (4 bytes) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ApplicationRemoved, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ApplicationRemoved failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_window_created_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_WINDOW_CREATED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 10)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, pdu.Flags); /* Flags (2 bytes) */ + Stream_Read_UINT32(s, pdu.AppId); /* AppId (4 bytes) */ + Stream_Read_UINT32(s, pdu.WndId); /* WndId (4 bytes) */ + + if ((error = encomsp_read_unicode_string(s, &(pdu.Name)))) + { + WLog_ERR(TAG, "encomsp_read_unicode_string failed with error %" PRIu32 "", error); + return error; + } + + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->WindowCreated, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->WindowCreated failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_window_removed_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_WINDOW_REMOVED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, pdu.WndId); /* WndId (4 bytes) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->WindowRemoved, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->WindowRemoved failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_show_window_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_SHOW_WINDOW_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, pdu.WndId); /* WndId (4 bytes) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ShowWindow, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ShowWindow failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_participant_created_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_PARTICIPANT_CREATED_PDU pdu = { 0 }; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 10)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, pdu.ParticipantId); /* ParticipantId (4 bytes) */ + Stream_Read_UINT32(s, pdu.GroupId); /* GroupId (4 bytes) */ + Stream_Read_UINT16(s, pdu.Flags); /* Flags (2 bytes) */ + + UINT error = encomsp_read_unicode_string(s, &(pdu.FriendlyName)); + if (error != CHANNEL_RC_OK) + { + WLog_ERR(TAG, "encomsp_read_unicode_string failed with error %" PRIu32 "", error); + return error; + } + + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ParticipantCreated, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ParticipantCreated failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_participant_removed_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_PARTICIPANT_REMOVED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 12)) + return ERROR_INVALID_DATA; + + const size_t beg = (Stream_GetPosition(s)) - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + Stream_Read_UINT32(s, pdu.ParticipantId); /* ParticipantId (4 bytes) */ + Stream_Read_UINT32(s, pdu.DiscType); /* DiscType (4 bytes) */ + Stream_Read_UINT32(s, pdu.DiscCode); /* DiscCode (4 bytes) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ParticipantRemoved, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ParticipantRemoved failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_change_participant_control_level_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_CHANGE_PARTICIPANT_CONTROL_LEVEL_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 6)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, pdu.Flags); /* Flags (2 bytes) */ + Stream_Read_UINT32(s, pdu.ParticipantId); /* ParticipantId (4 bytes) */ + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->ChangeParticipantControlLevel, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ChangeParticipantControlLevel failed with error %" PRIu32 "", + error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_send_change_participant_control_level_pdu( + EncomspClientContext* context, const ENCOMSP_CHANGE_PARTICIPANT_CONTROL_LEVEL_PDU* pdu) +{ + ENCOMSP_ORDER_HEADER header = { 0 }; + + WINPR_ASSERT(context); + encomspPlugin* encomsp = (encomspPlugin*)context->handle; + + header.Type = ODTYPE_PARTICIPANT_CTRL_CHANGED; + header.Length = ENCOMSP_ORDER_HEADER_SIZE + 6; + + wStream* s = Stream_New(NULL, header.Length); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + const UINT error = encomsp_write_header(s, &header); + if (error != CHANNEL_RC_OK) + { + WLog_ERR(TAG, "encomsp_write_header failed with error %" PRIu32 "!", error); + return error; + } + + Stream_Write_UINT16(s, pdu->Flags); /* Flags (2 bytes) */ + Stream_Write_UINT32(s, pdu->ParticipantId); /* ParticipantId (4 bytes) */ + Stream_SealLength(s); + return encomsp_virtual_channel_write(encomsp, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_graphics_stream_paused_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_GRAPHICS_STREAM_PAUSED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->GraphicsStreamPaused, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->GraphicsStreamPaused failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_graphics_stream_resumed_pdu(encomspPlugin* encomsp, wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_GRAPHICS_STREAM_RESUMED_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + EncomspClientContext* context = encomsp_get_client_interface(encomsp); + + if (!context) + return ERROR_INVALID_HANDLE; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_DATA; + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + + WINPR_ASSERT(header); + pdu.Length = header->Length; + pdu.Type = header->Type; + + const size_t end = Stream_GetPosition(s); + const size_t body = beg + header->Length; + + if (body < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if (body > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)(body - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, body); + } + + IFCALLRET(context->GraphicsStreamResumed, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->GraphicsStreamResumed failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_process_receive(encomspPlugin* encomsp, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + ENCOMSP_ORDER_HEADER header = { 0 }; + + WINPR_ASSERT(encomsp); + while (Stream_GetRemainingLength(s) > 0) + { + if ((error = encomsp_read_header(s, &header))) + { + WLog_ERR(TAG, "encomsp_read_header failed with error %" PRIu32 "!", error); + return error; + } + + // WLog_DBG(TAG, "EncomspReceive: Type: %"PRIu16" Length: %"PRIu16"", header.Type, + // header.Length); + + switch (header.Type) + { + case ODTYPE_FILTER_STATE_UPDATED: + if ((error = encomsp_recv_filter_updated_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, "encomsp_recv_filter_updated_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_APP_REMOVED: + if ((error = encomsp_recv_application_removed_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_application_removed_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_APP_CREATED: + if ((error = encomsp_recv_application_created_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_application_removed_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_WND_REMOVED: + if ((error = encomsp_recv_window_removed_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, "encomsp_recv_window_removed_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_WND_CREATED: + if ((error = encomsp_recv_window_created_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, "encomsp_recv_window_created_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_WND_SHOW: + if ((error = encomsp_recv_show_window_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, "encomsp_recv_show_window_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_PARTICIPANT_REMOVED: + if ((error = encomsp_recv_participant_removed_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_participant_removed_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_PARTICIPANT_CREATED: + if ((error = encomsp_recv_participant_created_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_participant_created_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_PARTICIPANT_CTRL_CHANGED: + if ((error = + encomsp_recv_change_participant_control_level_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_change_participant_control_level_pdu failed with error " + "%" PRIu32 "!", + error); + return error; + } + + break; + + case ODTYPE_GRAPHICS_STREAM_PAUSED: + if ((error = encomsp_recv_graphics_stream_paused_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_graphics_stream_paused_pdu failed with error %" PRIu32 + "!", + error); + return error; + } + + break; + + case ODTYPE_GRAPHICS_STREAM_RESUMED: + if ((error = encomsp_recv_graphics_stream_resumed_pdu(encomsp, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_graphics_stream_resumed_pdu failed with error %" PRIu32 + "!", + error); + return error; + } + + break; + + default: + WLog_ERR(TAG, "header.Type %" PRIu16 " not found", header.Type); + return ERROR_INVALID_DATA; + } + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_virtual_channel_event_data_received(encomspPlugin* encomsp, const void* pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + WINPR_ASSERT(encomsp); + + if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) + return CHANNEL_RC_OK; + + if (dataFlags & CHANNEL_FLAG_FIRST) + { + if (encomsp->data_in) + Stream_Free(encomsp->data_in, TRUE); + + encomsp->data_in = Stream_New(NULL, totalLength); + + if (!encomsp->data_in) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + + wStream* data_in = encomsp->data_in; + + if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return ERROR_INTERNAL_ERROR; + } + + Stream_Write(data_in, pData, dataLength); + + if (dataFlags & CHANNEL_FLAG_LAST) + { + if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) + { + WLog_ERR(TAG, "encomsp_plugin_process_received: read error"); + return ERROR_INVALID_DATA; + } + + encomsp->data_in = NULL; + Stream_SealLength(data_in); + Stream_SetPosition(data_in, 0); + + if (!MessageQueue_Post(encomsp->queue, NULL, 0, (void*)data_in, NULL)) + { + WLog_ERR(TAG, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + } + + return CHANNEL_RC_OK; +} + +static VOID VCAPITYPE encomsp_virtual_channel_open_event_ex(LPVOID lpUserParam, DWORD openHandle, + UINT event, LPVOID pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + UINT error = CHANNEL_RC_OK; + encomspPlugin* encomsp = (encomspPlugin*)lpUserParam; + + switch (event) + { + case CHANNEL_EVENT_DATA_RECEIVED: + if (!encomsp || (encomsp->OpenHandle != openHandle)) + { + WLog_ERR(TAG, "error no match"); + return; + } + if ((error = encomsp_virtual_channel_event_data_received(encomsp, pData, dataLength, + totalLength, dataFlags))) + WLog_ERR(TAG, + "encomsp_virtual_channel_event_data_received failed with error %" PRIu32 + "", + error); + + break; + + case CHANNEL_EVENT_WRITE_CANCELLED: + case CHANNEL_EVENT_WRITE_COMPLETE: + { + wStream* s = (wStream*)pData; + Stream_Free(s, TRUE); + } + break; + + case CHANNEL_EVENT_USER: + break; + default: + break; + } + + if (error && encomsp && encomsp->rdpcontext) + setChannelError(encomsp->rdpcontext, error, + "encomsp_virtual_channel_open_event reported an error"); +} + +static DWORD WINAPI encomsp_virtual_channel_client_thread(LPVOID arg) +{ + wStream* data = NULL; + wMessage message = { 0 }; + encomspPlugin* encomsp = (encomspPlugin*)arg; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(encomsp); + while (1) + { + if (!MessageQueue_Wait(encomsp->queue)) + { + WLog_ERR(TAG, "MessageQueue_Wait failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (!MessageQueue_Peek(encomsp->queue, &message, TRUE)) + { + WLog_ERR(TAG, "MessageQueue_Peek failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (message.id == WMQ_QUIT) + break; + + if (message.id == 0) + { + data = (wStream*)message.wParam; + + if ((error = encomsp_process_receive(encomsp, data))) + { + WLog_ERR(TAG, "encomsp_process_receive failed with error %" PRIu32 "!", error); + Stream_Free(data, TRUE); + break; + } + + Stream_Free(data, TRUE); + } + } + + if (error && encomsp->rdpcontext) + setChannelError(encomsp->rdpcontext, error, + "encomsp_virtual_channel_client_thread reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_virtual_channel_event_connected(encomspPlugin* encomsp, LPVOID pData, + UINT32 dataLength) +{ + WINPR_ASSERT(encomsp); + + encomsp->queue = MessageQueue_New(NULL); + + if (!encomsp->queue) + { + WLog_ERR(TAG, "MessageQueue_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if (!(encomsp->thread = CreateThread(NULL, 0, encomsp_virtual_channel_client_thread, + (void*)encomsp, 0, NULL))) + { + WLog_ERR(TAG, "CreateThread failed!"); + MessageQueue_Free(encomsp->queue); + return ERROR_INTERNAL_ERROR; + } + + return encomsp->channelEntryPoints.pVirtualChannelOpenEx( + encomsp->InitHandle, &encomsp->OpenHandle, encomsp->channelDef.name, + encomsp_virtual_channel_open_event_ex); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_virtual_channel_event_disconnected(encomspPlugin* encomsp) +{ + WINPR_ASSERT(encomsp); + if (encomsp->OpenHandle == 0) + return CHANNEL_RC_OK; + + if (encomsp->queue && encomsp->thread) + { + if (MessageQueue_PostQuit(encomsp->queue, 0) && + (WaitForSingleObject(encomsp->thread, INFINITE) == WAIT_FAILED)) + { + const UINT rc = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", rc); + return rc; + } + } + + MessageQueue_Free(encomsp->queue); + (void)CloseHandle(encomsp->thread); + encomsp->queue = NULL; + encomsp->thread = NULL; + + WINPR_ASSERT(encomsp->channelEntryPoints.pVirtualChannelCloseEx); + const UINT rc = encomsp->channelEntryPoints.pVirtualChannelCloseEx(encomsp->InitHandle, + encomsp->OpenHandle); + + if (CHANNEL_RC_OK != rc) + { + WLog_ERR(TAG, "pVirtualChannelClose failed with %s [%08" PRIX32 "]", WTSErrorToString(rc), + rc); + return rc; + } + + encomsp->OpenHandle = 0; + + if (encomsp->data_in) + { + Stream_Free(encomsp->data_in, TRUE); + encomsp->data_in = NULL; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_virtual_channel_event_terminated(encomspPlugin* encomsp) +{ + WINPR_ASSERT(encomsp); + + encomsp->InitHandle = 0; + free(encomsp->context); + free(encomsp); + return CHANNEL_RC_OK; +} + +static VOID VCAPITYPE encomsp_virtual_channel_init_event_ex(LPVOID lpUserParam, LPVOID pInitHandle, + UINT event, LPVOID pData, + UINT dataLength) +{ + UINT error = CHANNEL_RC_OK; + encomspPlugin* encomsp = (encomspPlugin*)lpUserParam; + + if (!encomsp || (encomsp->InitHandle != pInitHandle)) + { + WLog_ERR(TAG, "error no match"); + return; + } + + switch (event) + { + case CHANNEL_EVENT_INITIALIZED: + break; + + case CHANNEL_EVENT_CONNECTED: + if ((error = encomsp_virtual_channel_event_connected(encomsp, pData, dataLength))) + WLog_ERR(TAG, + "encomsp_virtual_channel_event_connected failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_DISCONNECTED: + if ((error = encomsp_virtual_channel_event_disconnected(encomsp))) + WLog_ERR(TAG, + "encomsp_virtual_channel_event_disconnected failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_TERMINATED: + encomsp_virtual_channel_event_terminated(encomsp); + break; + + default: + break; + } + + if (error && encomsp->rdpcontext) + setChannelError(encomsp->rdpcontext, error, + "encomsp_virtual_channel_init_event reported an error"); +} + +/* encomsp is always built-in */ +#define VirtualChannelEntryEx encomsp_VirtualChannelEntryEx + +FREERDP_ENTRY_POINT(BOOL VCAPITYPE VirtualChannelEntryEx(PCHANNEL_ENTRY_POINTS_EX pEntryPoints, + PVOID pInitHandle)) +{ + BOOL isFreerdp = FALSE; + encomspPlugin* encomsp = (encomspPlugin*)calloc(1, sizeof(encomspPlugin)); + + if (!encomsp) + { + WLog_ERR(TAG, "calloc failed!"); + return FALSE; + } + + encomsp->channelDef.options = CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | + CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL; + (void)sprintf_s(encomsp->channelDef.name, ARRAYSIZE(encomsp->channelDef.name), + ENCOMSP_SVC_CHANNEL_NAME); + CHANNEL_ENTRY_POINTS_FREERDP_EX* pEntryPointsEx = + (CHANNEL_ENTRY_POINTS_FREERDP_EX*)pEntryPoints; + WINPR_ASSERT(pEntryPointsEx); + + EncomspClientContext* context = NULL; + if ((pEntryPointsEx->cbSize >= sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)) && + (pEntryPointsEx->MagicNumber == FREERDP_CHANNEL_MAGIC_NUMBER)) + { + context = (EncomspClientContext*)calloc(1, sizeof(EncomspClientContext)); + + if (!context) + { + WLog_ERR(TAG, "calloc failed!"); + goto error_out; + } + + context->handle = (void*)encomsp; + context->FilterUpdated = NULL; + context->ApplicationCreated = NULL; + context->ApplicationRemoved = NULL; + context->WindowCreated = NULL; + context->WindowRemoved = NULL; + context->ShowWindow = NULL; + context->ParticipantCreated = NULL; + context->ParticipantRemoved = NULL; + context->ChangeParticipantControlLevel = encomsp_send_change_participant_control_level_pdu; + context->GraphicsStreamPaused = NULL; + context->GraphicsStreamResumed = NULL; + encomsp->context = context; + encomsp->rdpcontext = pEntryPointsEx->context; + isFreerdp = TRUE; + } + + CopyMemory(&(encomsp->channelEntryPoints), pEntryPoints, + sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)); + encomsp->InitHandle = pInitHandle; + const UINT rc = encomsp->channelEntryPoints.pVirtualChannelInitEx( + encomsp, context, pInitHandle, &encomsp->channelDef, 1, VIRTUAL_CHANNEL_VERSION_WIN2000, + encomsp_virtual_channel_init_event_ex); + + if (CHANNEL_RC_OK != rc) + { + WLog_ERR(TAG, "failed with %s [%08" PRIX32 "]", WTSErrorToString(rc), rc); + goto error_out; + } + + encomsp->channelEntryPoints.pInterface = context; + return TRUE; +error_out: + + if (isFreerdp) + free(encomsp->context); + + free(encomsp); + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.h new file mode 100644 index 0000000000000000000000000000000000000000..ad43ceae1944152591df22fe63a583ec1e39a0e6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/client/encomsp_main.h @@ -0,0 +1,42 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Multiparty Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_ENCOMSP_CLIENT_MAIN_H +#define FREERDP_CHANNEL_ENCOMSP_CLIENT_MAIN_H + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#define TAG CHANNELS_TAG("encomsp.client") + +typedef struct encomsp_plugin encomspPlugin; + +#endif /* FREERDP_CHANNEL_ENCOMSP_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c23795a3325fe9f35479e8c5efa9af2e64b8b580 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/CMakeLists.txt @@ -0,0 +1,25 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("encomsp") + +include_directories(..) + +set(${MODULE_PREFIX}_SRCS encomsp_main.c encomsp_main.h) + +set(${MODULE_PREFIX}_LIBS winpr) +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4613f9a5b539a72367e0d7eed7d609fd0a16d23d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.c @@ -0,0 +1,382 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Multiparty Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include + +#include +#include + +#include "encomsp_main.h" + +#define TAG CHANNELS_TAG("encomsp.server") + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_read_header(wStream* s, ENCOMSP_ORDER_HEADER* header) +{ + if (!Stream_CheckAndLogRequiredLength(TAG, s, ENCOMSP_ORDER_HEADER_SIZE)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, header->Type); /* Type (2 bytes) */ + Stream_Read_UINT16(s, header->Length); /* Length (2 bytes) */ + return CHANNEL_RC_OK; +} + +#if 0 + +static int encomsp_write_header(wStream* s, ENCOMSP_ORDER_HEADER* header) +{ + Stream_Write_UINT16(s, header->Type); /* Type (2 bytes) */ + Stream_Write_UINT16(s, header->Length); /* Length (2 bytes) */ + return 1; +} + +static int encomsp_read_unicode_string(wStream* s, ENCOMSP_UNICODE_STRING* str) +{ + ZeroMemory(str, sizeof(ENCOMSP_UNICODE_STRING)); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 2)) + return -1; + + Stream_Read_UINT16(s, str->cchString); /* cchString (2 bytes) */ + + if (str->cchString > 1024) + return -1; + + if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, str->cchString, sizeof(WCHAR))) + return -1; + + Stream_Read(s, &(str->wString), (str->cchString * 2)); /* String (variable) */ + return 1; +} + +#endif + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_recv_change_participant_control_level_pdu(EncomspServerContext* context, + wStream* s, + const ENCOMSP_ORDER_HEADER* header) +{ + ENCOMSP_CHANGE_PARTICIPANT_CONTROL_LEVEL_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + + const size_t pos = Stream_GetPosition(s); + if (pos < ENCOMSP_ORDER_HEADER_SIZE) + return ERROR_INVALID_PARAMETER; + + const size_t beg = pos - ENCOMSP_ORDER_HEADER_SIZE; + CopyMemory(&pdu, header, sizeof(ENCOMSP_ORDER_HEADER)); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 6)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, pdu.Flags); /* Flags (2 bytes) */ + Stream_Read_UINT32(s, pdu.ParticipantId); /* ParticipantId (4 bytes) */ + const size_t end = Stream_GetPosition(s); + + if ((beg + header->Length) < end) + { + WLog_ERR(TAG, "Not enough data!"); + return ERROR_INVALID_DATA; + } + + if ((beg + header->Length) > end) + { + if (!Stream_CheckAndLogRequiredLength(TAG, s, (size_t)((beg + header->Length) - end))) + return ERROR_INVALID_DATA; + + Stream_SetPosition(s, (beg + header->Length)); + } + + IFCALLRET(context->ChangeParticipantControlLevel, error, context, &pdu); + + if (error) + WLog_ERR(TAG, "context->ChangeParticipantControlLevel failed with error %" PRIu32 "", + error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_server_receive_pdu(EncomspServerContext* context, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + ENCOMSP_ORDER_HEADER header; + + while (Stream_GetRemainingLength(s) > 0) + { + if ((error = encomsp_read_header(s, &header))) + { + WLog_ERR(TAG, "encomsp_read_header failed with error %" PRIu32 "!", error); + return error; + } + + WLog_INFO(TAG, "EncomspReceive: Type: %" PRIu16 " Length: %" PRIu16 "", header.Type, + header.Length); + + switch (header.Type) + { + case ODTYPE_PARTICIPANT_CTRL_CHANGED: + if ((error = + encomsp_recv_change_participant_control_level_pdu(context, s, &header))) + { + WLog_ERR(TAG, + "encomsp_recv_change_participant_control_level_pdu failed with error " + "%" PRIu32 "!", + error); + return error; + } + + break; + + default: + WLog_ERR(TAG, "header.Type unknown %" PRIu16 "!", header.Type); + return ERROR_INVALID_DATA; + } + } + + return error; +} + +static DWORD WINAPI encomsp_server_thread(LPVOID arg) +{ + wStream* s = NULL; + DWORD nCount = 0; + void* buffer = NULL; + HANDLE events[8]; + HANDLE ChannelEvent = NULL; + DWORD BytesReturned = 0; + ENCOMSP_ORDER_HEADER* header = NULL; + EncomspServerContext* context = NULL; + UINT error = CHANNEL_RC_OK; + DWORD status = 0; + context = (EncomspServerContext*)arg; + + buffer = NULL; + BytesReturned = 0; + ChannelEvent = NULL; + s = Stream_New(NULL, 4096); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + if (WTSVirtualChannelQuery(context->priv->ChannelHandle, WTSVirtualEventHandle, &buffer, + &BytesReturned) == TRUE) + { + if (BytesReturned == sizeof(HANDLE)) + ChannelEvent = *(HANDLE*)buffer; + + WTSFreeMemory(buffer); + } + + nCount = 0; + events[nCount++] = ChannelEvent; + events[nCount++] = context->priv->StopEvent; + + while (1) + { + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "", error); + break; + } + + status = WaitForSingleObject(context->priv->StopEvent, 0); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); + break; + } + + if (status == WAIT_OBJECT_0) + { + break; + } + + if (!WTSVirtualChannelRead(context->priv->ChannelHandle, 0, NULL, 0, &BytesReturned)) + { + WLog_ERR(TAG, "WTSVirtualChannelRead failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (BytesReturned < 1) + continue; + + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + error = CHANNEL_RC_NO_MEMORY; + break; + } + + const size_t cap = Stream_Capacity(s); + if ((cap > UINT32_MAX) || + !WTSVirtualChannelRead(context->priv->ChannelHandle, 0, Stream_BufferAs(s, char), + (ULONG)cap, &BytesReturned)) + { + WLog_ERR(TAG, "WTSVirtualChannelRead failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (Stream_GetPosition(s) >= ENCOMSP_ORDER_HEADER_SIZE) + { + header = Stream_BufferAs(s, ENCOMSP_ORDER_HEADER); + + if (header->Length >= Stream_GetPosition(s)) + { + Stream_SealLength(s); + Stream_SetPosition(s, 0); + + if ((error = encomsp_server_receive_pdu(context, s))) + { + WLog_ERR(TAG, "encomsp_server_receive_pdu failed with error %" PRIu32 "!", + error); + break; + } + + Stream_SetPosition(s, 0); + } + } + } + + Stream_Free(s, TRUE); +out: + + if (error && context->rdpcontext) + setChannelError(context->rdpcontext, error, "encomsp_server_thread reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_server_start(EncomspServerContext* context) +{ + context->priv->ChannelHandle = + WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, ENCOMSP_SVC_CHANNEL_NAME); + + if (!context->priv->ChannelHandle) + return CHANNEL_RC_BAD_CHANNEL; + + if (!(context->priv->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + WLog_ERR(TAG, "CreateEvent failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (!(context->priv->Thread = + CreateThread(NULL, 0, encomsp_server_thread, (void*)context, 0, NULL))) + { + WLog_ERR(TAG, "CreateThread failed!"); + (void)CloseHandle(context->priv->StopEvent); + context->priv->StopEvent = NULL; + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT encomsp_server_stop(EncomspServerContext* context) +{ + UINT error = CHANNEL_RC_OK; + (void)SetEvent(context->priv->StopEvent); + + if (WaitForSingleObject(context->priv->Thread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); + return error; + } + + (void)CloseHandle(context->priv->Thread); + (void)CloseHandle(context->priv->StopEvent); + return error; +} + +EncomspServerContext* encomsp_server_context_new(HANDLE vcm) +{ + EncomspServerContext* context = NULL; + context = (EncomspServerContext*)calloc(1, sizeof(EncomspServerContext)); + + if (context) + { + context->vcm = vcm; + context->Start = encomsp_server_start; + context->Stop = encomsp_server_stop; + context->priv = (EncomspServerPrivate*)calloc(1, sizeof(EncomspServerPrivate)); + + if (!context->priv) + { + WLog_ERR(TAG, "calloc failed!"); + free(context); + return NULL; + } + } + + return context; +} + +void encomsp_server_context_free(EncomspServerContext* context) +{ + if (context) + { + if (context->priv->ChannelHandle != INVALID_HANDLE_VALUE) + (void)WTSVirtualChannelClose(context->priv->ChannelHandle); + + free(context->priv); + free(context); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.h new file mode 100644 index 0000000000000000000000000000000000000000..37d8c712376ea8bed718b4dd5f1fe0c3bdba0f44 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/encomsp/server/encomsp_main.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Multiparty Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_CHANNEL_ENCOMSP_SERVER_MAIN_H +#define FREERDP_CHANNEL_ENCOMSP_SERVER_MAIN_H + +#include +#include +#include + +#include + +struct s_encomsp_server_private +{ + HANDLE Thread; + HANDLE StopEvent; + void* ChannelHandle; +}; + +#endif /* FREERDP_CHANNEL_ENCOMSP_SERVER_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..04908389ab076e3cd7b5c6d837765e554c876773 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/CMakeLists.txt @@ -0,0 +1,26 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2017 David Fort +# +# 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. + +define_channel_client("geometry") + +set(${MODULE_PREFIX}_SRCS geometry_main.c geometry_main.h) + +set(${MODULE_PREFIX}_LIBS winpr) + +include_directories(..) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d86007592b4ac28a59635c28abff2a1eabdf13ff --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.c @@ -0,0 +1,402 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Geometry tracking Virtual Channel Extension + * + * Copyright 2017 David Fort + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("geometry.client") + +#include "geometry_main.h" + +typedef struct +{ + GENERIC_DYNVC_PLUGIN base; + GeometryClientContext* context; +} GEOMETRY_PLUGIN; + +static UINT32 mappedGeometryHash(const void* v) +{ + const UINT64* g = (const UINT64*)v; + return (UINT32)((*g >> 32) + (*g & 0xffffffff)); +} + +static BOOL mappedGeometryKeyCompare(const void* v1, const void* v2) +{ + const UINT64* g1 = (const UINT64*)v1; + const UINT64* g2 = (const UINT64*)v2; + return *g1 == *g2; +} + +static void freerdp_rgndata_reset(FREERDP_RGNDATA* data) +{ + data->nRectCount = 0; +} + +static UINT32 geometry_read_RGNDATA(wLog* logger, wStream* s, UINT32 len, FREERDP_RGNDATA* rgndata) +{ + UINT32 dwSize = 0; + UINT32 iType = 0; + INT32 right = 0; + INT32 bottom = 0; + INT32 x = 0; + INT32 y = 0; + INT32 w = 0; + INT32 h = 0; + + if (len < 32) + { + WLog_Print(logger, WLOG_ERROR, "invalid RGNDATA"); + return ERROR_INVALID_DATA; + } + + Stream_Read_UINT32(s, dwSize); + + if (dwSize != 32) + { + WLog_Print(logger, WLOG_ERROR, "invalid RGNDATA dwSize"); + return ERROR_INVALID_DATA; + } + + Stream_Read_UINT32(s, iType); + + if (iType != RDH_RECTANGLE) + { + WLog_Print(logger, WLOG_ERROR, "iType %" PRIu32 " for RGNDATA is not supported", iType); + return ERROR_UNSUPPORTED_TYPE; + } + + Stream_Read_UINT32(s, rgndata->nRectCount); + Stream_Seek_UINT32(s); /* nRgnSize IGNORED */ + Stream_Read_INT32(s, x); + Stream_Read_INT32(s, y); + Stream_Read_INT32(s, right); + Stream_Read_INT32(s, bottom); + if ((abs(x) > INT16_MAX) || (abs(y) > INT16_MAX)) + return ERROR_INVALID_DATA; + w = right - x; + h = bottom - y; + if ((abs(w) > INT16_MAX) || (abs(h) > INT16_MAX)) + return ERROR_INVALID_DATA; + rgndata->boundingRect.x = (INT16)x; + rgndata->boundingRect.y = (INT16)y; + rgndata->boundingRect.width = (INT16)w; + rgndata->boundingRect.height = (INT16)h; + len -= 32; + + if (len / (4 * 4) < rgndata->nRectCount) + { + WLog_Print(logger, WLOG_ERROR, "not enough data for region rectangles"); + return ERROR_INVALID_DATA; + } + + if (rgndata->nRectCount) + { + RDP_RECT* tmp = realloc(rgndata->rects, rgndata->nRectCount * sizeof(RDP_RECT)); + + if (!tmp) + { + WLog_Print(logger, WLOG_ERROR, "unable to allocate memory for %" PRIu32 " RECTs", + rgndata->nRectCount); + return CHANNEL_RC_NO_MEMORY; + } + rgndata->rects = tmp; + + for (UINT32 i = 0; i < rgndata->nRectCount; i++) + { + Stream_Read_INT32(s, x); + Stream_Read_INT32(s, y); + Stream_Read_INT32(s, right); + Stream_Read_INT32(s, bottom); + if ((abs(x) > INT16_MAX) || (abs(y) > INT16_MAX)) + return ERROR_INVALID_DATA; + w = right - x; + h = bottom - y; + if ((abs(w) > INT16_MAX) || (abs(h) > INT16_MAX)) + return ERROR_INVALID_DATA; + rgndata->rects[i].x = (INT16)x; + rgndata->rects[i].y = (INT16)y; + rgndata->rects[i].width = (INT16)w; + rgndata->rects[i].height = (INT16)h; + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT geometry_recv_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT32 length = 0; + UINT32 cbGeometryBuffer = 0; + MAPPED_GEOMETRY* mappedGeometry = NULL; + GEOMETRY_PLUGIN* geometry = NULL; + GeometryClientContext* context = NULL; + UINT ret = CHANNEL_RC_OK; + UINT32 updateType = 0; + UINT32 geometryType = 0; + UINT64 id = 0; + wLog* logger = NULL; + + geometry = (GEOMETRY_PLUGIN*)callback->plugin; + logger = geometry->base.log; + context = (GeometryClientContext*)geometry->base.iface.pInterface; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, length); /* Length (4 bytes) */ + + if (length < 73 || !Stream_CheckAndLogRequiredLength(TAG, s, (length - 4))) + { + WLog_Print(logger, WLOG_ERROR, "invalid packet length"); + return ERROR_INVALID_DATA; + } + + Stream_Read_UINT32(s, context->remoteVersion); + Stream_Read_UINT64(s, id); + Stream_Read_UINT32(s, updateType); + Stream_Seek_UINT32(s); /* flags */ + + mappedGeometry = HashTable_GetItemValue(context->geometries, &id); + + if (updateType == GEOMETRY_CLEAR) + { + if (!mappedGeometry) + { + WLog_Print(logger, WLOG_ERROR, + "geometry 0x%" PRIx64 " not found here, ignoring clear command", id); + return CHANNEL_RC_OK; + } + + WLog_Print(logger, WLOG_DEBUG, "clearing geometry 0x%" PRIx64 "", id); + + if (mappedGeometry->MappedGeometryClear && + !mappedGeometry->MappedGeometryClear(mappedGeometry)) + return ERROR_INTERNAL_ERROR; + + if (!HashTable_Remove(context->geometries, &id)) + WLog_Print(logger, WLOG_ERROR, "geometry not removed from geometries"); + } + else if (updateType == GEOMETRY_UPDATE) + { + BOOL newOne = FALSE; + + if (!mappedGeometry) + { + newOne = TRUE; + WLog_Print(logger, WLOG_DEBUG, "creating geometry 0x%" PRIx64 "", id); + mappedGeometry = calloc(1, sizeof(MAPPED_GEOMETRY)); + if (!mappedGeometry) + return CHANNEL_RC_NO_MEMORY; + + mappedGeometry->refCounter = 1; + mappedGeometry->mappingId = id; + + if (!HashTable_Insert(context->geometries, &(mappedGeometry->mappingId), + mappedGeometry)) + { + WLog_Print(logger, WLOG_ERROR, + "unable to register geometry 0x%" PRIx64 " in the table", id); + free(mappedGeometry); + return CHANNEL_RC_NO_MEMORY; + } + } + else + { + WLog_Print(logger, WLOG_DEBUG, "updating geometry 0x%" PRIx64 "", id); + } + + Stream_Read_UINT64(s, mappedGeometry->topLevelId); + + Stream_Read_INT32(s, mappedGeometry->left); + Stream_Read_INT32(s, mappedGeometry->top); + Stream_Read_INT32(s, mappedGeometry->right); + Stream_Read_INT32(s, mappedGeometry->bottom); + + Stream_Read_INT32(s, mappedGeometry->topLevelLeft); + Stream_Read_INT32(s, mappedGeometry->topLevelTop); + Stream_Read_INT32(s, mappedGeometry->topLevelRight); + Stream_Read_INT32(s, mappedGeometry->topLevelBottom); + + Stream_Read_UINT32(s, geometryType); + if (geometryType != 0x02) + WLog_Print(logger, WLOG_DEBUG, "geometryType should be set to 0x02 and is 0x%" PRIx32, + geometryType); + + Stream_Read_UINT32(s, cbGeometryBuffer); + if (!Stream_CheckAndLogRequiredLength(TAG, s, cbGeometryBuffer)) + { + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert ownership mappedGeometry + return ERROR_INVALID_DATA; + } + + if (cbGeometryBuffer) + { + ret = geometry_read_RGNDATA(logger, s, cbGeometryBuffer, &mappedGeometry->geometry); + if (ret != CHANNEL_RC_OK) + return ret; + } + else + { + freerdp_rgndata_reset(&mappedGeometry->geometry); + } + + if (newOne) + { + if (context->MappedGeometryAdded && + !context->MappedGeometryAdded(context, mappedGeometry)) + { + WLog_Print(logger, WLOG_ERROR, "geometry added callback failed"); + ret = ERROR_INTERNAL_ERROR; + } + } + else + { + if (mappedGeometry->MappedGeometryUpdate && + !mappedGeometry->MappedGeometryUpdate(mappedGeometry)) + { + WLog_Print(logger, WLOG_ERROR, "geometry update callback failed"); + ret = ERROR_INTERNAL_ERROR; + } + } + } + else + { + WLog_Print(logger, WLOG_ERROR, "unknown updateType=%" PRIu32 "", updateType); + ret = CHANNEL_RC_OK; + } + + return ret; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT geometry_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + return geometry_recv_pdu(callback, data); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT geometry_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + free(pChannelCallback); + return CHANNEL_RC_OK; +} + +static void mappedGeometryUnref_void(void* arg) +{ + MAPPED_GEOMETRY* g = (MAPPED_GEOMETRY*)arg; + mappedGeometryUnref(g); +} + +/** + * Channel Client Interface + */ + +static const IWTSVirtualChannelCallback geometry_callbacks = { geometry_on_data_received, + NULL, /* Open */ + geometry_on_close, NULL }; + +static UINT init_plugin_cb(GENERIC_DYNVC_PLUGIN* base, rdpContext* rcontext, rdpSettings* settings) +{ + GeometryClientContext* context = NULL; + GEOMETRY_PLUGIN* geometry = (GEOMETRY_PLUGIN*)base; + + WINPR_ASSERT(base); + WINPR_UNUSED(settings); + + context = (GeometryClientContext*)calloc(1, sizeof(GeometryClientContext)); + if (!context) + { + WLog_Print(base->log, WLOG_ERROR, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + context->geometries = HashTable_New(FALSE); + if (!context->geometries) + { + WLog_Print(base->log, WLOG_ERROR, "unable to allocate geometries"); + free(context); + return CHANNEL_RC_NO_MEMORY; + } + + HashTable_SetHashFunction(context->geometries, mappedGeometryHash); + { + wObject* obj = HashTable_KeyObject(context->geometries); + obj->fnObjectEquals = mappedGeometryKeyCompare; + } + { + wObject* obj = HashTable_ValueObject(context->geometries); + obj->fnObjectFree = mappedGeometryUnref_void; + } + context->handle = (void*)geometry; + + geometry->context = context; + geometry->base.iface.pInterface = (void*)context; + + return CHANNEL_RC_OK; +} + +static void terminate_plugin_cb(GENERIC_DYNVC_PLUGIN* base) +{ + GEOMETRY_PLUGIN* geometry = (GEOMETRY_PLUGIN*)base; + + if (geometry->context) + HashTable_Free(geometry->context->geometries); + free(geometry->context); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE geometry_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + return freerdp_generic_DVCPluginEntry(pEntryPoints, TAG, GEOMETRY_DVC_CHANNEL_NAME, + sizeof(GEOMETRY_PLUGIN), sizeof(GENERIC_CHANNEL_CALLBACK), + &geometry_callbacks, init_plugin_cb, terminate_plugin_cb); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.h new file mode 100644 index 0000000000000000000000000000000000000000..dc914b61878fbec3ab542d7610b5e29bc47b0796 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/geometry/client/geometry_main.h @@ -0,0 +1,30 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Geometry tracking virtual channel extension + * + * Copyright 2017 David Fort + * + * 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 FREERDP_CHANNEL_GEOMETRY_CLIENT_MAIN_H +#define FREERDP_CHANNEL_GEOMETRY_CLIENT_MAIN_H + +#include + +#include +#include +#include +#include + +#endif /* FREERDP_CHANNEL_GEOMETRY_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/location/client/location_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/location/client/location_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5abdb7c060e480c33921ad390ee021ca7ef58531 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/location/client/location_main.c @@ -0,0 +1,478 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Location Virtual Channel Extension + * + * Copyright 2024 Armin Novak + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("location.client") + +/* implement [MS-RDPEL] + * https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpel/4397a0af-c821-4b75-9068-476fb579c327 + */ +typedef struct +{ + GENERIC_DYNVC_PLUGIN baseDynPlugin; + LocationClientContext context; +} LOCATION_PLUGIN; + +typedef struct +{ + GENERIC_CHANNEL_CALLBACK baseCb; + UINT32 serverVersion; + UINT32 clientVersion; + UINT32 serverFlags; + UINT32 clientFlags; +} LOCATION_CALLBACK; + +static BOOL location_read_header(wLog* log, wStream* s, UINT16* ppduType, UINT32* ppduLength) +{ + WINPR_ASSERT(log); + WINPR_ASSERT(s); + WINPR_ASSERT(ppduType); + WINPR_ASSERT(ppduLength); + + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 6)) + return FALSE; + Stream_Read_UINT16(s, *ppduType); + Stream_Read_UINT32(s, *ppduLength); + if (*ppduLength < 6) + { + WLog_Print(log, WLOG_ERROR, + "RDPLOCATION_HEADER::pduLengh=%" PRIu16 " < sizeof(RDPLOCATION_HEADER)[6]", + *ppduLength); + return FALSE; + } + return Stream_CheckAndLogRequiredLengthWLog(log, s, *ppduLength - 6ull); +} + +static BOOL location_write_header(wStream* s, UINT16 pduType, UINT32 pduLength) +{ + if (!Stream_EnsureRemainingCapacity(s, 6)) + return FALSE; + Stream_Write_UINT16(s, pduType); + Stream_Write_UINT32(s, pduLength + 6); + return Stream_EnsureRemainingCapacity(s, pduLength); +} + +static BOOL location_read_server_ready_pdu(LOCATION_CALLBACK* callback, wStream* s, UINT32 pduSize) +{ + if (pduSize < 6 + 4) + return FALSE; // Short message + + Stream_Read_UINT32(s, callback->serverVersion); + if (pduSize >= 6 + 4 + 4) + Stream_Read_UINT32(s, callback->serverFlags); + return TRUE; +} + +static UINT location_channel_send(IWTSVirtualChannel* channel, wStream* s) +{ + const size_t len = Stream_GetPosition(s); + if (len > UINT32_MAX) + return ERROR_INTERNAL_ERROR; + + Stream_SetPosition(s, 2); + Stream_Write_UINT32(s, (UINT32)len); + + WINPR_ASSERT(channel); + WINPR_ASSERT(channel->Write); + return channel->Write(channel, (UINT32)len, Stream_Buffer(s), NULL); +} + +static UINT location_send_client_ready_pdu(const LOCATION_CALLBACK* callback) +{ + wStream sbuffer = { 0 }; + BYTE buffer[32] = { 0 }; + wStream* s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + WINPR_ASSERT(s); + + if (!location_write_header(s, PDUTYPE_CLIENT_READY, 8)) + return ERROR_OUTOFMEMORY; + + Stream_Write_UINT32(s, callback->clientVersion); + Stream_Write_UINT32(s, callback->clientFlags); + return location_channel_send(callback->baseCb.channel, s); +} + +static const char* location_version_str(UINT32 version, char* buffer, size_t size) +{ + const char* str = NULL; + switch (version) + { + case RDPLOCATION_PROTOCOL_VERSION_100: + str = "RDPLOCATION_PROTOCOL_VERSION_100"; + break; + case RDPLOCATION_PROTOCOL_VERSION_200: + str = "RDPLOCATION_PROTOCOL_VERSION_200"; + break; + default: + str = "RDPLOCATION_PROTOCOL_VERSION_UNKNOWN"; + break; + } + + (void)_snprintf(buffer, size, "%s [0x%08" PRIx32 "]", str, version); + return buffer; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT location_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + LOCATION_CALLBACK* callback = (LOCATION_CALLBACK*)pChannelCallback; + + WINPR_ASSERT(callback); + + LOCATION_PLUGIN* plugin = (LOCATION_PLUGIN*)callback->baseCb.plugin; + WINPR_ASSERT(plugin); + + UINT16 pduType = 0; + UINT32 pduLength = 0; + if (!location_read_header(plugin->baseDynPlugin.log, data, &pduType, &pduLength)) + return ERROR_INVALID_DATA; + + switch (pduType) + { + case PDUTYPE_SERVER_READY: + if (!location_read_server_ready_pdu(callback, data, pduLength)) + return ERROR_INVALID_DATA; + + switch (callback->serverVersion) + { + case RDPLOCATION_PROTOCOL_VERSION_200: + callback->clientVersion = RDPLOCATION_PROTOCOL_VERSION_200; + break; + case RDPLOCATION_PROTOCOL_VERSION_100: + callback->clientVersion = RDPLOCATION_PROTOCOL_VERSION_100; + break; + default: + callback->clientVersion = RDPLOCATION_PROTOCOL_VERSION_100; + if (callback->serverVersion > RDPLOCATION_PROTOCOL_VERSION_200) + callback->clientVersion = RDPLOCATION_PROTOCOL_VERSION_200; + break; + } + + char cbuffer[64] = { 0 }; + char sbuffer[64] = { 0 }; + WLog_Print(plugin->baseDynPlugin.log, WLOG_DEBUG, + "Server version %s, client version %s", + location_version_str(callback->serverVersion, sbuffer, sizeof(sbuffer)), + location_version_str(callback->clientVersion, cbuffer, sizeof(cbuffer))); + + if (!plugin->context.LocationStart) + { + WLog_Print(plugin->baseDynPlugin.log, WLOG_WARN, + "LocationStart=NULL, no location data will be sent"); + return CHANNEL_RC_OK; + } + const UINT res = + plugin->context.LocationStart(&plugin->context, callback->clientVersion, 0); + if (res != CHANNEL_RC_OK) + return res; + return location_send_client_ready_pdu(callback); + default: + WLog_WARN(TAG, "invalid pduType=%s"); + return ERROR_INVALID_DATA; + } +} + +static UINT location_send_base_location3d(IWTSVirtualChannel* channel, + const RDPLOCATION_BASE_LOCATION3D_PDU* pdu) +{ + wStream sbuffer = { 0 }; + BYTE buffer[32] = { 0 }; + wStream* s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + WINPR_ASSERT(s); + WINPR_ASSERT(channel); + WINPR_ASSERT(pdu); + + if (pdu->source) + WLog_DBG(TAG, + "latitude=%lf, longitude=%lf, altitude=%" PRId32 + ", speed=%lf, heading=%lf, haccuracy=%lf, source=%" PRIu8, + pdu->latitude, pdu->longitude, pdu->altitude, pdu->speed, pdu->heading, + pdu->horizontalAccuracy, *pdu->source); + else + WLog_DBG(TAG, "latitude=%lf, longitude=%lf, altitude=%" PRId32, pdu->latitude, + pdu->longitude, pdu->altitude); + + if (!location_write_header(s, PDUTYPE_BASE_LOCATION3D, pdu->source ? 25 : 12)) + return ERROR_OUTOFMEMORY; + + if (!freerdp_write_four_byte_float(s, pdu->latitude) || + !freerdp_write_four_byte_float(s, pdu->longitude) || + !freerdp_write_four_byte_signed_integer(s, pdu->altitude)) + return ERROR_INTERNAL_ERROR; + + if (pdu->source) + { + if (!freerdp_write_four_byte_float(s, *pdu->speed) || + !freerdp_write_four_byte_float(s, *pdu->heading) || + !freerdp_write_four_byte_float(s, *pdu->horizontalAccuracy)) + return ERROR_INTERNAL_ERROR; + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(UINT8, *pdu->source)); + } + + return location_channel_send(channel, s); +} + +static UINT location_send_location2d_delta(IWTSVirtualChannel* channel, + const RDPLOCATION_LOCATION2D_DELTA_PDU* pdu) +{ + wStream sbuffer = { 0 }; + BYTE buffer[32] = { 0 }; + wStream* s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + WINPR_ASSERT(s); + + WINPR_ASSERT(channel); + WINPR_ASSERT(pdu); + + const BOOL ext = pdu->speedDelta && pdu->headingDelta; + + if (ext) + WLog_DBG(TAG, "latitude=%lf, longitude=%lf, speed=%lf, heading=%lf", pdu->latitudeDelta, + pdu->longitudeDelta, pdu->speedDelta, pdu->headingDelta); + else + WLog_DBG(TAG, "latitude=%lf, longitude=%lf", pdu->latitudeDelta, pdu->longitudeDelta); + + if (!location_write_header(s, PDUTYPE_LOCATION2D_DELTA, ext ? 16 : 8)) + return ERROR_OUTOFMEMORY; + + if (!freerdp_write_four_byte_float(s, pdu->latitudeDelta) || + !freerdp_write_four_byte_float(s, pdu->longitudeDelta)) + return ERROR_INTERNAL_ERROR; + + if (ext) + { + if (!freerdp_write_four_byte_float(s, *pdu->speedDelta) || + !freerdp_write_four_byte_float(s, *pdu->headingDelta)) + return ERROR_INTERNAL_ERROR; + } + + return location_channel_send(channel, s); +} + +static UINT location_send_location3d_delta(IWTSVirtualChannel* channel, + const RDPLOCATION_LOCATION3D_DELTA_PDU* pdu) +{ + wStream sbuffer = { 0 }; + BYTE buffer[32] = { 0 }; + wStream* s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + WINPR_ASSERT(s); + + WINPR_ASSERT(channel); + WINPR_ASSERT(pdu); + + const BOOL ext = pdu->speedDelta && pdu->headingDelta; + + if (ext) + WLog_DBG(TAG, "latitude=%lf, longitude=%lf, altitude=%" PRId32 ", speed=%lf, heading=%lf", + pdu->latitudeDelta, pdu->longitudeDelta, pdu->altitudeDelta, pdu->speedDelta, + pdu->headingDelta); + else + WLog_DBG(TAG, "latitude=%lf, longitude=%lf, altitude=%" PRId32, pdu->latitudeDelta, + pdu->longitudeDelta, pdu->altitudeDelta); + + if (!location_write_header(s, PDUTYPE_LOCATION3D_DELTA, ext ? 20 : 12)) + return ERROR_OUTOFMEMORY; + + if (!freerdp_write_four_byte_float(s, pdu->latitudeDelta) || + !freerdp_write_four_byte_float(s, pdu->longitudeDelta) || + !freerdp_write_four_byte_signed_integer(s, pdu->altitudeDelta)) + return ERROR_INTERNAL_ERROR; + + if (ext) + { + if (!freerdp_write_four_byte_float(s, *pdu->speedDelta) || + !freerdp_write_four_byte_float(s, *pdu->headingDelta)) + return ERROR_INTERNAL_ERROR; + } + + return location_channel_send(channel, s); +} + +static UINT location_send(LocationClientContext* context, LOCATION_PDUTYPE type, size_t count, ...) +{ + WINPR_ASSERT(context); + + LOCATION_PLUGIN* loc = context->handle; + WINPR_ASSERT(loc); + + GENERIC_LISTENER_CALLBACK* cb = loc->baseDynPlugin.listener_callback; + WINPR_ASSERT(cb); + + IWTSVirtualChannel* channel = cb->channel; + WINPR_ASSERT(channel); + + const LOCATION_CALLBACK* callback = + (const LOCATION_CALLBACK*)loc->baseDynPlugin.channel_callbacks; + WINPR_ASSERT(callback); + + UINT32 res = ERROR_INTERNAL_ERROR; + va_list ap = { 0 }; + va_start(ap, count); + switch (type) + { + case PDUTYPE_BASE_LOCATION3D: + if ((count != 3) && (count != 7)) + res = ERROR_INVALID_PARAMETER; + else + { + RDPLOCATION_BASE_LOCATION3D_PDU pdu = { 0 }; + LOCATIONSOURCE source = LOCATIONSOURCE_IP; + double speed = FP_NAN; + double heading = FP_NAN; + double horizontalAccuracy = FP_NAN; + pdu.latitude = va_arg(ap, double); + pdu.longitude = va_arg(ap, double); + pdu.altitude = va_arg(ap, INT32); + if ((count > 3) && (callback->clientVersion >= RDPLOCATION_PROTOCOL_VERSION_200)) + { + speed = va_arg(ap, double); + heading = va_arg(ap, double); + horizontalAccuracy = va_arg(ap, double); + source = WINPR_ASSERTING_INT_CAST(LOCATIONSOURCE, va_arg(ap, int)); + pdu.speed = &speed; + pdu.heading = &heading; + pdu.horizontalAccuracy = &horizontalAccuracy; + pdu.source = &source; + } + res = location_send_base_location3d(channel, &pdu); + } + break; + case PDUTYPE_LOCATION2D_DELTA: + if ((count != 2) && (count != 4)) + res = ERROR_INVALID_PARAMETER; + else + { + RDPLOCATION_LOCATION2D_DELTA_PDU pdu = { 0 }; + + pdu.latitudeDelta = va_arg(ap, double); + pdu.longitudeDelta = va_arg(ap, double); + + double speedDelta = FP_NAN; + double headingDelta = FP_NAN; + if ((count > 2) && (callback->clientVersion >= RDPLOCATION_PROTOCOL_VERSION_200)) + { + speedDelta = va_arg(ap, double); + headingDelta = va_arg(ap, double); + pdu.speedDelta = &speedDelta; + pdu.headingDelta = &headingDelta; + } + res = location_send_location2d_delta(channel, &pdu); + } + break; + case PDUTYPE_LOCATION3D_DELTA: + if ((count != 3) && (count != 5)) + res = ERROR_INVALID_PARAMETER; + else + { + RDPLOCATION_LOCATION3D_DELTA_PDU pdu = { 0 }; + double speedDelta = FP_NAN; + double headingDelta = FP_NAN; + + pdu.latitudeDelta = va_arg(ap, double); + pdu.longitudeDelta = va_arg(ap, double); + pdu.altitudeDelta = va_arg(ap, INT32); + if ((count > 3) && (callback->clientVersion >= RDPLOCATION_PROTOCOL_VERSION_200)) + { + speedDelta = va_arg(ap, double); + headingDelta = va_arg(ap, double); + pdu.speedDelta = &speedDelta; + pdu.headingDelta = &headingDelta; + } + res = location_send_location3d_delta(channel, &pdu); + } + break; + default: + res = ERROR_INVALID_PARAMETER; + break; + } + va_end(ap); + return res; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT location_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + UINT res = CHANNEL_RC_OK; + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + + if (callback) + { + LOCATION_PLUGIN* plugin = (LOCATION_PLUGIN*)callback->plugin; + WINPR_ASSERT(plugin); + + res = IFCALLRESULT(CHANNEL_RC_OK, plugin->context.LocationStop, &plugin->context); + } + free(callback); + + return res; +} + +static UINT location_init(GENERIC_DYNVC_PLUGIN* plugin, rdpContext* context, rdpSettings* settings) +{ + LOCATION_PLUGIN* loc = (LOCATION_PLUGIN*)plugin; + + WINPR_ASSERT(loc); + + loc->context.LocationSend = location_send; + loc->context.handle = loc; + plugin->iface.pInterface = &loc->context; + return CHANNEL_RC_OK; +} + +static const IWTSVirtualChannelCallback location_callbacks = { location_on_data_received, + NULL, /* Open */ + location_on_close, NULL }; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE location_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + return freerdp_generic_DVCPluginEntry(pEntryPoints, TAG, LOCATION_DVC_CHANNEL_NAME, + sizeof(LOCATION_PLUGIN), sizeof(LOCATION_CALLBACK), + &location_callbacks, location_init, NULL); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7870016c33bc898464f1a2f7256ab06e4cc74337 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2023 Pascal Nowack +# +# 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. + +define_channel_server("location") + +set(${MODULE_PREFIX}_SRCS location_main.c) + +set(${MODULE_PREFIX}_LIBS freerdp) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/location_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/location_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4c0bd8c5e5bface5a5db871c6e38f5398be88a8c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/location/server/location_main.c @@ -0,0 +1,640 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Location Virtual Channel Extension + * + * Copyright 2023 Pascal Nowack + * + * 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 + +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("location.server") + +typedef enum +{ + LOCATION_INITIAL, + LOCATION_OPENED, +} eLocationChannelState; + +typedef struct +{ + LocationServerContext context; + + HANDLE stopEvent; + + HANDLE thread; + void* location_channel; + + DWORD SessionId; + + BOOL isOpened; + BOOL externalThread; + + /* Channel state */ + eLocationChannelState state; + + wStream* buffer; +} location_server; + +static UINT location_server_initialize(LocationServerContext* context, BOOL externalThread) +{ + UINT error = CHANNEL_RC_OK; + location_server* location = (location_server*)context; + + WINPR_ASSERT(location); + + if (location->isOpened) + { + WLog_WARN(TAG, "Application error: Location channel already initialized, " + "calling in this state is not possible!"); + return ERROR_INVALID_STATE; + } + + location->externalThread = externalThread; + + return error; +} + +static UINT location_server_open_channel(location_server* location) +{ + LocationServerContext* context = &location->context; + DWORD Error = ERROR_SUCCESS; + HANDLE hEvent = NULL; + DWORD BytesReturned = 0; + PULONG pSessionId = NULL; + UINT32 channelId = 0; + BOOL status = TRUE; + + WINPR_ASSERT(location); + + if (WTSQuerySessionInformationA(location->context.vcm, WTS_CURRENT_SESSION, WTSSessionId, + (LPSTR*)&pSessionId, &BytesReturned) == FALSE) + { + WLog_ERR(TAG, "WTSQuerySessionInformationA failed!"); + return ERROR_INTERNAL_ERROR; + } + + location->SessionId = (DWORD)*pSessionId; + WTSFreeMemory(pSessionId); + hEvent = WTSVirtualChannelManagerGetEventHandle(location->context.vcm); + + if (WaitForSingleObject(hEvent, 1000) == WAIT_FAILED) + { + Error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", Error); + return Error; + } + + location->location_channel = WTSVirtualChannelOpenEx( + location->SessionId, LOCATION_DVC_CHANNEL_NAME, WTS_CHANNEL_OPTION_DYNAMIC); + if (!location->location_channel) + { + Error = GetLastError(); + WLog_ERR(TAG, "WTSVirtualChannelOpenEx failed with error %" PRIu32 "!", Error); + return Error; + } + + channelId = WTSChannelGetIdByHandle(location->location_channel); + + IFCALLRET(context->ChannelIdAssigned, status, context, channelId); + if (!status) + { + WLog_ERR(TAG, "context->ChannelIdAssigned failed!"); + return ERROR_INTERNAL_ERROR; + } + + return Error; +} + +static UINT location_server_recv_client_ready(LocationServerContext* context, wStream* s, + const RDPLOCATION_HEADER* header) +{ + RDPLOCATION_CLIENT_READY_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + pdu.header = *header; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_NO_DATA; + + Stream_Read_UINT32(s, pdu.protocolVersion); + + if (Stream_GetRemainingLength(s) >= 4) + Stream_Read_UINT32(s, pdu.flags); + + IFCALLRET(context->ClientReady, error, context, &pdu); + if (error) + WLog_ERR(TAG, "context->ClientReady failed with error %" PRIu32 "", error); + + return error; +} + +static UINT location_server_recv_base_location3d(LocationServerContext* context, wStream* s, + const RDPLOCATION_HEADER* header) +{ + RDPLOCATION_BASE_LOCATION3D_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + double speed = 0.0; + double heading = 0.0; + double horizontalAccuracy = 0.0; + LOCATIONSOURCE source = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + pdu.header = *header; + + if (!freerdp_read_four_byte_float(s, &pdu.latitude) || + !freerdp_read_four_byte_float(s, &pdu.longitude) || + !freerdp_read_four_byte_signed_integer(s, &pdu.altitude)) + return FALSE; + + if (Stream_GetRemainingLength(s) >= 1) + { + if (!freerdp_read_four_byte_float(s, &speed) || + !freerdp_read_four_byte_float(s, &heading) || + !freerdp_read_four_byte_float(s, &horizontalAccuracy) || + !Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return FALSE; + + Stream_Read_UINT8(s, source); + + pdu.speed = &speed; + pdu.heading = &heading; + pdu.horizontalAccuracy = &horizontalAccuracy; + pdu.source = &source; + } + + IFCALLRET(context->BaseLocation3D, error, context, &pdu); + if (error) + WLog_ERR(TAG, "context->BaseLocation3D failed with error %" PRIu32 "", error); + + return error; +} + +static UINT location_server_recv_location2d_delta(LocationServerContext* context, wStream* s, + const RDPLOCATION_HEADER* header) +{ + RDPLOCATION_LOCATION2D_DELTA_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + double speedDelta = 0.0; + double headingDelta = 0.0; + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + pdu.header = *header; + + if (!freerdp_read_four_byte_float(s, &pdu.latitudeDelta) || + !freerdp_read_four_byte_float(s, &pdu.longitudeDelta)) + return FALSE; + + if (Stream_GetRemainingLength(s) >= 1) + { + if (!freerdp_read_four_byte_float(s, &speedDelta) || + !freerdp_read_four_byte_float(s, &headingDelta)) + return FALSE; + + pdu.speedDelta = &speedDelta; + pdu.headingDelta = &headingDelta; + } + + IFCALLRET(context->Location2DDelta, error, context, &pdu); + if (error) + WLog_ERR(TAG, "context->Location2DDelta failed with error %" PRIu32 "", error); + + return error; +} + +static UINT location_server_recv_location3d_delta(LocationServerContext* context, wStream* s, + const RDPLOCATION_HEADER* header) +{ + RDPLOCATION_LOCATION3D_DELTA_PDU pdu = { 0 }; + UINT error = CHANNEL_RC_OK; + double speedDelta = 0.0; + double headingDelta = 0.0; + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + pdu.header = *header; + + if (!freerdp_read_four_byte_float(s, &pdu.latitudeDelta) || + !freerdp_read_four_byte_float(s, &pdu.longitudeDelta) || + !freerdp_read_four_byte_signed_integer(s, &pdu.altitudeDelta)) + return FALSE; + + if (Stream_GetRemainingLength(s) >= 1) + { + if (!freerdp_read_four_byte_float(s, &speedDelta) || + !freerdp_read_four_byte_float(s, &headingDelta)) + return FALSE; + + pdu.speedDelta = &speedDelta; + pdu.headingDelta = &headingDelta; + } + + IFCALLRET(context->Location3DDelta, error, context, &pdu); + if (error) + WLog_ERR(TAG, "context->Location3DDelta failed with error %" PRIu32 "", error); + + return error; +} + +static UINT location_process_message(location_server* location) +{ + BOOL rc = 0; + UINT error = ERROR_INTERNAL_ERROR; + ULONG BytesReturned = 0; + RDPLOCATION_HEADER header = { 0 }; + wStream* s = NULL; + + WINPR_ASSERT(location); + WINPR_ASSERT(location->location_channel); + + s = location->buffer; + WINPR_ASSERT(s); + + Stream_SetPosition(s, 0); + rc = WTSVirtualChannelRead(location->location_channel, 0, NULL, 0, &BytesReturned); + if (!rc) + goto out; + + if (BytesReturned < 1) + { + error = CHANNEL_RC_OK; + goto out; + } + + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + if (WTSVirtualChannelRead(location->location_channel, 0, Stream_BufferAs(s, char), + (ULONG)Stream_Capacity(s), &BytesReturned) == FALSE) + { + WLog_ERR(TAG, "WTSVirtualChannelRead failed!"); + goto out; + } + + Stream_SetLength(s, BytesReturned); + if (!Stream_CheckAndLogRequiredLength(TAG, s, LOCATION_HEADER_SIZE)) + return ERROR_NO_DATA; + + Stream_Read_UINT16(s, header.pduType); + Stream_Read_UINT32(s, header.pduLength); + + switch (header.pduType) + { + case PDUTYPE_CLIENT_READY: + error = location_server_recv_client_ready(&location->context, s, &header); + break; + case PDUTYPE_BASE_LOCATION3D: + error = location_server_recv_base_location3d(&location->context, s, &header); + break; + case PDUTYPE_LOCATION2D_DELTA: + error = location_server_recv_location2d_delta(&location->context, s, &header); + break; + case PDUTYPE_LOCATION3D_DELTA: + error = location_server_recv_location3d_delta(&location->context, s, &header); + break; + default: + WLog_ERR(TAG, "location_process_message: unknown or invalid pduType %" PRIu8 "", + header.pduType); + break; + } + +out: + if (error) + WLog_ERR(TAG, "Response failed with error %" PRIu32 "!", error); + + return error; +} + +static UINT location_server_context_poll_int(LocationServerContext* context) +{ + location_server* location = (location_server*)context; + UINT error = ERROR_INTERNAL_ERROR; + + WINPR_ASSERT(location); + + switch (location->state) + { + case LOCATION_INITIAL: + error = location_server_open_channel(location); + if (error) + WLog_ERR(TAG, "location_server_open_channel failed with error %" PRIu32 "!", error); + else + location->state = LOCATION_OPENED; + break; + case LOCATION_OPENED: + error = location_process_message(location); + break; + default: + break; + } + + return error; +} + +static HANDLE location_server_get_channel_handle(location_server* location) +{ + void* buffer = NULL; + DWORD BytesReturned = 0; + HANDLE ChannelEvent = NULL; + + WINPR_ASSERT(location); + + if (WTSVirtualChannelQuery(location->location_channel, WTSVirtualEventHandle, &buffer, + &BytesReturned) == TRUE) + { + if (BytesReturned == sizeof(HANDLE)) + ChannelEvent = *(HANDLE*)buffer; + + WTSFreeMemory(buffer); + } + + return ChannelEvent; +} + +static DWORD WINAPI location_server_thread_func(LPVOID arg) +{ + DWORD nCount = 0; + HANDLE events[2] = { 0 }; + location_server* location = (location_server*)arg; + UINT error = CHANNEL_RC_OK; + DWORD status = 0; + + WINPR_ASSERT(location); + + nCount = 0; + events[nCount++] = location->stopEvent; + + while ((error == CHANNEL_RC_OK) && (WaitForSingleObject(events[0], 0) != WAIT_OBJECT_0)) + { + switch (location->state) + { + case LOCATION_INITIAL: + error = location_server_context_poll_int(&location->context); + if (error == CHANNEL_RC_OK) + { + events[1] = location_server_get_channel_handle(location); + nCount = 2; + } + break; + case LOCATION_OPENED: + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + switch (status) + { + case WAIT_OBJECT_0: + break; + case WAIT_OBJECT_0 + 1: + case WAIT_TIMEOUT: + error = location_server_context_poll_int(&location->context); + break; + + case WAIT_FAILED: + default: + error = ERROR_INTERNAL_ERROR; + break; + } + break; + default: + break; + } + } + + (void)WTSVirtualChannelClose(location->location_channel); + location->location_channel = NULL; + + if (error && location->context.rdpcontext) + setChannelError(location->context.rdpcontext, error, + "location_server_thread_func reported an error"); + + ExitThread(error); + return error; +} + +static UINT location_server_open(LocationServerContext* context) +{ + location_server* location = (location_server*)context; + + WINPR_ASSERT(location); + + if (!location->externalThread && (location->thread == NULL)) + { + location->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!location->stopEvent) + { + WLog_ERR(TAG, "CreateEvent failed!"); + return ERROR_INTERNAL_ERROR; + } + + location->thread = CreateThread(NULL, 0, location_server_thread_func, location, 0, NULL); + if (!location->thread) + { + WLog_ERR(TAG, "CreateThread failed!"); + (void)CloseHandle(location->stopEvent); + location->stopEvent = NULL; + return ERROR_INTERNAL_ERROR; + } + } + location->isOpened = TRUE; + + return CHANNEL_RC_OK; +} + +static UINT location_server_close(LocationServerContext* context) +{ + UINT error = CHANNEL_RC_OK; + location_server* location = (location_server*)context; + + WINPR_ASSERT(location); + + if (!location->externalThread && location->thread) + { + (void)SetEvent(location->stopEvent); + + if (WaitForSingleObject(location->thread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); + return error; + } + + (void)CloseHandle(location->thread); + (void)CloseHandle(location->stopEvent); + location->thread = NULL; + location->stopEvent = NULL; + } + if (location->externalThread) + { + if (location->state != LOCATION_INITIAL) + { + (void)WTSVirtualChannelClose(location->location_channel); + location->location_channel = NULL; + location->state = LOCATION_INITIAL; + } + } + location->isOpened = FALSE; + + return error; +} + +static UINT location_server_context_poll(LocationServerContext* context) +{ + location_server* location = (location_server*)context; + + WINPR_ASSERT(location); + + if (!location->externalThread) + return ERROR_INTERNAL_ERROR; + + return location_server_context_poll_int(context); +} + +static BOOL location_server_context_handle(LocationServerContext* context, HANDLE* handle) +{ + location_server* location = (location_server*)context; + + WINPR_ASSERT(location); + WINPR_ASSERT(handle); + + if (!location->externalThread) + return FALSE; + if (location->state == LOCATION_INITIAL) + return FALSE; + + *handle = location_server_get_channel_handle(location); + + return TRUE; +} + +static UINT location_server_packet_send(LocationServerContext* context, wStream* s) +{ + location_server* location = (location_server*)context; + UINT error = CHANNEL_RC_OK; + ULONG written = 0; + + WINPR_ASSERT(location); + WINPR_ASSERT(s); + + const size_t pos = Stream_GetPosition(s); + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(location->location_channel, Stream_BufferAs(s, char), (ULONG)pos, + &written)) + { + WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); + error = ERROR_INTERNAL_ERROR; + goto out; + } + + if (written < Stream_GetPosition(s)) + { + WLog_WARN(TAG, "Unexpected bytes written: %" PRIu32 "/%" PRIuz "", written, + Stream_GetPosition(s)); + } + +out: + Stream_Free(s, TRUE); + return error; +} + +static UINT location_server_send_server_ready(LocationServerContext* context, + const RDPLOCATION_SERVER_READY_PDU* serverReady) +{ + wStream* s = NULL; + UINT32 pduLength = 0; + UINT32 protocolVersion = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(serverReady); + + protocolVersion = serverReady->protocolVersion; + + pduLength = LOCATION_HEADER_SIZE + 4 + 4; + + s = Stream_New(NULL, pduLength); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + /* RDPLOCATION_HEADER */ + Stream_Write_UINT16(s, PDUTYPE_SERVER_READY); + Stream_Write_UINT32(s, pduLength); + + Stream_Write_UINT32(s, protocolVersion); + Stream_Write_UINT32(s, serverReady->flags); + + return location_server_packet_send(context, s); +} + +LocationServerContext* location_server_context_new(HANDLE vcm) +{ + location_server* location = (location_server*)calloc(1, sizeof(location_server)); + + if (!location) + return NULL; + + location->context.vcm = vcm; + location->context.Initialize = location_server_initialize; + location->context.Open = location_server_open; + location->context.Close = location_server_close; + location->context.Poll = location_server_context_poll; + location->context.ChannelHandle = location_server_context_handle; + + location->context.ServerReady = location_server_send_server_ready; + + location->buffer = Stream_New(NULL, 4096); + if (!location->buffer) + goto fail; + + return &location->context; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + location_server_context_free(&location->context); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void location_server_context_free(LocationServerContext* context) +{ + location_server* location = (location_server*)context; + + if (location) + { + location_server_close(context); + Stream_Free(location->buffer, TRUE); + } + + free(location); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c3769a78110677b8397bcbd682a97ff89660ad5d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/CMakeLists.txt @@ -0,0 +1,31 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client("printer") + +set(${MODULE_PREFIX}_SRCS printer_main.c) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DeviceServiceEntry") + +if(WITH_CUPS) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "cups" "") +endif() + +if(WIN32 AND NOT UWP) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "win" "") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/win/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/win/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..454683b22b0298a2c4bdf39f449a987399bec035 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/printer/client/win/CMakeLists.txt @@ -0,0 +1,26 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2019 Armin Novak +# Copyright 2019 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. +define_channel_client_subsystem("printer" "win" "") + +set(${MODULE_PREFIX}_SRCS printer_win.c) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) + +include_directories(..) + +add_channel_client_subsystem_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} "" TRUE "") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b996aed372114d93e36e35c437bba4c5595eeeb7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/CMakeLists.txt @@ -0,0 +1,44 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2016 Inuvika Inc. +# Copyright 2016 David PHAM-VAN +# +# 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. + +define_channel_client("rdpdr") + +include(CheckFunctionExists) +check_function_exists(getmntent_r FREERDP_HAVE_GETMNTENT_R) +if(FREERDP_HAVE_GETMNTENT_R) + add_compile_definitions(FREERDP_HAVE_GETMNTENT_R) +endif() + +set(${MODULE_PREFIX}_SRCS + irp.c + irp.h + devman.c + devman.h + rdpdr_main.c + rdpdr_main.h + rdpdr_capabilities.c + rdpdr_capabilities.h +) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) +if(APPLE AND (NOT IOS)) + find_library(CORESERVICES_LIBRARY CoreServices) + list(APPEND ${MODULE_PREFIX}_LIBS ${CORESERVICES_LIBRARY}) +endif() +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntryEx") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.c new file mode 100644 index 0000000000000000000000000000000000000000..5da3a410a38baedf5aa25f5627d8148a75aae674 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.c @@ -0,0 +1,236 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Armin Novak + * + * 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 + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "rdpdr_main.h" + +#include "devman.h" + +#define TAG CHANNELS_TAG("rdpdr.client") + +static void devman_device_free(void* obj) +{ + DEVICE* device = (DEVICE*)obj; + + if (!device) + return; + + IFCALL(device->Free, device); +} + +DEVMAN* devman_new(rdpdrPlugin* rdpdr) +{ + DEVMAN* devman = NULL; + + if (!rdpdr) + return NULL; + + devman = (DEVMAN*)calloc(1, sizeof(DEVMAN)); + + if (!devman) + { + WLog_Print(rdpdr->log, WLOG_INFO, "calloc failed!"); + return NULL; + } + + devman->plugin = (void*)rdpdr; + devman->id_sequence = 1; + devman->devices = ListDictionary_New(TRUE); + + if (!devman->devices) + { + WLog_Print(rdpdr->log, WLOG_INFO, "ListDictionary_New failed!"); + free(devman); + return NULL; + } + + ListDictionary_ValueObject(devman->devices)->fnObjectFree = devman_device_free; + return devman; +} + +void devman_free(DEVMAN* devman) +{ + ListDictionary_Free(devman->devices); + free(devman); +} + +void devman_unregister_device(DEVMAN* devman, void* key) +{ + DEVICE* device = NULL; + + if (!devman || !key) + return; + + device = (DEVICE*)ListDictionary_Take(devman->devices, key); + + if (device) + devman_device_free(device); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT devman_register_device(DEVMAN* devman, DEVICE* device) +{ + void* key = NULL; + + if (!devman || !device) + return ERROR_INVALID_PARAMETER; + + device->id = devman->id_sequence++; + key = (void*)(size_t)device->id; + + if (!ListDictionary_Add(devman->devices, key, device)) + { + WLog_INFO(TAG, "ListDictionary_Add failed!"); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +DEVICE* devman_get_device_by_id(DEVMAN* devman, UINT32 id) +{ + DEVICE* device = NULL; + void* key = (void*)(size_t)id; + + if (!devman) + { + WLog_ERR(TAG, "device manager=%p", devman); + return NULL; + } + + device = (DEVICE*)ListDictionary_GetItemValue(devman->devices, key); + if (!device) + WLog_WARN(TAG, "could not find device ID 0x%08" PRIx32, id); + return device; +} + +DEVICE* devman_get_device_by_type(DEVMAN* devman, UINT32 type) +{ + DEVICE* device = NULL; + ULONG_PTR* keys = NULL; + + if (!devman) + return NULL; + + ListDictionary_Lock(devman->devices); + const size_t count = ListDictionary_GetKeys(devman->devices, &keys); + + for (size_t x = 0; x < count; x++) + { + DEVICE* cur = (DEVICE*)ListDictionary_GetItemValue(devman->devices, (void*)keys[x]); + + if (!cur) + continue; + + if (cur->type != type) + continue; + + device = cur; + break; + } + + free(keys); + ListDictionary_Unlock(devman->devices); + return device; +} + +static const char DRIVE_SERVICE_NAME[] = "drive"; +static const char PRINTER_SERVICE_NAME[] = "printer"; +static const char SMARTCARD_SERVICE_NAME[] = "smartcard"; +static const char SERIAL_SERVICE_NAME[] = "serial"; +static const char PARALLEL_SERVICE_NAME[] = "parallel"; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT devman_load_device_service(DEVMAN* devman, const RDPDR_DEVICE* device, rdpContext* rdpcontext) +{ + const char* ServiceName = NULL; + DEVICE_SERVICE_ENTRY_POINTS ep = { 0 }; + union + { + const RDPDR_DEVICE* cdp; + RDPDR_DEVICE* dp; + } devconv; + + devconv.cdp = device; + if (!devman || !device || !rdpcontext) + return ERROR_INVALID_PARAMETER; + + if (device->Type == RDPDR_DTYP_FILESYSTEM) + ServiceName = DRIVE_SERVICE_NAME; + else if (device->Type == RDPDR_DTYP_PRINT) + ServiceName = PRINTER_SERVICE_NAME; + else if (device->Type == RDPDR_DTYP_SMARTCARD) + ServiceName = SMARTCARD_SERVICE_NAME; + else if (device->Type == RDPDR_DTYP_SERIAL) + ServiceName = SERIAL_SERVICE_NAME; + else if (device->Type == RDPDR_DTYP_PARALLEL) + ServiceName = PARALLEL_SERVICE_NAME; + + if (!ServiceName) + { + WLog_INFO(TAG, "ServiceName %s did not match!", ServiceName); + return ERROR_INVALID_NAME; + } + + if (device->Name) + WLog_INFO(TAG, "Loading device service %s [%s] (static)", ServiceName, device->Name); + else + WLog_INFO(TAG, "Loading device service %s (static)", ServiceName); + + PVIRTUALCHANNELENTRY pvce = + freerdp_load_channel_addin_entry(ServiceName, NULL, "DeviceServiceEntry", 0); + PDEVICE_SERVICE_ENTRY entry = WINPR_FUNC_PTR_CAST(pvce, PDEVICE_SERVICE_ENTRY); + + if (!entry) + { + WLog_INFO(TAG, "freerdp_load_channel_addin_entry failed!"); + return ERROR_INTERNAL_ERROR; + } + + ep.devman = devman; + ep.RegisterDevice = devman_register_device; + ep.device = devconv.dp; + ep.rdpcontext = rdpcontext; + return entry(&ep); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.h new file mode 100644 index 0000000000000000000000000000000000000000..2e6019e6d2fb0a0ba856668fb8b0674674334ef5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/devman.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_RDPDR_CLIENT_DEVMAN_H +#define FREERDP_CHANNEL_RDPDR_CLIENT_DEVMAN_H + +#include "rdpdr_main.h" + +void devman_unregister_device(DEVMAN* devman, void* key); +UINT devman_load_device_service(DEVMAN* devman, const RDPDR_DEVICE* device, rdpContext* rdpcontext); +DEVICE* devman_get_device_by_id(DEVMAN* devman, UINT32 id); +DEVICE* devman_get_device_by_type(DEVMAN* devman, UINT32 type); + +DEVMAN* devman_new(rdpdrPlugin* rdpdr); +void devman_free(DEVMAN* devman); + +#endif /* FREERDP_CHANNEL_RDPDR_CLIENT_DEVMAN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.c new file mode 100644 index 0000000000000000000000000000000000000000..554b087e48814a164abc1b5ba7909a5e848ac474 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.c @@ -0,0 +1,165 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include + +#include +#include + +#include + +#include "rdpdr_main.h" +#include "devman.h" +#include "irp.h" + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT irp_free(IRP* irp) +{ + if (!irp) + return CHANNEL_RC_OK; + + if (irp->input) + Stream_Release(irp->input); + if (irp->output) + Stream_Release(irp->output); + + winpr_aligned_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT irp_complete(IRP* irp) +{ + size_t pos = 0; + rdpdrPlugin* rdpdr = NULL; + UINT error = 0; + + WINPR_ASSERT(irp); + WINPR_ASSERT(irp->output); + WINPR_ASSERT(irp->devman); + + rdpdr = (rdpdrPlugin*)irp->devman->plugin; + WINPR_ASSERT(rdpdr); + + pos = Stream_GetPosition(irp->output); + Stream_SetPosition(irp->output, RDPDR_DEVICE_IO_RESPONSE_LENGTH - 4); + Stream_Write_INT32(irp->output, irp->IoStatus); /* IoStatus (4 bytes) */ + Stream_SetPosition(irp->output, pos); + + error = rdpdr_send(rdpdr, irp->output); + irp->output = NULL; + + irp_free(irp); + return error; +} + +IRP* irp_new(DEVMAN* devman, wStreamPool* pool, wStream* s, wLog* log, UINT* error) +{ + IRP* irp = NULL; + DEVICE* device = NULL; + UINT32 DeviceId = 0; + + WINPR_ASSERT(devman); + WINPR_ASSERT(pool); + WINPR_ASSERT(s); + + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 20)) + { + if (error) + *error = ERROR_INVALID_DATA; + return NULL; + } + + Stream_Read_UINT32(s, DeviceId); /* DeviceId (4 bytes) */ + device = devman_get_device_by_id(devman, DeviceId); + + if (!device) + { + if (error) + *error = ERROR_DEV_NOT_EXIST; + + return NULL; + } + + irp = (IRP*)winpr_aligned_malloc(sizeof(IRP), MEMORY_ALLOCATION_ALIGNMENT); + + if (!irp) + { + WLog_Print(log, WLOG_ERROR, "_aligned_malloc failed!"); + if (error) + *error = CHANNEL_RC_NO_MEMORY; + return NULL; + } + + ZeroMemory(irp, sizeof(IRP)); + + Stream_Read_UINT32(s, irp->FileId); /* FileId (4 bytes) */ + Stream_Read_UINT32(s, irp->CompletionId); /* CompletionId (4 bytes) */ + Stream_Read_UINT32(s, irp->MajorFunction); /* MajorFunction (4 bytes) */ + Stream_Read_UINT32(s, irp->MinorFunction); /* MinorFunction (4 bytes) */ + + Stream_AddRef(s); + irp->input = s; + irp->device = device; + irp->devman = devman; + + irp->output = StreamPool_Take(pool, 256); + if (!irp->output) + { + WLog_Print(log, WLOG_ERROR, "Stream_New failed!"); + irp_free(irp); + if (error) + *error = CHANNEL_RC_NO_MEMORY; + return NULL; + } + + if (!rdpdr_write_iocompletion_header(irp->output, DeviceId, irp->CompletionId, 0)) + { + irp_free(irp); + if (error) + *error = CHANNEL_RC_NO_MEMORY; + return NULL; + } + + irp->Complete = irp_complete; + irp->Discard = irp_free; + + irp->thread = NULL; + irp->cancelled = FALSE; + + if (error) + *error = CHANNEL_RC_OK; + + return irp; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.h new file mode 100644 index 0000000000000000000000000000000000000000..053829502fe2e8a96d8d3f169ce9a79a55fece55 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/irp.h @@ -0,0 +1,29 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * + * 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 FREERDP_CHANNEL_RDPDR_CLIENT_IRP_H +#define FREERDP_CHANNEL_RDPDR_CLIENT_IRP_H + +#include +#include "rdpdr_main.h" + +IRP* irp_new(DEVMAN* devman, wStreamPool* pool, wStream* s, wLog* log, UINT* error); + +#endif /* FREERDP_CHANNEL_RDPDR_CLIENT_IRP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.c new file mode 100644 index 0000000000000000000000000000000000000000..7d763c1a87c02b4a3b956d191a87dd78044961dc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.c @@ -0,0 +1,322 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015-2016 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Armin Novak + * + * 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 + +#include +#include +#include + +#include +#include + +#include +#include + +#include "rdpdr_main.h" +#include "rdpdr_capabilities.h" + +#define RDPDR_CAPABILITY_HEADER_LENGTH 8 + +/* Output device direction general capability set */ +static BOOL rdpdr_write_general_capset(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + const RDPDR_CAPABILITY_HEADER header = { CAP_GENERAL_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH + 36, + GENERAL_CAPABILITY_VERSION_02 }; + + const UINT32 ioCode1 = rdpdr->clientIOCode1 & rdpdr->serverIOCode1; + const UINT32 ioCode2 = rdpdr->clientIOCode2 & rdpdr->serverIOCode2; + + if (rdpdr_write_capset_header(rdpdr->log, s, &header) != CHANNEL_RC_OK) + return FALSE; + + if (!Stream_EnsureRemainingCapacity(s, 36)) + return FALSE; + + Stream_Write_UINT32(s, rdpdr->clientOsType); /* osType, ignored on receipt */ + Stream_Write_UINT32(s, rdpdr->clientOsVersion); /* osVersion, unused and must be set to zero */ + Stream_Write_UINT16(s, rdpdr->clientVersionMajor); /* protocolMajorVersion, must be set to 1 */ + Stream_Write_UINT16(s, rdpdr->clientVersionMinor); /* protocolMinorVersion */ + Stream_Write_UINT32(s, ioCode1); /* ioCode1 */ + Stream_Write_UINT32(s, ioCode2); /* ioCode2, must be set to zero, reserved for future use */ + Stream_Write_UINT32(s, rdpdr->clientExtendedPDU); /* extendedPDU */ + Stream_Write_UINT32(s, rdpdr->clientExtraFlags1); /* extraFlags1 */ + Stream_Write_UINT32( + s, + rdpdr->clientExtraFlags2); /* extraFlags2, must be set to zero, reserved for future use */ + Stream_Write_UINT32( + s, rdpdr->clientSpecialTypeDeviceCap); /* SpecialTypeDeviceCap, number of special devices to + be redirected before logon */ + return TRUE; +} + +/* Process device direction general capability set */ +static UINT rdpdr_process_general_capset(rdpdrPlugin* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(header); + + if (header->CapabilityLength != 36) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "CAP_GENERAL_TYPE::CapabilityLength expected 36, got %" PRIu32, + header->CapabilityLength); + return ERROR_INVALID_DATA; + } + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 36)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, rdpdr->serverOsType); /* osType, ignored on receipt */ + Stream_Read_UINT32(s, rdpdr->serverOsVersion); /* osVersion, unused and must be set to zero */ + Stream_Read_UINT16(s, rdpdr->serverVersionMajor); /* protocolMajorVersion, must be set to 1 */ + Stream_Read_UINT16(s, rdpdr->serverVersionMinor); /* protocolMinorVersion */ + Stream_Read_UINT32(s, rdpdr->serverIOCode1); /* ioCode1 */ + Stream_Read_UINT32( + s, rdpdr->serverIOCode2); /* ioCode2, must be set to zero, reserved for future use */ + Stream_Read_UINT32(s, rdpdr->serverExtendedPDU); /* extendedPDU */ + Stream_Read_UINT32(s, rdpdr->serverExtraFlags1); /* extraFlags1 */ + Stream_Read_UINT32( + s, + rdpdr->serverExtraFlags2); /* extraFlags2, must be set to zero, reserved for future use */ + Stream_Read_UINT32( + s, rdpdr->serverSpecialTypeDeviceCap); /* SpecialTypeDeviceCap, number of special devices to + be redirected before logon */ + return CHANNEL_RC_OK; +} + +/* Output printer direction capability set */ +static BOOL rdpdr_write_printer_capset(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_UNUSED(rdpdr); + const RDPDR_CAPABILITY_HEADER header = { CAP_PRINTER_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + PRINT_CAPABILITY_VERSION_01 }; + return rdpdr_write_capset_header(rdpdr->log, s, &header) == CHANNEL_RC_OK; +} + +/* Process printer direction capability set */ +static UINT rdpdr_process_printer_capset(rdpdrPlugin* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(header); + Stream_Seek(s, header->CapabilityLength); + return CHANNEL_RC_OK; +} + +/* Output port redirection capability set */ +static BOOL rdpdr_write_port_capset(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_UNUSED(rdpdr); + const RDPDR_CAPABILITY_HEADER header = { CAP_PORT_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + PORT_CAPABILITY_VERSION_01 }; + return rdpdr_write_capset_header(rdpdr->log, s, &header) == CHANNEL_RC_OK; +} + +/* Process port redirection capability set */ +static UINT rdpdr_process_port_capset(rdpdrPlugin* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(header); + Stream_Seek(s, header->CapabilityLength); + return CHANNEL_RC_OK; +} + +/* Output drive redirection capability set */ +static BOOL rdpdr_write_drive_capset(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_UNUSED(rdpdr); + const RDPDR_CAPABILITY_HEADER header = { CAP_DRIVE_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + DRIVE_CAPABILITY_VERSION_02 }; + return rdpdr_write_capset_header(rdpdr->log, s, &header) == CHANNEL_RC_OK; +} + +/* Process drive redirection capability set */ +static UINT rdpdr_process_drive_capset(rdpdrPlugin* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(header); + Stream_Seek(s, header->CapabilityLength); + return CHANNEL_RC_OK; +} + +/* Output smart card redirection capability set */ +static BOOL rdpdr_write_smartcard_capset(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_UNUSED(rdpdr); + const RDPDR_CAPABILITY_HEADER header = { CAP_SMARTCARD_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + SMARTCARD_CAPABILITY_VERSION_01 }; + return rdpdr_write_capset_header(rdpdr->log, s, &header) == CHANNEL_RC_OK; +} + +/* Process smartcard redirection capability set */ +static UINT rdpdr_process_smartcard_capset(rdpdrPlugin* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(header); + Stream_Seek(s, header->CapabilityLength); + return CHANNEL_RC_OK; +} + +UINT rdpdr_process_capability_request(rdpdrPlugin* rdpdr, wStream* s) +{ + UINT status = CHANNEL_RC_OK; + UINT16 numCapabilities = 0; + + if (!rdpdr || !s) + return CHANNEL_RC_NULL_DATA; + + WINPR_ASSERT(rdpdr->state == RDPDR_CHANNEL_STATE_SERVER_CAPS); + rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_CLIENT_CAPS); + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, numCapabilities); + Stream_Seek(s, 2); /* pad (2 bytes) */ + + memset(rdpdr->capabilities, 0, sizeof(rdpdr->capabilities)); + for (UINT16 i = 0; i < numCapabilities; i++) + { + RDPDR_CAPABILITY_HEADER header = { 0 }; + UINT error = rdpdr_read_capset_header(rdpdr->log, s, &header); + if (error != CHANNEL_RC_OK) + return error; + + switch (header.CapabilityType) + { + case CAP_GENERAL_TYPE: + rdpdr->capabilities[header.CapabilityType] = TRUE; + status = rdpdr_process_general_capset(rdpdr, s, &header); + break; + + case CAP_PRINTER_TYPE: + rdpdr->capabilities[header.CapabilityType] = TRUE; + status = rdpdr_process_printer_capset(rdpdr, s, &header); + break; + + case CAP_PORT_TYPE: + rdpdr->capabilities[header.CapabilityType] = TRUE; + status = rdpdr_process_port_capset(rdpdr, s, &header); + break; + + case CAP_DRIVE_TYPE: + rdpdr->capabilities[header.CapabilityType] = TRUE; + status = rdpdr_process_drive_capset(rdpdr, s, &header); + break; + + case CAP_SMARTCARD_TYPE: + rdpdr->capabilities[header.CapabilityType] = TRUE; + status = rdpdr_process_smartcard_capset(rdpdr, s, &header); + break; + + default: + break; + } + + if (status != CHANNEL_RC_OK) + return status; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpdr_send_capability_response(rdpdrPlugin* rdpdr) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->rdpcontext); + + rdpSettings* settings = rdpdr->rdpcontext->settings; + WINPR_ASSERT(settings); + + wStream* s = StreamPool_Take(rdpdr->pool, 256); + + if (!s) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + const RDPDR_DEVICE* cdrives = + freerdp_device_collection_find_type(settings, RDPDR_DTYP_FILESYSTEM); + const RDPDR_DEVICE* cserial = freerdp_device_collection_find_type(settings, RDPDR_DTYP_SERIAL); + const RDPDR_DEVICE* cparallel = + freerdp_device_collection_find_type(settings, RDPDR_DTYP_PARALLEL); + const RDPDR_DEVICE* csmart = + freerdp_device_collection_find_type(settings, RDPDR_DTYP_SMARTCARD); + const RDPDR_DEVICE* cprinter = freerdp_device_collection_find_type(settings, RDPDR_DTYP_PRINT); + + /* Only send capabilities the server announced */ + const BOOL drives = cdrives && rdpdr->capabilities[CAP_DRIVE_TYPE]; + const BOOL serial = cserial && rdpdr->capabilities[CAP_PORT_TYPE]; + const BOOL parallel = cparallel && rdpdr->capabilities[CAP_PORT_TYPE]; + const BOOL smart = csmart && rdpdr->capabilities[CAP_SMARTCARD_TYPE]; + const BOOL printer = cprinter && rdpdr->capabilities[CAP_PRINTER_TYPE]; + UINT16 count = 1; + if (drives) + count++; + if (serial || parallel) + count++; + if (smart) + count++; + if (printer) + count++; + + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); + Stream_Write_UINT16(s, PAKID_CORE_CLIENT_CAPABILITY); + Stream_Write_UINT16(s, count); /* numCapabilities */ + Stream_Write_UINT16(s, 0); /* pad */ + + if (!rdpdr_write_general_capset(rdpdr, s)) + goto fail; + + if (printer) + { + if (!rdpdr_write_printer_capset(rdpdr, s)) + goto fail; + } + if (serial || parallel) + { + if (!rdpdr_write_port_capset(rdpdr, s)) + goto fail; + } + if (drives) + { + if (!rdpdr_write_drive_capset(rdpdr, s)) + goto fail; + } + if (smart) + { + if (!rdpdr_write_smartcard_capset(rdpdr, s)) + goto fail; + } + return rdpdr_send(rdpdr, s); + +fail: + Stream_Release(s); + return ERROR_OUTOFMEMORY; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.h new file mode 100644 index 0000000000000000000000000000000000000000..d4e1ecb276c99ceb523915d9f383185c9e58fd4e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_capabilities.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_RDPDR_CLIENT_CAPABILITIES_H +#define FREERDP_CHANNEL_RDPDR_CLIENT_CAPABILITIES_H + +#include "rdpdr_main.h" + +UINT rdpdr_process_capability_request(rdpdrPlugin* rdpdr, wStream* s); +UINT rdpdr_send_capability_response(rdpdrPlugin* rdpdr); + +#endif /* FREERDP_CHANNEL_RDPDR_CLIENT_CAPABILITIES_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6b73a563a41029767a8208f5dcfe8e1aed5f4a0e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.c @@ -0,0 +1,2372 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015-2016 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Armin Novak + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif + +#ifdef __MACOSX__ +#include +#include +#include +#include +#include +#include +#endif + +#include "rdpdr_capabilities.h" + +#include "devman.h" +#include "irp.h" + +#include "rdpdr_main.h" + +#define TAG CHANNELS_TAG("rdpdr.client") + +/* IMPORTANT: Keep in sync with DRIVE_DEVICE */ +typedef struct +{ + DEVICE device; + WCHAR* path; + BOOL automount; +} DEVICE_DRIVE_EXT; + +static const char* rdpdr_state_str(enum RDPDR_CHANNEL_STATE state) +{ + switch (state) + { + case RDPDR_CHANNEL_STATE_INITIAL: + return "RDPDR_CHANNEL_STATE_INITIAL"; + case RDPDR_CHANNEL_STATE_ANNOUNCE: + return "RDPDR_CHANNEL_STATE_ANNOUNCE"; + case RDPDR_CHANNEL_STATE_ANNOUNCE_REPLY: + return "RDPDR_CHANNEL_STATE_ANNOUNCE_REPLY"; + case RDPDR_CHANNEL_STATE_NAME_REQUEST: + return "RDPDR_CHANNEL_STATE_NAME_REQUEST"; + case RDPDR_CHANNEL_STATE_SERVER_CAPS: + return "RDPDR_CHANNEL_STATE_SERVER_CAPS"; + case RDPDR_CHANNEL_STATE_CLIENT_CAPS: + return "RDPDR_CHANNEL_STATE_CLIENT_CAPS"; + case RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM: + return "RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM"; + case RDPDR_CHANNEL_STATE_READY: + return "RDPDR_CHANNEL_STATE_READY"; + case RDPDR_CHANNEL_STATE_USER_LOGGEDON: + return "RDPDR_CHANNEL_STATE_USER_LOGGEDON"; + default: + return "RDPDR_CHANNEL_STATE_UNKNOWN"; + } +} + +static const char* rdpdr_device_type_string(UINT32 type) +{ + switch (type) + { + case RDPDR_DTYP_SERIAL: + return "serial"; + case RDPDR_DTYP_PRINT: + return "printer"; + case RDPDR_DTYP_FILESYSTEM: + return "drive"; + case RDPDR_DTYP_SMARTCARD: + return "smartcard"; + case RDPDR_DTYP_PARALLEL: + return "parallel"; + default: + return "UNKNOWN"; + } +} + +static const char* support_str(BOOL val) +{ + if (val) + return "supported"; + return "not found"; +} + +static const char* rdpdr_caps_pdu_str(UINT32 flag) +{ + switch (flag) + { + case RDPDR_DEVICE_REMOVE_PDUS: + return "RDPDR_USER_LOGGEDON_PDU"; + case RDPDR_CLIENT_DISPLAY_NAME_PDU: + return "RDPDR_CLIENT_DISPLAY_NAME_PDU"; + case RDPDR_USER_LOGGEDON_PDU: + return "RDPDR_USER_LOGGEDON_PDU"; + default: + return "RDPDR_UNKNONW"; + } +} + +static BOOL rdpdr_check_extended_pdu_flag(rdpdrPlugin* rdpdr, UINT32 flag) +{ + WINPR_ASSERT(rdpdr); + + const BOOL client = (rdpdr->clientExtendedPDU & flag) != 0; + const BOOL server = (rdpdr->serverExtendedPDU & flag) != 0; + + if (!client || !server) + { + WLog_Print(rdpdr->log, WLOG_WARN, "Checking ExtendedPDU::%s, client %s, server %s", + rdpdr_caps_pdu_str(flag), support_str(client), support_str(server)); + return FALSE; + } + return TRUE; +} + +BOOL rdpdr_state_advance(rdpdrPlugin* rdpdr, enum RDPDR_CHANNEL_STATE next) +{ + WINPR_ASSERT(rdpdr); + + if (next != rdpdr->state) + WLog_Print(rdpdr->log, WLOG_DEBUG, "[RDPDR] transition from %s to %s", + rdpdr_state_str(rdpdr->state), rdpdr_state_str(next)); + rdpdr->state = next; + return TRUE; +} + +static BOOL device_foreach(rdpdrPlugin* rdpdr, BOOL abortOnFail, + BOOL (*fkt)(ULONG_PTR key, void* element, void* data), void* data) +{ + BOOL rc = TRUE; + ULONG_PTR* keys = NULL; + + ListDictionary_Lock(rdpdr->devman->devices); + const size_t count = ListDictionary_GetKeys(rdpdr->devman->devices, &keys); + for (size_t x = 0; x < count; x++) + { + void* element = ListDictionary_GetItemValue(rdpdr->devman->devices, (void*)keys[x]); + if (!fkt(keys[x], element, data)) + { + rc = FALSE; + if (abortOnFail) + break; + } + } + free(keys); + ListDictionary_Unlock(rdpdr->devman->devices); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_try_send_device_list_announce_request(rdpdrPlugin* rdpdr); + +static BOOL rdpdr_load_drive(rdpdrPlugin* rdpdr, const char* name, const char* path, BOOL automount) +{ + UINT rc = ERROR_INTERNAL_ERROR; + union + { + RDPDR_DRIVE* drive; + RDPDR_DEVICE* device; + } drive; + const char* args[] = { name, path, automount ? NULL : name }; + + drive.device = freerdp_device_new(RDPDR_DTYP_FILESYSTEM, ARRAYSIZE(args), args); + if (!drive.device) + goto fail; + + rc = devman_load_device_service(rdpdr->devman, drive.device, rdpdr->rdpcontext); + if (rc != CHANNEL_RC_OK) + goto fail; + +fail: + freerdp_device_free(drive.device); + return rc == CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_send_device_list_remove_request(rdpdrPlugin* rdpdr, UINT32 count, UINT32 ids[]) +{ + wStream* s = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(ids || (count == 0)); + + if (count == 0) + return CHANNEL_RC_OK; + + if (!rdpdr_check_extended_pdu_flag(rdpdr, RDPDR_DEVICE_REMOVE_PDUS)) + return CHANNEL_RC_OK; + + s = StreamPool_Take(rdpdr->pool, count * sizeof(UINT32) + 8); + + if (!s) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); + Stream_Write_UINT16(s, PAKID_CORE_DEVICELIST_REMOVE); + Stream_Write_UINT32(s, count); + + for (UINT32 i = 0; i < count; i++) + Stream_Write_UINT32(s, ids[i]); + + Stream_SealLength(s); + return rdpdr_send(rdpdr, s); +} + +#if defined(_UWP) || defined(__IOS__) + +static void first_hotplug(rdpdrPlugin* rdpdr) +{ +} + +static DWORD WINAPI drive_hotplug_thread_func(LPVOID arg) +{ + return CHANNEL_RC_OK; +} + +static UINT drive_hotplug_thread_terminate(rdpdrPlugin* rdpdr) +{ + return CHANNEL_RC_OK; +} + +#elif defined(_WIN32) + +static BOOL check_path(const char* path) +{ + UINT type = GetDriveTypeA(path); + + if (!(type == DRIVE_FIXED || type == DRIVE_REMOVABLE || type == DRIVE_CDROM || + type == DRIVE_REMOTE)) + return FALSE; + + return GetVolumeInformationA(path, NULL, 0, NULL, NULL, NULL, NULL, 0); +} + +static void first_hotplug(rdpdrPlugin* rdpdr) +{ + DWORD unitmask = GetLogicalDrives(); + + for (size_t i = 0; i < 26; i++) + { + if (unitmask & 0x01) + { + char drive_path[] = { 'c', ':', '\\', '\0' }; + char drive_name[] = { 'c', '\0' }; + drive_path[0] = 'A' + (char)i; + drive_name[0] = 'A' + (char)i; + + if (check_path(drive_path)) + { + rdpdr_load_drive(rdpdr, drive_name, drive_path, TRUE); + } + } + + unitmask = unitmask >> 1; + } +} + +static LRESULT CALLBACK hotplug_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) +{ + rdpdrPlugin* rdpdr; + PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam; + UINT error; + rdpdr = (rdpdrPlugin*)GetWindowLongPtr(hWnd, GWLP_USERDATA); + + switch (Msg) + { + case WM_DEVICECHANGE: + switch (wParam) + { + case DBT_DEVICEARRIVAL: + if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) + { + PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; + DWORD unitmask = lpdbv->dbcv_unitmask; + + for (int i = 0; i < 26; i++) + { + if (unitmask & 0x01) + { + char drive_path[] = { 'c', ':', '/', '\0' }; + char drive_name[] = { 'c', '\0' }; + drive_path[0] = 'A' + (char)i; + drive_name[0] = 'A' + (char)i; + + if (check_path(drive_path)) + { + rdpdr_load_drive(rdpdr, drive_name, drive_path, TRUE); + rdpdr_try_send_device_list_announce_request(rdpdr); + } + } + + unitmask = unitmask >> 1; + } + } + + break; + + case DBT_DEVICEREMOVECOMPLETE: + if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME) + { + PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb; + DWORD unitmask = lpdbv->dbcv_unitmask; + int count; + char drive_name_upper, drive_name_lower; + ULONG_PTR* keys = NULL; + DEVICE_DRIVE_EXT* device_ext; + UINT32 ids[1]; + + for (int i = 0; i < 26; i++) + { + if (unitmask & 0x01) + { + drive_name_upper = 'A' + i; + drive_name_lower = 'a' + i; + count = ListDictionary_GetKeys(rdpdr->devman->devices, &keys); + + for (int j = 0; j < count; j++) + { + device_ext = (DEVICE_DRIVE_EXT*)ListDictionary_GetItemValue( + rdpdr->devman->devices, (void*)keys[j]); + + if (device_ext->device.type != RDPDR_DTYP_FILESYSTEM) + continue; + + if (device_ext->path[0] == drive_name_upper || + device_ext->path[0] == drive_name_lower) + { + if (device_ext->automount) + { + devman_unregister_device(rdpdr->devman, (void*)keys[j]); + ids[0] = keys[j]; + + if ((error = rdpdr_send_device_list_remove_request( + rdpdr, 1, ids))) + { + // dont end on error, just report ? + WLog_Print( + rdpdr->log, WLOG_ERROR, + "rdpdr_send_device_list_remove_request failed " + "with error %" PRIu32 "!", + error); + } + + break; + } + } + } + + free(keys); + } + + unitmask = unitmask >> 1; + } + } + + break; + + default: + break; + } + + break; + + default: + return DefWindowProc(hWnd, Msg, wParam, lParam); + } + + return DefWindowProc(hWnd, Msg, wParam, lParam); +} + +static DWORD WINAPI drive_hotplug_thread_func(LPVOID arg) +{ + rdpdrPlugin* rdpdr; + WNDCLASSEX wnd_cls; + HWND hwnd; + MSG msg; + BOOL bRet; + DEV_BROADCAST_HANDLE NotificationFilter; + HDEVNOTIFY hDevNotify; + rdpdr = (rdpdrPlugin*)arg; + /* init windows class */ + wnd_cls.cbSize = sizeof(WNDCLASSEX); + wnd_cls.style = CS_HREDRAW | CS_VREDRAW; + wnd_cls.lpfnWndProc = hotplug_proc; + wnd_cls.cbClsExtra = 0; + wnd_cls.cbWndExtra = 0; + wnd_cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wnd_cls.hCursor = NULL; + wnd_cls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); + wnd_cls.lpszMenuName = NULL; + wnd_cls.lpszClassName = L"DRIVE_HOTPLUG"; + wnd_cls.hInstance = NULL; + wnd_cls.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + RegisterClassEx(&wnd_cls); + /* create window */ + hwnd = CreateWindowEx(0, L"DRIVE_HOTPLUG", NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); + SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)rdpdr); + rdpdr->hotplug_wnd = hwnd; + /* register device interface to hwnd */ + NotificationFilter.dbch_size = sizeof(DEV_BROADCAST_HANDLE); + NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE; + hDevNotify = RegisterDeviceNotification(hwnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); + + /* message loop */ + while ((bRet = GetMessage(&msg, 0, 0, 0)) != 0) + { + if (bRet == -1) + { + break; + } + else + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + UnregisterDeviceNotification(hDevNotify); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_hotplug_thread_terminate(rdpdrPlugin* rdpdr) +{ + UINT error = CHANNEL_RC_OK; + + if (rdpdr->hotplug_wnd && !PostMessage(rdpdr->hotplug_wnd, WM_QUIT, 0, 0)) + { + error = GetLastError(); + WLog_Print(rdpdr->log, WLOG_ERROR, "PostMessage failed with error %" PRIu32 "", error); + } + + return error; +} + +#elif defined(__MACOSX__) + +#define MAX_USB_DEVICES 100 + +typedef struct +{ + char* path; + BOOL to_add; +} hotplug_dev; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT handle_hotplug(rdpdrPlugin* rdpdr) +{ + struct dirent* pDirent = NULL; + char fullpath[PATH_MAX] = { 0 }; + char* szdir = (char*)"/Volumes"; + struct stat buf = { 0 }; + hotplug_dev dev_array[MAX_USB_DEVICES] = { 0 }; + int count = 0; + DEVICE_DRIVE_EXT* device_ext = NULL; + ULONG_PTR* keys = NULL; + int size = 0; + UINT error = ERROR_INTERNAL_ERROR; + UINT32 ids[1]; + + DIR* pDir = opendir(szdir); + + if (pDir == NULL) + { + printf("Cannot open directory\n"); + return ERROR_OPEN_FAILED; + } + + while ((pDirent = readdir(pDir)) != NULL) + { + if (pDirent->d_name[0] != '.') + { + (void)sprintf_s(fullpath, ARRAYSIZE(fullpath), "%s/%s", szdir, pDirent->d_name); + if (stat(fullpath, &buf) != 0) + continue; + + if (S_ISDIR(buf.st_mode)) + { + dev_array[size].path = _strdup(fullpath); + + if (!dev_array[size].path) + { + closedir(pDir); + error = CHANNEL_RC_NO_MEMORY; + goto cleanup; + } + + dev_array[size++].to_add = TRUE; + } + } + } + + closedir(pDir); + /* delete removed devices */ + count = ListDictionary_GetKeys(rdpdr->devman->devices, &keys); + + for (size_t j = 0; j < count; j++) + { + char* path = NULL; + BOOL dev_found = FALSE; + device_ext = + (DEVICE_DRIVE_EXT*)ListDictionary_GetItemValue(rdpdr->devman->devices, (void*)keys[j]); + + if (!device_ext || !device_ext->automount) + continue; + + if (device_ext->device.type != RDPDR_DTYP_FILESYSTEM) + continue; + + if (device_ext->path == NULL) + continue; + + path = ConvertWCharToUtf8Alloc(device_ext->path, NULL); + if (!path) + continue; + + /* not pluggable device */ + if (strstr(path, "/Volumes/") == NULL) + { + free(path); + continue; + } + + for (size_t i = 0; i < size; i++) + { + if (strstr(path, dev_array[i].path) != NULL) + { + dev_found = TRUE; + dev_array[i].to_add = FALSE; + break; + } + } + + free(path); + + if (!dev_found) + { + devman_unregister_device(rdpdr->devman, (void*)keys[j]); + ids[0] = keys[j]; + + if ((error = rdpdr_send_device_list_remove_request(rdpdr, 1, ids))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_send_device_list_remove_request failed with error %" PRIu32 "!", + error); + goto cleanup; + } + } + } + + /* add new devices */ + for (size_t i = 0; i < size; i++) + { + const hotplug_dev* dev = &dev_array[i]; + if (dev->to_add) + { + const char* path = dev->path; + const char* name = strrchr(path, '/') + 1; + error = rdpdr_load_drive(rdpdr, name, path, TRUE); + if (error) + goto cleanup; + } + } + +cleanup: + free(keys); + + for (size_t i = 0; i < size; i++) + free(dev_array[i].path); + + return error; +} + +static void drive_hotplug_fsevent_callback(ConstFSEventStreamRef streamRef, + void* clientCallBackInfo, size_t numEvents, + void* eventPaths, + const FSEventStreamEventFlags eventFlags[], + const FSEventStreamEventId eventIds[]) +{ + rdpdrPlugin* rdpdr; + UINT error; + char** paths = (char**)eventPaths; + rdpdr = (rdpdrPlugin*)clientCallBackInfo; + + for (size_t i = 0; i < numEvents; i++) + { + if (strcmp(paths[i], "/Volumes/") == 0) + { + if ((error = handle_hotplug(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "handle_hotplug failed with error %" PRIu32 "!", + error); + } + else + rdpdr_try_send_device_list_announce_request(rdpdr); + + return; + } + } +} + +static void first_hotplug(rdpdrPlugin* rdpdr) +{ + UINT error; + + if ((error = handle_hotplug(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "handle_hotplug failed with error %" PRIu32 "!", error); + } +} + +static DWORD WINAPI drive_hotplug_thread_func(LPVOID arg) +{ + rdpdrPlugin* rdpdr; + FSEventStreamRef fsev; + rdpdr = (rdpdrPlugin*)arg; + CFStringRef path = CFSTR("/Volumes/"); + CFArrayRef pathsToWatch = CFArrayCreate(kCFAllocatorMalloc, (const void**)&path, 1, NULL); + FSEventStreamContext ctx = { 0 }; + + ctx.info = arg; + + WINPR_ASSERT(!rdpdr->stopEvent); + rdpdr->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!rdpdr->stopEvent) + goto out; + + fsev = + FSEventStreamCreate(kCFAllocatorMalloc, drive_hotplug_fsevent_callback, &ctx, pathsToWatch, + kFSEventStreamEventIdSinceNow, 1, kFSEventStreamCreateFlagNone); + + rdpdr->runLoop = CFRunLoopGetCurrent(); + FSEventStreamScheduleWithRunLoop(fsev, rdpdr->runLoop, kCFRunLoopDefaultMode); + FSEventStreamStart(fsev); + CFRunLoopRun(); + FSEventStreamStop(fsev); + FSEventStreamRelease(fsev); +out: + if (rdpdr->stopEvent) + { + (void)CloseHandle(rdpdr->stopEvent); + rdpdr->stopEvent = NULL; + } + ExitThread(CHANNEL_RC_OK); + return CHANNEL_RC_OK; +} + +#else + +static const char* automountLocations[] = { "/run/user/%lu/gvfs", "/run/media/%s", "/media/%s", + "/media", "/mnt" }; + +static BOOL isAutomountLocation(const char* path) +{ + const size_t nrLocations = sizeof(automountLocations) / sizeof(automountLocations[0]); + char buffer[MAX_PATH] = { 0 }; + uid_t uid = getuid(); + char uname[MAX_PATH] = { 0 }; + ULONG size = sizeof(uname) - 1; + + if (!GetUserNameExA(NameSamCompatible, uname, &size)) + return FALSE; + + if (!path) + return FALSE; + + for (size_t x = 0; x < nrLocations; x++) + { + const char* location = automountLocations[x]; + size_t length = 0; + + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL + if (strstr(location, "%lu")) + (void)snprintf(buffer, sizeof(buffer), location, (unsigned long)uid); + else if (strstr(location, "%s")) + (void)snprintf(buffer, sizeof(buffer), location, uname); + else + (void)snprintf(buffer, sizeof(buffer), "%s", location); + WINPR_PRAGMA_DIAG_POP + + length = strnlen(buffer, sizeof(buffer)); + + if (strncmp(buffer, path, length) == 0) + { + const char* rest = &path[length]; + + /* Only consider mount locations with max depth of 1 below the + * base path or the base path itself. */ + if (*rest == '\0') + return TRUE; + else if (*rest == '/') + { + const char* token = strstr(&rest[1], "/"); + + if (!token || (token[1] == '\0')) + return TRUE; + } + } + } + + return FALSE; +} + +#define MAX_USB_DEVICES 100 + +typedef struct +{ + char* path; + BOOL to_add; +} hotplug_dev; + +static void handle_mountpoint(hotplug_dev* dev_array, size_t* size, const char* mountpoint) +{ + if (!mountpoint) + return; + /* copy hotpluged device mount point to the dev_array */ + if (isAutomountLocation(mountpoint) && (*size < MAX_USB_DEVICES)) + { + dev_array[*size].path = _strdup(mountpoint); + dev_array[*size].to_add = TRUE; + (*size)++; + } +} + +#ifdef __sun +#include +static UINT handle_platform_mounts_sun(wLog* log, hotplug_dev* dev_array, size_t* size) +{ + FILE* f; + struct mnttab ent; + f = winpr_fopen("/etc/mnttab", "r"); + if (f == NULL) + { + WLog_Print(log, WLOG_ERROR, "fopen failed!"); + return ERROR_OPEN_FAILED; + } + while (getmntent(f, &ent) == 0) + { + handle_mountpoint(dev_array, size, ent.mnt_mountp); + } + fclose(f); + return ERROR_SUCCESS; +} +#endif + +#if defined(__FreeBSD__) || defined(__OpenBSD__) +#include +static UINT handle_platform_mounts_bsd(wLog* log, hotplug_dev* dev_array, size_t* size) +{ + int mntsize; + struct statfs* mntbuf = NULL; + + mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + if (!mntsize) + { + /* TODO: handle 'errno' */ + WLog_Print(log, WLOG_ERROR, "getmntinfo failed!"); + return ERROR_OPEN_FAILED; + } + for (size_t idx = 0; idx < (size_t)mntsize; idx++) + { + handle_mountpoint(dev_array, size, mntbuf[idx].f_mntonname); + } + free(mntbuf); + return ERROR_SUCCESS; +} +#endif + +#if defined(__LINUX__) || defined(__linux__) +#include +static struct mntent* getmntent_x(FILE* f, struct mntent* buffer, char* pathbuffer, + size_t pathbuffersize) +{ +#if defined(FREERDP_HAVE_GETMNTENT_R) + WINPR_ASSERT(pathbuffersize <= INT32_MAX); + return getmntent_r(f, buffer, pathbuffer, (int)pathbuffersize); +#else + (void)buffer; + (void)pathbuffer; + (void)pathbuffersize; + return getmntent(f); +#endif +} + +static UINT handle_platform_mounts_linux(wLog* log, hotplug_dev* dev_array, size_t* size) +{ + FILE* f = NULL; + struct mntent mnt = { 0 }; + char pathbuffer[PATH_MAX] = { 0 }; + struct mntent* ent = NULL; + f = winpr_fopen("/proc/mounts", "r"); + if (f == NULL) + { + WLog_Print(log, WLOG_ERROR, "fopen failed!"); + return ERROR_OPEN_FAILED; + } + while ((ent = getmntent_x(f, &mnt, pathbuffer, sizeof(pathbuffer))) != NULL) + { + handle_mountpoint(dev_array, size, ent->mnt_dir); + } + (void)fclose(f); + return ERROR_SUCCESS; +} +#endif + +static UINT handle_platform_mounts(wLog* log, hotplug_dev* dev_array, size_t* size) +{ +#ifdef __sun + return handle_platform_mounts_sun(log, dev_array, size); +#elif defined(__FreeBSD__) || defined(__OpenBSD__) + return handle_platform_mounts_bsd(log, dev_array, size); +#elif defined(__LINUX__) || defined(__linux__) + return handle_platform_mounts_linux(log, dev_array, size); +#endif + return ERROR_CALL_NOT_IMPLEMENTED; +} + +static BOOL device_not_plugged(ULONG_PTR key, void* element, void* data) +{ + const WCHAR* path = (const WCHAR*)data; + DEVICE_DRIVE_EXT* device_ext = (DEVICE_DRIVE_EXT*)element; + + WINPR_UNUSED(key); + WINPR_ASSERT(path); + + if (!device_ext || (device_ext->device.type != RDPDR_DTYP_FILESYSTEM) || !device_ext->path) + return TRUE; + if (_wcscmp(device_ext->path, path) != 0) + return TRUE; + return FALSE; +} + +static BOOL device_already_plugged(rdpdrPlugin* rdpdr, const hotplug_dev* device) +{ + BOOL rc = FALSE; + WCHAR* path = NULL; + + if (!rdpdr || !device) + return TRUE; + if (!device->to_add) + return TRUE; + + WINPR_ASSERT(rdpdr->devman); + WINPR_ASSERT(device->path); + + path = ConvertUtf8ToWCharAlloc(device->path, NULL); + if (!path) + return TRUE; + + rc = device_foreach(rdpdr, TRUE, device_not_plugged, path); + free(path); + return !rc; +} + +struct hotplug_delete_arg +{ + hotplug_dev* dev_array; + size_t dev_array_size; + rdpdrPlugin* rdpdr; +}; + +static BOOL hotplug_delete_foreach(ULONG_PTR key, void* element, void* data) +{ + char* path = NULL; + BOOL dev_found = FALSE; + struct hotplug_delete_arg* arg = (struct hotplug_delete_arg*)data; + DEVICE_DRIVE_EXT* device_ext = (DEVICE_DRIVE_EXT*)element; + + WINPR_ASSERT(arg); + WINPR_ASSERT(arg->rdpdr); + WINPR_ASSERT(arg->dev_array || (arg->dev_array_size == 0)); + WINPR_ASSERT(key <= UINT32_MAX); + + if (!device_ext || (device_ext->device.type != RDPDR_DTYP_FILESYSTEM) || !device_ext->path || + !device_ext->automount) + return TRUE; + + WINPR_ASSERT(device_ext->path); + path = ConvertWCharToUtf8Alloc(device_ext->path, NULL); + if (!path) + return FALSE; + + /* not pluggable device */ + if (isAutomountLocation(path)) + { + for (size_t i = 0; i < arg->dev_array_size; i++) + { + hotplug_dev* cur = &arg->dev_array[i]; + if (cur->path && strstr(path, cur->path) != NULL) + { + dev_found = TRUE; + cur->to_add = FALSE; + break; + } + } + } + + free(path); + + if (!dev_found) + { + UINT error = 0; + UINT32 ids[1] = { (UINT32)key }; + + WINPR_ASSERT(arg->rdpdr->devman); + devman_unregister_device(arg->rdpdr->devman, (void*)key); + WINPR_ASSERT(key <= UINT32_MAX); + + error = rdpdr_send_device_list_remove_request(arg->rdpdr, 1, ids); + if (error) + { + WLog_Print(arg->rdpdr->log, WLOG_ERROR, + "rdpdr_send_device_list_remove_request failed with error %" PRIu32 "!", + error); + return FALSE; + } + } + + return TRUE; +} + +static UINT handle_hotplug(rdpdrPlugin* rdpdr) +{ + hotplug_dev dev_array[MAX_USB_DEVICES] = { 0 }; + size_t size = 0; + UINT error = ERROR_SUCCESS; + struct hotplug_delete_arg arg = { dev_array, ARRAYSIZE(dev_array), rdpdr }; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->devman); + + error = handle_platform_mounts(rdpdr->log, dev_array, &size); + + /* delete removed devices */ + /* Ignore result */ device_foreach(rdpdr, FALSE, hotplug_delete_foreach, &arg); + + /* add new devices */ + for (size_t i = 0; i < size; i++) + { + hotplug_dev* cur = &dev_array[i]; + if (!device_already_plugged(rdpdr, cur)) + { + const char* path = cur->path; + const char* name = strrchr(path, '/') + 1; + + rdpdr_load_drive(rdpdr, name, path, TRUE); + error = ERROR_DISK_CHANGE; + } + } + + for (size_t i = 0; i < size; i++) + free(dev_array[i].path); + + return error; +} + +static void first_hotplug(rdpdrPlugin* rdpdr) +{ + UINT error = 0; + + WINPR_ASSERT(rdpdr); + if ((error = handle_hotplug(rdpdr))) + { + switch (error) + { + case ERROR_DISK_CHANGE: + case CHANNEL_RC_OK: + case ERROR_OPEN_FAILED: + case ERROR_CALL_NOT_IMPLEMENTED: + break; + default: + WLog_Print(rdpdr->log, WLOG_ERROR, "handle_hotplug failed with error %" PRIu32 "!", + error); + break; + } + } +} + +static DWORD WINAPI drive_hotplug_thread_func(LPVOID arg) +{ + rdpdrPlugin* rdpdr = NULL; + UINT error = 0; + rdpdr = (rdpdrPlugin*)arg; + + WINPR_ASSERT(rdpdr); + + WINPR_ASSERT(!rdpdr->stopEvent); + rdpdr->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!rdpdr->stopEvent) + goto out; + + while (WaitForSingleObject(rdpdr->stopEvent, 1000) == WAIT_TIMEOUT) + { + error = handle_hotplug(rdpdr); + switch (error) + { + case ERROR_DISK_CHANGE: + rdpdr_try_send_device_list_announce_request(rdpdr); + break; + case CHANNEL_RC_OK: + case ERROR_OPEN_FAILED: + case ERROR_CALL_NOT_IMPLEMENTED: + break; + default: + WLog_Print(rdpdr->log, WLOG_ERROR, "handle_hotplug failed with error %" PRIu32 "!", + error); + goto out; + } + } + +out: + error = GetLastError(); + if (error && rdpdr->rdpcontext) + setChannelError(rdpdr->rdpcontext, error, "reported an error"); + + if (rdpdr->stopEvent) + { + (void)CloseHandle(rdpdr->stopEvent); + rdpdr->stopEvent = NULL; + } + + ExitThread(error); + return error; +} + +#endif + +#if !defined(_WIN32) && !defined(__IOS__) +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT drive_hotplug_thread_terminate(rdpdrPlugin* rdpdr) +{ + UINT error = 0; + + WINPR_ASSERT(rdpdr); + + if (rdpdr->hotplugThread) + { +#if !defined(_WIN32) + if (rdpdr->stopEvent) + (void)SetEvent(rdpdr->stopEvent); +#endif +#ifdef __MACOSX__ + CFRunLoopStop(rdpdr->runLoop); +#endif + + if (WaitForSingleObject(rdpdr->hotplugThread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_Print(rdpdr->log, WLOG_ERROR, "WaitForSingleObject failed with error %" PRIu32 "!", + error); + return error; + } + + (void)CloseHandle(rdpdr->hotplugThread); + rdpdr->hotplugThread = NULL; + } + + return CHANNEL_RC_OK; +} + +#endif + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_process_connect(rdpdrPlugin* rdpdr) +{ + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(rdpdr); + + rdpdr->devman = devman_new(rdpdr); + + if (!rdpdr->devman) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "devman_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + WINPR_ASSERT(rdpdr->rdpcontext); + + rdpSettings* settings = rdpdr->rdpcontext->settings; + WINPR_ASSERT(settings); + + rdpdr->ignoreInvalidDevices = freerdp_settings_get_bool(settings, FreeRDP_IgnoreInvalidDevices); + + const char* name = freerdp_settings_get_string(settings, FreeRDP_ClientHostname); + if (!name) + name = freerdp_settings_get_string(settings, FreeRDP_ComputerName); + if (!name) + { + DWORD size = ARRAYSIZE(rdpdr->computerName); + if (!GetComputerNameExA(ComputerNameNetBIOS, rdpdr->computerName, &size)) + return ERROR_INTERNAL_ERROR; + } + else + strncpy(rdpdr->computerName, name, strnlen(name, sizeof(rdpdr->computerName))); + + for (UINT32 index = 0; index < freerdp_settings_get_uint32(settings, FreeRDP_DeviceCount); + index++) + { + const RDPDR_DEVICE* device = + freerdp_settings_get_pointer_array(settings, FreeRDP_DeviceArray, index); + + if (device->Type == RDPDR_DTYP_FILESYSTEM) + { + const char DynamicDrives[] = "DynamicDrives"; + const RDPDR_DRIVE* drive = (const RDPDR_DRIVE*)device; + if (!drive->Path) + continue; + + const char wildcard[] = "*"; + BOOL hotplugAll = strncmp(drive->Path, wildcard, sizeof(wildcard)) == 0; + BOOL hotplugLater = strncmp(drive->Path, DynamicDrives, sizeof(DynamicDrives)) == 0; + + if (hotplugAll || hotplugLater) + { + if (!rdpdr->async) + { + WLog_Print(rdpdr->log, WLOG_WARN, + "Drive hotplug is not supported in synchronous mode!"); + continue; + } + + if (hotplugAll) + first_hotplug(rdpdr); + + /* There might be multiple hotplug related device entries. + * Ensure the thread is only started once + */ + if (!rdpdr->hotplugThread) + { + rdpdr->hotplugThread = + CreateThread(NULL, 0, drive_hotplug_thread_func, rdpdr, 0, NULL); + if (!rdpdr->hotplugThread) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "CreateThread failed!"); + return ERROR_INTERNAL_ERROR; + } + } + + continue; + } + } + + if ((error = devman_load_device_service(rdpdr->devman, device, rdpdr->rdpcontext))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "devman_load_device_service failed with error %" PRIu32 "!", error); + return error; + } + } + + return error; +} + +static UINT rdpdr_process_server_announce_request(rdpdrPlugin* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, rdpdr->serverVersionMajor); + Stream_Read_UINT16(s, rdpdr->serverVersionMinor); + Stream_Read_UINT32(s, rdpdr->clientID); + rdpdr->sequenceId++; + + rdpdr->clientVersionMajor = MIN(RDPDR_VERSION_MAJOR, rdpdr->serverVersionMajor); + rdpdr->clientVersionMinor = MIN(RDPDR_VERSION_MINOR_RDP10X, rdpdr->serverVersionMinor); + WLog_Print(rdpdr->log, WLOG_DEBUG, + "[rdpdr] server announces version %" PRIu32 ".%" PRIu32 ", client uses %" PRIu32 + ".%" PRIu32, + rdpdr->serverVersionMajor, rdpdr->serverVersionMinor, rdpdr->clientVersionMajor, + rdpdr->clientVersionMinor); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_send_client_announce_reply(rdpdrPlugin* rdpdr) +{ + wStream* s = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->state == RDPDR_CHANNEL_STATE_ANNOUNCE); + rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_ANNOUNCE_REPLY); + + s = StreamPool_Take(rdpdr->pool, 12); + + if (!s) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); /* Component (2 bytes) */ + Stream_Write_UINT16(s, PAKID_CORE_CLIENTID_CONFIRM); /* PacketId (2 bytes) */ + Stream_Write_UINT16(s, rdpdr->clientVersionMajor); + Stream_Write_UINT16(s, rdpdr->clientVersionMinor); + Stream_Write_UINT32(s, rdpdr->clientID); + return rdpdr_send(rdpdr, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_send_client_name_request(rdpdrPlugin* rdpdr) +{ + wStream* s = NULL; + WCHAR* computerNameW = NULL; + size_t computerNameLenW = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->state == RDPDR_CHANNEL_STATE_ANNOUNCE_REPLY); + rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_NAME_REQUEST); + + const size_t len = strnlen(rdpdr->computerName, sizeof(rdpdr->computerName)); + if (len == 0) + return ERROR_INTERNAL_ERROR; + + WINPR_ASSERT(rdpdr->computerName); + computerNameW = ConvertUtf8NToWCharAlloc(rdpdr->computerName, len, &computerNameLenW); + computerNameLenW *= sizeof(WCHAR); + + if (computerNameLenW > 0) + computerNameLenW += sizeof(WCHAR); // also write '\0' + + s = StreamPool_Take(rdpdr->pool, 16U + computerNameLenW); + + if (!s) + { + free(computerNameW); + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); /* Component (2 bytes) */ + Stream_Write_UINT16(s, PAKID_CORE_CLIENT_NAME); /* PacketId (2 bytes) */ + Stream_Write_UINT32(s, 1); /* unicodeFlag, 0 for ASCII and 1 for Unicode */ + Stream_Write_UINT32(s, 0); /* codePage, must be set to zero */ + Stream_Write_UINT32(s, + (UINT32)computerNameLenW); /* computerNameLen, including null terminator */ + Stream_Write(s, computerNameW, computerNameLenW); + free(computerNameW); + return rdpdr_send(rdpdr, s); +} + +static UINT rdpdr_process_server_clientid_confirm(rdpdrPlugin* rdpdr, wStream* s) +{ + UINT16 versionMajor = 0; + UINT16 versionMinor = 0; + UINT32 clientID = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, versionMajor); + Stream_Read_UINT16(s, versionMinor); + Stream_Read_UINT32(s, clientID); + + if (versionMajor != rdpdr->clientVersionMajor || versionMinor != rdpdr->clientVersionMinor) + { + WLog_Print(rdpdr->log, WLOG_WARN, + "[rdpdr] server announced version %" PRIu32 ".%" PRIu32 ", client uses %" PRIu32 + ".%" PRIu32 " but clientid confirm requests version %" PRIu32 ".%" PRIu32, + rdpdr->serverVersionMajor, rdpdr->serverVersionMinor, rdpdr->clientVersionMajor, + rdpdr->clientVersionMinor, versionMajor, versionMinor); + rdpdr->clientVersionMajor = versionMajor; + rdpdr->clientVersionMinor = versionMinor; + } + + if (clientID != rdpdr->clientID) + rdpdr->clientID = clientID; + + return CHANNEL_RC_OK; +} + +struct device_announce_arg +{ + rdpdrPlugin* rdpdr; + wStream* s; + BOOL userLoggedOn; + UINT32 count; +}; + +static BOOL device_announce(ULONG_PTR key, void* element, void* data) +{ + struct device_announce_arg* arg = data; + rdpdrPlugin* rdpdr = NULL; + DEVICE* device = (DEVICE*)element; + + WINPR_UNUSED(key); + + WINPR_ASSERT(arg); + WINPR_ASSERT(device); + WINPR_ASSERT(arg->rdpdr); + WINPR_ASSERT(arg->s); + + rdpdr = arg->rdpdr; + + /** + * 1. versionMinor 0x0005 doesn't send PAKID_CORE_USER_LOGGEDON + * so all devices should be sent regardless of user_loggedon + * 2. smartcard devices should be always sent + * 3. other devices are sent only after user_loggedon + */ + + if ((rdpdr->clientVersionMinor == RDPDR_VERSION_MINOR_RDP51) || + (device->type == RDPDR_DTYP_SMARTCARD) || arg->userLoggedOn) + { + size_t data_len = (device->data == NULL ? 0 : Stream_GetPosition(device->data)); + + if (!Stream_EnsureRemainingCapacity(arg->s, 20 + data_len)) + { + Stream_Release(arg->s); + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); + return FALSE; + } + + Stream_Write_UINT32(arg->s, device->type); /* deviceType */ + Stream_Write_UINT32(arg->s, device->id); /* deviceID */ + strncpy(Stream_Pointer(arg->s), device->name, 8); + + for (size_t i = 0; i < 8; i++) + { + BYTE c = 0; + Stream_Peek_UINT8(arg->s, c); + + if (c > 0x7F) + Stream_Write_UINT8(arg->s, '_'); + else + Stream_Seek_UINT8(arg->s); + } + + WINPR_ASSERT(data_len <= UINT32_MAX); + Stream_Write_UINT32(arg->s, (UINT32)data_len); + + if (data_len > 0) + Stream_Write(arg->s, Stream_Buffer(device->data), data_len); + + arg->count++; + WLog_Print(rdpdr->log, WLOG_INFO, + "registered [%09s] device #%" PRIu32 ": %s (type=%" PRIu32 " id=%" PRIu32 ")", + rdpdr_device_type_string(device->type), arg->count, device->name, device->type, + device->id); + } + return TRUE; +} + +static UINT rdpdr_send_device_list_announce_request(rdpdrPlugin* rdpdr, BOOL userLoggedOn) +{ + size_t pos = 0; + wStream* s = NULL; + size_t count_pos = 0; + struct device_announce_arg arg = { 0 }; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->devman); + + if (userLoggedOn) + { + rdpdr->userLoggedOn = TRUE; + } + + s = StreamPool_Take(rdpdr->pool, 256); + + if (!s) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); /* Component (2 bytes) */ + Stream_Write_UINT16(s, PAKID_CORE_DEVICELIST_ANNOUNCE); /* PacketId (2 bytes) */ + count_pos = Stream_GetPosition(s); + Stream_Seek_UINT32(s); /* deviceCount */ + + arg.rdpdr = rdpdr; + arg.userLoggedOn = userLoggedOn; + arg.s = s; + if (!device_foreach(rdpdr, TRUE, device_announce, &arg)) + return ERROR_INVALID_DATA; + + if (arg.count == 0) + { + Stream_Release(s); + return CHANNEL_RC_OK; + } + pos = Stream_GetPosition(s); + Stream_SetPosition(s, count_pos); + Stream_Write_UINT32(s, arg.count); + Stream_SetPosition(s, pos); + Stream_SealLength(s); + return rdpdr_send(rdpdr, s); +} + +UINT rdpdr_try_send_device_list_announce_request(rdpdrPlugin* rdpdr) +{ + WINPR_ASSERT(rdpdr); + if (rdpdr->state != RDPDR_CHANNEL_STATE_READY) + { + WLog_Print(rdpdr->log, WLOG_DEBUG, + "hotplug event received, but channel [RDPDR] is not ready (state %s), ignoring.", + rdpdr_state_str(rdpdr->state)); + return CHANNEL_RC_OK; + } + return rdpdr_send_device_list_announce_request(rdpdr, rdpdr->userLoggedOn); +} + +static UINT dummy_irp_response(rdpdrPlugin* rdpdr, wStream* s) +{ + wStream* output = NULL; + UINT32 DeviceId = 0; + UINT32 FileId = 0; + UINT32 CompletionId = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + output = StreamPool_Take(rdpdr->pool, 256); // RDPDR_DEVICE_IO_RESPONSE_LENGTH + if (!output) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_SetPosition(s, 4); /* see "rdpdr_process_receive" */ + + Stream_Read_UINT32(s, DeviceId); /* DeviceId (4 bytes) */ + Stream_Read_UINT32(s, FileId); /* FileId (4 bytes) */ + Stream_Read_UINT32(s, CompletionId); /* CompletionId (4 bytes) */ + + if (!rdpdr_write_iocompletion_header(output, DeviceId, CompletionId, STATUS_UNSUCCESSFUL)) + return CHANNEL_RC_NO_MEMORY; + + return rdpdr_send(rdpdr, output); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_process_irp(rdpdrPlugin* rdpdr, wStream* s) +{ + IRP* irp = NULL; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + irp = irp_new(rdpdr->devman, rdpdr->pool, s, rdpdr->log, &error); + + if (!irp) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "irp_new failed with %" PRIu32 "!", error); + + if (error == CHANNEL_RC_OK || (error == ERROR_DEV_NOT_EXIST && rdpdr->ignoreInvalidDevices)) + { + return dummy_irp_response(rdpdr, s); + } + + return error; + } + + if (irp->device->IRPRequest) + IFCALLRET(irp->device->IRPRequest, error, irp->device, irp); + else + irp->Discard(irp); + + if (error != CHANNEL_RC_OK) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "device->IRPRequest failed with error %" PRIu32 "", + error); + irp->Discard(irp); + } + + return error; +} + +static UINT rdpdr_process_component(rdpdrPlugin* rdpdr, UINT16 component, UINT16 packetId, + wStream* s) +{ + UINT32 type = 0; + DEVICE* device = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + switch (component) + { + case RDPDR_CTYP_PRN: + type = RDPDR_DTYP_PRINT; + break; + + default: + return ERROR_INVALID_DATA; + } + + device = devman_get_device_by_type(rdpdr->devman, type); + + if (!device) + return ERROR_DEV_NOT_EXIST; + + return IFCALLRESULT(ERROR_INVALID_PARAMETER, device->CustomComponentRequest, device, component, + packetId, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static BOOL device_init(ULONG_PTR key, void* element, void* data) +{ + wLog* log = data; + UINT error = CHANNEL_RC_OK; + DEVICE* device = element; + + WINPR_UNUSED(key); + WINPR_UNUSED(data); + + IFCALLRET(device->Init, error, device); + + if (error != CHANNEL_RC_OK) + { + WLog_Print(log, WLOG_ERROR, "Device init failed with %s", WTSErrorToString(error)); + return FALSE; + } + return TRUE; +} + +static UINT rdpdr_process_init(rdpdrPlugin* rdpdr) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->devman); + + rdpdr->userLoggedOn = FALSE; /* reset possible received state */ + if (!device_foreach(rdpdr, TRUE, device_init, rdpdr->log)) + return ERROR_INTERNAL_ERROR; + return CHANNEL_RC_OK; +} + +static BOOL state_match(enum RDPDR_CHANNEL_STATE state, size_t count, va_list ap) +{ + for (size_t x = 0; x < count; x++) + { + enum RDPDR_CHANNEL_STATE cur = va_arg(ap, enum RDPDR_CHANNEL_STATE); + if (state == cur) + return TRUE; + } + return FALSE; +} + +static const char* state_str(size_t count, va_list ap, char* buffer, size_t size) +{ + for (size_t x = 0; x < count; x++) + { + enum RDPDR_CHANNEL_STATE cur = va_arg(ap, enum RDPDR_CHANNEL_STATE); + const char* curstr = rdpdr_state_str(cur); + winpr_str_append(curstr, buffer, size, "|"); + } + return buffer; +} + +static BOOL rdpdr_state_check(rdpdrPlugin* rdpdr, UINT16 packetid, enum RDPDR_CHANNEL_STATE next, + size_t count, ...) +{ + va_list ap = { 0 }; + WINPR_ASSERT(rdpdr); + + va_start(ap, count); + BOOL rc = state_match(rdpdr->state, count, ap); + va_end(ap); + + if (!rc) + { + const char* strstate = rdpdr_state_str(rdpdr->state); + char buffer[256] = { 0 }; + + va_start(ap, count); + state_str(count, ap, buffer, sizeof(buffer)); + va_end(ap); + + WLog_Print(rdpdr->log, WLOG_ERROR, + "channel [RDPDR] received %s, expected states [%s] but have state %s, aborting.", + rdpdr_packetid_string(packetid), buffer, strstate); + + rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_INITIAL); + return FALSE; + } + return rdpdr_state_advance(rdpdr, next); +} + +static BOOL rdpdr_check_channel_state(rdpdrPlugin* rdpdr, UINT16 packetid) +{ + WINPR_ASSERT(rdpdr); + + switch (packetid) + { + case PAKID_CORE_SERVER_ANNOUNCE: + /* windows servers sometimes send this message. + * it seems related to session login (e.g. first initialization for RDP/TLS style login, + * then reinitialize the channel after login successful + */ + rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_INITIAL); + return rdpdr_state_check(rdpdr, packetid, RDPDR_CHANNEL_STATE_ANNOUNCE, 1, + RDPDR_CHANNEL_STATE_INITIAL); + case PAKID_CORE_SERVER_CAPABILITY: + return rdpdr_state_check( + rdpdr, packetid, RDPDR_CHANNEL_STATE_SERVER_CAPS, 6, + RDPDR_CHANNEL_STATE_NAME_REQUEST, RDPDR_CHANNEL_STATE_SERVER_CAPS, + RDPDR_CHANNEL_STATE_READY, RDPDR_CHANNEL_STATE_CLIENT_CAPS, + RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM, RDPDR_CHANNEL_STATE_USER_LOGGEDON); + case PAKID_CORE_CLIENTID_CONFIRM: + return rdpdr_state_check(rdpdr, packetid, RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM, 3, + RDPDR_CHANNEL_STATE_CLIENT_CAPS, RDPDR_CHANNEL_STATE_READY, + RDPDR_CHANNEL_STATE_USER_LOGGEDON); + case PAKID_CORE_USER_LOGGEDON: + if (!rdpdr_check_extended_pdu_flag(rdpdr, RDPDR_USER_LOGGEDON_PDU)) + return FALSE; + + return rdpdr_state_check( + rdpdr, packetid, RDPDR_CHANNEL_STATE_USER_LOGGEDON, 4, + RDPDR_CHANNEL_STATE_NAME_REQUEST, RDPDR_CHANNEL_STATE_CLIENT_CAPS, + RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM, RDPDR_CHANNEL_STATE_READY); + default: + { + enum RDPDR_CHANNEL_STATE state = RDPDR_CHANNEL_STATE_READY; + return rdpdr_state_check(rdpdr, packetid, state, 1, state); + } + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_process_receive(rdpdrPlugin* rdpdr, wStream* s) +{ + UINT16 component = 0; + UINT16 packetId = 0; + UINT32 deviceId = 0; + UINT32 status = 0; + UINT error = ERROR_INVALID_DATA; + + if (!rdpdr || !s) + return CHANNEL_RC_NULL_DATA; + + rdpdr_dump_received_packet(rdpdr->log, WLOG_TRACE, s, "[rdpdr-channel] receive"); + if (Stream_GetRemainingLength(s) >= 4) + { + Stream_Read_UINT16(s, component); /* Component (2 bytes) */ + Stream_Read_UINT16(s, packetId); /* PacketId (2 bytes) */ + + if (component == RDPDR_CTYP_CORE) + { + if (!rdpdr_check_channel_state(rdpdr, packetId)) + return CHANNEL_RC_OK; + + switch (packetId) + { + case PAKID_CORE_SERVER_ANNOUNCE: + if ((error = rdpdr_process_server_announce_request(rdpdr, s))) + { + } + else if ((error = rdpdr_send_client_announce_reply(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_send_client_announce_reply failed with error %" PRIu32 "", + error); + } + else if ((error = rdpdr_send_client_name_request(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_send_client_name_request failed with error %" PRIu32 "", + error); + } + else if ((error = rdpdr_process_init(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_process_init failed with error %" PRIu32 "", error); + } + + break; + + case PAKID_CORE_SERVER_CAPABILITY: + if ((error = rdpdr_process_capability_request(rdpdr, s))) + { + } + else if ((error = rdpdr_send_capability_response(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_send_capability_response failed with error %" PRIu32 "", + error); + } + + break; + + case PAKID_CORE_CLIENTID_CONFIRM: + if ((error = rdpdr_process_server_clientid_confirm(rdpdr, s))) + { + } + else if ((error = rdpdr_send_device_list_announce_request(rdpdr, FALSE))) + { + WLog_Print( + rdpdr->log, WLOG_ERROR, + "rdpdr_send_device_list_announce_request failed with error %" PRIu32 "", + error); + } + else if (!rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_READY)) + { + error = ERROR_INTERNAL_ERROR; + } + break; + + case PAKID_CORE_USER_LOGGEDON: + if ((error = rdpdr_send_device_list_announce_request(rdpdr, TRUE))) + { + WLog_Print( + rdpdr->log, WLOG_ERROR, + "rdpdr_send_device_list_announce_request failed with error %" PRIu32 "", + error); + } + else if (!rdpdr_state_advance(rdpdr, RDPDR_CHANNEL_STATE_READY)) + { + error = ERROR_INTERNAL_ERROR; + } + + break; + + case PAKID_CORE_DEVICE_REPLY: + + /* connect to a specific resource */ + if (Stream_GetRemainingLength(s) >= 8) + { + Stream_Read_UINT32(s, deviceId); + Stream_Read_UINT32(s, status); + + if (status != 0) + devman_unregister_device(rdpdr->devman, (void*)((size_t)deviceId)); + error = CHANNEL_RC_OK; + } + + break; + + case PAKID_CORE_DEVICE_IOREQUEST: + if ((error = rdpdr_process_irp(rdpdr, s))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_process_irp failed with error %" PRIu32 "", error); + return error; + } + else + s = NULL; + + break; + + default: + WLog_Print(rdpdr->log, WLOG_ERROR, + "RDPDR_CTYP_CORE unknown PacketId: 0x%04" PRIX16 "", packetId); + error = ERROR_INVALID_DATA; + break; + } + } + else + { + error = rdpdr_process_component(rdpdr, component, packetId, s); + + if (error != CHANNEL_RC_OK) + { + DWORD level = WLOG_ERROR; + if (rdpdr->ignoreInvalidDevices) + { + if (error == ERROR_DEV_NOT_EXIST) + { + level = WLOG_WARN; + error = CHANNEL_RC_OK; + } + } + WLog_Print(rdpdr->log, level, + "Unknown message: Component: %s [0x%04" PRIX16 + "] PacketId: %s [0x%04" PRIX16 "]", + rdpdr_component_string(component), component, + rdpdr_packetid_string(packetId), packetId); + } + } + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpdr_send(rdpdrPlugin* rdpdr, wStream* s) +{ + rdpdrPlugin* plugin = rdpdr; + + if (!s) + { + Stream_Release(s); + return CHANNEL_RC_NULL_DATA; + } + + if (!plugin) + { + Stream_Release(s); + return CHANNEL_RC_BAD_INIT_HANDLE; + } + + const size_t pos = Stream_GetPosition(s); + UINT status = ERROR_INTERNAL_ERROR; + if (pos <= UINT32_MAX) + { + rdpdr_dump_send_packet(rdpdr->log, WLOG_TRACE, s, "[rdpdr-channel] send"); + status = plugin->channelEntryPoints.pVirtualChannelWriteEx( + plugin->InitHandle, plugin->OpenHandle, Stream_Buffer(s), (UINT32)pos, s); + } + + if (status != CHANNEL_RC_OK) + { + Stream_Release(s); + WLog_Print(rdpdr->log, WLOG_ERROR, "pVirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + } + + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_virtual_channel_event_data_received(rdpdrPlugin* rdpdr, void* pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + wStream* data_in = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(pData || (dataLength == 0)); + + if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) + { + /* + * According to MS-RDPBCGR 2.2.6.1, "All virtual channel traffic MUST be suspended. + * This flag is only valid in server-to-client virtual channel traffic. It MUST be + * ignored in client-to-server data." Thus it would be best practice to cease data + * transmission. However, simply returning here avoids a crash. + */ + return CHANNEL_RC_OK; + } + + if (dataFlags & CHANNEL_FLAG_FIRST) + { + if (rdpdr->data_in != NULL) + Stream_Release(rdpdr->data_in); + + rdpdr->data_in = StreamPool_Take(rdpdr->pool, totalLength); + + if (!rdpdr->data_in) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + + data_in = rdpdr->data_in; + + if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); + return ERROR_INVALID_DATA; + } + + Stream_Write(data_in, pData, dataLength); + + if (dataFlags & CHANNEL_FLAG_LAST) + { + const size_t pos = Stream_GetPosition(data_in); + const size_t cap = Stream_Capacity(data_in); + if (cap < pos) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_virtual_channel_event_data_received: read error"); + return ERROR_INTERNAL_ERROR; + } + + Stream_SealLength(data_in); + Stream_SetPosition(data_in, 0); + + if (rdpdr->async) + { + if (!MessageQueue_Post(rdpdr->queue, NULL, 0, (void*)data_in, NULL)) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + rdpdr->data_in = NULL; + } + else + { + UINT error = rdpdr_process_receive(rdpdr, data_in); + Stream_Release(data_in); + rdpdr->data_in = NULL; + if (error) + return error; + } + } + + return CHANNEL_RC_OK; +} + +static VOID VCAPITYPE rdpdr_virtual_channel_open_event_ex(LPVOID lpUserParam, DWORD openHandle, + UINT event, LPVOID pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + UINT error = CHANNEL_RC_OK; + rdpdrPlugin* rdpdr = (rdpdrPlugin*)lpUserParam; + + WINPR_ASSERT(rdpdr); + switch (event) + { + case CHANNEL_EVENT_DATA_RECEIVED: + if (!rdpdr || !pData || (rdpdr->OpenHandle != openHandle)) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "error no match"); + return; + } + if ((error = rdpdr_virtual_channel_event_data_received(rdpdr, pData, dataLength, + totalLength, dataFlags))) + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_virtual_channel_event_data_received failed with error %" PRIu32 + "!", + error); + + break; + + case CHANNEL_EVENT_WRITE_CANCELLED: + case CHANNEL_EVENT_WRITE_COMPLETE: + { + wStream* s = (wStream*)pData; + Stream_Release(s); + } + break; + + case CHANNEL_EVENT_USER: + break; + default: + break; + } + + if (error && rdpdr && rdpdr->rdpcontext) + setChannelError(rdpdr->rdpcontext, error, + "rdpdr_virtual_channel_open_event_ex reported an error"); +} + +static DWORD WINAPI rdpdr_virtual_channel_client_thread(LPVOID arg) +{ + rdpdrPlugin* rdpdr = (rdpdrPlugin*)arg; + UINT error = 0; + + if (!rdpdr) + { + ExitThread((DWORD)CHANNEL_RC_NULL_DATA); + return CHANNEL_RC_NULL_DATA; + } + + if ((error = rdpdr_process_connect(rdpdr))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "rdpdr_process_connect failed with error %" PRIu32 "!", + error); + + if (rdpdr->rdpcontext) + setChannelError(rdpdr->rdpcontext, error, + "rdpdr_virtual_channel_client_thread reported an error"); + + ExitThread(error); + return error; + } + + while (1) + { + wMessage message = { 0 }; + WINPR_ASSERT(rdpdr); + + if (!MessageQueue_Wait(rdpdr->queue)) + break; + + if (MessageQueue_Peek(rdpdr->queue, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + break; + + if (message.id == 0) + { + wStream* data = (wStream*)message.wParam; + + error = rdpdr_process_receive(rdpdr, data); + + Stream_Release(data); + if (error) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_process_receive failed with error %" PRIu32 "!", error); + + if (rdpdr->rdpcontext) + setChannelError(rdpdr->rdpcontext, error, + "rdpdr_virtual_channel_client_thread reported an error"); + + goto fail; + } + } + } + } + +fail: + if ((error = drive_hotplug_thread_terminate(rdpdr))) + WLog_Print(rdpdr->log, WLOG_ERROR, + "drive_hotplug_thread_terminate failed with error %" PRIu32 "!", error); + + ExitThread(error); + return error; +} + +static void queue_free(void* obj) +{ + wStream* s = NULL; + wMessage* msg = (wMessage*)obj; + + if (!msg || (msg->id != 0)) + return; + + s = (wStream*)msg->wParam; + WINPR_ASSERT(s); + Stream_Release(s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_virtual_channel_event_connected(rdpdrPlugin* rdpdr, LPVOID pData, + UINT32 dataLength) +{ + wObject* obj = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_UNUSED(pData); + WINPR_UNUSED(dataLength); + + if (rdpdr->async) + { + rdpdr->queue = MessageQueue_New(NULL); + + if (!rdpdr->queue) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "MessageQueue_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + obj = MessageQueue_Object(rdpdr->queue); + obj->fnObjectFree = queue_free; + + if (!(rdpdr->thread = CreateThread(NULL, 0, rdpdr_virtual_channel_client_thread, + (void*)rdpdr, 0, NULL))) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "CreateThread failed!"); + return ERROR_INTERNAL_ERROR; + } + } + else + { + UINT error = rdpdr_process_connect(rdpdr); + if (error) + { + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_process_connect failed with error %" PRIu32 "!", error); + return error; + } + } + + return rdpdr->channelEntryPoints.pVirtualChannelOpenEx(rdpdr->InitHandle, &rdpdr->OpenHandle, + rdpdr->channelDef.name, + rdpdr_virtual_channel_open_event_ex); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_virtual_channel_event_disconnected(rdpdrPlugin* rdpdr) +{ + UINT error = 0; + + WINPR_ASSERT(rdpdr); + + if (rdpdr->OpenHandle == 0) + return CHANNEL_RC_OK; + + if (rdpdr->queue && rdpdr->thread) + { + if (MessageQueue_PostQuit(rdpdr->queue, 0) && + (WaitForSingleObject(rdpdr->thread, INFINITE) == WAIT_FAILED)) + { + error = GetLastError(); + WLog_Print(rdpdr->log, WLOG_ERROR, "WaitForSingleObject failed with error %" PRIu32 "!", + error); + return error; + } + } + + if (rdpdr->thread) + (void)CloseHandle(rdpdr->thread); + MessageQueue_Free(rdpdr->queue); + rdpdr->queue = NULL; + rdpdr->thread = NULL; + + WINPR_ASSERT(rdpdr->channelEntryPoints.pVirtualChannelCloseEx); + error = rdpdr->channelEntryPoints.pVirtualChannelCloseEx(rdpdr->InitHandle, rdpdr->OpenHandle); + + if (CHANNEL_RC_OK != error) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "pVirtualChannelCloseEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(error), error); + } + + rdpdr->OpenHandle = 0; + + if (rdpdr->data_in) + { + Stream_Release(rdpdr->data_in); + rdpdr->data_in = NULL; + } + + if (rdpdr->devman) + { + devman_free(rdpdr->devman); + rdpdr->devman = NULL; + } + + return error; +} + +static void rdpdr_virtual_channel_event_terminated(rdpdrPlugin* rdpdr) +{ + WINPR_ASSERT(rdpdr); + rdpdr->InitHandle = 0; + StreamPool_Free(rdpdr->pool); + free(rdpdr); +} + +static VOID VCAPITYPE rdpdr_virtual_channel_init_event_ex(LPVOID lpUserParam, LPVOID pInitHandle, + UINT event, LPVOID pData, UINT dataLength) +{ + UINT error = CHANNEL_RC_OK; + rdpdrPlugin* rdpdr = (rdpdrPlugin*)lpUserParam; + + if (!rdpdr || (rdpdr->InitHandle != pInitHandle)) + { + WLog_ERR(TAG, "error no match"); + return; + } + + WINPR_ASSERT(pData || (dataLength == 0)); + + switch (event) + { + case CHANNEL_EVENT_INITIALIZED: + break; + + case CHANNEL_EVENT_CONNECTED: + if ((error = rdpdr_virtual_channel_event_connected(rdpdr, pData, dataLength))) + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_virtual_channel_event_connected failed with error %" PRIu32 "!", + error); + + break; + + case CHANNEL_EVENT_DISCONNECTED: + if ((error = rdpdr_virtual_channel_event_disconnected(rdpdr))) + WLog_Print(rdpdr->log, WLOG_ERROR, + "rdpdr_virtual_channel_event_disconnected failed with error %" PRIu32 + "!", + error); + + break; + + case CHANNEL_EVENT_TERMINATED: + rdpdr_virtual_channel_event_terminated(rdpdr); + rdpdr = NULL; + break; + + case CHANNEL_EVENT_ATTACHED: + case CHANNEL_EVENT_DETACHED: + default: + WLog_Print(rdpdr->log, WLOG_ERROR, "unknown event %" PRIu32 "!", event); + break; + } + + if (error && rdpdr && rdpdr->rdpcontext) + setChannelError(rdpdr->rdpcontext, error, + "rdpdr_virtual_channel_init_event_ex reported an error"); +} + +/* rdpdr is always built-in */ +#define VirtualChannelEntryEx rdpdr_VirtualChannelEntryEx + +FREERDP_ENTRY_POINT(BOOL VCAPITYPE VirtualChannelEntryEx(PCHANNEL_ENTRY_POINTS pEntryPoints, + PVOID pInitHandle)) +{ + UINT rc = 0; + rdpdrPlugin* rdpdr = NULL; + CHANNEL_ENTRY_POINTS_FREERDP_EX* pEntryPointsEx = NULL; + + WINPR_ASSERT(pEntryPoints); + WINPR_ASSERT(pInitHandle); + + rdpdr = (rdpdrPlugin*)calloc(1, sizeof(rdpdrPlugin)); + + if (!rdpdr) + { + WLog_ERR(TAG, "calloc failed!"); + return FALSE; + } + rdpdr->log = WLog_Get(TAG); + + rdpdr->clientExtendedPDU = + RDPDR_DEVICE_REMOVE_PDUS | RDPDR_CLIENT_DISPLAY_NAME_PDU | RDPDR_USER_LOGGEDON_PDU; + rdpdr->clientIOCode1 = + RDPDR_IRP_MJ_CREATE | RDPDR_IRP_MJ_CLEANUP | RDPDR_IRP_MJ_CLOSE | RDPDR_IRP_MJ_READ | + RDPDR_IRP_MJ_WRITE | RDPDR_IRP_MJ_FLUSH_BUFFERS | RDPDR_IRP_MJ_SHUTDOWN | + RDPDR_IRP_MJ_DEVICE_CONTROL | RDPDR_IRP_MJ_QUERY_VOLUME_INFORMATION | + RDPDR_IRP_MJ_SET_VOLUME_INFORMATION | RDPDR_IRP_MJ_QUERY_INFORMATION | + RDPDR_IRP_MJ_SET_INFORMATION | RDPDR_IRP_MJ_DIRECTORY_CONTROL | RDPDR_IRP_MJ_LOCK_CONTROL | + RDPDR_IRP_MJ_QUERY_SECURITY | RDPDR_IRP_MJ_SET_SECURITY; + + rdpdr->clientExtraFlags1 = ENABLE_ASYNCIO; + + rdpdr->pool = StreamPool_New(TRUE, 1024); + if (!rdpdr->pool) + { + free(rdpdr); + return FALSE; + } + + rdpdr->channelDef.options = + CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | CHANNEL_OPTION_COMPRESS_RDP; + (void)sprintf_s(rdpdr->channelDef.name, ARRAYSIZE(rdpdr->channelDef.name), + RDPDR_SVC_CHANNEL_NAME); + rdpdr->sequenceId = 0; + pEntryPointsEx = (CHANNEL_ENTRY_POINTS_FREERDP_EX*)pEntryPoints; + + if ((pEntryPointsEx->cbSize >= sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)) && + (pEntryPointsEx->MagicNumber == FREERDP_CHANNEL_MAGIC_NUMBER)) + { + rdpdr->rdpcontext = pEntryPointsEx->context; + if (!freerdp_settings_get_bool(rdpdr->rdpcontext->settings, + FreeRDP_SynchronousStaticChannels)) + rdpdr->async = TRUE; + } + + CopyMemory(&(rdpdr->channelEntryPoints), pEntryPoints, sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)); + rdpdr->InitHandle = pInitHandle; + rc = rdpdr->channelEntryPoints.pVirtualChannelInitEx( + rdpdr, NULL, pInitHandle, &rdpdr->channelDef, 1, VIRTUAL_CHANNEL_VERSION_WIN2000, + rdpdr_virtual_channel_init_event_ex); + + if (CHANNEL_RC_OK != rc) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "pVirtualChannelInitEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(rc), rc); + free(rdpdr); + return FALSE; + } + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.h new file mode 100644 index 0000000000000000000000000000000000000000..4604732a0008c45502daf2337943e08788343ae5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/client/rdpdr_main.h @@ -0,0 +1,122 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 Inuvika Inc. + * Copyright 2016 David PHAM-VAN + * + * 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 FREERDP_CHANNEL_RDPDR_CLIENT_MAIN_H +#define FREERDP_CHANNEL_RDPDR_CLIENT_MAIN_H + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#ifdef __MACOSX__ +#include +#endif + +enum RDPDR_CHANNEL_STATE +{ + RDPDR_CHANNEL_STATE_INITIAL = 0, + RDPDR_CHANNEL_STATE_ANNOUNCE, + RDPDR_CHANNEL_STATE_ANNOUNCE_REPLY, + RDPDR_CHANNEL_STATE_NAME_REQUEST, + RDPDR_CHANNEL_STATE_SERVER_CAPS, + RDPDR_CHANNEL_STATE_CLIENT_CAPS, + RDPDR_CHANNEL_STATE_CLIENTID_CONFIRM, + RDPDR_CHANNEL_STATE_READY, + RDPDR_CHANNEL_STATE_USER_LOGGEDON +}; + +typedef struct +{ + CHANNEL_DEF channelDef; + CHANNEL_ENTRY_POINTS_FREERDP_EX channelEntryPoints; + + enum RDPDR_CHANNEL_STATE state; + HANDLE thread; + wStream* data_in; + void* InitHandle; + DWORD OpenHandle; + wMessageQueue* queue; + + DEVMAN* devman; + BOOL ignoreInvalidDevices; + + UINT32 serverOsType; + UINT32 serverOsVersion; + UINT16 serverVersionMajor; + UINT16 serverVersionMinor; + UINT32 serverExtendedPDU; + UINT32 serverIOCode1; + UINT32 serverIOCode2; + UINT32 serverExtraFlags1; + UINT32 serverExtraFlags2; + UINT32 serverSpecialTypeDeviceCap; + + UINT32 clientOsType; + UINT32 clientOsVersion; + UINT16 clientVersionMajor; + UINT16 clientVersionMinor; + UINT32 clientExtendedPDU; + UINT32 clientIOCode1; + UINT32 clientIOCode2; + UINT32 clientExtraFlags1; + UINT32 clientExtraFlags2; + UINT32 clientSpecialTypeDeviceCap; + + UINT32 clientID; + char computerName[256]; + + UINT32 sequenceId; + BOOL userLoggedOn; + + /* hotplug support */ + HANDLE hotplugThread; +#ifdef _WIN32 + HWND hotplug_wnd; +#endif +#ifdef __MACOSX__ + CFRunLoopRef runLoop; +#endif +#ifndef _WIN32 + HANDLE stopEvent; +#endif + rdpContext* rdpcontext; + wStreamPool* pool; + wLog* log; + BOOL async; + BOOL capabilities[6]; +} rdpdrPlugin; + +BOOL rdpdr_state_advance(rdpdrPlugin* rdpdr, enum RDPDR_CHANNEL_STATE next); +UINT rdpdr_send(rdpdrPlugin* rdpdr, wStream* s); + +#endif /* FREERDP_CHANNEL_RDPDR_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..96112aef03f9478907243add5604e6673c59501e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("rdpdr") + +set(${MODULE_PREFIX}_SRCS rdpdr_main.c rdpdr_main.h) + +set(${MODULE_PREFIX}_LIBS freerdp) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1ded8e22e438800df8169557f6b41a5f0f11d1df --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.c @@ -0,0 +1,3594 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel Extension + * + * Copyright 2014 Dell Software + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015-2022 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2022 Armin Novak + * + * 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 +#include +#include + +#include +#include +#include +#include +#include + +#include +#include "rdpdr_main.h" + +#define RDPDR_ADD_PRINTER_EVENT 0x00000001 +#define RDPDR_UPDATE_PRINTER_EVENT 0x00000002 +#define RDPDR_DELETE_PRINTER_EVENT 0x00000003 +#define RDPDR_RENAME_PRINTER_EVENT 0x00000004 + +#define RDPDR_HEADER_LENGTH 4 +#define RDPDR_CAPABILITY_HEADER_LENGTH 8 + +struct s_rdpdr_server_private +{ + HANDLE Thread; + HANDLE StopEvent; + void* ChannelHandle; + + UINT32 ClientId; + UINT16 VersionMajor; + UINT16 VersionMinor; + char* ClientComputerName; + + BOOL UserLoggedOnPdu; + + wListDictionary* IrpList; + UINT32 NextCompletionId; + + wHashTable* devicelist; + wLog* log; +}; + +static void rdpdr_device_free(RdpdrDevice* device) +{ + if (!device) + return; + free(device->DeviceData); + free(device); +} + +static void rdpdr_device_free_h(void* obj) +{ + RdpdrDevice* other = obj; + rdpdr_device_free(other); +} + +static UINT32 rdpdr_deviceid_hash(const void* id) +{ + WINPR_ASSERT(id); + return *((const UINT32*)id); +} + +static BOOL rdpdr_device_equal(const void* v1, const void* v2) +{ + const UINT32* p1 = (const UINT32*)v1; + const UINT32* p2 = (const UINT32*)v2; + if (!p1 && !p2) + return TRUE; + if (!p1 || !p2) + return FALSE; + return *p1 == *p2; +} + +static RdpdrDevice* rdpdr_device_new(void) +{ + return calloc(1, sizeof(RdpdrDevice)); +} + +static void* rdpdr_device_clone(const void* val) +{ + const RdpdrDevice* other = val; + + if (!other) + return NULL; + + RdpdrDevice* tmp = rdpdr_device_new(); + if (!tmp) + goto fail; + + *tmp = *other; + if (other->DeviceData) + { + tmp->DeviceData = malloc(other->DeviceDataLength); + if (!tmp->DeviceData) + goto fail; + memcpy(tmp->DeviceData, other->DeviceData, other->DeviceDataLength); + } + return tmp; + +fail: + rdpdr_device_free(tmp); + return NULL; +} + +static RdpdrDevice* rdpdr_get_device_by_id(RdpdrServerPrivate* priv, UINT32 DeviceId) +{ + WINPR_ASSERT(priv); + + return HashTable_GetItemValue(priv->devicelist, &DeviceId); +} + +static BOOL rdpdr_remove_device_by_id(RdpdrServerPrivate* priv, UINT32 DeviceId) +{ + const RdpdrDevice* device = rdpdr_get_device_by_id(priv, DeviceId); + WINPR_ASSERT(priv); + + if (!device) + { + WLog_Print(priv->log, WLOG_WARN, "[del] Device Id: 0x%08" PRIX32 ": no such device", + DeviceId); + return FALSE; + } + WLog_Print(priv->log, WLOG_DEBUG, + "[del] Device Name: %s Id: 0x%08" PRIX32 " DataLength: %" PRIu32 "", + device->PreferredDosName, device->DeviceId, device->DeviceDataLength); + return HashTable_Remove(priv->devicelist, &DeviceId); +} + +static BOOL rdpdr_add_device(RdpdrServerPrivate* priv, const RdpdrDevice* device) +{ + WINPR_ASSERT(priv); + WINPR_ASSERT(device); + + WLog_Print(priv->log, WLOG_DEBUG, + "[add] Device Name: %s Id: 0x%08" PRIX32 " DataLength: %" PRIu32 "", + device->PreferredDosName, device->DeviceId, device->DeviceDataLength); + + return HashTable_Insert(priv->devicelist, &device->DeviceId, device); +} + +static UINT32 g_ClientId = 0; + +static const WCHAR* rdpdr_read_ustring(wLog* log, wStream* s, size_t bytelen) +{ + const size_t charlen = (bytelen + 1) / sizeof(WCHAR); + const WCHAR* str = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, bytelen)) + return NULL; + if (_wcsnlen(str, charlen) == charlen) + { + WLog_Print(log, WLOG_WARN, "[rdpdr] unicode string not '\0' terminated"); + return NULL; + } + Stream_Seek(s, bytelen); + return str; +} + +static RDPDR_IRP* rdpdr_server_irp_new(void) +{ + RDPDR_IRP* irp = (RDPDR_IRP*)calloc(1, sizeof(RDPDR_IRP)); + return irp; +} + +static void rdpdr_server_irp_free(RDPDR_IRP* irp) +{ + free(irp); +} + +static BOOL rdpdr_server_enqueue_irp(RdpdrServerContext* context, RDPDR_IRP* irp) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + const uintptr_t key = irp->CompletionId + 1ull; + return ListDictionary_Add(context->priv->IrpList, (void*)key, irp); +} + +static RDPDR_IRP* rdpdr_server_dequeue_irp(RdpdrServerContext* context, UINT32 completionId) +{ + RDPDR_IRP* irp = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + const uintptr_t key = completionId + 1ull; + irp = (RDPDR_IRP*)ListDictionary_Take(context->priv->IrpList, (void*)key); + return irp; +} + +static UINT rdpdr_seal_send_free_request(RdpdrServerContext* context, wStream* s) +{ + BOOL status = 0; + ULONG written = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + + Stream_SealLength(s); + const size_t length = Stream_Length(s); + WINPR_ASSERT(length <= UINT32_MAX); + Stream_SetPosition(s, 0); + + if (length >= RDPDR_HEADER_LENGTH) + { + RDPDR_HEADER header = { 0 }; + Stream_Read_UINT16(s, header.Component); + Stream_Read_UINT16(s, header.PacketId); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "sending message {Component %s[%04" PRIx16 "], PacketId %s[%04" PRIx16 "]", + rdpdr_component_string(header.Component), header.Component, + rdpdr_packetid_string(header.PacketId), header.PacketId); + } + winpr_HexLogDump(context->priv->log, WLOG_DEBUG, Stream_Buffer(s), Stream_Length(s)); + status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (ULONG)length, &written); + Stream_Free(s, TRUE); + return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_announce_request(RdpdrServerContext* context) +{ + UINT error = 0; + wStream* s = NULL; + RDPDR_HEADER header = { 0 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + header.Component = RDPDR_CTYP_CORE; + header.PacketId = PAKID_CORE_SERVER_ANNOUNCE; + + error = IFCALLRESULT(CHANNEL_RC_OK, context->SendServerAnnounce, context); + if (error != CHANNEL_RC_OK) + return error; + + s = Stream_New(NULL, RDPDR_HEADER_LENGTH + 8); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, header.Component); /* Component (2 bytes) */ + Stream_Write_UINT16(s, header.PacketId); /* PacketId (2 bytes) */ + Stream_Write_UINT16(s, context->priv->VersionMajor); /* VersionMajor (2 bytes) */ + Stream_Write_UINT16(s, context->priv->VersionMinor); /* VersionMinor (2 bytes) */ + Stream_Write_UINT32(s, context->priv->ClientId); /* ClientId (4 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_announce_response(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 ClientId = 0; + UINT16 VersionMajor = 0; + UINT16 VersionMinor = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(header); + + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, VersionMajor); /* VersionMajor (2 bytes) */ + Stream_Read_UINT16(s, VersionMinor); /* VersionMinor (2 bytes) */ + Stream_Read_UINT32(s, ClientId); /* ClientId (4 bytes) */ + WLog_Print(context->priv->log, WLOG_DEBUG, + "Client Announce Response: VersionMajor: 0x%08" PRIX16 " VersionMinor: 0x%04" PRIX16 + " ClientId: 0x%08" PRIX32 "", + VersionMajor, VersionMinor, ClientId); + context->priv->ClientId = ClientId; + + return IFCALLRESULT(CHANNEL_RC_OK, context->ReceiveAnnounceResponse, context, VersionMajor, + VersionMinor, ClientId); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_client_name_request(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 UnicodeFlag = 0; + UINT32 CodePage = 0; + UINT32 ComputerNameLen = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 12)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, UnicodeFlag); /* UnicodeFlag (4 bytes) */ + Stream_Read_UINT32(s, CodePage); /* CodePage (4 bytes), MUST be set to zero */ + Stream_Read_UINT32(s, ComputerNameLen); /* ComputerNameLen (4 bytes) */ + /* UnicodeFlag is either 0 or 1, the other 31 bits must be ignored. + */ + UnicodeFlag = UnicodeFlag & 0x00000001; + + if (CodePage != 0) + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.2.4 Client Name Request (DR_CORE_CLIENT_NAME_REQ)::CodePage " + "must be 0, but is 0x%08" PRIx32, + CodePage); + + /** + * Caution: ComputerNameLen is given *bytes*, + * not in characters, including the NULL terminator! + */ + + if (UnicodeFlag) + { + if ((ComputerNameLen % 2) || ComputerNameLen > 512 || ComputerNameLen < 2) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "invalid unicode computer name length: %" PRIu32 "", ComputerNameLen); + return ERROR_INVALID_DATA; + } + } + else + { + if (ComputerNameLen > 256 || ComputerNameLen < 1) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "invalid ascii computer name length: %" PRIu32 "", ComputerNameLen); + return ERROR_INVALID_DATA; + } + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, ComputerNameLen)) + return ERROR_INVALID_DATA; + + /* ComputerName must be null terminated, check if it really is */ + const char* computerName = Stream_ConstPointer(s); + if (computerName[ComputerNameLen - 1] || (UnicodeFlag && computerName[ComputerNameLen - 2])) + { + WLog_Print(context->priv->log, WLOG_ERROR, "computer name must be null terminated"); + return ERROR_INVALID_DATA; + } + + if (context->priv->ClientComputerName) + { + free(context->priv->ClientComputerName); + context->priv->ClientComputerName = NULL; + } + + if (UnicodeFlag) + { + context->priv->ClientComputerName = + Stream_Read_UTF16_String_As_UTF8(s, ComputerNameLen / sizeof(WCHAR), NULL); + if (!context->priv->ClientComputerName) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed to convert client computer name"); + return ERROR_INVALID_DATA; + } + } + else + { + const char* name = Stream_ConstPointer(s); + context->priv->ClientComputerName = _strdup(name); + Stream_Seek(s, ComputerNameLen); + + if (!context->priv->ClientComputerName) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed to duplicate client computer name"); + return CHANNEL_RC_NO_MEMORY; + } + } + + WLog_Print(context->priv->log, WLOG_DEBUG, "ClientComputerName: %s", + context->priv->ClientComputerName); + return IFCALLRESULT(CHANNEL_RC_OK, context->ReceiveClientNameRequest, context, ComputerNameLen, + context->priv->ClientComputerName); +} + +static UINT rdpdr_server_write_capability_set_header_cb(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + UINT error = rdpdr_write_capset_header(context->priv->log, s, header); + if (error != CHANNEL_RC_OK) + return error; + + return IFCALLRESULT(CHANNEL_RC_OK, context->SendCaps, context, header, 0, NULL); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_general_capability_set(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + UINT32 ioCode1 = 0; + UINT32 extraFlags1 = 0; + UINT32 extendedPdu = 0; + UINT16 VersionMajor = 0; + UINT16 VersionMinor = 0; + UINT32 SpecialTypeDeviceCap = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Seek_UINT32(s); /* osType (4 bytes), ignored on receipt */ + Stream_Seek_UINT32(s); /* osVersion (4 bytes), unused and must be set to zero */ + Stream_Read_UINT16(s, VersionMajor); /* protocolMajorVersion (2 bytes) */ + Stream_Read_UINT16(s, VersionMinor); /* protocolMinorVersion (2 bytes) */ + Stream_Read_UINT32(s, ioCode1); /* ioCode1 (4 bytes) */ + Stream_Seek_UINT32(s); /* ioCode2 (4 bytes), must be set to zero, reserved for future use */ + Stream_Read_UINT32(s, extendedPdu); /* extendedPdu (4 bytes) */ + Stream_Read_UINT32(s, extraFlags1); /* extraFlags1 (4 bytes) */ + Stream_Seek_UINT32(s); /* extraFlags2 (4 bytes), must be set to zero, reserved for future use */ + + if (VersionMajor != RDPDR_MAJOR_RDP_VERSION) + { + WLog_Print(context->priv->log, WLOG_ERROR, "unsupported RDPDR version %" PRIu16 ".%" PRIu16, + VersionMajor, VersionMinor); + return ERROR_INVALID_DATA; + } + + switch (VersionMinor) + { + case RDPDR_MINOR_RDP_VERSION_13: + case RDPDR_MINOR_RDP_VERSION_6_X: + case RDPDR_MINOR_RDP_VERSION_5_2: + case RDPDR_MINOR_RDP_VERSION_5_1: + case RDPDR_MINOR_RDP_VERSION_5_0: + break; + default: + WLog_Print(context->priv->log, WLOG_WARN, + "unsupported RDPDR minor version %" PRIu16 ".%" PRIu16, VersionMajor, + VersionMinor); + break; + } + + if (header->Version == GENERAL_CAPABILITY_VERSION_02) + { + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, SpecialTypeDeviceCap); /* SpecialTypeDeviceCap (4 bytes) */ + } + + context->priv->UserLoggedOnPdu = (extendedPdu & RDPDR_USER_LOGGEDON_PDU) ? TRUE : FALSE; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_write_general_capability_set(RdpdrServerContext* context, wStream* s) +{ + UINT32 ioCode1 = 0; + UINT32 extendedPdu = 0; + UINT32 extraFlags1 = 0; + UINT32 SpecialTypeDeviceCap = 0; + const RDPDR_CAPABILITY_HEADER header = { CAP_GENERAL_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH + 36, + GENERAL_CAPABILITY_VERSION_02 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + ioCode1 = 0; + ioCode1 |= RDPDR_IRP_MJ_CREATE; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_CLEANUP; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_CLOSE; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_READ; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_WRITE; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_FLUSH_BUFFERS; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_SHUTDOWN; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_DEVICE_CONTROL; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_QUERY_VOLUME_INFORMATION; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_SET_VOLUME_INFORMATION; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_QUERY_INFORMATION; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_SET_INFORMATION; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_DIRECTORY_CONTROL; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_LOCK_CONTROL; /* always set */ + ioCode1 |= RDPDR_IRP_MJ_QUERY_SECURITY; /* optional */ + ioCode1 |= RDPDR_IRP_MJ_SET_SECURITY; /* optional */ + extendedPdu = 0; + extendedPdu |= RDPDR_CLIENT_DISPLAY_NAME_PDU; /* always set */ + extendedPdu |= RDPDR_DEVICE_REMOVE_PDUS; /* optional */ + + if (context->priv->UserLoggedOnPdu) + extendedPdu |= RDPDR_USER_LOGGEDON_PDU; /* optional */ + + extraFlags1 = 0; + extraFlags1 |= ENABLE_ASYNCIO; /* optional */ + SpecialTypeDeviceCap = 0; + + UINT error = rdpdr_write_capset_header(context->priv->log, s, &header); + if (error != CHANNEL_RC_OK) + return error; + + const BYTE* data = Stream_ConstPointer(s); + const size_t start = Stream_GetPosition(s); + Stream_Write_UINT32(s, 0); /* osType (4 bytes), ignored on receipt */ + Stream_Write_UINT32(s, 0); /* osVersion (4 bytes), unused and must be set to zero */ + Stream_Write_UINT16(s, context->priv->VersionMajor); /* protocolMajorVersion (2 bytes) */ + Stream_Write_UINT16(s, context->priv->VersionMinor); /* protocolMinorVersion (2 bytes) */ + Stream_Write_UINT32(s, ioCode1); /* ioCode1 (4 bytes) */ + Stream_Write_UINT32(s, 0); /* ioCode2 (4 bytes), must be set to zero, reserved for future use */ + Stream_Write_UINT32(s, extendedPdu); /* extendedPdu (4 bytes) */ + Stream_Write_UINT32(s, extraFlags1); /* extraFlags1 (4 bytes) */ + Stream_Write_UINT32( + s, 0); /* extraFlags2 (4 bytes), must be set to zero, reserved for future use */ + Stream_Write_UINT32(s, SpecialTypeDeviceCap); /* SpecialTypeDeviceCap (4 bytes) */ + const size_t end = Stream_GetPosition(s); + return IFCALLRESULT(CHANNEL_RC_OK, context->SendCaps, context, &header, end - start, data); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_printer_capability_set(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + WINPR_UNUSED(context); + WINPR_UNUSED(header); + WINPR_UNUSED(s); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_write_printer_capability_set(RdpdrServerContext* context, wStream* s) +{ + const RDPDR_CAPABILITY_HEADER header = { CAP_PRINTER_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + PRINT_CAPABILITY_VERSION_01 }; + WINPR_UNUSED(context); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + return rdpdr_server_write_capability_set_header_cb(context, s, &header); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_port_capability_set(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(context); + WINPR_UNUSED(s); + WINPR_UNUSED(header); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_write_port_capability_set(RdpdrServerContext* context, wStream* s) +{ + const RDPDR_CAPABILITY_HEADER header = { CAP_PORT_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + PORT_CAPABILITY_VERSION_01 }; + WINPR_UNUSED(context); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + return rdpdr_server_write_capability_set_header_cb(context, s, &header); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_drive_capability_set(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_UNUSED(context); + WINPR_UNUSED(header); + WINPR_UNUSED(s); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_write_drive_capability_set(RdpdrServerContext* context, wStream* s) +{ + const RDPDR_CAPABILITY_HEADER header = { CAP_DRIVE_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + DRIVE_CAPABILITY_VERSION_02 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_UNUSED(context); + + return rdpdr_server_write_capability_set_header_cb(context, s, &header); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_smartcard_capability_set(RdpdrServerContext* context, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_UNUSED(context); + WINPR_UNUSED(header); + WINPR_UNUSED(s); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_write_smartcard_capability_set(RdpdrServerContext* context, wStream* s) +{ + const RDPDR_CAPABILITY_HEADER header = { CAP_SMARTCARD_TYPE, RDPDR_CAPABILITY_HEADER_LENGTH, + SMARTCARD_CAPABILITY_VERSION_01 }; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WINPR_UNUSED(context); + + return rdpdr_server_write_capability_set_header_cb(context, s, &header); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_core_capability_request(RdpdrServerContext* context) +{ + wStream* s = NULL; + RDPDR_HEADER header = { 0 }; + UINT16 numCapabilities = 0; + UINT error = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + header.Component = RDPDR_CTYP_CORE; + header.PacketId = PAKID_CORE_SERVER_CAPABILITY; + numCapabilities = 1; + + if ((context->supported & RDPDR_DTYP_FILESYSTEM) != 0) + numCapabilities++; + + if (((context->supported & RDPDR_DTYP_PARALLEL) != 0) || + ((context->supported & RDPDR_DTYP_SERIAL) != 0)) + numCapabilities++; + + if ((context->supported & RDPDR_DTYP_PRINT) != 0) + numCapabilities++; + + if ((context->supported & RDPDR_DTYP_SMARTCARD) != 0) + numCapabilities++; + + s = Stream_New(NULL, RDPDR_HEADER_LENGTH + 512); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, header.Component); /* Component (2 bytes) */ + Stream_Write_UINT16(s, header.PacketId); /* PacketId (2 bytes) */ + Stream_Write_UINT16(s, numCapabilities); /* numCapabilities (2 bytes) */ + Stream_Write_UINT16(s, 0); /* Padding (2 bytes) */ + + if ((error = rdpdr_server_write_general_capability_set(context, s))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_write_general_capability_set failed with error %" PRIu32 "!", + error); + goto out; + } + + if ((context->supported & RDPDR_DTYP_FILESYSTEM) != 0) + { + if ((error = rdpdr_server_write_drive_capability_set(context, s))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_write_drive_capability_set failed with error %" PRIu32 "!", + error); + goto out; + } + } + + if (((context->supported & RDPDR_DTYP_PARALLEL) != 0) || + ((context->supported & RDPDR_DTYP_SERIAL) != 0)) + { + if ((error = rdpdr_server_write_port_capability_set(context, s))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_write_port_capability_set failed with error %" PRIu32 "!", + error); + goto out; + } + } + + if ((context->supported & RDPDR_DTYP_PRINT) != 0) + { + if ((error = rdpdr_server_write_printer_capability_set(context, s))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_write_printer_capability_set failed with error %" PRIu32 "!", + error); + goto out; + } + } + + if ((context->supported & RDPDR_DTYP_SMARTCARD) != 0) + { + if ((error = rdpdr_server_write_smartcard_capability_set(context, s))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_write_printer_capability_set failed with error %" PRIu32 "!", + error); + goto out; + } + } + + return rdpdr_seal_send_free_request(context, s); +out: + Stream_Free(s, TRUE); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_core_capability_response(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT status = 0; + UINT16 numCapabilities = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, numCapabilities); /* numCapabilities (2 bytes) */ + Stream_Seek_UINT16(s); /* Padding (2 bytes) */ + + UINT16 caps = 0; + for (UINT16 i = 0; i < numCapabilities; i++) + { + RDPDR_CAPABILITY_HEADER capabilityHeader = { 0 }; + const size_t start = Stream_GetPosition(s); + + if ((status = rdpdr_read_capset_header(context->priv->log, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", status); + return status; + } + + status = IFCALLRESULT(CHANNEL_RC_OK, context->ReceiveCaps, context, &capabilityHeader, + Stream_GetRemainingLength(s), Stream_ConstPointer(s)); + if (status != CHANNEL_RC_OK) + return status; + + caps |= capabilityHeader.CapabilityType; + switch (capabilityHeader.CapabilityType) + { + case CAP_GENERAL_TYPE: + if ((status = + rdpdr_server_read_general_capability_set(context, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", + status); + return status; + } + + break; + + case CAP_PRINTER_TYPE: + if ((status = + rdpdr_server_read_printer_capability_set(context, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", + status); + return status; + } + + break; + + case CAP_PORT_TYPE: + if ((status = rdpdr_server_read_port_capability_set(context, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", + status); + return status; + } + + break; + + case CAP_DRIVE_TYPE: + if ((status = + rdpdr_server_read_drive_capability_set(context, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", + status); + return status; + } + + break; + + case CAP_SMARTCARD_TYPE: + if ((status = + rdpdr_server_read_smartcard_capability_set(context, s, &capabilityHeader))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "failed with error %" PRIu32 "!", + status); + return status; + } + + break; + + default: + WLog_Print(context->priv->log, WLOG_WARN, "Unknown capabilityType %" PRIu16 "", + capabilityHeader.CapabilityType); + Stream_Seek(s, capabilityHeader.CapabilityLength); + return ERROR_INVALID_DATA; + } + + for (UINT16 x = 0; x < 16; x++) + { + const UINT16 mask = (UINT16)(1 << x); + if (((caps & mask) != 0) && ((context->supported & mask) == 0)) + { + WLog_Print(context->priv->log, WLOG_WARN, + "client sent capability %s we did not announce!", + freerdp_rdpdr_dtyp_string(mask)); + } + + /* we assume the server supports the capability. so only deactivate what the client did + * not respond with */ + if ((caps & mask) == 0) + context->supported &= ~mask; + } + + const size_t end = Stream_GetPosition(s); + const size_t diff = end - start; + if (diff != capabilityHeader.CapabilityLength + RDPDR_CAPABILITY_HEADER_LENGTH) + { + WLog_Print(context->priv->log, WLOG_WARN, + "{capability %s[0x%04" PRIx16 "]} processed %" PRIuz + " bytes, but expected to be %" PRIu16, + rdpdr_cap_type_string(capabilityHeader.CapabilityType), + capabilityHeader.CapabilityType, diff, capabilityHeader.CapabilityLength); + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_client_id_confirm(RdpdrServerContext* context) +{ + wStream* s = NULL; + RDPDR_HEADER header = { 0 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + header.Component = RDPDR_CTYP_CORE; + header.PacketId = PAKID_CORE_CLIENTID_CONFIRM; + s = Stream_New(NULL, RDPDR_HEADER_LENGTH + 8); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, header.Component); /* Component (2 bytes) */ + Stream_Write_UINT16(s, header.PacketId); /* PacketId (2 bytes) */ + Stream_Write_UINT16(s, context->priv->VersionMajor); /* VersionMajor (2 bytes) */ + Stream_Write_UINT16(s, context->priv->VersionMinor); /* VersionMinor (2 bytes) */ + Stream_Write_UINT32(s, context->priv->ClientId); /* ClientId (4 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_device_list_announce_request(RdpdrServerContext* context, + wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 DeviceCount = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, DeviceCount); /* DeviceCount (4 bytes) */ + WLog_Print(context->priv->log, WLOG_DEBUG, "DeviceCount: %" PRIu32 "", DeviceCount); + + for (UINT32 i = 0; i < DeviceCount; i++) + { + UINT error = 0; + RdpdrDevice device = { 0 }; + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 20)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, device.DeviceType); /* DeviceType (4 bytes) */ + Stream_Read_UINT32(s, device.DeviceId); /* DeviceId (4 bytes) */ + Stream_Read(s, device.PreferredDosName, 8); /* PreferredDosName (8 bytes) */ + Stream_Read_UINT32(s, device.DeviceDataLength); /* DeviceDataLength (4 bytes) */ + device.DeviceData = Stream_Pointer(s); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, device.DeviceDataLength)) + return ERROR_INVALID_DATA; + + if (!rdpdr_add_device(context->priv, &device)) + return ERROR_INTERNAL_ERROR; + + error = IFCALLRESULT(CHANNEL_RC_OK, context->ReceiveDeviceAnnounce, context, &device); + if (error != CHANNEL_RC_OK) + return error; + + switch (device.DeviceType) + { + case RDPDR_DTYP_FILESYSTEM: + if ((context->supported & RDPDR_DTYP_FILESYSTEM) != 0) + error = IFCALLRESULT(CHANNEL_RC_OK, context->OnDriveCreate, context, &device); + break; + + case RDPDR_DTYP_PRINT: + if ((context->supported & RDPDR_DTYP_PRINT) != 0) + error = IFCALLRESULT(CHANNEL_RC_OK, context->OnPrinterCreate, context, &device); + break; + + case RDPDR_DTYP_SERIAL: + if (device.DeviceDataLength != 0) + { + WLog_Print(context->priv->log, WLOG_WARN, + "[rdpdr] RDPDR_DTYP_SERIAL::DeviceDataLength != 0 [%" PRIu32 "]", + device.DeviceDataLength); + error = ERROR_INVALID_DATA; + } + else if ((context->supported & RDPDR_DTYP_SERIAL) != 0) + error = + IFCALLRESULT(CHANNEL_RC_OK, context->OnSerialPortCreate, context, &device); + break; + + case RDPDR_DTYP_PARALLEL: + if (device.DeviceDataLength != 0) + { + WLog_Print(context->priv->log, WLOG_WARN, + "[rdpdr] RDPDR_DTYP_PARALLEL::DeviceDataLength != 0 [%" PRIu32 "]", + device.DeviceDataLength); + error = ERROR_INVALID_DATA; + } + else if ((context->supported & RDPDR_DTYP_PARALLEL) != 0) + error = IFCALLRESULT(CHANNEL_RC_OK, context->OnParallelPortCreate, context, + &device); + break; + + case RDPDR_DTYP_SMARTCARD: + if (device.DeviceDataLength != 0) + { + WLog_Print(context->priv->log, WLOG_WARN, + "[rdpdr] RDPDR_DTYP_SMARTCARD::DeviceDataLength != 0 [%" PRIu32 "]", + device.DeviceDataLength); + error = ERROR_INVALID_DATA; + } + else if ((context->supported & RDPDR_DTYP_SMARTCARD) != 0) + error = + IFCALLRESULT(CHANNEL_RC_OK, context->OnSmartcardCreate, context, &device); + break; + + default: + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.2.9 Client Device List Announce Request " + "(DR_CORE_DEVICELIST_ANNOUNCE_REQ) unknown device type %04" PRIx16 + " at position %" PRIu32, + device.DeviceType, i); + error = ERROR_INVALID_DATA; + break; + } + + if (error != CHANNEL_RC_OK) + return error; + + Stream_Seek(s, device.DeviceDataLength); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_device_list_remove_request(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 DeviceCount = 0; + UINT32 DeviceType = 0; + UINT32 DeviceId = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, DeviceCount); /* DeviceCount (4 bytes) */ + WLog_Print(context->priv->log, WLOG_DEBUG, "DeviceCount: %" PRIu32 "", DeviceCount); + + for (UINT32 i = 0; i < DeviceCount; i++) + { + UINT error = 0; + const RdpdrDevice* device = NULL; + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, DeviceId); /* DeviceId (4 bytes) */ + device = rdpdr_get_device_by_id(context->priv, DeviceId); + WLog_Print(context->priv->log, WLOG_DEBUG, "Device %" PRIu32 " Id: 0x%08" PRIX32 "", i, + DeviceId); + DeviceType = 0; + if (device) + DeviceType = device->DeviceType; + + error = + IFCALLRESULT(CHANNEL_RC_OK, context->ReceiveDeviceRemove, context, DeviceId, device); + if (error != CHANNEL_RC_OK) + return error; + + switch (DeviceType) + { + case RDPDR_DTYP_FILESYSTEM: + if ((context->supported & RDPDR_DTYP_FILESYSTEM) != 0) + error = IFCALLRESULT(CHANNEL_RC_OK, context->OnDriveDelete, context, DeviceId); + break; + + case RDPDR_DTYP_PRINT: + if ((context->supported & RDPDR_DTYP_PRINT) != 0) + error = + IFCALLRESULT(CHANNEL_RC_OK, context->OnPrinterDelete, context, DeviceId); + break; + + case RDPDR_DTYP_SERIAL: + if ((context->supported & RDPDR_DTYP_SERIAL) != 0) + error = + IFCALLRESULT(CHANNEL_RC_OK, context->OnSerialPortDelete, context, DeviceId); + break; + + case RDPDR_DTYP_PARALLEL: + if ((context->supported & RDPDR_DTYP_PARALLEL) != 0) + error = IFCALLRESULT(CHANNEL_RC_OK, context->OnParallelPortDelete, context, + DeviceId); + break; + + case RDPDR_DTYP_SMARTCARD: + if ((context->supported & RDPDR_DTYP_SMARTCARD) != 0) + error = + IFCALLRESULT(CHANNEL_RC_OK, context->OnSmartcardDelete, context, DeviceId); + break; + + default: + break; + } + + if (error != CHANNEL_RC_OK) + return error; + + if (!rdpdr_remove_device_by_id(context->priv, DeviceId)) + return ERROR_INVALID_DATA; + } + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_create_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + const WCHAR* path = NULL; + UINT32 DesiredAccess = 0; + UINT32 AllocationSize = 0; + UINT32 FileAttributes = 0; + UINT32 SharedAccess = 0; + UINT32 CreateDisposition = 0; + UINT32 CreateOptions = 0; + UINT32 PathLength = 0; + + WINPR_ASSERT(context); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, DesiredAccess); + Stream_Read_UINT32(s, AllocationSize); + Stream_Read_UINT32(s, FileAttributes); + Stream_Read_UINT32(s, SharedAccess); + Stream_Read_UINT32(s, CreateDisposition); + Stream_Read_UINT32(s, CreateOptions); + Stream_Read_UINT32(s, PathLength); + + path = rdpdr_read_ustring(context->priv->log, s, PathLength); + if (!path && (PathLength > 0)) + return ERROR_INVALID_DATA; + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4.1 Device Create Request (DR_CREATE_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_close_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Seek(s, 32); /* Padding */ + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4.2 Device Close Request (DR_CLOSE_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_read_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 Length = 0; + UINT64 Offset = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, Length); + Stream_Read_UINT64(s, Offset); + Stream_Seek(s, 20); /* Padding */ + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4.3 Device Read Request (DR_READ_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_write_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 Length = 0; + UINT64 Offset = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, Length); + Stream_Read_UINT64(s, Offset); + Stream_Seek(s, 20); /* Padding */ + + const BYTE* data = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, Length)) + return ERROR_INVALID_DATA; + Stream_Seek(s, Length); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4.4 Device Write Request (DR_WRITE_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", data); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_device_control_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 OutputBufferLength = 0; + UINT32 InputBufferLength = 0; + UINT32 IoControlCode = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, OutputBufferLength); + Stream_Read_UINT32(s, InputBufferLength); + Stream_Read_UINT32(s, IoControlCode); + Stream_Seek(s, 20); /* Padding */ + + const BYTE* InputBuffer = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, InputBufferLength)) + return ERROR_INVALID_DATA; + Stream_Seek(s, InputBufferLength); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4.5 Device Control Request (DR_CONTROL_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", InputBuffer); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_query_volume_information_request(RdpdrServerContext* context, + wStream* s, UINT32 DeviceId, + UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 FsInformationClass = 0; + UINT32 Length = 0; + + WINPR_ASSERT(context); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, FsInformationClass); + Stream_Read_UINT32(s, Length); + Stream_Seek(s, 24); /* Padding */ + + const BYTE* QueryVolumeBuffer = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, Length)) + return ERROR_INVALID_DATA; + Stream_Seek(s, Length); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.6 Server Drive Query Volume Information Request " + "(DR_DRIVE_QUERY_VOLUME_INFORMATION_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", QueryVolumeBuffer); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_set_volume_information_request(RdpdrServerContext* context, + wStream* s, UINT32 DeviceId, + UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 FsInformationClass = 0; + UINT32 Length = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, FsInformationClass); + Stream_Read_UINT32(s, Length); + Stream_Seek(s, 24); /* Padding */ + + const BYTE* SetVolumeBuffer = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, Length)) + return ERROR_INVALID_DATA; + Stream_Seek(s, Length); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.7 Server Drive Set Volume Information Request " + "(DR_DRIVE_SET_VOLUME_INFORMATION_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", SetVolumeBuffer); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_query_information_request(RdpdrServerContext* context, + wStream* s, UINT32 DeviceId, + UINT32 FileId, UINT32 CompletionId) +{ + UINT32 FsInformationClass = 0; + UINT32 Length = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, FsInformationClass); + Stream_Read_UINT32(s, Length); + Stream_Seek(s, 24); /* Padding */ + + const BYTE* QueryBuffer = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, Length)) + return ERROR_INVALID_DATA; + Stream_Seek(s, Length); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.8 Server Drive Query Information Request " + "(DR_DRIVE_QUERY_INFORMATION_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", QueryBuffer); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_set_information_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 FsInformationClass = 0; + UINT32 Length = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, FsInformationClass); + Stream_Read_UINT32(s, Length); + Stream_Seek(s, 24); /* Padding */ + + const BYTE* SetBuffer = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, Length)) + return ERROR_INVALID_DATA; + Stream_Seek(s, Length); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.9 Server Drive Set Information Request " + "(DR_DRIVE_SET_INFORMATION_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", SetBuffer); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_query_directory_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + BYTE InitialQuery = 0; + UINT32 FsInformationClass = 0; + UINT32 PathLength = 0; + const WCHAR* Path = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, FsInformationClass); + Stream_Read_UINT8(s, InitialQuery); + Stream_Read_UINT32(s, PathLength); + Stream_Seek(s, 23); /* Padding */ + + Path = rdpdr_read_ustring(context->priv->log, s, PathLength); + if (!Path && (PathLength > 0)) + return ERROR_INVALID_DATA; + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.10 Server Drive Query Directory Request " + "(DR_DRIVE_QUERY_DIRECTORY_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_change_directory_request(RdpdrServerContext* context, + wStream* s, UINT32 DeviceId, + UINT32 FileId, UINT32 CompletionId) +{ + BYTE WatchTree = 0; + UINT32 CompletionFilter = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, WatchTree); + Stream_Read_UINT32(s, CompletionFilter); + Stream_Seek(s, 27); /* Padding */ + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.11 Server Drive NotifyChange Directory Request " + "(DR_DRIVE_NOTIFY_CHANGE_DIRECTORY_REQ) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_io_directory_control_request(RdpdrServerContext* context, + wStream* s, UINT32 DeviceId, + UINT32 FileId, UINT32 CompletionId, + UINT32 MinorFunction) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + switch (MinorFunction) + { + case IRP_MN_QUERY_DIRECTORY: + return rdpdr_server_receive_io_query_directory_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MN_NOTIFY_CHANGE_DIRECTORY: + return rdpdr_server_receive_io_change_directory_request(context, s, DeviceId, FileId, + CompletionId); + default: + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4 Device I/O Request (DR_DEVICE_IOREQUEST) " + "MajorFunction=%s, MinorFunction=%08" PRIx32 " is not supported", + rdpdr_irp_string(IRP_MJ_DIRECTORY_CONTROL), MinorFunction); + return ERROR_INVALID_DATA; + } +} + +static UINT rdpdr_server_receive_io_lock_control_request(RdpdrServerContext* context, wStream* s, + UINT32 DeviceId, UINT32 FileId, + UINT32 CompletionId) +{ + UINT32 Operation = 0; + UINT32 Lock = 0; + UINT32 NumLocks = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, Operation); + Stream_Read_UINT32(s, Lock); + Stream_Read_UINT32(s, NumLocks); + Stream_Seek(s, 20); /* Padding */ + + Lock &= 0x01; /* Only byte 0 is of importance */ + + for (UINT32 x = 0; x < NumLocks; x++) + { + UINT64 Length = 0; + UINT64 Offset = 0; + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 16)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT64(s, Length); + Stream_Read_UINT64(s, Offset); + } + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.3.3.12 Server Drive Lock Control Request (DR_DRIVE_LOCK_REQ) " + "[Lock=0x%08" PRIx32 "]" + "not implemented", + Lock); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_device_io_request(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 DeviceId = 0; + UINT32 FileId = 0; + UINT32 CompletionId = 0; + UINT32 MajorFunction = 0; + UINT32 MinorFunction = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 20)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, DeviceId); + Stream_Read_UINT32(s, FileId); + Stream_Read_UINT32(s, CompletionId); + Stream_Read_UINT32(s, MajorFunction); + Stream_Read_UINT32(s, MinorFunction); + if ((MinorFunction != 0) && (MajorFunction != IRP_MJ_DIRECTORY_CONTROL)) + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4 Device I/O Request (DR_DEVICE_IOREQUEST) MajorFunction=%s, " + "MinorFunction=0x%08" PRIx32 " != 0", + rdpdr_irp_string(MajorFunction), MinorFunction); + + switch (MajorFunction) + { + case IRP_MJ_CREATE: + return rdpdr_server_receive_io_create_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_CLOSE: + return rdpdr_server_receive_io_close_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_READ: + return rdpdr_server_receive_io_read_request(context, s, DeviceId, FileId, CompletionId); + case IRP_MJ_WRITE: + return rdpdr_server_receive_io_write_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_DEVICE_CONTROL: + return rdpdr_server_receive_io_device_control_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_QUERY_VOLUME_INFORMATION: + return rdpdr_server_receive_io_query_volume_information_request(context, s, DeviceId, + FileId, CompletionId); + case IRP_MJ_QUERY_INFORMATION: + return rdpdr_server_receive_io_query_information_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_SET_INFORMATION: + return rdpdr_server_receive_io_set_information_request(context, s, DeviceId, FileId, + CompletionId); + case IRP_MJ_DIRECTORY_CONTROL: + return rdpdr_server_receive_io_directory_control_request(context, s, DeviceId, FileId, + CompletionId, MinorFunction); + case IRP_MJ_LOCK_CONTROL: + return rdpdr_server_receive_io_lock_control_request(context, s, DeviceId, FileId, + CompletionId); + default: + WLog_Print( + context->priv->log, WLOG_WARN, + "[MS-RDPEFS] 2.2.1.4 Device I/O Request (DR_DEVICE_IOREQUEST) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, + "got DeviceId=0x%08" PRIx32 ", FileId=0x%08" PRIx32 + ", CompletionId=0x%08" PRIx32 ", MajorFunction=0x%08" PRIx32 + ", MinorFunction=0x%08" PRIx32, + DeviceId, FileId, CompletionId, MajorFunction, MinorFunction); + return ERROR_INVALID_DATA; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_device_io_completion(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 deviceId = 0; + UINT32 completionId = 0; + UINT32 ioStatus = 0; + RDPDR_IRP* irp = NULL; + UINT error = CHANNEL_RC_OK; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + WINPR_UNUSED(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 12)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, deviceId); + Stream_Read_UINT32(s, completionId); + Stream_Read_UINT32(s, ioStatus); + WLog_Print(context->priv->log, WLOG_DEBUG, + "deviceId=%" PRIu32 ", completionId=0x%" PRIx32 ", ioStatus=0x%" PRIx32 "", deviceId, + completionId, ioStatus); + irp = rdpdr_server_dequeue_irp(context, completionId); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "IRP not found for completionId=0x%" PRIx32 "", + completionId); + return CHANNEL_RC_OK; + } + + /* Invoke the callback. */ + if (irp->Callback) + { + error = (*irp->Callback)(context, s, irp, deviceId, completionId, ioStatus); + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_user_logged_on(RdpdrServerContext* context) +{ + wStream* s = NULL; + RDPDR_HEADER header = { 0 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + header.Component = RDPDR_CTYP_CORE; + header.PacketId = PAKID_CORE_USER_LOGGEDON; + s = Stream_New(NULL, RDPDR_HEADER_LENGTH); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(s, header.Component); /* Component (2 bytes) */ + Stream_Write_UINT16(s, header.PacketId); /* PacketId (2 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +static UINT rdpdr_server_receive_prn_cache_add_printer(RdpdrServerContext* context, wStream* s) +{ + char PortDosName[9] = { 0 }; + UINT32 PnPNameLen = 0; + UINT32 DriverNameLen = 0; + UINT32 PrinterNameLen = 0; + UINT32 CachedFieldsLen = 0; + const WCHAR* PnPName = NULL; + const WCHAR* DriverName = NULL; + const WCHAR* PrinterName = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 24)) + return ERROR_INVALID_DATA; + + Stream_Read(s, PortDosName, 8); + Stream_Read_UINT32(s, PnPNameLen); + Stream_Read_UINT32(s, DriverNameLen); + Stream_Read_UINT32(s, PrinterNameLen); + Stream_Read_UINT32(s, CachedFieldsLen); + + PnPName = rdpdr_read_ustring(context->priv->log, s, PnPNameLen); + if (!PnPName && (PnPNameLen > 0)) + return ERROR_INVALID_DATA; + DriverName = rdpdr_read_ustring(context->priv->log, s, DriverNameLen); + if (!DriverName && (DriverNameLen > 0)) + return ERROR_INVALID_DATA; + PrinterName = rdpdr_read_ustring(context->priv->log, s, PrinterNameLen); + if (!PrinterName && (PrinterNameLen > 0)) + return ERROR_INVALID_DATA; + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, CachedFieldsLen)) + return ERROR_INVALID_DATA; + Stream_Seek(s, CachedFieldsLen); + + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEPC] 2.2.2.3 Add Printer Cachedata (DR_PRN_ADD_CACHEDATA) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_prn_cache_update_printer(RdpdrServerContext* context, wStream* s) +{ + UINT32 PrinterNameLen = 0; + UINT32 CachedFieldsLen = 0; + const WCHAR* PrinterName = NULL; + + WINPR_ASSERT(context); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, PrinterNameLen); + Stream_Read_UINT32(s, CachedFieldsLen); + + PrinterName = rdpdr_read_ustring(context->priv->log, s, PrinterNameLen); + if (!PrinterName && (PrinterNameLen > 0)) + return ERROR_INVALID_DATA; + + const BYTE* config = Stream_ConstPointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, CachedFieldsLen)) + return ERROR_INVALID_DATA; + Stream_Seek(s, CachedFieldsLen); + + WLog_Print( + context->priv->log, WLOG_WARN, + "[MS-RDPEPC] 2.2.2.4 Update Printer Cachedata (DR_PRN_UPDATE_CACHEDATA) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO: parse %p", config); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_prn_cache_delete_printer(RdpdrServerContext* context, wStream* s) +{ + UINT32 PrinterNameLen = 0; + const WCHAR* PrinterName = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, PrinterNameLen); + + PrinterName = rdpdr_read_ustring(context->priv->log, s, PrinterNameLen); + if (!PrinterName && (PrinterNameLen > 0)) + return ERROR_INVALID_DATA; + + WLog_Print( + context->priv->log, WLOG_WARN, + "[MS-RDPEPC] 2.2.2.5 Delete Printer Cachedata (DR_PRN_DELETE_CACHEDATA) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_prn_cache_rename_cachedata(RdpdrServerContext* context, wStream* s) +{ + UINT32 OldPrinterNameLen = 0; + UINT32 NewPrinterNameLen = 0; + const WCHAR* OldPrinterName = NULL; + const WCHAR* NewPrinterName = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, OldPrinterNameLen); + Stream_Read_UINT32(s, NewPrinterNameLen); + + OldPrinterName = rdpdr_read_ustring(context->priv->log, s, OldPrinterNameLen); + if (!OldPrinterName && (OldPrinterNameLen > 0)) + return ERROR_INVALID_DATA; + NewPrinterName = rdpdr_read_ustring(context->priv->log, s, NewPrinterNameLen); + if (!NewPrinterName && (NewPrinterNameLen > 0)) + return ERROR_INVALID_DATA; + + WLog_Print( + context->priv->log, WLOG_WARN, + "[MS-RDPEPC] 2.2.2.6 Rename Printer Cachedata (DR_PRN_RENAME_CACHEDATA) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "TODO"); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_receive_prn_cache_data_request(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 EventId = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, EventId); + switch (EventId) + { + case RDPDR_ADD_PRINTER_EVENT: + return rdpdr_server_receive_prn_cache_add_printer(context, s); + case RDPDR_UPDATE_PRINTER_EVENT: + return rdpdr_server_receive_prn_cache_update_printer(context, s); + case RDPDR_DELETE_PRINTER_EVENT: + return rdpdr_server_receive_prn_cache_delete_printer(context, s); + case RDPDR_RENAME_PRINTER_EVENT: + return rdpdr_server_receive_prn_cache_rename_cachedata(context, s); + default: + WLog_Print(context->priv->log, WLOG_WARN, + "[MS-RDPEPC] PAKID_PRN_CACHE_DATA unknown EventId=0x%08" PRIx32, EventId); + return ERROR_INVALID_DATA; + } +} + +static UINT rdpdr_server_receive_prn_using_xps_request(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT32 PrinterId = 0; + UINT32 Flags = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, PrinterId); + Stream_Read_UINT32(s, Flags); + + WLog_Print( + context->priv->log, WLOG_WARN, + "[MS-RDPEPC] 2.2.2.2 Server Printer Set XPS Mode (DR_PRN_USING_XPS) not implemented"); + WLog_Print(context->priv->log, WLOG_WARN, "PrinterId=0x%08" PRIx32 ", Flags=0x%08" PRIx32, + PrinterId, Flags); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_receive_pdu(RdpdrServerContext* context, wStream* s, + const RDPDR_HEADER* header) +{ + UINT error = ERROR_INVALID_DATA; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "receiving message {Component %s[%04" PRIx16 "], PacketId %s[%04" PRIx16 "]", + rdpdr_component_string(header->Component), header->Component, + rdpdr_packetid_string(header->PacketId), header->PacketId); + + if (header->Component == RDPDR_CTYP_CORE) + { + switch (header->PacketId) + { + case PAKID_CORE_SERVER_ANNOUNCE: + WLog_Print(context->priv->log, WLOG_ERROR, + "[MS-RDPEFS] 2.2.2.2 Server Announce Request " + "(DR_CORE_SERVER_ANNOUNCE_REQ) must not be sent by a client!"); + break; + + case PAKID_CORE_CLIENTID_CONFIRM: + error = rdpdr_server_receive_announce_response(context, s, header); + break; + + case PAKID_CORE_CLIENT_NAME: + error = rdpdr_server_receive_client_name_request(context, s, header); + if (error == CHANNEL_RC_OK) + error = rdpdr_server_send_core_capability_request(context); + if (error == CHANNEL_RC_OK) + error = rdpdr_server_send_client_id_confirm(context); + break; + + case PAKID_CORE_USER_LOGGEDON: + WLog_Print(context->priv->log, WLOG_ERROR, + "[MS-RDPEFS] 2.2.2.5 Server User Logged On (DR_CORE_USER_LOGGEDON) " + "must not be sent by a client!"); + break; + + case PAKID_CORE_SERVER_CAPABILITY: + WLog_Print(context->priv->log, WLOG_ERROR, + "[MS-RDPEFS] 2.2.2.7 Server Core Capability Request " + "(DR_CORE_CAPABILITY_REQ) must not be sent by a client!"); + break; + + case PAKID_CORE_CLIENT_CAPABILITY: + error = rdpdr_server_receive_core_capability_response(context, s, header); + if (error == CHANNEL_RC_OK) + { + if (context->priv->UserLoggedOnPdu) + error = rdpdr_server_send_user_logged_on(context); + } + + break; + + case PAKID_CORE_DEVICELIST_ANNOUNCE: + error = rdpdr_server_receive_device_list_announce_request(context, s, header); + break; + + case PAKID_CORE_DEVICELIST_REMOVE: + error = rdpdr_server_receive_device_list_remove_request(context, s, header); + break; + + case PAKID_CORE_DEVICE_REPLY: + WLog_Print(context->priv->log, WLOG_ERROR, + "[MS-RDPEFS] 2.2.2.1 Server Device Announce Response " + "(DR_CORE_DEVICE_ANNOUNCE_RSP) must not be sent by a client!"); + break; + + case PAKID_CORE_DEVICE_IOREQUEST: + error = rdpdr_server_receive_device_io_request(context, s, header); + break; + + case PAKID_CORE_DEVICE_IOCOMPLETION: + error = rdpdr_server_receive_device_io_completion(context, s, header); + break; + + default: + WLog_Print(context->priv->log, WLOG_WARN, + "Unknown RDPDR_HEADER.Component: %s [0x%04" PRIx16 "], PacketId: %s", + rdpdr_component_string(header->Component), header->Component, + rdpdr_packetid_string(header->PacketId)); + break; + } + } + else if (header->Component == RDPDR_CTYP_PRN) + { + switch (header->PacketId) + { + case PAKID_PRN_CACHE_DATA: + error = rdpdr_server_receive_prn_cache_data_request(context, s, header); + break; + + case PAKID_PRN_USING_XPS: + error = rdpdr_server_receive_prn_using_xps_request(context, s, header); + break; + + default: + WLog_Print(context->priv->log, WLOG_WARN, + "Unknown RDPDR_HEADER.Component: %s [0x%04" PRIx16 "], PacketId: %s", + rdpdr_component_string(header->Component), header->Component, + rdpdr_packetid_string(header->PacketId)); + break; + } + } + else + { + WLog_Print(context->priv->log, WLOG_WARN, + "Unknown RDPDR_HEADER.Component: %s [0x%04" PRIx16 "], PacketId: %s", + rdpdr_component_string(header->Component), header->Component, + rdpdr_packetid_string(header->PacketId)); + } + + return IFCALLRESULT(error, context->ReceivePDU, context, header, error); +} + +static DWORD WINAPI rdpdr_server_thread(LPVOID arg) +{ + DWORD status = 0; + DWORD nCount = 0; + void* buffer = NULL; + HANDLE events[8] = { 0 }; + HANDLE ChannelEvent = NULL; + DWORD BytesReturned = 0; + UINT error = 0; + RdpdrServerContext* context = (RdpdrServerContext*)arg; + wStream* s = Stream_New(NULL, 4096); + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + if (WTSVirtualChannelQuery(context->priv->ChannelHandle, WTSVirtualEventHandle, &buffer, + &BytesReturned) == TRUE) + { + if (BytesReturned == sizeof(HANDLE)) + ChannelEvent = *(HANDLE*)buffer; + + WTSFreeMemory(buffer); + } + + nCount = 0; + events[nCount++] = ChannelEvent; + events[nCount++] = context->priv->StopEvent; + + if ((error = rdpdr_server_send_announce_request(context))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_send_announce_request failed with error %" PRIu32 "!", error); + goto out_stream; + } + + while (1) + { + size_t capacity = 0; + BytesReturned = 0; + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_Print(context->priv->log, WLOG_ERROR, + "WaitForMultipleObjects failed with error %" PRIu32 "!", error); + goto out_stream; + } + + status = WaitForSingleObject(context->priv->StopEvent, 0); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_Print(context->priv->log, WLOG_ERROR, + "WaitForSingleObject failed with error %" PRIu32 "!", error); + goto out_stream; + } + + if (status == WAIT_OBJECT_0) + break; + + if (!WTSVirtualChannelRead(context->priv->ChannelHandle, 0, NULL, 0, &BytesReturned)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "WTSVirtualChannelRead failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + capacity = MIN(Stream_Capacity(s), UINT32_MAX); + if (!WTSVirtualChannelRead(context->priv->ChannelHandle, 0, Stream_BufferAs(s, char), + (ULONG)capacity, &BytesReturned)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "WTSVirtualChannelRead failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (BytesReturned >= RDPDR_HEADER_LENGTH) + { + Stream_SetPosition(s, 0); + Stream_SetLength(s, BytesReturned); + + while (Stream_GetRemainingLength(s) >= RDPDR_HEADER_LENGTH) + { + RDPDR_HEADER header = { 0 }; + + Stream_Read_UINT16(s, header.Component); /* Component (2 bytes) */ + Stream_Read_UINT16(s, header.PacketId); /* PacketId (2 bytes) */ + + if ((error = rdpdr_server_receive_pdu(context, s, &header))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_receive_pdu failed with error %" PRIu32 "!", error); + goto out_stream; + } + } + } + } + +out_stream: + Stream_Free(s, TRUE); +out: + + if (error && context->rdpcontext) + setChannelError(context->rdpcontext, error, "rdpdr_server_thread reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_start(RdpdrServerContext* context) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + context->priv->ChannelHandle = + WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, RDPDR_SVC_CHANNEL_NAME); + + if (!context->priv->ChannelHandle) + { + WLog_Print(context->priv->log, WLOG_ERROR, "WTSVirtualChannelOpen failed!"); + return CHANNEL_RC_BAD_CHANNEL; + } + + if (!(context->priv->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "CreateEvent failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (!(context->priv->Thread = + CreateThread(NULL, 0, rdpdr_server_thread, (void*)context, 0, NULL))) + { + WLog_Print(context->priv->log, WLOG_ERROR, "CreateThread failed!"); + (void)CloseHandle(context->priv->StopEvent); + context->priv->StopEvent = NULL; + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_stop(RdpdrServerContext* context) +{ + UINT error = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + if (context->priv->StopEvent) + { + (void)SetEvent(context->priv->StopEvent); + + if (WaitForSingleObject(context->priv->Thread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_Print(context->priv->log, WLOG_ERROR, + "WaitForSingleObject failed with error %" PRIu32 "!", error); + return error; + } + + (void)CloseHandle(context->priv->Thread); + context->priv->Thread = NULL; + (void)CloseHandle(context->priv->StopEvent); + context->priv->StopEvent = NULL; + } + + if (context->priv->ChannelHandle) + { + (void)WTSVirtualChannelClose(context->priv->ChannelHandle); + context->priv->ChannelHandle = NULL; + } + return CHANNEL_RC_OK; +} + +static void rdpdr_server_write_device_iorequest(wStream* s, UINT32 deviceId, UINT32 fileId, + UINT32 completionId, UINT32 majorFunction, + UINT32 minorFunction) +{ + Stream_Write_UINT16(s, RDPDR_CTYP_CORE); /* Component (2 bytes) */ + Stream_Write_UINT16(s, PAKID_CORE_DEVICE_IOREQUEST); /* PacketId (2 bytes) */ + Stream_Write_UINT32(s, deviceId); /* DeviceId (4 bytes) */ + Stream_Write_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Write_UINT32(s, completionId); /* CompletionId (4 bytes) */ + Stream_Write_UINT32(s, majorFunction); /* MajorFunction (4 bytes) */ + Stream_Write_UINT32(s, minorFunction); /* MinorFunction (4 bytes) */ +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_read_file_directory_information(wLog* log, wStream* s, + FILE_DIRECTORY_INFORMATION* fdi) +{ + UINT32 fileNameLength = 0; + WINPR_ASSERT(fdi); + ZeroMemory(fdi, sizeof(FILE_DIRECTORY_INFORMATION)); + + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 64)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fdi->NextEntryOffset); /* NextEntryOffset (4 bytes) */ + Stream_Read_UINT32(s, fdi->FileIndex); /* FileIndex (4 bytes) */ + Stream_Read_INT64(s, fdi->CreationTime.QuadPart); /* CreationTime (8 bytes) */ + Stream_Read_INT64(s, fdi->LastAccessTime.QuadPart); /* LastAccessTime (8 bytes) */ + Stream_Read_INT64(s, fdi->LastWriteTime.QuadPart); /* LastWriteTime (8 bytes) */ + Stream_Read_INT64(s, fdi->ChangeTime.QuadPart); /* ChangeTime (8 bytes) */ + Stream_Read_INT64(s, fdi->EndOfFile.QuadPart); /* EndOfFile (8 bytes) */ + Stream_Read_INT64(s, fdi->AllocationSize.QuadPart); /* AllocationSize (8 bytes) */ + Stream_Read_UINT32(s, fdi->FileAttributes); /* FileAttributes (4 bytes) */ + Stream_Read_UINT32(s, fileNameLength); /* FileNameLength (4 bytes) */ + + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, fileNameLength)) + return ERROR_INVALID_DATA; + + if (Stream_Read_UTF16_String_As_UTF8_Buffer(s, fileNameLength / sizeof(WCHAR), fdi->FileName, + ARRAYSIZE(fdi->FileName)) < 0) + return ERROR_INVALID_DATA; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_create_request(RdpdrServerContext* context, UINT32 deviceId, + UINT32 completionId, const char* path, + UINT32 desiredAccess, UINT32 createOptions, + UINT32 createDisposition) +{ + size_t pathLength = 0; + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceCreateRequest: deviceId=%" PRIu32 + ", path=%s, desiredAccess=0x%" PRIx32 " createOptions=0x%" PRIx32 + " createDisposition=0x%" PRIx32 "", + deviceId, path, desiredAccess, createOptions, createDisposition); + /* Compute the required Unicode size. */ + pathLength = (strlen(path) + 1U) * sizeof(WCHAR); + s = Stream_New(NULL, 256U + pathLength); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, 0, completionId, IRP_MJ_CREATE, 0); + Stream_Write_UINT32(s, desiredAccess); /* DesiredAccess (4 bytes) */ + Stream_Write_UINT32(s, 0); /* AllocationSize (8 bytes) */ + Stream_Write_UINT32(s, 0); + Stream_Write_UINT32(s, 0); /* FileAttributes (4 bytes) */ + Stream_Write_UINT32(s, 3); /* SharedAccess (4 bytes) */ + Stream_Write_UINT32(s, createDisposition); /* CreateDisposition (4 bytes) */ + Stream_Write_UINT32(s, createOptions); /* CreateOptions (4 bytes) */ + WINPR_ASSERT(pathLength <= UINT32_MAX); + Stream_Write_UINT32(s, (UINT32)pathLength); /* PathLength (4 bytes) */ + /* Convert the path to Unicode. */ + if (Stream_Write_UTF16_String_From_UTF8(s, pathLength / sizeof(WCHAR), path, + pathLength / sizeof(WCHAR), TRUE) < 0) + { + Stream_Free(s, TRUE); + return ERROR_INTERNAL_ERROR; + } + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_close_request(RdpdrServerContext* context, UINT32 deviceId, + UINT32 fileId, UINT32 completionId) +{ + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceCloseRequest: deviceId=%" PRIu32 ", fileId=%" PRIu32 "", + deviceId, fileId); + s = Stream_New(NULL, 128); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, fileId, completionId, IRP_MJ_CLOSE, 0); + Stream_Zero(s, 32); /* Padding (32 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_read_request(RdpdrServerContext* context, UINT32 deviceId, + UINT32 fileId, UINT32 completionId, UINT32 length, + UINT32 offset) +{ + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceReadRequest: deviceId=%" PRIu32 ", fileId=%" PRIu32 + ", length=%" PRIu32 ", offset=%" PRIu32 "", + deviceId, fileId, length, offset); + s = Stream_New(NULL, 128); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, fileId, completionId, IRP_MJ_READ, 0); + Stream_Write_UINT32(s, length); /* Length (4 bytes) */ + Stream_Write_UINT32(s, offset); /* Offset (8 bytes) */ + Stream_Write_UINT32(s, 0); + Stream_Zero(s, 20); /* Padding (20 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_write_request(RdpdrServerContext* context, UINT32 deviceId, + UINT32 fileId, UINT32 completionId, + const char* data, UINT32 length, UINT32 offset) +{ + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceWriteRequest: deviceId=%" PRIu32 ", fileId=%" PRIu32 + ", length=%" PRIu32 ", offset=%" PRIu32 "", + deviceId, fileId, length, offset); + s = Stream_New(NULL, 64 + length); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, fileId, completionId, IRP_MJ_WRITE, 0); + Stream_Write_UINT32(s, length); /* Length (4 bytes) */ + Stream_Write_UINT32(s, offset); /* Offset (8 bytes) */ + Stream_Write_UINT32(s, 0); + Stream_Zero(s, 20); /* Padding (20 bytes) */ + Stream_Write(s, data, length); /* WriteData (variable) */ + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_query_directory_request(RdpdrServerContext* context, + UINT32 deviceId, UINT32 fileId, + UINT32 completionId, const char* path) +{ + size_t pathLength = 0; + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceQueryDirectoryRequest: deviceId=%" PRIu32 ", fileId=%" PRIu32 + ", path=%s", + deviceId, fileId, path); + /* Compute the required Unicode size. */ + pathLength = path ? (strlen(path) + 1) * sizeof(WCHAR) : 0; + s = Stream_New(NULL, 64 + pathLength); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, fileId, completionId, IRP_MJ_DIRECTORY_CONTROL, + IRP_MN_QUERY_DIRECTORY); + Stream_Write_UINT32(s, FileDirectoryInformation); /* FsInformationClass (4 bytes) */ + Stream_Write_UINT8(s, path ? 1 : 0); /* InitialQuery (1 byte) */ + WINPR_ASSERT(pathLength <= UINT32_MAX); + Stream_Write_UINT32(s, (UINT32)pathLength); /* PathLength (4 bytes) */ + Stream_Zero(s, 23); /* Padding (23 bytes) */ + + /* Convert the path to Unicode. */ + if (pathLength > 0) + { + if (Stream_Write_UTF16_String_From_UTF8(s, pathLength / sizeof(WCHAR), path, + pathLength / sizeof(WCHAR), TRUE) < 0) + { + Stream_Free(s, TRUE); + return ERROR_INTERNAL_ERROR; + } + } + + return rdpdr_seal_send_free_request(context, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_send_device_file_rename_request(RdpdrServerContext* context, + UINT32 deviceId, UINT32 fileId, + UINT32 completionId, const char* path) +{ + size_t pathLength = 0; + wStream* s = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerSendDeviceFileNameRequest: deviceId=%" PRIu32 ", fileId=%" PRIu32 + ", path=%s", + deviceId, fileId, path); + /* Compute the required Unicode size. */ + pathLength = path ? (strlen(path) + 1) * sizeof(WCHAR) : 0; + s = Stream_New(NULL, 64 + pathLength); + + if (!s) + { + WLog_Print(context->priv->log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + rdpdr_server_write_device_iorequest(s, deviceId, fileId, completionId, IRP_MJ_SET_INFORMATION, + 0); + Stream_Write_UINT32(s, FileRenameInformation); /* FsInformationClass (4 bytes) */ + WINPR_ASSERT(pathLength <= UINT32_MAX - 6U); + Stream_Write_UINT32(s, (UINT32)pathLength + 6U); /* Length (4 bytes) */ + Stream_Zero(s, 24); /* Padding (24 bytes) */ + /* RDP_FILE_RENAME_INFORMATION */ + Stream_Write_UINT8(s, 0); /* ReplaceIfExists (1 byte) */ + Stream_Write_UINT8(s, 0); /* RootDirectory (1 byte) */ + Stream_Write_UINT32(s, (UINT32)pathLength); /* FileNameLength (4 bytes) */ + + /* Convert the path to Unicode. */ + if (pathLength > 0) + { + if (Stream_Write_UTF16_String_From_UTF8(s, pathLength / sizeof(WCHAR), path, + pathLength / sizeof(WCHAR), TRUE) < 0) + { + Stream_Free(s, TRUE); + return ERROR_INTERNAL_ERROR; + } + } + + return rdpdr_seal_send_free_request(context, s); +} + +static void rdpdr_server_convert_slashes(char* path, int size) +{ + WINPR_ASSERT(path || (size <= 0)); + + for (int i = 0; (i < size) && (path[i] != '\0'); i++) + { + if (path[i] == '/') + path[i] = '\\'; + } +} + +/************************************************* + * Drive Create Directory + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_create_directory_callback2(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(irp); + WINPR_UNUSED(s); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveCreateDirectoryCallback2: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + /* Invoke the create directory completion routine. */ + context->OnDriveCreateDirectoryComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_create_directory_callback1(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + UINT8 information = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(s); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveCreateDirectoryCallback1: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (ioStatus != STATUS_SUCCESS) + { + /* Invoke the create directory completion routine. */ + context->OnDriveCreateDirectoryComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Read_UINT8(s, information); /* Information (1 byte) */ + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_create_directory_callback2; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to close the file */ + return rdpdr_server_send_device_close_request(context, deviceId, fileId, irp->CompletionId); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_create_directory(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* path) +{ + RDPDR_IRP* irp = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(callbackData); + WINPR_ASSERT(path); + irp = rdpdr_server_irp_new(); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_create_directory_callback1; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, path, sizeof(irp->PathName) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the file. */ + return rdpdr_server_send_device_create_request( + context, deviceId, irp->CompletionId, irp->PathName, FILE_READ_DATA | SYNCHRONIZE, + FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE); +} + +/************************************************* + * Drive Delete Directory + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_directory_callback2(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + WINPR_UNUSED(s); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveDeleteDirectoryCallback2: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + /* Invoke the delete directory completion routine. */ + context->OnDriveDeleteDirectoryComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_directory_callback1(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + UINT8 information = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveDeleteDirectoryCallback1: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (ioStatus != STATUS_SUCCESS) + { + /* Invoke the delete directory completion routine. */ + context->OnDriveDeleteFileComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Read_UINT8(s, information); /* Information (1 byte) */ + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_delete_directory_callback2; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to close the file */ + return rdpdr_server_send_device_close_request(context, deviceId, fileId, irp->CompletionId); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_directory(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* path) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_delete_directory_callback1; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, path, sizeof(irp->PathName) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the file. */ + return rdpdr_server_send_device_create_request( + context, deviceId, irp->CompletionId, irp->PathName, DELETE | SYNCHRONIZE, + FILE_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN); +} + +/************************************************* + * Drive Query Directory + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_query_directory_callback2(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT error = 0; + UINT32 length = 0; + FILE_DIRECTORY_INFORMATION fdi = { 0 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveQueryDirectoryCallback2: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, length); /* Length (4 bytes) */ + + if (length > 0) + { + if ((error = rdpdr_server_read_file_directory_information(context->priv->log, s, &fdi))) + { + WLog_Print(context->priv->log, WLOG_ERROR, + "rdpdr_server_read_file_directory_information failed with error %" PRIu32 + "!", + error); + return error; + } + } + else + { + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Seek(s, 1); /* Padding (1 byte) */ + } + + if (ioStatus == STATUS_SUCCESS) + { + /* Invoke the query directory completion routine. */ + context->OnDriveQueryDirectoryComplete(context, irp->CallbackData, ioStatus, + length > 0 ? &fdi : NULL); + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_query_directory_callback2; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to query the directory. */ + return rdpdr_server_send_device_query_directory_request(context, irp->DeviceId, irp->FileId, + irp->CompletionId, NULL); + } + else + { + /* Invoke the query directory completion routine. */ + context->OnDriveQueryDirectoryComplete(context, irp->CallbackData, ioStatus, NULL); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_query_directory_callback1(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveQueryDirectoryCallback1: deviceId=%" PRIu32 + ", completionId=%" PRIu32 ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (ioStatus != STATUS_SUCCESS) + { + /* Invoke the query directory completion routine. */ + context->OnDriveQueryDirectoryComplete(context, irp->CallbackData, ioStatus, NULL); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_query_directory_callback2; + irp->DeviceId = deviceId; + irp->FileId = fileId; + winpr_str_append("\\*.*", irp->PathName, ARRAYSIZE(irp->PathName), NULL); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to query the directory. */ + return rdpdr_server_send_device_query_directory_request(context, deviceId, fileId, + irp->CompletionId, irp->PathName); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_query_directory(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* path) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_query_directory_callback1; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, path, sizeof(irp->PathName) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the directory. */ + return rdpdr_server_send_device_create_request( + context, deviceId, irp->CompletionId, irp->PathName, FILE_READ_DATA | SYNCHRONIZE, + FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN); +} + +/************************************************* + * Drive Open File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_open_file_callback(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + UINT8 information = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveOpenFileCallback: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Read_UINT8(s, information); /* Information (1 byte) */ + /* Invoke the open file completion routine. */ + context->OnDriveOpenFileComplete(context, irp->CallbackData, ioStatus, deviceId, fileId); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_open_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* path, UINT32 desiredAccess, + UINT32 createDisposition) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_open_file_callback; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, path, sizeof(irp->PathName) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the file. */ + return rdpdr_server_send_device_create_request(context, deviceId, irp->CompletionId, + irp->PathName, desiredAccess | SYNCHRONIZE, + FILE_SYNCHRONOUS_IO_NONALERT, createDisposition); +} + +/************************************************* + * Drive Read File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_read_file_callback(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 length = 0; + char* buffer = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveReadFileCallback: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, length); /* Length (4 bytes) */ + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, length)) + return ERROR_INVALID_DATA; + + if (length > 0) + { + buffer = Stream_Pointer(s); + Stream_Seek(s, length); + } + + /* Invoke the read file completion routine. */ + context->OnDriveReadFileComplete(context, irp->CallbackData, ioStatus, buffer, length); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_read_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, UINT32 fileId, UINT32 length, + UINT32 offset) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_read_file_callback; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the directory. */ + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): rdpdr_server_enqueue_irp owns irp + return rdpdr_server_send_device_read_request(context, deviceId, fileId, irp->CompletionId, + length, offset); +} + +/************************************************* + * Drive Write File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_write_file_callback(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 length = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveWriteFileCallback: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, length); /* Length (4 bytes) */ + Stream_Seek(s, 1); /* Padding (1 byte) */ + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, length)) + return ERROR_INVALID_DATA; + + /* Invoke the write file completion routine. */ + context->OnDriveWriteFileComplete(context, irp->CallbackData, ioStatus, length); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_write_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, UINT32 fileId, const char* buffer, + UINT32 length, UINT32 offset) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_write_file_callback; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the directory. */ + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): rdpdr_server_enqueue_irp owns irp + return rdpdr_server_send_device_write_request(context, deviceId, fileId, irp->CompletionId, + buffer, length, offset); +} + +/************************************************* + * Drive Close File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_close_file_callback(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + WINPR_UNUSED(s); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveCloseFileCallback: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + // padding 5 bytes + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Seek(s, 5); + + /* Invoke the close file completion routine. */ + context->OnDriveCloseFileComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_close_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, UINT32 fileId) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_close_file_callback; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the directory. */ + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): rdpdr_server_enqueue_irp owns irp + return rdpdr_server_send_device_close_request(context, deviceId, fileId, irp->CompletionId); +} + +/************************************************* + * Drive Delete File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_file_callback2(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + WINPR_UNUSED(s); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveDeleteFileCallback2: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + /* Invoke the delete file completion routine. */ + context->OnDriveDeleteFileComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_file_callback1(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + UINT8 information = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveDeleteFileCallback1: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (ioStatus != STATUS_SUCCESS) + { + /* Invoke the close file completion routine. */ + context->OnDriveDeleteFileComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Read_UINT8(s, information); /* Information (1 byte) */ + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_delete_file_callback2; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to close the file */ + return rdpdr_server_send_device_close_request(context, deviceId, fileId, irp->CompletionId); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_delete_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* path) +{ + RDPDR_IRP* irp = rdpdr_server_irp_new(); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_delete_file_callback1; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, path, sizeof(irp->PathName) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the file. */ + return rdpdr_server_send_device_create_request( + context, deviceId, irp->CompletionId, irp->PathName, FILE_READ_DATA | SYNCHRONIZE, + FILE_DELETE_ON_CLOSE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN); +} + +/************************************************* + * Drive Rename File + ************************************************/ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_rename_file_callback3(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + WINPR_UNUSED(context); + WINPR_UNUSED(s); + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveRenameFileCallback3: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_rename_file_callback2(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 length = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveRenameFileCallback2: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, length); /* Length (4 bytes) */ + Stream_Seek(s, 1); /* Padding (1 byte) */ + /* Invoke the rename file completion routine. */ + context->OnDriveRenameFileComplete(context, irp->CallbackData, ioStatus); + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_rename_file_callback3; + irp->DeviceId = deviceId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to close the file */ + return rdpdr_server_send_device_close_request(context, deviceId, irp->FileId, + irp->CompletionId); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_rename_file_callback1(RdpdrServerContext* context, wStream* s, + RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus) +{ + UINT32 fileId = 0; + UINT8 information = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + WINPR_ASSERT(irp); + WLog_Print(context->priv->log, WLOG_DEBUG, + "RdpdrServerDriveRenameFileCallback1: deviceId=%" PRIu32 ", completionId=%" PRIu32 + ", ioStatus=0x%" PRIx32 "", + deviceId, completionId, ioStatus); + + if (ioStatus != STATUS_SUCCESS) + { + /* Invoke the rename file completion routine. */ + context->OnDriveRenameFileComplete(context, irp->CallbackData, ioStatus); + /* Destroy the IRP. */ + rdpdr_server_irp_free(irp); + return CHANNEL_RC_OK; + } + + if (!Stream_CheckAndLogRequiredLengthWLog(context->priv->log, s, 5)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, fileId); /* FileId (4 bytes) */ + Stream_Read_UINT8(s, information); /* Information (1 byte) */ + /* Setup the IRP. */ + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_rename_file_callback2; + irp->DeviceId = deviceId; + irp->FileId = fileId; + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to rename the file */ + return rdpdr_server_send_device_file_rename_request(context, deviceId, fileId, + irp->CompletionId, irp->ExtraBuffer); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpdr_server_drive_rename_file(RdpdrServerContext* context, void* callbackData, + UINT32 deviceId, const char* oldPath, + const char* newPath) +{ + RDPDR_IRP* irp = NULL; + WINPR_ASSERT(context); + WINPR_ASSERT(context->priv); + irp = rdpdr_server_irp_new(); + + if (!irp) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_irp_new failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + irp->CompletionId = context->priv->NextCompletionId++; + irp->Callback = rdpdr_server_drive_rename_file_callback1; + irp->CallbackData = callbackData; + irp->DeviceId = deviceId; + strncpy(irp->PathName, oldPath, sizeof(irp->PathName) - 1); + strncpy(irp->ExtraBuffer, newPath, sizeof(irp->ExtraBuffer) - 1); + rdpdr_server_convert_slashes(irp->PathName, sizeof(irp->PathName)); + rdpdr_server_convert_slashes(irp->ExtraBuffer, sizeof(irp->ExtraBuffer)); + + if (!rdpdr_server_enqueue_irp(context, irp)) + { + WLog_Print(context->priv->log, WLOG_ERROR, "rdpdr_server_enqueue_irp failed!"); + rdpdr_server_irp_free(irp); + return ERROR_INTERNAL_ERROR; + } + + /* Send a request to open the file. */ + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): rdpdr_server_enqueue_irp owns irp + return rdpdr_server_send_device_create_request(context, deviceId, irp->CompletionId, + irp->PathName, FILE_READ_DATA | SYNCHRONIZE, + FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN); +} + +static void rdpdr_server_private_free(RdpdrServerPrivate* ctx) +{ + if (!ctx) + return; + ListDictionary_Free(ctx->IrpList); + HashTable_Free(ctx->devicelist); + free(ctx->ClientComputerName); + free(ctx); +} + +#define TAG CHANNELS_TAG("rdpdr.server") +static RdpdrServerPrivate* rdpdr_server_private_new(void) +{ + RdpdrServerPrivate* priv = (RdpdrServerPrivate*)calloc(1, sizeof(RdpdrServerPrivate)); + + if (!priv) + goto fail; + + priv->log = WLog_Get(TAG); + priv->VersionMajor = RDPDR_VERSION_MAJOR; + priv->VersionMinor = RDPDR_VERSION_MINOR_RDP6X; + priv->ClientId = g_ClientId++; + priv->UserLoggedOnPdu = TRUE; + priv->NextCompletionId = 1; + priv->IrpList = ListDictionary_New(TRUE); + + if (!priv->IrpList) + goto fail; + + priv->devicelist = HashTable_New(FALSE); + if (!priv->devicelist) + goto fail; + + HashTable_SetHashFunction(priv->devicelist, rdpdr_deviceid_hash); + wObject* obj = HashTable_ValueObject(priv->devicelist); + WINPR_ASSERT(obj); + obj->fnObjectFree = rdpdr_device_free_h; + obj->fnObjectNew = rdpdr_device_clone; + + obj = HashTable_KeyObject(priv->devicelist); + obj->fnObjectEquals = rdpdr_device_equal; + + return priv; +fail: + rdpdr_server_private_free(priv); + return NULL; +} + +RdpdrServerContext* rdpdr_server_context_new(HANDLE vcm) +{ + RdpdrServerContext* context = (RdpdrServerContext*)calloc(1, sizeof(RdpdrServerContext)); + + if (!context) + goto fail; + + context->vcm = vcm; + context->Start = rdpdr_server_start; + context->Stop = rdpdr_server_stop; + context->DriveCreateDirectory = rdpdr_server_drive_create_directory; + context->DriveDeleteDirectory = rdpdr_server_drive_delete_directory; + context->DriveQueryDirectory = rdpdr_server_drive_query_directory; + context->DriveOpenFile = rdpdr_server_drive_open_file; + context->DriveReadFile = rdpdr_server_drive_read_file; + context->DriveWriteFile = rdpdr_server_drive_write_file; + context->DriveCloseFile = rdpdr_server_drive_close_file; + context->DriveDeleteFile = rdpdr_server_drive_delete_file; + context->DriveRenameFile = rdpdr_server_drive_rename_file; + context->priv = rdpdr_server_private_new(); + if (!context->priv) + goto fail; + + /* By default announce everything, the server application can deactivate that later on */ + context->supported = UINT16_MAX; + + return context; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + rdpdr_server_context_free(context); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void rdpdr_server_context_free(RdpdrServerContext* context) +{ + if (!context) + return; + + rdpdr_server_private_free(context->priv); + free(context); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.h new file mode 100644 index 0000000000000000000000000000000000000000..dabbae24ad8bcae1153e0098451b0bd6d2a00d4b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpdr/server/rdpdr_main.h @@ -0,0 +1,47 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Device Redirection Virtual Channel Extension + * + * Copyright 2014 Dell Software + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_RDPDR_SERVER_MAIN_H +#define FREERDP_CHANNEL_RDPDR_SERVER_MAIN_H + +#include +#include +#include +#include + +#include +#include + +typedef struct S_RDPDR_IRP +{ + UINT32 CompletionId; + UINT32 DeviceId; + UINT32 FileId; + char PathName[256]; + char ExtraBuffer[256]; + void* CallbackData; + UINT(*Callback) + (RdpdrServerContext* context, wStream* s, struct S_RDPDR_IRP* irp, UINT32 deviceId, + UINT32 completionId, UINT32 ioStatus); +} RDPDR_IRP; + +#endif /* FREERDP_CHANNEL_RDPDR_SERVER_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a8028c3090d6c4826b0c31dbd2c2f7015625bf74 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/CMakeLists.txt @@ -0,0 +1,54 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2024 Oleg Turovski +# +# 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. + +define_channel_client("rdpecam") + +if(NOT WITH_SWSCALE OR NOT WITH_FFMPEG) + message(FATAL_ERROR "WITH_FFMPEG and WITH_SWSCALE required for CHANNEL_RDPECAM_CLIENT") +endif() + +# currently camera redirect client supported for platforms with Video4Linux only +find_package(FFmpeg REQUIRED COMPONENTS SWSCALE) +find_package(V4L) +if(V4L_FOUND) + set(WITH_V4L ON) + add_compile_definitions("WITH_V4L") +else() + message(FATAL_ERROR "libv4l-dev required for CHANNEL_RDPECAM_CLIENT") +endif() + +option(RDPECAM_INPUT_FORMAT_H264 "[MS-RDPECAM] Enable H264 camera format (passthrough)" ON) +if(RDPECAM_INPUT_FORMAT_H264) + add_compile_definitions("WITH_INPUT_FORMAT_H264") +endif() + +option(RDPECAM_INPUT_FORMAT_MJPG "[MS-RDPECAM] Enable MJPG camera format" ON) +if(RDPECAM_INPUT_FORMAT_MJPG) + add_compile_definitions("WITH_INPUT_FORMAT_MJPG") +endif() + +include_directories(SYSTEM ${SWSCALE_INCLUDE_DIRS}) + +set(${MODULE_PREFIX}_SRCS camera_device_enum_main.c camera_device_main.c encoding.c) + +set(${MODULE_PREFIX}_LIBS freerdp winpr ${SWSCALE_LIBRARIES} ${FFMPEG_LIBRARIES}) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DVCPluginEntry") + +if(V4L_FOUND) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "v4l" "") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_enum_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_enum_main.c new file mode 100644 index 0000000000000000000000000000000000000000..b60522169d0381e004947f93c19f1302a48ca1d6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_enum_main.c @@ -0,0 +1,566 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MS-RDPECAM Implementation, Device Enumeration Channel + * + * Copyright 2024 Oleg Turovski + * + * 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 +#include + +#include "camera.h" + +#define TAG CHANNELS_TAG("rdpecam-enum.client") + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT ecam_channel_send_error_response(CameraPlugin* ecam, GENERIC_CHANNEL_CALLBACK* hchannel, + CAM_ERROR_CODE code) +{ + CAM_MSG_ID msg = CAM_MSG_ID_ErrorResponse; + + WINPR_ASSERT(ecam); + + wStream* s = Stream_New(NULL, CAM_HEADER_SIZE + 4); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + Stream_Write_UINT32(s, code); + + return ecam_channel_write(ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT ecam_channel_send_generic_msg(CameraPlugin* ecam, GENERIC_CHANNEL_CALLBACK* hchannel, + CAM_MSG_ID msg) +{ + WINPR_ASSERT(ecam); + + wStream* s = Stream_New(NULL, CAM_HEADER_SIZE); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + + return ecam_channel_write(ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT ecam_channel_write(CameraPlugin* ecam, GENERIC_CHANNEL_CALLBACK* hchannel, CAM_MSG_ID msg, + wStream* out, BOOL freeStream) +{ + if (!hchannel || !out) + return ERROR_INVALID_PARAMETER; + + Stream_SealLength(out); + WINPR_ASSERT(Stream_Length(out) <= UINT32_MAX); + + WLog_DBG(TAG, "ChannelId=%d, MessageId=0x%02" PRIx8 ", Length=%d", + hchannel->channel_mgr->GetChannelId(hchannel->channel), msg, Stream_Length(out)); + + const UINT error = hchannel->channel->Write(hchannel->channel, (ULONG)Stream_Length(out), + Stream_Buffer(out), NULL); + + if (freeStream) + Stream_Free(out, TRUE); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_send_device_added_notification(CameraPlugin* ecam, + GENERIC_CHANNEL_CALLBACK* hchannel, + const char* deviceName, const char* channelName) +{ + CAM_MSG_ID msg = CAM_MSG_ID_DeviceAddedNotification; + + WINPR_ASSERT(ecam); + + wStream* s = Stream_New(NULL, 256); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + + size_t devNameLen = strlen(deviceName); + if (Stream_Write_UTF16_String_From_UTF8(s, devNameLen + 1, deviceName, devNameLen, TRUE) < 0) + { + Stream_Free(s, TRUE); + return ERROR_INTERNAL_ERROR; + } + Stream_Write(s, channelName, strlen(channelName) + 1); + + return ecam_channel_write(ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_ihal_device_added_callback(CameraPlugin* ecam, GENERIC_CHANNEL_CALLBACK* hchannel, + const char* deviceId, const char* deviceName) +{ + WLog_DBG(TAG, "deviceId=%s, deviceName=%s", deviceId, deviceName); + + if (!HashTable_ContainsKey(ecam->devices, deviceId)) + { + CameraDevice* dev = ecam_dev_create(ecam, deviceId, deviceName); + if (!HashTable_Insert(ecam->devices, deviceId, dev)) + { + ecam_dev_destroy(dev); + return ERROR_INTERNAL_ERROR; + } + } + else + { + WLog_DBG(TAG, "Device %s already exists", deviceId); + } + + ecam_send_device_added_notification(ecam, hchannel, deviceName, deviceId /*channelName*/); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_enumerate_devices(CameraPlugin* ecam, GENERIC_CHANNEL_CALLBACK* hchannel) +{ + ecam->ihal->Enumerate(ecam->ihal, ecam_ihal_device_added_callback, ecam, hchannel); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_process_select_version_response(CameraPlugin* ecam, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s, + BYTE serverVersion) +{ + const BYTE clientVersion = ECAM_PROTO_VERSION; + + /* check remaining s capacity */ + + WLog_DBG(TAG, "ServerVersion=%" PRIu8 ", ClientVersion=%" PRIu8, serverVersion, clientVersion); + + if (serverVersion > clientVersion) + { + WLog_ERR(TAG, + "Incompatible protocol version server=%" PRIu8 ", client supports version=%" PRIu8, + serverVersion, clientVersion); + return CHANNEL_RC_OK; + } + ecam->version = serverVersion; + + if (ecam->ihal) + ecam_enumerate_devices(ecam, hchannel); + else + WLog_ERR(TAG, "No HAL registered"); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + UINT error = CHANNEL_RC_OK; + BYTE version = 0; + BYTE messageId = 0; + GENERIC_CHANNEL_CALLBACK* hchannel = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + + if (!hchannel || !data) + return ERROR_INVALID_PARAMETER; + + CameraPlugin* ecam = (CameraPlugin*)hchannel->plugin; + + if (!ecam) + return ERROR_INTERNAL_ERROR; + + if (!Stream_CheckAndLogRequiredCapacity(TAG, data, CAM_HEADER_SIZE)) + return ERROR_NO_DATA; + + Stream_Read_UINT8(data, version); + Stream_Read_UINT8(data, messageId); + WLog_DBG(TAG, "ChannelId=%d, MessageId=0x%02" PRIx8 ", Version=%d", + hchannel->channel_mgr->GetChannelId(hchannel->channel), messageId, version); + + switch (messageId) + { + case CAM_MSG_ID_SelectVersionResponse: + error = ecam_process_select_version_response(ecam, hchannel, data, version); + break; + + default: + WLog_WARN(TAG, "unknown MessageId=0x%02" PRIx8 "", messageId); + error = ERROR_INVALID_DATA; + ecam_channel_send_error_response(ecam, hchannel, CAM_ERROR_CODE_OperationNotSupported); + break; + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_on_open(IWTSVirtualChannelCallback* pChannelCallback) +{ + GENERIC_CHANNEL_CALLBACK* hchannel = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + WINPR_ASSERT(hchannel); + + CameraPlugin* ecam = (CameraPlugin*)hchannel->plugin; + WINPR_ASSERT(ecam); + + WLog_DBG(TAG, "entered"); + return ecam_channel_send_generic_msg(ecam, hchannel, CAM_MSG_ID_SelectVersionRequest); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + GENERIC_CHANNEL_CALLBACK* hchannel = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + WINPR_ASSERT(hchannel); + + WLog_DBG(TAG, "entered"); + + free(hchannel); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_on_new_channel_connection(IWTSListenerCallback* pListenerCallback, + IWTSVirtualChannel* pChannel, BYTE* Data, BOOL* pbAccept, + IWTSVirtualChannelCallback** ppCallback) +{ + GENERIC_LISTENER_CALLBACK* hlistener = (GENERIC_LISTENER_CALLBACK*)pListenerCallback; + + if (!hlistener || !hlistener->plugin) + return ERROR_INTERNAL_ERROR; + + WLog_DBG(TAG, "entered"); + GENERIC_CHANNEL_CALLBACK* hchannel = + (GENERIC_CHANNEL_CALLBACK*)calloc(1, sizeof(GENERIC_CHANNEL_CALLBACK)); + + if (!hchannel) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + hchannel->iface.OnDataReceived = ecam_on_data_received; + hchannel->iface.OnOpen = ecam_on_open; + hchannel->iface.OnClose = ecam_on_close; + hchannel->plugin = hlistener->plugin; + hchannel->channel_mgr = hlistener->channel_mgr; + hchannel->channel = pChannel; + *ppCallback = (IWTSVirtualChannelCallback*)hchannel; + return CHANNEL_RC_OK; +} + +static void ecam_dev_destroy_pv(void* obj) +{ + CameraDevice* dev = obj; + ecam_dev_destroy(dev); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChannelManager* pChannelMgr) +{ + CameraPlugin* ecam = (CameraPlugin*)pPlugin; + + WLog_DBG(TAG, "entered"); + + if (!ecam || !pChannelMgr) + return ERROR_INVALID_PARAMETER; + + if (ecam->initialized) + { + WLog_ERR(TAG, "[%s] plugin initialized twice, aborting", RDPECAM_CONTROL_DVC_CHANNEL_NAME); + return ERROR_INVALID_DATA; + } + + ecam->version = ECAM_PROTO_VERSION; + + ecam->devices = HashTable_New(FALSE); + if (!ecam->devices) + { + WLog_ERR(TAG, "HashTable_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + HashTable_SetupForStringData(ecam->devices, FALSE); + + wObject* obj = HashTable_ValueObject(ecam->devices); + WINPR_ASSERT(obj); + obj->fnObjectFree = ecam_dev_destroy_pv; + + ecam->hlistener = (GENERIC_LISTENER_CALLBACK*)calloc(1, sizeof(GENERIC_LISTENER_CALLBACK)); + + if (!ecam->hlistener) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + ecam->hlistener->iface.OnNewChannelConnection = ecam_on_new_channel_connection; + ecam->hlistener->plugin = pPlugin; + ecam->hlistener->channel_mgr = pChannelMgr; + const UINT rc = pChannelMgr->CreateListener(pChannelMgr, RDPECAM_CONTROL_DVC_CHANNEL_NAME, 0, + &ecam->hlistener->iface, &ecam->listener); + + ecam->initialized = (rc == CHANNEL_RC_OK); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_plugin_terminated(IWTSPlugin* pPlugin) +{ + CameraPlugin* ecam = (CameraPlugin*)pPlugin; + + if (!ecam) + return ERROR_INVALID_DATA; + + WLog_DBG(TAG, "entered"); + + if (ecam->hlistener) + { + IWTSVirtualChannelManager* mgr = ecam->hlistener->channel_mgr; + if (mgr) + IFCALL(mgr->DestroyListener, mgr, ecam->listener); + } + + free(ecam->hlistener); + + HashTable_Free(ecam->devices); + + if (ecam->ihal) + ecam->ihal->Free(ecam->ihal); + + free(ecam); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_plugin_attached(IWTSPlugin* pPlugin) +{ + CameraPlugin* ecam = (CameraPlugin*)pPlugin; + UINT error = CHANNEL_RC_OK; + + if (!ecam) + return ERROR_INVALID_PARAMETER; + + ecam->attached = TRUE; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_plugin_detached(IWTSPlugin* pPlugin) +{ + CameraPlugin* ecam = (CameraPlugin*)pPlugin; + UINT error = CHANNEL_RC_OK; + + if (!ecam) + return ERROR_INVALID_PARAMETER; + + ecam->attached = FALSE; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_register_hal_plugin(IWTSPlugin* pPlugin, ICamHal* ihal) +{ + CameraPlugin* ecam = (CameraPlugin*)pPlugin; + + WINPR_ASSERT(ecam); + + if (ecam->ihal) + { + WLog_DBG(TAG, "already registered"); + return ERROR_ALREADY_EXISTS; + } + + WLog_DBG(TAG, "HAL registered"); + ecam->ihal = ihal; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_load_hal_plugin(CameraPlugin* ecam, const char* name, const ADDIN_ARGV* args) +{ + WINPR_ASSERT(ecam); + + FREERDP_CAMERA_HAL_ENTRY_POINTS entryPoints = { 0 }; + UINT error = ERROR_INTERNAL_ERROR; + union + { + PVIRTUALCHANNELENTRY pvce; + const PFREERDP_CAMERA_HAL_ENTRY entry; + } cnv; + cnv.pvce = freerdp_load_channel_addin_entry(RDPECAM_CHANNEL_NAME, name, NULL, 0); + + if (cnv.entry == NULL) + { + WLog_ERR(TAG, + "freerdp_load_channel_addin_entry did not return any function pointers for %s ", + name); + return ERROR_INVALID_FUNCTION; + } + + entryPoints.plugin = &ecam->iface; + entryPoints.pRegisterCameraHal = ecam_register_hal_plugin; + entryPoints.args = args; + entryPoints.ecam = ecam; + + error = cnv.entry(&entryPoints); + if (error) + { + WLog_ERR(TAG, "%s entry returned error %" PRIu32 ".", name, error); + return error; + } + + WLog_INFO(TAG, "Loaded %s HAL for ecam", name); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE rdpecam_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + UINT error = CHANNEL_RC_INITIALIZATION_ERROR; + + WINPR_ASSERT(pEntryPoints); + WINPR_ASSERT(pEntryPoints->GetPlugin); + CameraPlugin* ecam = (CameraPlugin*)pEntryPoints->GetPlugin(pEntryPoints, RDPECAM_CHANNEL_NAME); + + if (ecam != NULL) + return CHANNEL_RC_ALREADY_INITIALIZED; + + ecam = (CameraPlugin*)calloc(1, sizeof(CameraPlugin)); + + if (!ecam) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + ecam->attached = TRUE; + ecam->iface.Initialize = ecam_plugin_initialize; + ecam->iface.Connected = NULL; /* server connects to client */ + ecam->iface.Disconnected = NULL; + ecam->iface.Terminated = ecam_plugin_terminated; + ecam->iface.Attached = ecam_plugin_attached; + ecam->iface.Detached = ecam_plugin_detached; + + /* TODO: camera redirect only supported for platforms with Video4Linux */ +#if defined(WITH_V4L) + ecam->subsystem = "v4l"; +#else + ecam->subsystem = NULL; +#endif + + if (ecam->subsystem) + { + if ((error = ecam_load_hal_plugin(ecam, ecam->subsystem, NULL /*args*/))) + { + WLog_ERR(TAG, + "Unable to load camera redirection subsystem %s because of error %" PRIu32 "", + ecam->subsystem, error); + goto out; + } + } + + error = pEntryPoints->RegisterPlugin(pEntryPoints, RDPECAM_CHANNEL_NAME, &ecam->iface); + if (error == CHANNEL_RC_OK) + return error; + +out: + ecam_plugin_terminated(&ecam->iface); + return error; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5c6dbb7fdba29b1e03d5e4a18b4852fb5107d912 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/camera_device_main.c @@ -0,0 +1,801 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MS-RDPECAM Implementation, Device Channels + * + * Copyright 2024 Oleg Turovski + * + * 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 +#include + +#include "camera.h" + +#define TAG CHANNELS_TAG("rdpecam-device.client") + +/* supported formats in preference order: + * H264, MJPG, I420 (used as input for H264 encoder), other YUV based, RGB based + */ +static const CAM_MEDIA_FORMAT_INFO supportedFormats[] = { +/* inputFormat, outputFormat */ +#if defined(WITH_INPUT_FORMAT_H264) + { CAM_MEDIA_FORMAT_H264, CAM_MEDIA_FORMAT_H264 }, /* passthrough */ + { CAM_MEDIA_FORMAT_MJPG_H264, CAM_MEDIA_FORMAT_H264 }, +#endif +#if defined(WITH_INPUT_FORMAT_MJPG) + { CAM_MEDIA_FORMAT_MJPG, CAM_MEDIA_FORMAT_H264 }, +#endif + { CAM_MEDIA_FORMAT_I420, CAM_MEDIA_FORMAT_H264 }, + { CAM_MEDIA_FORMAT_YUY2, CAM_MEDIA_FORMAT_H264 }, + { CAM_MEDIA_FORMAT_NV12, CAM_MEDIA_FORMAT_H264 }, + { CAM_MEDIA_FORMAT_RGB24, CAM_MEDIA_FORMAT_H264 }, + { CAM_MEDIA_FORMAT_RGB32, CAM_MEDIA_FORMAT_H264 }, +}; +static const size_t nSupportedFormats = ARRAYSIZE(supportedFormats); + +static void ecam_dev_write_media_type(wStream* s, CAM_MEDIA_TYPE_DESCRIPTION* mediaType) +{ + WINPR_ASSERT(mediaType); + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, mediaType->Format)); + Stream_Write_UINT32(s, mediaType->Width); + Stream_Write_UINT32(s, mediaType->Height); + Stream_Write_UINT32(s, mediaType->FrameRateNumerator); + Stream_Write_UINT32(s, mediaType->FrameRateDenominator); + Stream_Write_UINT32(s, mediaType->PixelAspectRatioNumerator); + Stream_Write_UINT32(s, mediaType->PixelAspectRatioDenominator); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, mediaType->Flags)); +} + +static BOOL ecam_dev_read_media_type(wStream* s, CAM_MEDIA_TYPE_DESCRIPTION* mediaType) +{ + WINPR_ASSERT(mediaType); + + Stream_Read_UINT8(s, mediaType->Format); + Stream_Read_UINT32(s, mediaType->Width); + Stream_Read_UINT32(s, mediaType->Height); + Stream_Read_UINT32(s, mediaType->FrameRateNumerator); + Stream_Read_UINT32(s, mediaType->FrameRateDenominator); + Stream_Read_UINT32(s, mediaType->PixelAspectRatioNumerator); + Stream_Read_UINT32(s, mediaType->PixelAspectRatioDenominator); + Stream_Read_UINT8(s, mediaType->Flags); + return TRUE; +} + +static void ecam_dev_print_media_type(CAM_MEDIA_TYPE_DESCRIPTION* mediaType) +{ + WINPR_ASSERT(mediaType); + + WLog_DBG(TAG, "Format: %d, width: %d, height: %d, fps: %d, flags: %d", mediaType->Format, + mediaType->Width, mediaType->Height, mediaType->FrameRateNumerator, mediaType->Flags); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_send_sample_response(CameraDevice* dev, size_t streamIndex, const BYTE* sample, + size_t size) +{ + WINPR_ASSERT(dev); + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + CAM_MSG_ID msg = CAM_MSG_ID_SampleResponse; + + Stream_SetPosition(stream->sampleRespBuffer, 0); + + Stream_Write_UINT8(stream->sampleRespBuffer, + WINPR_ASSERTING_INT_CAST(uint8_t, dev->ecam->version)); + Stream_Write_UINT8(stream->sampleRespBuffer, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + Stream_Write_UINT8(stream->sampleRespBuffer, WINPR_ASSERTING_INT_CAST(uint8_t, streamIndex)); + + Stream_Write(stream->sampleRespBuffer, sample, size); + + /* channel write is protected by critical section in dvcman_write_channel */ + return ecam_channel_write(dev->ecam, stream->hSampleReqChannel, msg, stream->sampleRespBuffer, + FALSE /* don't free stream */); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_sample_captured_callback(CameraDevice* dev, int streamIndex, + const BYTE* sample, size_t size) +{ + BYTE* encodedSample = NULL; + size_t encodedSize = 0; + + WINPR_ASSERT(dev); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + return ERROR_INVALID_INDEX; + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + if (!stream->streaming) + return CHANNEL_RC_OK; + + if (streamInputFormat(stream) != streamOutputFormat(stream)) + { + if (!ecam_encoder_compress(stream, sample, size, &encodedSample, &encodedSize)) + { + WLog_DBG(TAG, "Frame drop or error in ecam_encoder_compress"); + return CHANNEL_RC_OK; + } + + if (!stream->streaming) + return CHANNEL_RC_OK; + } + else /* passthrough */ + { + encodedSample = WINPR_CAST_CONST_PTR_AWAY(sample, BYTE*); + encodedSize = size; + } + + if (stream->nSampleCredits == 0) + { + WLog_DBG(TAG, "Skip sample: no credits left"); + return CHANNEL_RC_OK; + } + stream->nSampleCredits--; + + return ecam_dev_send_sample_response(dev, WINPR_ASSERTING_INT_CAST(size_t, streamIndex), + encodedSample, encodedSize); +} + +static void ecam_dev_stop_stream(CameraDevice* dev, size_t streamIndex) +{ + WINPR_ASSERT(dev); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + return; + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + if (stream->streaming) + { + stream->streaming = FALSE; + dev->ihal->StopStream(dev->ihal, dev->deviceId, 0); + } + + if (stream->sampleRespBuffer) + { + Stream_Free(stream->sampleRespBuffer, TRUE); + stream->sampleRespBuffer = NULL; + } + + ecam_encoder_context_free(stream); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_stop_streams_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + WINPR_ASSERT(dev); + WINPR_UNUSED(s); + + for (size_t i = 0; i < ECAM_DEVICE_MAX_STREAMS; i++) + ecam_dev_stop_stream(dev, i); + + return ecam_channel_send_generic_msg(dev->ecam, hchannel, CAM_MSG_ID_SuccessResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_start_streams_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + BYTE streamIndex = 0; + CAM_MEDIA_TYPE_DESCRIPTION mediaType = { 0 }; + + WINPR_ASSERT(dev); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1 + 26)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, streamIndex); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + { + WLog_ERR(TAG, "Incorrect streamIndex %" PRIuz, streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_InvalidStreamNumber); + return ERROR_INVALID_INDEX; + } + + if (!ecam_dev_read_media_type(s, &mediaType)) + { + WLog_ERR(TAG, "Unable to read MEDIA_TYPE_DESCRIPTION"); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_InvalidMessage); + return ERROR_INVALID_DATA; + } + + ecam_dev_print_media_type(&mediaType); + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + if (stream->streaming) + { + WLog_ERR(TAG, "Streaming already in progress, device %s, streamIndex %d", dev->deviceId, + streamIndex); + return CAM_ERROR_CODE_UnexpectedError; + } + + /* saving media type description for CurrentMediaTypeRequest, + * to be done before calling ecam_encoder_context_init + */ + stream->currMediaType = mediaType; + + /* initialize encoder, if input and output formats differ */ + if (streamInputFormat(stream) != streamOutputFormat(stream) && + !ecam_encoder_context_init(stream)) + { + WLog_ERR(TAG, "stream_ecam_encoder_init failed"); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_UnexpectedError); + return ERROR_INVALID_DATA; + } + + stream->sampleRespBuffer = Stream_New(NULL, ECAM_SAMPLE_RESPONSE_BUFFER_SIZE); + if (!stream->sampleRespBuffer) + { + WLog_ERR(TAG, "Stream_New failed"); + ecam_dev_stop_stream(dev, streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_OutOfMemory); + return ERROR_INVALID_DATA; + } + + /* replacing outputFormat with inputFormat in mediaType before starting stream */ + mediaType.Format = streamInputFormat(stream); + + stream->nSampleCredits = 0; + + UINT error = dev->ihal->StartStream(dev->ihal, dev, streamIndex, &mediaType, + ecam_dev_sample_captured_callback); + if (error) + { + WLog_ERR(TAG, "StartStream failure"); + ecam_dev_stop_stream(dev, streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, error); + return ERROR_INVALID_DATA; + } + + stream->streaming = TRUE; + return ecam_channel_send_generic_msg(dev->ecam, hchannel, CAM_MSG_ID_SuccessResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_property_list_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + WINPR_ASSERT(dev); + // TODO: supported properties implementation + + return ecam_channel_send_generic_msg(dev->ecam, hchannel, CAM_MSG_ID_PropertyListResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_send_current_media_type_response(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, + CAM_MEDIA_TYPE_DESCRIPTION* mediaType) +{ + CAM_MSG_ID msg = CAM_MSG_ID_CurrentMediaTypeResponse; + + WINPR_ASSERT(dev); + + wStream* s = Stream_New(NULL, CAM_HEADER_SIZE + sizeof(CAM_MEDIA_TYPE_DESCRIPTION)); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, dev->ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + + ecam_dev_write_media_type(s, mediaType); + + return ecam_channel_write(dev->ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_sample_request(CameraDevice* dev, GENERIC_CHANNEL_CALLBACK* hchannel, + wStream* s) +{ + BYTE streamIndex = 0; + + WINPR_ASSERT(dev); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, streamIndex); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + { + WLog_ERR(TAG, "Incorrect streamIndex %d", streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_InvalidStreamNumber); + return ERROR_INVALID_INDEX; + } + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + /* need to save channel because responses are asynchronous and coming from capture thread */ + if (stream->hSampleReqChannel != hchannel) + stream->hSampleReqChannel = hchannel; + + /* allow to send that many unsolicited samples */ + stream->nSampleCredits = ECAM_MAX_SAMPLE_CREDITS; + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_current_media_type_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, + wStream* s) +{ + BYTE streamIndex = 0; + + WINPR_ASSERT(dev); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, streamIndex); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + { + WLog_ERR(TAG, "Incorrect streamIndex %d", streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_InvalidStreamNumber); + return ERROR_INVALID_INDEX; + } + + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + if (stream->currMediaType.Format == 0) + { + WLog_ERR(TAG, "Current media type unknown for streamIndex %d", streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_NotInitialized); + return ERROR_DEVICE_REINITIALIZATION_NEEDED; + } + + return ecam_dev_send_current_media_type_response(dev, hchannel, &stream->currMediaType); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_send_media_type_list_response(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, + CAM_MEDIA_TYPE_DESCRIPTION* mediaTypes, + size_t nMediaTypes) +{ + CAM_MSG_ID msg = CAM_MSG_ID_MediaTypeListResponse; + + WINPR_ASSERT(dev); + + wStream* s = Stream_New(NULL, CAM_HEADER_SIZE + ECAM_MAX_MEDIA_TYPE_DESCRIPTORS * + sizeof(CAM_MEDIA_TYPE_DESCRIPTION)); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, dev->ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + + for (size_t i = 0; i < nMediaTypes; i++, mediaTypes++) + { + ecam_dev_write_media_type(s, mediaTypes); + } + + return ecam_channel_write(dev->ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_media_type_list_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + BYTE streamIndex = 0; + CAM_MEDIA_TYPE_DESCRIPTION* mediaTypes = NULL; + size_t nMediaTypes = ECAM_MAX_MEDIA_TYPE_DESCRIPTORS; + + WINPR_ASSERT(dev); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, streamIndex); + + if (streamIndex >= ECAM_DEVICE_MAX_STREAMS) + { + WLog_ERR(TAG, "Incorrect streamIndex %d", streamIndex); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_InvalidStreamNumber); + return ERROR_INVALID_INDEX; + } + CameraDeviceStream* stream = &dev->streams[streamIndex]; + + mediaTypes = + (CAM_MEDIA_TYPE_DESCRIPTION*)calloc(nMediaTypes, sizeof(CAM_MEDIA_TYPE_DESCRIPTION)); + if (!mediaTypes) + { + WLog_ERR(TAG, "calloc failed"); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_OutOfMemory); + return CHANNEL_RC_NO_MEMORY; + } + + INT16 formatIndex = + dev->ihal->GetMediaTypeDescriptions(dev->ihal, dev->deviceId, streamIndex, supportedFormats, + nSupportedFormats, mediaTypes, &nMediaTypes); + if (formatIndex == -1 || nMediaTypes == 0) + { + WLog_ERR(TAG, "Camera doesn't support any compatible video formats"); + ecam_channel_send_error_response(dev->ecam, hchannel, CAM_ERROR_CODE_ItemNotFound); + error = ERROR_DEVICE_FEATURE_NOT_SUPPORTED; + goto error; + } + + stream->formats = supportedFormats[formatIndex]; + + /* replacing inputFormat with outputFormat in mediaTypes before sending response */ + for (size_t i = 0; i < nMediaTypes; i++) + { + mediaTypes[i].Format = streamOutputFormat(stream); + mediaTypes[i].Flags = CAM_MEDIA_TYPE_DESCRIPTION_FLAG_DecodingRequired; + } + + if (stream->currMediaType.Format == 0) + { + /* saving 1st media type description for CurrentMediaTypeRequest */ + stream->currMediaType = mediaTypes[0]; + } + + error = ecam_dev_send_media_type_list_response(dev, hchannel, mediaTypes, nMediaTypes); + +error: + free(mediaTypes); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_send_stream_list_response(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel) +{ + CAM_MSG_ID msg = CAM_MSG_ID_StreamListResponse; + + WINPR_ASSERT(dev); + + wStream* s = Stream_New(NULL, CAM_HEADER_SIZE + sizeof(CAM_STREAM_DESCRIPTION)); + if (!s) + { + WLog_ERR(TAG, "Stream_New failed"); + return ERROR_NOT_ENOUGH_MEMORY; + } + + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, dev->ecam->version)); + Stream_Write_UINT8(s, WINPR_ASSERTING_INT_CAST(uint8_t, msg)); + + /* single stream description */ + Stream_Write_UINT16(s, CAM_STREAM_FRAME_SOURCE_TYPE_Color); + Stream_Write_UINT8(s, CAM_STREAM_CATEGORY_Capture); + Stream_Write_UINT8(s, TRUE /* Selected */); + Stream_Write_UINT8(s, FALSE /* CanBeShared */); + + return ecam_channel_write(dev->ecam, hchannel, msg, s, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_stream_list_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + return ecam_dev_send_stream_list_response(dev, hchannel); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_activate_device_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, wStream* s) +{ + WINPR_ASSERT(dev); + + /* TODO: TBD if this is required */ + return ecam_channel_send_generic_msg(dev->ecam, hchannel, CAM_MSG_ID_SuccessResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_process_deactivate_device_request(CameraDevice* dev, + GENERIC_CHANNEL_CALLBACK* hchannel, + wStream* s) +{ + WINPR_ASSERT(dev); + WINPR_UNUSED(s); + + for (size_t i = 0; i < ECAM_DEVICE_MAX_STREAMS; i++) + ecam_dev_stop_stream(dev, i); + + return ecam_channel_send_generic_msg(dev->ecam, hchannel, CAM_MSG_ID_SuccessResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + UINT error = CHANNEL_RC_OK; + BYTE version = 0; + BYTE messageId = 0; + GENERIC_CHANNEL_CALLBACK* hchannel = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + + if (!hchannel || !data) + return ERROR_INVALID_PARAMETER; + + CameraDevice* dev = (CameraDevice*)hchannel->plugin; + + if (!dev) + return ERROR_INTERNAL_ERROR; + + if (!Stream_CheckAndLogRequiredCapacity(TAG, data, CAM_HEADER_SIZE)) + return ERROR_NO_DATA; + + Stream_Read_UINT8(data, version); + Stream_Read_UINT8(data, messageId); + WLog_DBG(TAG, "ChannelId=%d, MessageId=0x%02" PRIx8 ", Version=%d", + hchannel->channel_mgr->GetChannelId(hchannel->channel), messageId, version); + + switch (messageId) + { + case CAM_MSG_ID_ActivateDeviceRequest: + error = ecam_dev_process_activate_device_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_DeactivateDeviceRequest: + error = ecam_dev_process_deactivate_device_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_StreamListRequest: + error = ecam_dev_process_stream_list_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_MediaTypeListRequest: + error = ecam_dev_process_media_type_list_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_CurrentMediaTypeRequest: + error = ecam_dev_process_current_media_type_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_PropertyListRequest: + error = ecam_dev_process_property_list_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_StartStreamsRequest: + error = ecam_dev_process_start_streams_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_StopStreamsRequest: + error = ecam_dev_process_stop_streams_request(dev, hchannel, data); + break; + + case CAM_MSG_ID_SampleRequest: + error = ecam_dev_process_sample_request(dev, hchannel, data); + break; + + default: + WLog_WARN(TAG, "unknown MessageId=0x%02" PRIx8 "", messageId); + error = ERROR_INVALID_DATA; + ecam_channel_send_error_response(dev->ecam, hchannel, + CAM_ERROR_CODE_OperationNotSupported); + break; + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_on_open(IWTSVirtualChannelCallback* pChannelCallback) +{ + WLog_DBG(TAG, "entered"); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + GENERIC_CHANNEL_CALLBACK* hchannel = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + WINPR_ASSERT(hchannel); + + CameraDevice* dev = (CameraDevice*)hchannel->plugin; + WINPR_ASSERT(dev); + + WLog_DBG(TAG, "entered"); + + /* make sure this channel is not used for sample responses */ + for (size_t i = 0; i < ECAM_DEVICE_MAX_STREAMS; i++) + if (dev->streams[i].hSampleReqChannel == hchannel) + dev->streams[i].hSampleReqChannel = NULL; + + free(hchannel); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT ecam_dev_on_new_channel_connection(IWTSListenerCallback* pListenerCallback, + IWTSVirtualChannel* pChannel, BYTE* Data, + BOOL* pbAccept, + IWTSVirtualChannelCallback** ppCallback) +{ + GENERIC_LISTENER_CALLBACK* hlistener = (GENERIC_LISTENER_CALLBACK*)pListenerCallback; + + if (!hlistener || !hlistener->plugin) + return ERROR_INTERNAL_ERROR; + + WLog_DBG(TAG, "entered"); + GENERIC_CHANNEL_CALLBACK* hchannel = + (GENERIC_CHANNEL_CALLBACK*)calloc(1, sizeof(GENERIC_CHANNEL_CALLBACK)); + + if (!hchannel) + { + WLog_ERR(TAG, "calloc failed"); + return CHANNEL_RC_NO_MEMORY; + } + + hchannel->iface.OnDataReceived = ecam_dev_on_data_received; + hchannel->iface.OnOpen = ecam_dev_on_open; + hchannel->iface.OnClose = ecam_dev_on_close; + hchannel->plugin = hlistener->plugin; + hchannel->channel_mgr = hlistener->channel_mgr; + hchannel->channel = pChannel; + *ppCallback = (IWTSVirtualChannelCallback*)hchannel; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return CameraDevice pointer or NULL in case of error + */ +CameraDevice* ecam_dev_create(CameraPlugin* ecam, const char* deviceId, const char* deviceName) +{ + WINPR_ASSERT(ecam); + WINPR_ASSERT(ecam->hlistener); + + IWTSVirtualChannelManager* pChannelMgr = ecam->hlistener->channel_mgr; + WINPR_ASSERT(pChannelMgr); + + WLog_DBG(TAG, "entered for %s", deviceId); + + CameraDevice* dev = (CameraDevice*)calloc(1, sizeof(CameraDevice)); + + if (!dev) + { + WLog_ERR(TAG, "calloc failed"); + return NULL; + } + + dev->ecam = ecam; + dev->ihal = ecam->ihal; + strncpy(dev->deviceId, deviceId, sizeof(dev->deviceId) - 1); + dev->hlistener = (GENERIC_LISTENER_CALLBACK*)calloc(1, sizeof(GENERIC_LISTENER_CALLBACK)); + + if (!dev->hlistener) + { + free(dev); + WLog_ERR(TAG, "calloc failed"); + return NULL; + } + + dev->hlistener->iface.OnNewChannelConnection = ecam_dev_on_new_channel_connection; + dev->hlistener->plugin = (IWTSPlugin*)dev; + dev->hlistener->channel_mgr = pChannelMgr; + if (CHANNEL_RC_OK != pChannelMgr->CreateListener(pChannelMgr, deviceId, 0, + &dev->hlistener->iface, &dev->listener)) + { + free(dev->hlistener); + free(dev); + WLog_ERR(TAG, "CreateListener failed"); + return NULL; + } + + return dev; +} + +/** + * Function description + * + * OBJECT_FREE_FN for devices hash table value + * + */ +void ecam_dev_destroy(CameraDevice* dev) +{ + if (!dev) + return; + + WLog_DBG(TAG, "entered for %s", dev->deviceId); + + if (dev->hlistener) + { + IWTSVirtualChannelManager* mgr = dev->hlistener->channel_mgr; + if (mgr) + IFCALL(mgr->DestroyListener, mgr, dev->listener); + } + + free(dev->hlistener); + + for (size_t i = 0; i < ECAM_DEVICE_MAX_STREAMS; i++) + ecam_dev_stop_stream(dev, i); + + free(dev); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/encoding.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/encoding.c new file mode 100644 index 0000000000000000000000000000000000000000..520a8d5a8cbbbfe4405a64a920b599498cc09ec4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/encoding.c @@ -0,0 +1,613 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MS-RDPECAM Implementation, Video Encoding + * + * Copyright 2024 Oleg Turovski + * + * 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 +#include + +#include "camera.h" + +#define TAG CHANNELS_TAG("rdpecam-video.client") + +#if defined(WITH_INPUT_FORMAT_H264) +/* + * demux a H264 frame from a MJPG container + * args: + * srcData - pointer to buffer with h264 muxed in MJPG container + * srcSize - buff size + * h264_data - pointer to h264 data + * h264_max_size - maximum size allowed by h264_data buffer + * + * Credits: + * guvcview http://guvcview.sourceforge.net + * Paulo Assis + * + * see Figure 5 Payload Size in USB_Video_Payload_H 264_1 0.pdf + * for format details + * + * @return: data size and copies demuxed data to h264 buffer + */ +static size_t demux_uvcH264(const BYTE* srcData, size_t srcSize, BYTE* h264_data, + size_t h264_max_size) +{ + WINPR_ASSERT(h264_data); + WINPR_ASSERT(srcData); + + if (srcSize < 30) + { + WLog_ERR(TAG, "Expected srcSize >= 30, got %" PRIuz, srcSize); + return 0; + } + const uint8_t* spl = NULL; + uint8_t* ph264 = h264_data; + + /* search for 1st APP4 marker + * (30 = 2 APP4 marker + 2 length + 22 header + 4 payload size) + */ + for (const uint8_t* sp = srcData; sp < srcData + srcSize - 30; sp++) + { + if (sp[0] == 0xFF && sp[1] == 0xE4) + { + spl = sp + 2; /* exclude APP4 marker */ + break; + } + } + + if (spl == NULL) + { + WLog_ERR(TAG, "Expected 1st APP4 marker but none found"); + return 0; + } + + if (spl > srcData + srcSize - 4) + { + WLog_ERR(TAG, "Payload + Header size bigger than srcData buffer"); + return 0; + } + + /* 1st segment length in big endian + * includes payload size + header + 6 bytes (2 length + 4 payload size) + */ + uint16_t length = (uint16_t)(spl[0] << 8) & UINT16_MAX; + length |= (uint16_t)spl[1]; + + spl += 2; /* header */ + /* header length in little endian at offset 2 */ + uint16_t header_length = (uint16_t)spl[2]; + header_length |= (uint16_t)spl[3] << 8; + + spl += header_length; + if (spl > srcData + srcSize) + { + WLog_ERR(TAG, "Header size bigger than srcData buffer"); + return 0; + } + + /* payload size in little endian */ + uint32_t payload_size = (uint32_t)spl[0] << 0; + payload_size |= (uint32_t)spl[1] << 8; + payload_size |= (uint32_t)spl[2] << 16; + payload_size |= (uint32_t)spl[3] << 24; + + if (payload_size > h264_max_size) + { + WLog_ERR(TAG, "Payload size bigger than h264_data buffer"); + return 0; + } + + spl += 4; /* payload start */ + const uint8_t* epl = spl + payload_size; /* payload end */ + + if (epl > srcData + srcSize) + { + WLog_ERR(TAG, "Payload size bigger than srcData buffer"); + return 0; + } + + length -= header_length + 6; + + /* copy 1st segment to h264 buffer */ + memcpy(ph264, spl, length); + ph264 += length; + spl += length; + + /* copy other segments */ + while (epl > spl + 4) + { + if (spl[0] != 0xFF || spl[1] != 0xE4) + { + WLog_ERR(TAG, "Expected 2nd+ APP4 marker but none found"); + const intptr_t diff = ph264 - h264_data; + return WINPR_ASSERTING_INT_CAST(size_t, diff); + } + + /* 2nd+ segment length in big endian */ + length = (uint16_t)(spl[2] << 8) & UINT16_MAX; + length |= (uint16_t)spl[3]; + if (length < 2) + { + WLog_ERR(TAG, "Expected 2nd+ APP4 length >= 2 but have %" PRIu16, length); + return 0; + } + + length -= 2; + spl += 4; /* APP4 marker + length */ + + /* copy segment to h264 buffer */ + memcpy(ph264, spl, length); + ph264 += length; + spl += length; + } + + const intptr_t diff = ph264 - h264_data; + return WINPR_ASSERTING_INT_CAST(size_t, diff); +} +#endif + +/** + * Function description + * + * @return bitrate in bps + */ +UINT32 h264_get_max_bitrate(UINT32 height) +{ + static struct Bitrates + { + UINT32 height; + UINT32 bitrate; /* kbps */ + + } bitrates[] = { + /* source: https://livekit.io/webrtc/bitrate-guide (webcam streaming) + * + * sorted by height in descending order + */ + { 1080, 2700 }, { 720, 1250 }, { 480, 700 }, { 360, 400 }, + { 240, 170 }, { 180, 140 }, { 0, 100 }, + }; + const size_t nBitrates = ARRAYSIZE(bitrates); + + for (size_t i = 0; i < nBitrates; i++) + { + if (height >= bitrates[i].height) + { + UINT32 bitrate = bitrates[i].bitrate; + WLog_DBG(TAG, "Setting h264 max bitrate: %u kbps", bitrate); + return bitrate * 1000; + } + } + + WINPR_ASSERT(FALSE); + return 0; +} + +/** + * Function description + * + * @return enum AVPixelFormat value + */ +static enum AVPixelFormat ecamToAVPixFormat(CAM_MEDIA_FORMAT ecamFormat) +{ + switch (ecamFormat) + { + case CAM_MEDIA_FORMAT_YUY2: + return AV_PIX_FMT_YUYV422; + case CAM_MEDIA_FORMAT_NV12: + return AV_PIX_FMT_NV12; + case CAM_MEDIA_FORMAT_I420: + return AV_PIX_FMT_YUV420P; + case CAM_MEDIA_FORMAT_RGB24: + return AV_PIX_FMT_RGB24; + case CAM_MEDIA_FORMAT_RGB32: + return AV_PIX_FMT_RGB32; + default: + WLog_ERR(TAG, "Unsupported ecamFormat %d", ecamFormat); + return AV_PIX_FMT_NONE; + } +} + +/** + * Function description + * initialize libswscale + * + * @return success/failure + */ +static BOOL ecam_init_sws_context(CameraDeviceStream* stream, enum AVPixelFormat pixFormat) +{ + WINPR_ASSERT(stream); + + if (stream->sws) + return TRUE; + + /* replacing deprecated JPEG formats, still produced by decoder */ + switch (pixFormat) + { + case AV_PIX_FMT_YUVJ411P: + pixFormat = AV_PIX_FMT_YUV411P; + break; + + case AV_PIX_FMT_YUVJ420P: + pixFormat = AV_PIX_FMT_YUV420P; + break; + + case AV_PIX_FMT_YUVJ422P: + pixFormat = AV_PIX_FMT_YUV422P; + break; + + case AV_PIX_FMT_YUVJ440P: + pixFormat = AV_PIX_FMT_YUV440P; + break; + + case AV_PIX_FMT_YUVJ444P: + pixFormat = AV_PIX_FMT_YUV444P; + break; + + default: + break; + } + + const int width = (int)stream->currMediaType.Width; + const int height = (int)stream->currMediaType.Height; + + const enum AVPixelFormat outPixFormat = + h264_context_get_option(stream->h264, H264_CONTEXT_OPTION_HW_ACCEL) ? AV_PIX_FMT_NV12 + : AV_PIX_FMT_YUV420P; + + stream->sws = + sws_getContext(width, height, pixFormat, width, height, outPixFormat, 0, NULL, NULL, NULL); + if (!stream->sws) + { + WLog_ERR(TAG, "sws_getContext failed"); + return FALSE; + } + + return TRUE; +} + +/** + * Function description + * + * @return success/failure + */ +static BOOL ecam_encoder_compress_h264(CameraDeviceStream* stream, const BYTE* srcData, + size_t srcSize, BYTE** ppDstData, size_t* pDstSize) +{ + UINT32 dstSize = 0; + BYTE* srcSlice[4] = { 0 }; + int srcLineSizes[4] = { 0 }; + BYTE* yuvData[3] = { 0 }; + UINT32 yuvLineSizes[3] = { 0 }; + prim_size_t size = { stream->currMediaType.Width, stream->currMediaType.Height }; + CAM_MEDIA_FORMAT inputFormat = streamInputFormat(stream); + enum AVPixelFormat pixFormat = AV_PIX_FMT_NONE; + +#if defined(WITH_INPUT_FORMAT_H264) + if (inputFormat == CAM_MEDIA_FORMAT_MJPG_H264) + { + const size_t rc = + demux_uvcH264(srcData, srcSize, stream->h264Frame, stream->h264FrameMaxSize); + dstSize = WINPR_ASSERTING_INT_CAST(uint32_t, rc); + *ppDstData = stream->h264Frame; + *pDstSize = dstSize; + return dstSize > 0; + } + else +#endif + +#if defined(WITH_INPUT_FORMAT_MJPG) + if (inputFormat == CAM_MEDIA_FORMAT_MJPG) + { + stream->avInputPkt->data = WINPR_CAST_CONST_PTR_AWAY(srcData, uint8_t*); + WINPR_ASSERT(srcSize <= INT32_MAX); + stream->avInputPkt->size = (int)srcSize; + + if (avcodec_send_packet(stream->avContext, stream->avInputPkt) < 0) + { + WLog_ERR(TAG, "avcodec_send_packet failed"); + return FALSE; + } + + if (avcodec_receive_frame(stream->avContext, stream->avOutFrame) < 0) + { + WLog_ERR(TAG, "avcodec_receive_frame failed"); + return FALSE; + } + + for (size_t i = 0; i < 4; i++) + { + srcSlice[i] = stream->avOutFrame->data[i]; + srcLineSizes[i] = stream->avOutFrame->linesize[i]; + } + + /* get pixFormat produced by MJPEG decoder */ + pixFormat = stream->avContext->pix_fmt; + } + else +#endif + { + pixFormat = ecamToAVPixFormat(inputFormat); + + if (av_image_fill_linesizes(srcLineSizes, pixFormat, (int)size.width) < 0) + { + WLog_ERR(TAG, "av_image_fill_linesizes failed"); + return FALSE; + } + + if (av_image_fill_pointers(srcSlice, pixFormat, (int)size.height, + WINPR_CAST_CONST_PTR_AWAY(srcData, BYTE*), srcLineSizes) < 0) + { + WLog_ERR(TAG, "av_image_fill_pointers failed"); + return FALSE; + } + } + + /* get buffers for YUV420P or NV12 */ + if (h264_get_yuv_buffer(stream->h264, 0, size.width, size.height, yuvData, yuvLineSizes) < 0) + return FALSE; + + /* convert from source format to YUV420P or NV12 */ + if (!ecam_init_sws_context(stream, pixFormat)) + return FALSE; + + const BYTE* cSrcSlice[4] = { srcSlice[0], srcSlice[1], srcSlice[2], srcSlice[3] }; + if (sws_scale(stream->sws, cSrcSlice, srcLineSizes, 0, (int)size.height, yuvData, + (int*)yuvLineSizes) <= 0) + return FALSE; + + /* encode from YUV420P or NV12 to H264 */ + if (h264_compress(stream->h264, ppDstData, &dstSize) < 0) + return FALSE; + + *pDstSize = dstSize; + + return TRUE; +} + +/** + * Function description + * + */ +static void ecam_encoder_context_free_h264(CameraDeviceStream* stream) +{ + WINPR_ASSERT(stream); + + if (stream->sws) + { + sws_freeContext(stream->sws); + stream->sws = NULL; + } + +#if defined(WITH_INPUT_FORMAT_MJPG) + if (stream->avOutFrame) + av_frame_free(&stream->avOutFrame); /* sets to NULL */ + + if (stream->avInputPkt) + { + stream->avInputPkt->data = NULL; + stream->avInputPkt->size = 0; + av_packet_free(&stream->avInputPkt); /* sets to NULL */ + } + + if (stream->avContext) + avcodec_free_context(&stream->avContext); /* sets to NULL */ +#endif + +#if defined(WITH_INPUT_FORMAT_H264) + if (stream->h264Frame) + { + free(stream->h264Frame); + stream->h264Frame = NULL; + } +#endif + + if (stream->h264) + { + h264_context_free(stream->h264); + stream->h264 = NULL; + } +} + +#if defined(WITH_INPUT_FORMAT_MJPG) +/** + * Function description + * + * @return success/failure + */ +static BOOL ecam_init_mjpeg_decoder(CameraDeviceStream* stream) +{ + WINPR_ASSERT(stream); + + const AVCodec* avcodec = avcodec_find_decoder(AV_CODEC_ID_MJPEG); + if (!avcodec) + { + WLog_ERR(TAG, "avcodec_find_decoder failed to find MJPEG codec"); + return FALSE; + } + + stream->avContext = avcodec_alloc_context3(avcodec); + if (!stream->avContext) + { + WLog_ERR(TAG, "avcodec_alloc_context3 failed"); + return FALSE; + } + + stream->avContext->width = WINPR_ASSERTING_INT_CAST(int, stream->currMediaType.Width); + stream->avContext->height = WINPR_ASSERTING_INT_CAST(int, stream->currMediaType.Height); + + /* AV_EF_EXPLODE flag is to abort decoding on minor error detection, + * return error, so we can skip corrupted frames, if any */ + stream->avContext->err_recognition |= AV_EF_EXPLODE; + + if (avcodec_open2(stream->avContext, avcodec, NULL) < 0) + { + WLog_ERR(TAG, "avcodec_open2 failed"); + return FALSE; + } + + stream->avInputPkt = av_packet_alloc(); + if (!stream->avInputPkt) + { + WLog_ERR(TAG, "av_packet_alloc failed"); + return FALSE; + } + + stream->avOutFrame = av_frame_alloc(); + if (!stream->avOutFrame) + { + WLog_ERR(TAG, "av_frame_alloc failed"); + return FALSE; + } + + return TRUE; +} +#endif + +/** + * Function description + * + * @return success/failure + */ +static BOOL ecam_encoder_context_init_h264(CameraDeviceStream* stream) +{ + WINPR_ASSERT(stream); + +#if defined(WITH_INPUT_FORMAT_H264) + if (streamInputFormat(stream) == CAM_MEDIA_FORMAT_MJPG_H264) + { + stream->h264FrameMaxSize = 1ULL * stream->currMediaType.Width * + stream->currMediaType.Height; /* 1 byte per pixel */ + stream->h264Frame = (BYTE*)calloc(stream->h264FrameMaxSize, sizeof(BYTE)); + return TRUE; /* encoder not needed */ + } +#endif + + if (!stream->h264) + stream->h264 = h264_context_new(TRUE); + + if (!stream->h264) + { + WLog_ERR(TAG, "h264_context_new failed"); + return FALSE; + } + + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_USAGETYPE, + H264_CAMERA_VIDEO_REAL_TIME)) + goto fail; + + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_FRAMERATE, + stream->currMediaType.FrameRateNumerator / + stream->currMediaType.FrameRateDenominator)) + goto fail; + + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_BITRATE, + h264_get_max_bitrate(stream->currMediaType.Height))) + goto fail; + + /* Using CQP mode for rate control. It produces more comparable quality + * between VAAPI and software encoding than VBR mode + */ + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_RATECONTROL, + H264_RATECONTROL_CQP)) + goto fail; + + /* Using 26 as CQP value. Lower values will produce better quality but + * higher bitrate; higher values - lower bitrate but degraded quality + */ + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_QP, 26)) + goto fail; + + /* Requesting hardware acceleration before calling h264_context_reset */ + if (!h264_context_set_option(stream->h264, H264_CONTEXT_OPTION_HW_ACCEL, TRUE)) + goto fail; + + if (!h264_context_reset(stream->h264, stream->currMediaType.Width, + stream->currMediaType.Height)) + { + WLog_ERR(TAG, "h264_context_reset failed"); + goto fail; + } + +#if defined(WITH_INPUT_FORMAT_MJPG) + if (streamInputFormat(stream) == CAM_MEDIA_FORMAT_MJPG && !ecam_init_mjpeg_decoder(stream)) + goto fail; +#endif + + return TRUE; + +fail: + ecam_encoder_context_free_h264(stream); + return FALSE; +} + +/** + * Function description + * + * @return success/failure + */ +BOOL ecam_encoder_context_init(CameraDeviceStream* stream) +{ + CAM_MEDIA_FORMAT format = streamOutputFormat(stream); + + switch (format) + { + case CAM_MEDIA_FORMAT_H264: + return ecam_encoder_context_init_h264(stream); + + default: + WLog_ERR(TAG, "Unsupported output format %d", format); + return FALSE; + } +} + +/** + * Function description + * + * @return success/failure + */ +BOOL ecam_encoder_context_free(CameraDeviceStream* stream) +{ + CAM_MEDIA_FORMAT format = streamOutputFormat(stream); + switch (format) + { + case CAM_MEDIA_FORMAT_H264: + ecam_encoder_context_free_h264(stream); + break; + + default: + return FALSE; + } + return TRUE; +} + +/** + * Function description + * + * @return success/failure + */ +BOOL ecam_encoder_compress(CameraDeviceStream* stream, const BYTE* srcData, size_t srcSize, + BYTE** ppDstData, size_t* pDstSize) +{ + CAM_MEDIA_FORMAT format = streamOutputFormat(stream); + switch (format) + { + case CAM_MEDIA_FORMAT_H264: + return ecam_encoder_compress_h264(stream, srcData, srcSize, ppDstData, pDstSize); + default: + WLog_ERR(TAG, "Unsupported output format %d", format); + return FALSE; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f7699d1bcee49ae774d7134bec928f002b99d9e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/CMakeLists.txt @@ -0,0 +1,30 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2024 Oleg Turovski +# +# 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. + +if(WITH_V4L) + + define_channel_client_subsystem("rdpecam" "v4l" "") + + set(${MODULE_PREFIX}_SRCS camera_v4l.c uvc_h264.c) + + set(${MODULE_PREFIX}_LIBS winpr freerdp ${V4L_TARGETS}) + + include_directories(..) + + add_channel_client_subsystem_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} "" TRUE "") + +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/camera_v4l.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/camera_v4l.h new file mode 100644 index 0000000000000000000000000000000000000000..8f1a32fec16325fd084a71411fdf1aa19b476ad1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/camera_v4l.h @@ -0,0 +1,54 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MS-RDPECAM Implementation, V4L Interface + * + * Copyright 2025 Oleg Turovski + * + * 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 CAMERA_V4L_H +#define CAMERA_V4L_H + +#include +#include + +#include "../camera.h" + +typedef struct +{ + void* start; + size_t length; + +} CamV4lBuffer; + +typedef struct +{ + CRITICAL_SECTION lock; + + /* members used to call the callback */ + CameraDevice* dev; + int streamIndex; + ICamHalSampleCapturedCallback sampleCallback; + + BOOL streaming; + int fd; + uint8_t h264UnitId; /* UVC H264 UnitId, if 0 then UVC H264 is not supported */ + + size_t nBuffers; + CamV4lBuffer* buffers; + HANDLE captureThread; + +} CamV4lStream; + +#endif /* CAMERA_V4L_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/uvc_h264.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/uvc_h264.h new file mode 100644 index 0000000000000000000000000000000000000000..c8a4e3ce402df7a6863923f591833c8698316b45 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpecam/client/v4l/uvc_h264.h @@ -0,0 +1,169 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MS-RDPECAM Implementation, UVC H264 support + * + * See USB_Video_Payload_H 264_1 0.pdf for more details + * + * Credits: + * guvcview http://guvcview.sourceforge.net + * Paulo Assis + * + * Copyright 2025 Oleg Turovski + * + * 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 UVC_H264_H +#define UVC_H264_H + +#include + +#include "../camera.h" +#include "camera_v4l.h" + +/* UVC H.264 control selectors */ +#define UVCX_VIDEO_CONFIG_PROBE 0x01 +#define UVCX_VIDEO_CONFIG_COMMIT 0x02 +#define UVCX_RATE_CONTROL_MODE 0x03 +#define UVCX_TEMPORAL_SCALE_MODE 0x04 +#define UVCX_SPATIAL_SCALE_MODE 0x05 +#define UVCX_SNR_SCALE_MODE 0x06 +#define UVCX_LTR_BUFFER_SIZE_CONTROL 0x07 +#define UVCX_LTR_PICTURE_CONTROL 0x08 +#define UVCX_PICTURE_TYPE_CONTROL 0x09 +#define UVCX_VERSION 0x0A +#define UVCX_ENCODER_RESET 0x0B +#define UVCX_FRAMERATE_CONFIG 0x0C +#define UVCX_VIDEO_ADVANCE_CONFIG 0x0D +#define UVCX_BITRATE_LAYERS 0x0E +#define UVCX_QP_STEPS_LAYERS 0x0F + +/* Video Class-Specific Request Codes */ +#define UVC_RC_UNDEFINED 0x00 +#define UVC_SET_CUR 0x01 +#define UVC_GET_CUR 0x81 +#define UVC_GET_MIN 0x82 +#define UVC_GET_MAX 0x83 +#define UVC_GET_RES 0x84 +#define UVC_GET_LEN 0x85 +#define UVC_GET_INFO 0x86 +#define UVC_GET_DEF 0x87 + +/* bStreamMuxOption defines */ +#define STREAMMUX_H264 (1 << 0) | (1 << 1) + +/* wProfile defines */ +#define PROFILE_BASELINE 0x4200 +#define PROFILE_MAIN 0x4D00 +#define PROFILE_HIGH 0x6400 + +/* bUsageType defines */ +#define USAGETYPE_REALTIME 0x01 + +/* bRateControlMode defines */ +#define RATECONTROL_CBR 0x01 +#define RATECONTROL_VBR 0x02 +#define RATECONTROL_CONST_QP 0x03 + +/* bEntropyCABAC defines */ +#define ENTROPY_CABAC 0x01 + +/* bmHints defines */ +#define BMHINTS_RESOLUTION 0x0001 +#define BMHINTS_PROFILE 0x0002 +#define BMHINTS_RATECONTROL 0x0004 +#define BMHINTS_USAGE 0x0008 +#define BMHINTS_SLICEMODE 0x0010 +#define BMHINTS_SLICEUNITS 0x0020 +#define BMHINTS_MVCVIEW 0x0040 +#define BMHINTS_TEMPORAL 0x0080 +#define BMHINTS_SNR 0x0100 +#define BMHINTS_SPATIAL 0x0200 +#define BMHINTS_SPATIAL_RATIO 0x0400 +#define BMHINTS_FRAME_INTERVAL 0x0800 +#define BMHINTS_LEAKY_BKT_SIZE 0x1000 +#define BMHINTS_BITRATE 0x2000 +#define BMHINTS_ENTROPY 0x4000 +#define BMHINTS_IFRAMEPERIOD 0x8000 + +/* USB related defines */ +#define USB_VIDEO_CONTROL 0x01 +#define USB_VIDEO_CONTROL_INTERFACE 0x24 +#define USB_VIDEO_CONTROL_XU_TYPE 0x06 + +#define MAX_DEVPATH_DEPTH 8 +#define MAX_DEVPATH_STR_SIZE 32 + +#define WINPR_PACK_PUSH +#include + +/* h264 probe commit struct (uvc 1.1) - packed */ +typedef struct +{ + uint32_t dwFrameInterval; + uint32_t dwBitRate; + uint16_t bmHints; + uint16_t wConfigurationIndex; + uint16_t wWidth; + uint16_t wHeight; + uint16_t wSliceUnits; + uint16_t wSliceMode; + uint16_t wProfile; + uint16_t wIFramePeriod; + uint16_t wEstimatedVideoDelay; + uint16_t wEstimatedMaxConfigDelay; + uint8_t bUsageType; + uint8_t bRateControlMode; + uint8_t bTemporalScaleMode; + uint8_t bSpatialScaleMode; + uint8_t bSNRScaleMode; + uint8_t bStreamMuxOption; + uint8_t bStreamFormat; + uint8_t bEntropyCABAC; + uint8_t bTimestamp; + uint8_t bNumOfReorderFrames; + uint8_t bPreviewFlipped; + uint8_t bView; + uint8_t bReserved1; + uint8_t bReserved2; + uint8_t bStreamID; + uint8_t bSpatialLayerRatio; + uint16_t wLeakyBucketSize; + +} uvcx_video_config_probe_commit_t; + +/* encoder reset struct - packed */ +typedef struct +{ + uint16_t wLayerID; + +} uvcx_encoder_reset; + +/* xu_descriptor struct - packed */ +typedef struct +{ + int8_t bLength; + int8_t bDescriptorType; + int8_t bDescriptorSubType; + int8_t bUnitID; + uint8_t guidExtensionCode[16]; + +} xu_descriptor; + +#define WINPR_PACK_POP +#include + +uint8_t get_uvc_h624_unit_id(const char* deviceId); +BOOL set_h264_muxed_format(CamV4lStream* stream, const CAM_MEDIA_TYPE_DESCRIPTION* mediaType); + +#endif /* UVC_H264_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1b153a794b0bb60d85bdb417cc6a32e30f032653 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/CMakeLists.txt @@ -0,0 +1,25 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2013 Marc-Andre Moreau +# +# 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. + +define_channel_client("rdpei") + +set(${MODULE_PREFIX}_SRCS rdpei_main.c rdpei_main.h ../rdpei_common.c ../rdpei_common.h) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) +include_directories(..) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.c new file mode 100644 index 0000000000000000000000000000000000000000..db5a80c957337a4fab9384a41dee9af6fee3ab8a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.c @@ -0,0 +1,1596 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Input Virtual Channel Extension + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "rdpei_common.h" + +#include "rdpei_main.h" + +#define RDPEI_TAG CHANNELS_TAG("rdpei.client") + +/** + * Touch Input + * http://msdn.microsoft.com/en-us/library/windows/desktop/dd562197/ + * + * Windows Touch Input + * http://msdn.microsoft.com/en-us/library/windows/desktop/dd317321/ + * + * Input: Touch injection sample + * http://code.msdn.microsoft.com/windowsdesktop/Touch-Injection-Sample-444d9bf7 + * + * Pointer Input Message Reference + * http://msdn.microsoft.com/en-us/library/hh454916/ + * + * POINTER_INFO Structure + * http://msdn.microsoft.com/en-us/library/hh454907/ + * + * POINTER_TOUCH_INFO Structure + * http://msdn.microsoft.com/en-us/library/hh454910/ + */ + +#define MAX_CONTACTS 64 +#define MAX_PEN_CONTACTS 4 + +typedef struct +{ + GENERIC_DYNVC_PLUGIN base; + + RdpeiClientContext* context; + + UINT32 version; + UINT32 features; /* SC_READY_MULTIPEN_INJECTION_SUPPORTED */ + UINT16 maxTouchContacts; + UINT64 currentFrameTime; + UINT64 previousFrameTime; + RDPINPUT_CONTACT_POINT contactPoints[MAX_CONTACTS]; + + UINT64 currentPenFrameTime; + UINT64 previousPenFrameTime; + UINT16 maxPenContacts; + RDPINPUT_PEN_CONTACT_POINT penContactPoints[MAX_PEN_CONTACTS]; + + CRITICAL_SECTION lock; + rdpContext* rdpcontext; + + HANDLE thread; + + HANDLE event; + UINT64 lastPollEventTime; + BOOL running; + BOOL async; +} RDPEI_PLUGIN; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_send_frame(RdpeiClientContext* context, RDPINPUT_TOUCH_FRAME* frame); + +#ifdef WITH_DEBUG_RDPEI +static const char* rdpei_eventid_string(UINT16 event) +{ + switch (event) + { + case EVENTID_SC_READY: + return "EVENTID_SC_READY"; + case EVENTID_CS_READY: + return "EVENTID_CS_READY"; + case EVENTID_TOUCH: + return "EVENTID_TOUCH"; + case EVENTID_SUSPEND_TOUCH: + return "EVENTID_SUSPEND_TOUCH"; + case EVENTID_RESUME_TOUCH: + return "EVENTID_RESUME_TOUCH"; + case EVENTID_DISMISS_HOVERING_CONTACT: + return "EVENTID_DISMISS_HOVERING_CONTACT"; + case EVENTID_PEN: + return "EVENTID_PEN"; + default: + return "EVENTID_UNKNOWN"; + } +} +#endif + +static RDPINPUT_CONTACT_POINT* rdpei_contact(RDPEI_PLUGIN* rdpei, INT32 externalId, BOOL active) +{ + for (UINT16 i = 0; i < rdpei->maxTouchContacts; i++) + { + RDPINPUT_CONTACT_POINT* contactPoint = &rdpei->contactPoints[i]; + + if (!contactPoint->active && active) + continue; + else if (!contactPoint->active && !active) + { + contactPoint->contactId = i; + contactPoint->externalId = externalId; + contactPoint->active = TRUE; + return contactPoint; + } + else if (contactPoint->externalId == externalId) + { + return contactPoint; + } + } + return NULL; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_add_frame(RdpeiClientContext* context) +{ + RDPEI_PLUGIN* rdpei = NULL; + RDPINPUT_TOUCH_FRAME frame = { 0 }; + RDPINPUT_CONTACT_DATA contacts[MAX_CONTACTS] = { 0 }; + + if (!context || !context->handle) + return ERROR_INTERNAL_ERROR; + + rdpei = (RDPEI_PLUGIN*)context->handle; + frame.contacts = contacts; + + for (UINT16 i = 0; i < rdpei->maxTouchContacts; i++) + { + RDPINPUT_CONTACT_POINT* contactPoint = &rdpei->contactPoints[i]; + RDPINPUT_CONTACT_DATA* contact = &contactPoint->data; + + if (contactPoint->dirty) + { + contacts[frame.contactCount] = *contact; + rdpei->contactPoints[i].dirty = FALSE; + frame.contactCount++; + } + else if (contactPoint->active) + { + if (contact->contactFlags & RDPINPUT_CONTACT_FLAG_DOWN) + { + contact->contactFlags = RDPINPUT_CONTACT_FLAG_UPDATE; + contact->contactFlags |= RDPINPUT_CONTACT_FLAG_INRANGE; + contact->contactFlags |= RDPINPUT_CONTACT_FLAG_INCONTACT; + } + + contacts[frame.contactCount] = *contact; + frame.contactCount++; + } + if (contact->contactFlags & RDPINPUT_CONTACT_FLAG_UP) + { + contactPoint->active = FALSE; + contactPoint->externalId = 0; + contactPoint->contactId = 0; + } + } + + if (frame.contactCount > 0) + { + UINT error = rdpei_send_frame(context, &frame); + if (error != CHANNEL_RC_OK) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_send_frame failed with error %" PRIu32 "!", error); + return error; + } + } + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_send_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s, UINT16 eventId, + size_t pduLength) +{ + UINT status = 0; + + if (!callback || !s || !callback->channel || !callback->channel->Write) + return ERROR_INTERNAL_ERROR; + + if (pduLength > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (!rdpei) + return ERROR_INTERNAL_ERROR; + + Stream_SetPosition(s, 0); + Stream_Write_UINT16(s, eventId); /* eventId (2 bytes) */ + Stream_Write_UINT32(s, (UINT32)pduLength); /* pduLength (4 bytes) */ + Stream_SetPosition(s, Stream_Length(s)); + status = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s), + NULL); +#ifdef WITH_DEBUG_RDPEI + WLog_Print(rdpei->base.log, WLOG_DEBUG, + "rdpei_send_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 " status: %" PRIu32 "", + eventId, rdpei_eventid_string(eventId), pduLength, status); +#endif + return status; +} + +static UINT rdpei_write_pen_frame(wStream* s, const RDPINPUT_PEN_FRAME* frame) +{ + if (!s || !frame) + return ERROR_INTERNAL_ERROR; + + if (!rdpei_write_2byte_unsigned(s, frame->contactCount)) + return ERROR_OUTOFMEMORY; + if (!rdpei_write_8byte_unsigned(s, frame->frameOffset)) + return ERROR_OUTOFMEMORY; + for (UINT16 x = 0; x < frame->contactCount; x++) + { + const RDPINPUT_PEN_CONTACT* contact = &frame->contacts[x]; + + if (!Stream_EnsureRemainingCapacity(s, 1)) + return ERROR_OUTOFMEMORY; + Stream_Write_UINT8(s, contact->deviceId); + if (!rdpei_write_2byte_unsigned(s, contact->fieldsPresent)) + return ERROR_OUTOFMEMORY; + if (!rdpei_write_4byte_signed(s, contact->x)) + return ERROR_OUTOFMEMORY; + if (!rdpei_write_4byte_signed(s, contact->y)) + return ERROR_OUTOFMEMORY; + if (!rdpei_write_4byte_unsigned(s, contact->contactFlags)) + return ERROR_OUTOFMEMORY; + if (contact->fieldsPresent & RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT) + { + if (!rdpei_write_4byte_unsigned(s, contact->penFlags)) + return ERROR_OUTOFMEMORY; + } + if (contact->fieldsPresent & RDPINPUT_PEN_CONTACT_PRESSURE_PRESENT) + { + if (!rdpei_write_4byte_unsigned(s, contact->pressure)) + return ERROR_OUTOFMEMORY; + } + if (contact->fieldsPresent & RDPINPUT_PEN_CONTACT_ROTATION_PRESENT) + { + if (!rdpei_write_2byte_unsigned(s, contact->rotation)) + return ERROR_OUTOFMEMORY; + } + if (contact->fieldsPresent & RDPINPUT_PEN_CONTACT_TILTX_PRESENT) + { + if (!rdpei_write_2byte_signed(s, contact->tiltX)) + return ERROR_OUTOFMEMORY; + } + if (contact->fieldsPresent & RDPINPUT_PEN_CONTACT_TILTY_PRESENT) + { + if (!rdpei_write_2byte_signed(s, contact->tiltY)) + return ERROR_OUTOFMEMORY; + } + } + return CHANNEL_RC_OK; +} + +static UINT rdpei_send_pen_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, size_t frameOffset, + const RDPINPUT_PEN_FRAME* frames, size_t count) +{ + UINT status = 0; + wStream* s = NULL; + + WINPR_ASSERT(callback); + + if (frameOffset > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + if (count > UINT16_MAX) + return ERROR_INVALID_PARAMETER; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (!rdpei) + return ERROR_INTERNAL_ERROR; + + if (!frames || (count == 0)) + return ERROR_INTERNAL_ERROR; + + s = Stream_New(NULL, 64); + + if (!s) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Seek(s, RDPINPUT_HEADER_LENGTH); + /** + * the time that has elapsed (in milliseconds) from when the oldest touch frame + * was generated to when it was encoded for transmission by the client. + */ + rdpei_write_4byte_unsigned(s, + (UINT32)frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_2byte_unsigned(s, (UINT16)count); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */ + + for (size_t x = 0; x < count; x++) + { + if ((status = rdpei_write_pen_frame(s, &frames[x]))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_write_pen_frame failed with error %" PRIu32 "!", status); + Stream_Free(s, TRUE); + return status; + } + } + Stream_SealLength(s); + + status = rdpei_send_pdu(callback, s, EVENTID_PEN, Stream_Length(s)); + Stream_Free(s, TRUE); + return status; +} + +static UINT rdpei_send_pen_frame(RdpeiClientContext* context, RDPINPUT_PEN_FRAME* frame) +{ + const UINT64 currentTime = GetTickCount64(); + RDPEI_PLUGIN* rdpei = NULL; + GENERIC_CHANNEL_CALLBACK* callback = NULL; + UINT error = 0; + + if (!context) + return ERROR_INTERNAL_ERROR; + rdpei = (RDPEI_PLUGIN*)context->handle; + if (!rdpei || !rdpei->base.listener_callback) + return ERROR_INTERNAL_ERROR; + if (!rdpei || !rdpei->rdpcontext) + return ERROR_INTERNAL_ERROR; + if (freerdp_settings_get_bool(rdpei->rdpcontext->settings, FreeRDP_SuspendInput)) + return CHANNEL_RC_OK; + + callback = rdpei->base.listener_callback->channel_callback; + /* Just ignore the event if the channel is not connected */ + if (!callback) + return CHANNEL_RC_OK; + + if (!rdpei->previousPenFrameTime && !rdpei->currentPenFrameTime) + { + rdpei->currentPenFrameTime = currentTime; + frame->frameOffset = 0; + } + else + { + rdpei->currentPenFrameTime = currentTime; + frame->frameOffset = rdpei->currentPenFrameTime - rdpei->previousPenFrameTime; + } + + if ((error = rdpei_send_pen_event_pdu(callback, frame->frameOffset, frame, 1))) + return error; + + rdpei->previousPenFrameTime = rdpei->currentPenFrameTime; + return error; +} + +static UINT rdpei_add_pen_frame(RdpeiClientContext* context) +{ + RDPEI_PLUGIN* rdpei = NULL; + RDPINPUT_PEN_FRAME penFrame = { 0 }; + RDPINPUT_PEN_CONTACT penContacts[MAX_PEN_CONTACTS] = { 0 }; + + if (!context || !context->handle) + return ERROR_INTERNAL_ERROR; + + rdpei = (RDPEI_PLUGIN*)context->handle; + + penFrame.contacts = penContacts; + + for (UINT16 i = 0; i < rdpei->maxPenContacts; i++) + { + RDPINPUT_PEN_CONTACT_POINT* contact = &(rdpei->penContactPoints[i]); + + if (contact->dirty) + { + penContacts[penFrame.contactCount++] = contact->data; + contact->dirty = FALSE; + } + else if (contact->active) + { + if (contact->data.contactFlags & RDPINPUT_CONTACT_FLAG_DOWN) + { + contact->data.contactFlags = RDPINPUT_CONTACT_FLAG_UPDATE; + contact->data.contactFlags |= RDPINPUT_CONTACT_FLAG_INRANGE; + contact->data.contactFlags |= RDPINPUT_CONTACT_FLAG_INCONTACT; + } + + penContacts[penFrame.contactCount++] = contact->data; + } + if (contact->data.contactFlags & RDPINPUT_CONTACT_FLAG_CANCELED) + { + contact->externalId = 0; + contact->active = FALSE; + } + } + + if (penFrame.contactCount > 0) + return rdpei_send_pen_frame(context, &penFrame); + return CHANNEL_RC_OK; +} + +static UINT rdpei_update(wLog* log, RdpeiClientContext* context) +{ + UINT error = rdpei_add_frame(context); + if (error != CHANNEL_RC_OK) + { + WLog_Print(log, WLOG_ERROR, "rdpei_add_frame failed with error %" PRIu32 "!", error); + return error; + } + + return rdpei_add_pen_frame(context); +} + +static BOOL rdpei_poll_run_unlocked(rdpContext* context, void* userdata) +{ + RDPEI_PLUGIN* rdpei = userdata; + WINPR_ASSERT(rdpei); + WINPR_ASSERT(context); + + const UINT64 now = GetTickCount64(); + + /* Send an event every ~20ms */ + if ((now < rdpei->lastPollEventTime) || (now - rdpei->lastPollEventTime < 20ULL)) + return TRUE; + + rdpei->lastPollEventTime = now; + + const UINT error = rdpei_update(rdpei->base.log, rdpei->context); + + (void)ResetEvent(rdpei->event); + + if (error != CHANNEL_RC_OK) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "rdpei_add_frame failed with error %" PRIu32 "!", + error); + setChannelError(context, error, "rdpei_add_frame reported an error"); + return FALSE; + } + + return TRUE; +} + +static BOOL rdpei_poll_run(rdpContext* context, void* userdata) +{ + RDPEI_PLUGIN* rdpei = userdata; + WINPR_ASSERT(rdpei); + + EnterCriticalSection(&rdpei->lock); + BOOL rc = rdpei_poll_run_unlocked(context, userdata); + LeaveCriticalSection(&rdpei->lock); + return rc; +} + +static DWORD WINAPI rdpei_periodic_update(LPVOID arg) +{ + DWORD status = 0; + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)arg; + UINT error = CHANNEL_RC_OK; + RdpeiClientContext* context = NULL; + + if (!rdpei) + { + error = ERROR_INVALID_PARAMETER; + goto out; + } + + context = rdpei->context; + + if (!context) + { + error = ERROR_INVALID_PARAMETER; + goto out; + } + + while (rdpei->running) + { + status = WaitForSingleObject(rdpei->event, 20); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_Print(rdpei->base.log, WLOG_ERROR, + "WaitForMultipleObjects failed with error %" PRIu32 "!", error); + break; + } + + if (!rdpei_poll_run(rdpei->rdpcontext, rdpei)) + error = ERROR_INTERNAL_ERROR; + } + +out: + + if (error && rdpei && rdpei->rdpcontext) + setChannelError(rdpei->rdpcontext, error, "rdpei_schedule_thread reported an error"); + + if (rdpei) + rdpei->running = FALSE; + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_send_cs_ready_pdu(GENERIC_CHANNEL_CALLBACK* callback) +{ + UINT status = 0; + wStream* s = NULL; + UINT32 flags = 0; + UINT32 pduLength = 0; + RDPEI_PLUGIN* rdpei = NULL; + + if (!callback || !callback->plugin) + return ERROR_INTERNAL_ERROR; + rdpei = (RDPEI_PLUGIN*)callback->plugin; + + flags |= CS_READY_FLAGS_SHOW_TOUCH_VISUALS & rdpei->context->clientFeaturesMask; + if (rdpei->version > RDPINPUT_PROTOCOL_V10) + flags |= CS_READY_FLAGS_DISABLE_TIMESTAMP_INJECTION & rdpei->context->clientFeaturesMask; + if (rdpei->features & SC_READY_MULTIPEN_INJECTION_SUPPORTED) + flags |= CS_READY_FLAGS_ENABLE_MULTIPEN_INJECTION & rdpei->context->clientFeaturesMask; + + pduLength = RDPINPUT_HEADER_LENGTH + 10; + s = Stream_New(NULL, pduLength); + + if (!s) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Seek(s, RDPINPUT_HEADER_LENGTH); + Stream_Write_UINT32(s, flags); /* flags (4 bytes) */ + Stream_Write_UINT32(s, rdpei->version); /* protocolVersion (4 bytes) */ + Stream_Write_UINT16(s, rdpei->maxTouchContacts); /* maxTouchContacts (2 bytes) */ + Stream_SealLength(s); + status = rdpei_send_pdu(callback, s, EVENTID_CS_READY, pduLength); + Stream_Free(s, TRUE); + return status; +} + +#if defined(WITH_DEBUG_RDPEI) +static void rdpei_print_contact_flags(wLog* log, UINT32 contactFlags) +{ + if (contactFlags & RDPINPUT_CONTACT_FLAG_DOWN) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_DOWN"); + + if (contactFlags & RDPINPUT_CONTACT_FLAG_UPDATE) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_UPDATE"); + + if (contactFlags & RDPINPUT_CONTACT_FLAG_UP) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_UP"); + + if (contactFlags & RDPINPUT_CONTACT_FLAG_INRANGE) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_INRANGE"); + + if (contactFlags & RDPINPUT_CONTACT_FLAG_INCONTACT) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_INCONTACT"); + + if (contactFlags & RDPINPUT_CONTACT_FLAG_CANCELED) + WLog_Print(log, WLOG_DEBUG, " RDPINPUT_CONTACT_FLAG_CANCELED"); +} +#endif + +static INT16 bounded(INT32 val) +{ + if (val < INT16_MIN) + return INT16_MIN; + if (val > INT16_MAX) + return INT16_MAX; + return (INT16)val; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_write_touch_frame(wLog* log, wStream* s, RDPINPUT_TOUCH_FRAME* frame) +{ + int rectSize = 2; + RDPINPUT_CONTACT_DATA* contact = NULL; + if (!s || !frame) + return ERROR_INTERNAL_ERROR; +#ifdef WITH_DEBUG_RDPEI + WLog_Print(log, WLOG_DEBUG, "contactCount: %" PRIu32 "", frame->contactCount); + WLog_Print(log, WLOG_DEBUG, "frameOffset: 0x%016" PRIX64 "", frame->frameOffset); +#endif + rdpei_write_2byte_unsigned(s, + frame->contactCount); /* contactCount (TWO_BYTE_UNSIGNED_INTEGER) */ + /** + * the time offset from the previous frame (in microseconds). + * If this is the first frame being transmitted then this field MUST be set to zero. + */ + rdpei_write_8byte_unsigned(s, frame->frameOffset * + 1000); /* frameOffset (EIGHT_BYTE_UNSIGNED_INTEGER) */ + + if (!Stream_EnsureRemainingCapacity(s, (size_t)frame->contactCount * 64)) + { + WLog_Print(log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + for (UINT32 index = 0; index < frame->contactCount; index++) + { + contact = &frame->contacts[index]; + contact->fieldsPresent |= CONTACT_DATA_CONTACTRECT_PRESENT; + contact->contactRectLeft = bounded(contact->x - rectSize); + contact->contactRectTop = bounded(contact->y - rectSize); + contact->contactRectRight = bounded(contact->x + rectSize); + contact->contactRectBottom = bounded(contact->y + rectSize); +#ifdef WITH_DEBUG_RDPEI + WLog_Print(log, WLOG_DEBUG, "contact[%" PRIu32 "].contactId: %" PRIu32 "", index, + contact->contactId); + WLog_Print(log, WLOG_DEBUG, "contact[%" PRIu32 "].fieldsPresent: %" PRIu32 "", index, + contact->fieldsPresent); + WLog_Print(log, WLOG_DEBUG, "contact[%" PRIu32 "].x: %" PRId32 "", index, contact->x); + WLog_Print(log, WLOG_DEBUG, "contact[%" PRIu32 "].y: %" PRId32 "", index, contact->y); + WLog_Print(log, WLOG_DEBUG, "contact[%" PRIu32 "].contactFlags: 0x%08" PRIX32 "", index, + contact->contactFlags); + rdpei_print_contact_flags(log, contact->contactFlags); +#endif + Stream_Write_UINT8( + s, WINPR_ASSERTING_INT_CAST(uint8_t, contact->contactId)); /* contactId (1 byte) */ + /* fieldsPresent (TWO_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_2byte_unsigned(s, contact->fieldsPresent); + rdpei_write_4byte_signed(s, contact->x); /* x (FOUR_BYTE_SIGNED_INTEGER) */ + rdpei_write_4byte_signed(s, contact->y); /* y (FOUR_BYTE_SIGNED_INTEGER) */ + /* contactFlags (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_4byte_unsigned(s, contact->contactFlags); + + if (contact->fieldsPresent & CONTACT_DATA_CONTACTRECT_PRESENT) + { + /* contactRectLeft (TWO_BYTE_SIGNED_INTEGER) */ + rdpei_write_2byte_signed(s, contact->contactRectLeft); + /* contactRectTop (TWO_BYTE_SIGNED_INTEGER) */ + rdpei_write_2byte_signed(s, contact->contactRectTop); + /* contactRectRight (TWO_BYTE_SIGNED_INTEGER) */ + rdpei_write_2byte_signed(s, contact->contactRectRight); + /* contactRectBottom (TWO_BYTE_SIGNED_INTEGER) */ + rdpei_write_2byte_signed(s, contact->contactRectBottom); + } + + if (contact->fieldsPresent & CONTACT_DATA_ORIENTATION_PRESENT) + { + /* orientation (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_4byte_unsigned(s, contact->orientation); + } + + if (contact->fieldsPresent & CONTACT_DATA_PRESSURE_PRESENT) + { + /* pressure (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_4byte_unsigned(s, contact->pressure); + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_send_touch_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, + RDPINPUT_TOUCH_FRAME* frame) +{ + UINT status = 0; + + WINPR_ASSERT(callback); + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (!rdpei || !rdpei->rdpcontext) + return ERROR_INTERNAL_ERROR; + if (freerdp_settings_get_bool(rdpei->rdpcontext->settings, FreeRDP_SuspendInput)) + return CHANNEL_RC_OK; + + if (!frame) + return ERROR_INTERNAL_ERROR; + + size_t pduLength = 64ULL + (64ULL * frame->contactCount); + wStream* s = Stream_New(NULL, pduLength); + + if (!s) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Seek(s, RDPINPUT_HEADER_LENGTH); + /** + * the time that has elapsed (in milliseconds) from when the oldest touch frame + * was generated to when it was encoded for transmission by the client. + */ + rdpei_write_4byte_unsigned( + s, (UINT32)frame->frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_2byte_unsigned(s, 1); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */ + + status = rdpei_write_touch_frame(rdpei->base.log, s, frame); + if (status) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_write_touch_frame failed with error %" PRIu32 "!", status); + Stream_Free(s, TRUE); + return status; + } + + Stream_SealLength(s); + status = rdpei_send_pdu(callback, s, EVENTID_TOUCH, Stream_Length(s)); + Stream_Free(s, TRUE); + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_recv_sc_ready_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT32 features = 0; + UINT32 protocolVersion = 0; + + if (!callback || !callback->plugin) + return ERROR_INTERNAL_ERROR; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpei->base.log, s, 4)) + return ERROR_INVALID_DATA; + Stream_Read_UINT32(s, protocolVersion); /* protocolVersion (4 bytes) */ + + if (protocolVersion >= RDPINPUT_PROTOCOL_V300) + { + if (!Stream_CheckAndLogRequiredLengthWLog(rdpei->base.log, s, 4)) + return ERROR_INVALID_DATA; + } + + if (Stream_GetRemainingLength(s) >= 4) + Stream_Read_UINT32(s, features); + + if (rdpei->version > protocolVersion) + rdpei->version = protocolVersion; + rdpei->features = features; +#if 0 + + if (protocolVersion != RDPINPUT_PROTOCOL_V10) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "Unknown [MS-RDPEI] protocolVersion: 0x%08"PRIX32"", protocolVersion); + return -1; + } + +#endif + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_recv_suspend_touch_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + + WINPR_UNUSED(s); + + if (!callback || !callback->plugin) + return ERROR_INTERNAL_ERROR; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + RdpeiClientContext* context = rdpei->context; + if (!rdpei) + return ERROR_INTERNAL_ERROR; + + IFCALLRET(context->SuspendTouch, error, context); + + if (error) + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei->SuspendTouch failed with error %" PRIu32 "!", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_recv_resume_touch_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + if (!s || !callback) + return ERROR_INTERNAL_ERROR; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (!rdpei) + return ERROR_INTERNAL_ERROR; + + RdpeiClientContext* context = (RdpeiClientContext*)callback->plugin->pInterface; + if (!context) + return ERROR_INTERNAL_ERROR; + + IFCALLRET(context->ResumeTouch, error, context); + + if (error) + WLog_Print(rdpei->base.log, WLOG_ERROR, "rdpei->ResumeTouch failed with error %" PRIu32 "!", + error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_recv_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s) +{ + UINT16 eventId = 0; + UINT32 pduLength = 0; + UINT error = 0; + + if (!callback || !s) + return ERROR_INTERNAL_ERROR; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (!rdpei) + return ERROR_INTERNAL_ERROR; + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpei->base.log, s, 6)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, eventId); /* eventId (2 bytes) */ + Stream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */ +#ifdef WITH_DEBUG_RDPEI + WLog_Print(rdpei->base.log, WLOG_DEBUG, + "rdpei_recv_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 "", eventId, + rdpei_eventid_string(eventId), pduLength); +#endif + + if ((pduLength < 6) || !Stream_CheckAndLogRequiredLengthWLog(rdpei->base.log, s, pduLength - 6)) + return ERROR_INVALID_DATA; + + switch (eventId) + { + case EVENTID_SC_READY: + if ((error = rdpei_recv_sc_ready_pdu(callback, s))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_recv_sc_ready_pdu failed with error %" PRIu32 "!", error); + return error; + } + + if ((error = rdpei_send_cs_ready_pdu(callback))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_send_cs_ready_pdu failed with error %" PRIu32 "!", error); + return error; + } + + break; + + case EVENTID_SUSPEND_TOUCH: + if ((error = rdpei_recv_suspend_touch_pdu(callback, s))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_recv_suspend_touch_pdu failed with error %" PRIu32 "!", error); + return error; + } + + break; + + case EVENTID_RESUME_TOUCH: + if ((error = rdpei_recv_resume_touch_pdu(callback, s))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_recv_resume_touch_pdu failed with error %" PRIu32 "!", error); + return error; + } + + break; + + default: + break; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + return rdpei_recv_pdu(callback, data); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + if (callback) + { + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; + if (rdpei && rdpei->base.listener_callback) + { + if (rdpei->base.listener_callback->channel_callback == callback) + rdpei->base.listener_callback->channel_callback = NULL; + } + } + free(callback); + return CHANNEL_RC_OK; +} + +/** + * Channel Client Interface + */ + +static UINT32 rdpei_get_version(RdpeiClientContext* context) +{ + RDPEI_PLUGIN* rdpei = NULL; + if (!context || !context->handle) + return 0; + rdpei = (RDPEI_PLUGIN*)context->handle; + return rdpei->version; +} + +static UINT32 rdpei_get_features(RdpeiClientContext* context) +{ + RDPEI_PLUGIN* rdpei = NULL; + if (!context || !context->handle) + return 0; + rdpei = (RDPEI_PLUGIN*)context->handle; + return rdpei->features; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_send_frame(RdpeiClientContext* context, RDPINPUT_TOUCH_FRAME* frame) +{ + UINT64 currentTime = GetTickCount64(); + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle; + GENERIC_CHANNEL_CALLBACK* callback = NULL; + UINT error = 0; + + callback = rdpei->base.listener_callback->channel_callback; + + /* Just ignore the event if the channel is not connected */ + if (!callback) + return CHANNEL_RC_OK; + + if (!rdpei->previousFrameTime && !rdpei->currentFrameTime) + { + rdpei->currentFrameTime = currentTime; + frame->frameOffset = 0; + } + else + { + rdpei->currentFrameTime = currentTime; + frame->frameOffset = rdpei->currentFrameTime - rdpei->previousFrameTime; + } + + if ((error = rdpei_send_touch_event_pdu(callback, frame))) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, + "rdpei_send_touch_event_pdu failed with error %" PRIu32 "!", error); + return error; + } + + rdpei->previousFrameTime = rdpei->currentFrameTime; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_add_contact(RdpeiClientContext* context, const RDPINPUT_CONTACT_DATA* contact) +{ + RDPINPUT_CONTACT_POINT* contactPoint = NULL; + RDPEI_PLUGIN* rdpei = NULL; + if (!context || !contact || !context->handle) + return ERROR_INTERNAL_ERROR; + + rdpei = (RDPEI_PLUGIN*)context->handle; + + EnterCriticalSection(&rdpei->lock); + contactPoint = &rdpei->contactPoints[contact->contactId]; + contactPoint->data = *contact; + contactPoint->dirty = TRUE; + (void)SetEvent(rdpei->event); + LeaveCriticalSection(&rdpei->lock); + + return CHANNEL_RC_OK; +} + +static UINT rdpei_touch_process(RdpeiClientContext* context, INT32 externalId, UINT32 contactFlags, + INT32 x, INT32 y, INT32* contactId, UINT32 fieldFlags, va_list ap) +{ + INT64 contactIdlocal = -1; + RDPINPUT_CONTACT_POINT* contactPoint = NULL; + UINT error = CHANNEL_RC_OK; + + if (!context || !contactId || !context->handle) + return ERROR_INTERNAL_ERROR; + + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle; + /* Create a new contact point in an empty slot */ + EnterCriticalSection(&rdpei->lock); + const BOOL begin = (contactFlags & RDPINPUT_CONTACT_FLAG_DOWN) != 0; + contactPoint = rdpei_contact(rdpei, externalId, !begin); + if (contactPoint) + contactIdlocal = contactPoint->contactId; + LeaveCriticalSection(&rdpei->lock); + + if (contactIdlocal > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + + if (contactIdlocal >= 0) + { + RDPINPUT_CONTACT_DATA contact = { 0 }; + contact.x = x; + contact.y = y; + contact.contactId = (UINT32)contactIdlocal; + contact.contactFlags = contactFlags; + contact.fieldsPresent = WINPR_ASSERTING_INT_CAST(UINT16, fieldFlags); + + if (fieldFlags & CONTACT_DATA_CONTACTRECT_PRESENT) + { + INT32 val = va_arg(ap, INT32); + contact.contactRectLeft = WINPR_ASSERTING_INT_CAST(INT16, val); + + val = va_arg(ap, INT32); + contact.contactRectTop = WINPR_ASSERTING_INT_CAST(INT16, val); + + val = va_arg(ap, INT32); + contact.contactRectRight = WINPR_ASSERTING_INT_CAST(INT16, val); + + val = va_arg(ap, INT32); + contact.contactRectBottom = WINPR_ASSERTING_INT_CAST(INT16, val); + } + if (fieldFlags & CONTACT_DATA_ORIENTATION_PRESENT) + { + UINT32 p = va_arg(ap, UINT32); + if (p >= 360) + { + WLog_Print(rdpei->base.log, WLOG_WARN, + "TouchContact %" PRId64 ": Invalid orientation value %" PRIu32 + "degree, clamping to 359 degree", + contactIdlocal, p); + p = 359; + } + contact.orientation = p; + } + if (fieldFlags & CONTACT_DATA_PRESSURE_PRESENT) + { + UINT32 p = va_arg(ap, UINT32); + if (p > 1024) + { + WLog_Print(rdpei->base.log, WLOG_WARN, + "TouchContact %" PRId64 ": Invalid pressure value %" PRIu32 + ", clamping to 1024", + contactIdlocal, p); + p = 1024; + } + contact.pressure = p; + } + + error = context->AddContact(context, &contact); + } + + if (contactId) + *contactId = (INT32)contactIdlocal; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_touch_begin(RdpeiClientContext* context, INT32 externalId, INT32 x, INT32 y, + INT32* contactId) +{ + UINT rc = 0; + va_list ap = { 0 }; + rc = rdpei_touch_process(context, externalId, + RDPINPUT_CONTACT_FLAG_DOWN | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + x, y, contactId, 0, ap); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_touch_update(RdpeiClientContext* context, INT32 externalId, INT32 x, INT32 y, + INT32* contactId) +{ + UINT rc = 0; + va_list ap = { 0 }; + rc = rdpei_touch_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + x, y, contactId, 0, ap); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_touch_end(RdpeiClientContext* context, INT32 externalId, INT32 x, INT32 y, + INT32* contactId) +{ + UINT error = 0; + va_list ap = { 0 }; + error = rdpei_touch_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + x, y, contactId, 0, ap); + if (error != CHANNEL_RC_OK) + return error; + error = + rdpei_touch_process(context, externalId, RDPINPUT_CONTACT_FLAG_UP, x, y, contactId, 0, ap); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_touch_cancel(RdpeiClientContext* context, INT32 externalId, INT32 x, INT32 y, + INT32* contactId) +{ + UINT rc = 0; + va_list ap = { 0 }; + rc = rdpei_touch_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UP | RDPINPUT_CONTACT_FLAG_CANCELED, x, y, + contactId, 0, ap); + return rc; +} + +static UINT rdpei_touch_raw_event(RdpeiClientContext* context, INT32 externalId, INT32 x, INT32 y, + INT32* contactId, UINT32 flags, UINT32 fieldFlags, ...) +{ + UINT rc = 0; + va_list ap; + va_start(ap, fieldFlags); + rc = rdpei_touch_process(context, externalId, flags, x, y, contactId, fieldFlags, ap); + va_end(ap); + return rc; +} + +static UINT rdpei_touch_raw_event_va(RdpeiClientContext* context, INT32 externalId, INT32 x, + INT32 y, INT32* contactId, UINT32 flags, UINT32 fieldFlags, + va_list args) +{ + return rdpei_touch_process(context, externalId, flags, x, y, contactId, fieldFlags, args); +} + +static RDPINPUT_PEN_CONTACT_POINT* rdpei_pen_contact(RDPEI_PLUGIN* rdpei, INT32 externalId, + BOOL active) +{ + if (!rdpei) + return NULL; + + for (UINT32 x = 0; x < rdpei->maxPenContacts; x++) + { + RDPINPUT_PEN_CONTACT_POINT* contact = &rdpei->penContactPoints[x]; + if (active) + { + if (contact->active) + { + if (contact->externalId == externalId) + return contact; + } + } + else + { + if (!contact->active) + { + contact->externalId = externalId; + contact->active = TRUE; + return contact; + } + } + } + return NULL; +} + +static UINT rdpei_add_pen(RdpeiClientContext* context, INT32 externalId, + const RDPINPUT_PEN_CONTACT* contact) +{ + RDPEI_PLUGIN* rdpei = NULL; + RDPINPUT_PEN_CONTACT_POINT* contactPoint = NULL; + + if (!context || !contact || !context->handle) + return ERROR_INTERNAL_ERROR; + + rdpei = (RDPEI_PLUGIN*)context->handle; + + EnterCriticalSection(&rdpei->lock); + contactPoint = rdpei_pen_contact(rdpei, externalId, TRUE); + if (contactPoint) + { + contactPoint->data = *contact; + contactPoint->dirty = TRUE; + (void)SetEvent(rdpei->event); + } + LeaveCriticalSection(&rdpei->lock); + + return CHANNEL_RC_OK; +} + +static UINT rdpei_pen_process(RdpeiClientContext* context, INT32 externalId, UINT32 contactFlags, + UINT32 fieldFlags, INT32 x, INT32 y, va_list ap) +{ + RDPINPUT_PEN_CONTACT_POINT* contactPoint = NULL; + RDPEI_PLUGIN* rdpei = NULL; + UINT error = CHANNEL_RC_OK; + + if (!context || !context->handle) + return ERROR_INTERNAL_ERROR; + + rdpei = (RDPEI_PLUGIN*)context->handle; + + EnterCriticalSection(&rdpei->lock); + // Start a new contact only when it is not active. + contactPoint = rdpei_pen_contact(rdpei, externalId, TRUE); + if (!contactPoint) + { + const UINT32 mask = RDPINPUT_CONTACT_FLAG_INRANGE; + if ((contactFlags & mask) == mask) + { + contactPoint = rdpei_pen_contact(rdpei, externalId, FALSE); + } + } + LeaveCriticalSection(&rdpei->lock); + if (contactPoint != NULL) + { + RDPINPUT_PEN_CONTACT contact = { 0 }; + + contact.x = x; + contact.y = y; + contact.fieldsPresent = WINPR_ASSERTING_INT_CAST(UINT16, fieldFlags); + + contact.contactFlags = contactFlags; + if (fieldFlags & RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT) + { + const UINT32 val = va_arg(ap, UINT32); + contact.penFlags = WINPR_ASSERTING_INT_CAST(UINT16, val); + } + if (fieldFlags & RDPINPUT_PEN_CONTACT_PRESSURE_PRESENT) + { + const UINT32 val = va_arg(ap, UINT32); + contact.pressure = WINPR_ASSERTING_INT_CAST(UINT16, val); + } + if (fieldFlags & RDPINPUT_PEN_CONTACT_ROTATION_PRESENT) + { + const UINT32 val = va_arg(ap, UINT32); + contact.rotation = WINPR_ASSERTING_INT_CAST(UINT16, val); + } + if (fieldFlags & RDPINPUT_PEN_CONTACT_TILTX_PRESENT) + { + const INT32 val = va_arg(ap, INT32); + contact.tiltX = WINPR_ASSERTING_INT_CAST(INT16, val); + } + if (fieldFlags & RDPINPUT_PEN_CONTACT_TILTY_PRESENT) + { + const INT32 val = va_arg(ap, INT32); + WINPR_ASSERT((val >= INT16_MIN) && (val <= INT16_MAX)); + contact.tiltY = WINPR_ASSERTING_INT_CAST(INT16, val); + } + + error = context->AddPen(context, externalId, &contact); + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_begin(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, + INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_DOWN | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + fieldFlags, x, y, ap); + va_end(ap); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_update(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, + INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + fieldFlags, x, y, ap); + va_end(ap); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_end(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, INT32 x, + INT32 y, ...) +{ + UINT error = 0; + va_list ap; + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UP | RDPINPUT_CONTACT_FLAG_INRANGE, fieldFlags, + x, y, ap); + va_end(ap); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_hover_begin(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, + INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE, + fieldFlags, x, y, ap); + va_end(ap); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_hover_update(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, + INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE, + fieldFlags, x, y, ap); + va_end(ap); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT rdpei_pen_hover_cancel(RdpeiClientContext* context, INT32 externalId, UINT32 fieldFlags, + INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_CANCELED, + fieldFlags, x, y, ap); + va_end(ap); + + return error; +} + +static UINT rdpei_pen_raw_event(RdpeiClientContext* context, INT32 externalId, UINT32 contactFlags, + UINT32 fieldFlags, INT32 x, INT32 y, ...) +{ + UINT error = 0; + va_list ap; + + va_start(ap, y); + error = rdpei_pen_process(context, externalId, contactFlags, fieldFlags, x, y, ap); + va_end(ap); + return error; +} + +static UINT rdpei_pen_raw_event_va(RdpeiClientContext* context, INT32 externalId, + UINT32 contactFlags, UINT32 fieldFlags, INT32 x, INT32 y, + va_list args) +{ + return rdpei_pen_process(context, externalId, contactFlags, fieldFlags, x, y, args); +} + +static UINT init_plugin_cb(GENERIC_DYNVC_PLUGIN* base, rdpContext* rcontext, rdpSettings* settings) +{ + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)base; + + WINPR_ASSERT(base); + WINPR_UNUSED(settings); + + rdpei->version = RDPINPUT_PROTOCOL_V300; + rdpei->currentFrameTime = 0; + rdpei->previousFrameTime = 0; + rdpei->maxTouchContacts = MAX_CONTACTS; + rdpei->maxPenContacts = MAX_PEN_CONTACTS; + rdpei->rdpcontext = rcontext; + + WINPR_ASSERT(rdpei->base.log); + + InitializeCriticalSection(&rdpei->lock); + rdpei->event = CreateEventA(NULL, TRUE, FALSE, NULL); + if (!rdpei->event) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + RdpeiClientContext* context = (RdpeiClientContext*)calloc(1, sizeof(RdpeiClientContext)); + if (!context) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + context->clientFeaturesMask = UINT32_MAX; + context->handle = (void*)rdpei; + context->GetVersion = rdpei_get_version; + context->GetFeatures = rdpei_get_features; + context->AddContact = rdpei_add_contact; + context->TouchBegin = rdpei_touch_begin; + context->TouchUpdate = rdpei_touch_update; + context->TouchEnd = rdpei_touch_end; + context->TouchCancel = rdpei_touch_cancel; + context->TouchRawEvent = rdpei_touch_raw_event; + context->TouchRawEventVA = rdpei_touch_raw_event_va; + context->AddPen = rdpei_add_pen; + context->PenBegin = rdpei_pen_begin; + context->PenUpdate = rdpei_pen_update; + context->PenEnd = rdpei_pen_end; + context->PenHoverBegin = rdpei_pen_hover_begin; + context->PenHoverUpdate = rdpei_pen_hover_update; + context->PenHoverCancel = rdpei_pen_hover_cancel; + context->PenRawEvent = rdpei_pen_raw_event; + context->PenRawEventVA = rdpei_pen_raw_event_va; + + rdpei->context = context; + rdpei->base.iface.pInterface = (void*)context; + + rdpei->async = + !freerdp_settings_get_bool(rdpei->rdpcontext->settings, FreeRDP_SynchronousDynamicChannels); + if (rdpei->async) + { + rdpei->running = TRUE; + + rdpei->thread = CreateThread(NULL, 0, rdpei_periodic_update, rdpei, 0, NULL); + if (!rdpei->thread) + { + WLog_Print(rdpei->base.log, WLOG_ERROR, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + else + { + if (!freerdp_client_channel_register(rdpei->rdpcontext->channels, rdpei->event, + rdpei_poll_run, rdpei)) + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +static void terminate_plugin_cb(GENERIC_DYNVC_PLUGIN* base) +{ + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)base; + WINPR_ASSERT(rdpei); + + rdpei->running = FALSE; + if (rdpei->event) + (void)SetEvent(rdpei->event); + + if (rdpei->thread) + { + (void)WaitForSingleObject(rdpei->thread, INFINITE); + (void)CloseHandle(rdpei->thread); + } + + if (rdpei->event && !rdpei->async) + (void)freerdp_client_channel_unregister(rdpei->rdpcontext->channels, rdpei->event); + + if (rdpei->event) + (void)CloseHandle(rdpei->event); + + DeleteCriticalSection(&rdpei->lock); + free(rdpei->context); +} + +static const IWTSVirtualChannelCallback geometry_callbacks = { rdpei_on_data_received, + NULL, /* Open */ + rdpei_on_close, NULL }; + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE rdpei_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + return freerdp_generic_DVCPluginEntry(pEntryPoints, RDPEI_TAG, RDPEI_DVC_CHANNEL_NAME, + sizeof(RDPEI_PLUGIN), sizeof(GENERIC_CHANNEL_CALLBACK), + &geometry_callbacks, init_plugin_cb, terminate_plugin_cb); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.h new file mode 100644 index 0000000000000000000000000000000000000000..c46709ab61b03ab34c9fe2bd41627a73c3237a87 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/client/rdpei_main.h @@ -0,0 +1,87 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Input Virtual Channel Extension + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 FREERDP_CHANNEL_RDPEI_CLIENT_MAIN_H +#define FREERDP_CHANNEL_RDPEI_CLIENT_MAIN_H + +#include + +#include +#include +#include +#include + +#include +#include + +/** + * Touch Contact State Transitions + * + * ENGAGED -> UPDATE | INRANGE | INCONTACT -> ENGAGED + * ENGAGED -> UP | INRANGE -> HOVERING + * ENGAGED -> UP -> OUT_OF_RANGE + * ENGAGED -> UP | CANCELED -> OUT_OF_RANGE + * + * HOVERING -> UPDATE | INRANGE -> HOVERING + * HOVERING -> DOWN | INRANGE | INCONTACT -> ENGAGED + * HOVERING -> UPDATE -> OUT_OF_RANGE + * HOVERING -> UPDATE | CANCELED -> OUT_OF_RANGE + * + * OUT_OF_RANGE -> DOWN | INRANGE | INCONTACT -> ENGAGED + * OUT_OF_RANGE -> UPDATE | INRANGE -> HOVERING + * + * When a contact is in the "hovering" or "engaged" state, it is referred to as being "active". + * "Hovering" contacts are in range of the digitizer, while "engaged" contacts are in range of + * the digitizer and in contact with the digitizer surface. MS-RDPEI remotes only active contacts + * and contacts that are transitioning to the "out of range" state; see section 2.2.3.3.1.1 for + * an enumeration of valid state flags combinations. + * + * When transitioning from the "engaged" state to the "hovering" state, or from the "engaged" + * state to the "out of range" state, the contact position cannot change; it is only allowed + * to change after the transition has taken place. + * + */ + +typedef struct +{ + BOOL dirty; + BOOL active; + UINT32 contactId; + INT32 externalId; + RDPINPUT_CONTACT_DATA data; +} RDPINPUT_CONTACT_POINT; + +typedef struct +{ + BOOL dirty; + BOOL active; + INT32 externalId; + RDPINPUT_PEN_CONTACT data; +} RDPINPUT_PEN_CONTACT_POINT; + +#ifdef WITH_DEBUG_DVC +#define DEBUG_DVC(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_DVC(...) \ + do \ + { \ + } while (0) +#endif + +#endif /* FREERDP_CHANNEL_RDPEI_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..346c2ffd7131b565eec32c0acca7e244b1ea6716 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/CMakeLists.txt @@ -0,0 +1,25 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2014 Thincast Technologies Gmbh. +# Copyright 2014 David FORT +# +# 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. + +define_channel_server("rdpei") + +set(${MODULE_PREFIX}_SRCS rdpei_main.c rdpei_main.h ../rdpei_common.c ../rdpei_common.h) + +set(${MODULE_PREFIX}_LIBS winpr) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.c new file mode 100644 index 0000000000000000000000000000000000000000..0d75eaeb7dd5d95d54187ac1b96cca1b0f2843bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.c @@ -0,0 +1,733 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Extended Input channel server-side implementation + * + * Copyright 2014 Thincast Technologies Gmbh. + * Copyright 2014 David FORT + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include +#include + +#include "rdpei_main.h" +#include "../rdpei_common.h" +#include +#include + +enum RdpEiState +{ + STATE_INITIAL, + STATE_WAITING_CLIENT_READY, + STATE_WAITING_FRAME, + STATE_SUSPENDED, +}; + +struct s_rdpei_server_private +{ + HANDLE channelHandle; + HANDLE eventHandle; + + UINT32 expectedBytes; + BOOL waitingHeaders; + wStream* inputStream; + wStream* outputStream; + + UINT16 currentMsgType; + + RDPINPUT_TOUCH_EVENT touchEvent; + RDPINPUT_PEN_EVENT penEvent; + + enum RdpEiState automataState; +}; + +RdpeiServerContext* rdpei_server_context_new(HANDLE vcm) +{ + RdpeiServerContext* ret = calloc(1, sizeof(*ret)); + RdpeiServerPrivate* priv = NULL; + + if (!ret) + return NULL; + + ret->priv = priv = calloc(1, sizeof(*ret->priv)); + if (!priv) + goto fail; + + priv->inputStream = Stream_New(NULL, 256); + if (!priv->inputStream) + goto fail; + + priv->outputStream = Stream_New(NULL, 200); + if (!priv->inputStream) + goto fail; + + ret->vcm = vcm; + rdpei_server_context_reset(ret); + return ret; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + rdpei_server_context_free(ret); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_server_init(RdpeiServerContext* context) +{ + void* buffer = NULL; + DWORD bytesReturned = 0; + RdpeiServerPrivate* priv = context->priv; + UINT32 channelId = 0; + BOOL status = TRUE; + + priv->channelHandle = WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, RDPEI_DVC_CHANNEL_NAME, + WTS_CHANNEL_OPTION_DYNAMIC); + if (!priv->channelHandle) + { + WLog_ERR(TAG, "WTSVirtualChannelOpenEx failed!"); + return CHANNEL_RC_INITIALIZATION_ERROR; + } + + channelId = WTSChannelGetIdByHandle(priv->channelHandle); + + IFCALLRET(context->onChannelIdAssigned, status, context, channelId); + if (!status) + { + WLog_ERR(TAG, "context->onChannelIdAssigned failed!"); + goto out_close; + } + + if (!WTSVirtualChannelQuery(priv->channelHandle, WTSVirtualEventHandle, &buffer, + &bytesReturned) || + (bytesReturned != sizeof(HANDLE))) + { + WLog_ERR(TAG, + "WTSVirtualChannelQuery failed or invalid invalid returned size(%" PRIu32 ")!", + bytesReturned); + if (buffer) + WTSFreeMemory(buffer); + goto out_close; + } + priv->eventHandle = *(HANDLE*)buffer; + WTSFreeMemory(buffer); + + return CHANNEL_RC_OK; + +out_close: + (void)WTSVirtualChannelClose(priv->channelHandle); + return CHANNEL_RC_INITIALIZATION_ERROR; +} + +void rdpei_server_context_reset(RdpeiServerContext* context) +{ + RdpeiServerPrivate* priv = context->priv; + + priv->channelHandle = INVALID_HANDLE_VALUE; + priv->expectedBytes = RDPINPUT_HEADER_LENGTH; + priv->waitingHeaders = TRUE; + priv->automataState = STATE_INITIAL; + Stream_SetPosition(priv->inputStream, 0); +} + +void rdpei_server_context_free(RdpeiServerContext* context) +{ + RdpeiServerPrivate* priv = NULL; + + if (!context) + return; + priv = context->priv; + if (priv) + { + if (priv->channelHandle != INVALID_HANDLE_VALUE) + (void)WTSVirtualChannelClose(priv->channelHandle); + Stream_Free(priv->inputStream, TRUE); + } + free(priv); + free(context); +} + +HANDLE rdpei_server_get_event_handle(RdpeiServerContext* context) +{ + return context->priv->eventHandle; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT read_cs_ready_message(RdpeiServerContext* context, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + if (!Stream_CheckAndLogRequiredLength(TAG, s, 10)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, context->protocolFlags); + Stream_Read_UINT32(s, context->clientVersion); + Stream_Read_UINT16(s, context->maxTouchPoints); + + switch (context->clientVersion) + { + case RDPINPUT_PROTOCOL_V10: + case RDPINPUT_PROTOCOL_V101: + case RDPINPUT_PROTOCOL_V200: + case RDPINPUT_PROTOCOL_V300: + break; + default: + WLog_ERR(TAG, "unhandled RPDEI protocol version 0x%" PRIx32 "", context->clientVersion); + break; + } + + IFCALLRET(context->onClientReady, error, context); + if (error) + WLog_ERR(TAG, "context->onClientReady failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT read_touch_contact_data(RdpeiServerContext* context, wStream* s, + RDPINPUT_CONTACT_DATA* contactData) +{ + WINPR_UNUSED(context); + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, contactData->contactId); + if (!rdpei_read_2byte_unsigned(s, &contactData->fieldsPresent) || + !rdpei_read_4byte_signed(s, &contactData->x) || + !rdpei_read_4byte_signed(s, &contactData->y) || + !rdpei_read_4byte_unsigned(s, &contactData->contactFlags)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (contactData->fieldsPresent & CONTACT_DATA_CONTACTRECT_PRESENT) + { + if (!rdpei_read_2byte_signed(s, &contactData->contactRectLeft) || + !rdpei_read_2byte_signed(s, &contactData->contactRectTop) || + !rdpei_read_2byte_signed(s, &contactData->contactRectRight) || + !rdpei_read_2byte_signed(s, &contactData->contactRectBottom)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + } + + if ((contactData->fieldsPresent & CONTACT_DATA_ORIENTATION_PRESENT) && + !rdpei_read_4byte_unsigned(s, &contactData->orientation)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + if ((contactData->fieldsPresent & CONTACT_DATA_PRESSURE_PRESENT) && + !rdpei_read_4byte_unsigned(s, &contactData->pressure)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +static UINT read_pen_contact(RdpeiServerContext* context, wStream* s, + RDPINPUT_PEN_CONTACT* contactData) +{ + WINPR_UNUSED(context); + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, contactData->deviceId); + if (!rdpei_read_2byte_unsigned(s, &contactData->fieldsPresent) || + !rdpei_read_4byte_signed(s, &contactData->x) || + !rdpei_read_4byte_signed(s, &contactData->y) || + !rdpei_read_4byte_unsigned(s, &contactData->contactFlags)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (contactData->fieldsPresent & RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT) + { + if (!rdpei_read_4byte_unsigned(s, &contactData->penFlags)) + return ERROR_INVALID_DATA; + } + if (contactData->fieldsPresent & RDPINPUT_PEN_CONTACT_PRESSURE_PRESENT) + { + if (!rdpei_read_4byte_unsigned(s, &contactData->pressure)) + return ERROR_INVALID_DATA; + } + if (contactData->fieldsPresent & RDPINPUT_PEN_CONTACT_ROTATION_PRESENT) + { + if (!rdpei_read_2byte_unsigned(s, &contactData->rotation)) + return ERROR_INVALID_DATA; + } + if (contactData->fieldsPresent & RDPINPUT_PEN_CONTACT_TILTX_PRESENT) + { + if (!rdpei_read_2byte_signed(s, &contactData->tiltX)) + return ERROR_INVALID_DATA; + } + if (contactData->fieldsPresent & RDPINPUT_PEN_CONTACT_TILTY_PRESENT) + { + if (!rdpei_read_2byte_signed(s, &contactData->tiltY)) + return ERROR_INVALID_DATA; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT read_touch_frame(RdpeiServerContext* context, wStream* s, RDPINPUT_TOUCH_FRAME* frame) +{ + RDPINPUT_CONTACT_DATA* contact = NULL; + UINT error = 0; + + if (!rdpei_read_2byte_unsigned(s, &frame->contactCount) || + !rdpei_read_8byte_unsigned(s, &frame->frameOffset)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + frame->contacts = contact = calloc(frame->contactCount, sizeof(RDPINPUT_CONTACT_DATA)); + if (!frame->contacts) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + for (UINT32 i = 0; i < frame->contactCount; i++, contact++) + { + if ((error = read_touch_contact_data(context, s, contact))) + { + WLog_ERR(TAG, "read_touch_contact_data failed with error %" PRIu32 "!", error); + frame->contactCount = WINPR_ASSERTING_INT_CAST(UINT16, i); + touch_frame_reset(frame); + return error; + } + } + return CHANNEL_RC_OK; +} + +static UINT read_pen_frame(RdpeiServerContext* context, wStream* s, RDPINPUT_PEN_FRAME* frame) +{ + RDPINPUT_PEN_CONTACT* contact = NULL; + UINT error = 0; + + if (!rdpei_read_2byte_unsigned(s, &frame->contactCount) || + !rdpei_read_8byte_unsigned(s, &frame->frameOffset)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + frame->contacts = contact = calloc(frame->contactCount, sizeof(RDPINPUT_PEN_CONTACT)); + if (!frame->contacts) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + for (UINT32 i = 0; i < frame->contactCount; i++, contact++) + { + if ((error = read_pen_contact(context, s, contact))) + { + WLog_ERR(TAG, "read_touch_contact_data failed with error %" PRIu32 "!", error); + frame->contactCount = WINPR_ASSERTING_INT_CAST(UINT16, i); + + pen_frame_reset(frame); + return error; + } + } + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT read_touch_event(RdpeiServerContext* context, wStream* s) +{ + UINT16 frameCount = 0; + RDPINPUT_TOUCH_EVENT* event = &context->priv->touchEvent; + RDPINPUT_TOUCH_FRAME* frame = NULL; + UINT error = CHANNEL_RC_OK; + + if (!rdpei_read_4byte_unsigned(s, &event->encodeTime) || + !rdpei_read_2byte_unsigned(s, &frameCount)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + event->frameCount = frameCount; + event->frames = frame = calloc(event->frameCount, sizeof(RDPINPUT_TOUCH_FRAME)); + if (!event->frames) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + for (UINT32 i = 0; i < frameCount; i++, frame++) + { + if ((error = read_touch_frame(context, s, frame))) + { + WLog_ERR(TAG, "read_touch_contact_data failed with error %" PRIu32 "!", error); + event->frameCount = WINPR_ASSERTING_INT_CAST(UINT16, i); + + goto out_cleanup; + } + } + + IFCALLRET(context->onTouchEvent, error, context, event); + if (error) + WLog_ERR(TAG, "context->onTouchEvent failed with error %" PRIu32 "", error); + +out_cleanup: + touch_event_reset(event); + return error; +} + +static UINT read_pen_event(RdpeiServerContext* context, wStream* s) +{ + UINT16 frameCount = 0; + RDPINPUT_PEN_EVENT* event = &context->priv->penEvent; + RDPINPUT_PEN_FRAME* frame = NULL; + UINT error = CHANNEL_RC_OK; + + if (!rdpei_read_4byte_unsigned(s, &event->encodeTime) || + !rdpei_read_2byte_unsigned(s, &frameCount)) + { + WLog_ERR(TAG, "rdpei_read_ failed!"); + return ERROR_INTERNAL_ERROR; + } + + event->frameCount = frameCount; + event->frames = frame = calloc(event->frameCount, sizeof(RDPINPUT_PEN_FRAME)); + if (!event->frames) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + for (UINT32 i = 0; i < frameCount; i++, frame++) + { + if ((error = read_pen_frame(context, s, frame))) + { + WLog_ERR(TAG, "read_pen_frame failed with error %" PRIu32 "!", error); + event->frameCount = WINPR_ASSERTING_INT_CAST(UINT16, i); + + goto out_cleanup; + } + } + + IFCALLRET(context->onPenEvent, error, context, event); + if (error) + WLog_ERR(TAG, "context->onPenEvent failed with error %" PRIu32 "", error); + +out_cleanup: + pen_event_reset(event); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT read_dismiss_hovering_contact(RdpeiServerContext* context, wStream* s) +{ + BYTE contactId = 0; + UINT error = CHANNEL_RC_OK; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, contactId); + + IFCALLRET(context->onTouchReleased, error, context, contactId); + if (error) + WLog_ERR(TAG, "context->onTouchReleased failed with error %" PRIu32 "", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_server_handle_messages(RdpeiServerContext* context) +{ + DWORD bytesReturned = 0; + RdpeiServerPrivate* priv = context->priv; + wStream* s = priv->inputStream; + UINT error = CHANNEL_RC_OK; + + if (!WTSVirtualChannelRead(priv->channelHandle, 0, Stream_Pointer(s), priv->expectedBytes, + &bytesReturned)) + { + if (GetLastError() == ERROR_NO_DATA) + return ERROR_READ_FAULT; + + WLog_DBG(TAG, "channel connection closed"); + return CHANNEL_RC_OK; + } + priv->expectedBytes -= bytesReturned; + Stream_Seek(s, bytesReturned); + + if (priv->expectedBytes) + return CHANNEL_RC_OK; + + Stream_SealLength(s); + Stream_SetPosition(s, 0); + + if (priv->waitingHeaders) + { + UINT32 pduLen = 0; + + /* header case */ + Stream_Read_UINT16(s, priv->currentMsgType); + Stream_Read_UINT16(s, pduLen); + + if (pduLen < RDPINPUT_HEADER_LENGTH) + { + WLog_ERR(TAG, "invalid pduLength %" PRIu32 "", pduLen); + return ERROR_INVALID_DATA; + } + priv->expectedBytes = pduLen - RDPINPUT_HEADER_LENGTH; + priv->waitingHeaders = FALSE; + Stream_SetPosition(s, 0); + if (priv->expectedBytes) + { + if (!Stream_EnsureCapacity(s, priv->expectedBytes)) + { + WLog_ERR(TAG, "Stream_EnsureCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + return CHANNEL_RC_OK; + } + } + + /* when here we have the header + the body */ + switch (priv->currentMsgType) + { + case EVENTID_CS_READY: + if (priv->automataState != STATE_WAITING_CLIENT_READY) + { + WLog_ERR(TAG, "not expecting a CS_READY packet in this state(%d)", + priv->automataState); + return ERROR_INVALID_STATE; + } + + if ((error = read_cs_ready_message(context, s))) + { + WLog_ERR(TAG, "read_cs_ready_message failed with error %" PRIu32 "", error); + return error; + } + break; + + case EVENTID_TOUCH: + if ((error = read_touch_event(context, s))) + { + WLog_ERR(TAG, "read_touch_event failed with error %" PRIu32 "", error); + return error; + } + break; + case EVENTID_DISMISS_HOVERING_CONTACT: + if ((error = read_dismiss_hovering_contact(context, s))) + { + WLog_ERR(TAG, "read_dismiss_hovering_contact failed with error %" PRIu32 "", error); + return error; + } + break; + case EVENTID_PEN: + if ((error = read_pen_event(context, s))) + { + WLog_ERR(TAG, "read_pen_event failed with error %" PRIu32 "", error); + return error; + } + break; + default: + WLog_ERR(TAG, "unexpected message type 0x%" PRIx16 "", priv->currentMsgType); + } + + Stream_SetPosition(s, 0); + priv->waitingHeaders = TRUE; + priv->expectedBytes = RDPINPUT_HEADER_LENGTH; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_server_send_sc_ready(RdpeiServerContext* context, UINT32 version, UINT32 features) +{ + ULONG written = 0; + RdpeiServerPrivate* priv = context->priv; + UINT32 pduLen = 4; + + if (priv->automataState != STATE_INITIAL) + { + WLog_ERR(TAG, "called from unexpected state %d", priv->automataState); + return ERROR_INVALID_STATE; + } + + Stream_SetPosition(priv->outputStream, 0); + + if (version >= RDPINPUT_PROTOCOL_V300) + pduLen += 4; + + if (!Stream_EnsureCapacity(priv->outputStream, RDPINPUT_HEADER_LENGTH + pduLen)) + { + WLog_ERR(TAG, "Stream_EnsureCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(priv->outputStream, EVENTID_SC_READY); + Stream_Write_UINT32(priv->outputStream, RDPINPUT_HEADER_LENGTH + pduLen); + Stream_Write_UINT32(priv->outputStream, version); + if (version >= RDPINPUT_PROTOCOL_V300) + Stream_Write_UINT32(priv->outputStream, features); + + const size_t pos = Stream_GetPosition(priv->outputStream); + + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), + (ULONG)pos, &written)) + { + WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); + return ERROR_INTERNAL_ERROR; + } + + priv->automataState = STATE_WAITING_CLIENT_READY; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_server_suspend(RdpeiServerContext* context) +{ + ULONG written = 0; + RdpeiServerPrivate* priv = context->priv; + + switch (priv->automataState) + { + case STATE_SUSPENDED: + WLog_ERR(TAG, "already suspended"); + return CHANNEL_RC_OK; + case STATE_WAITING_FRAME: + break; + default: + WLog_ERR(TAG, "called from unexpected state %d", priv->automataState); + return ERROR_INVALID_STATE; + } + + Stream_SetPosition(priv->outputStream, 0); + if (!Stream_EnsureCapacity(priv->outputStream, RDPINPUT_HEADER_LENGTH)) + { + WLog_ERR(TAG, "Stream_EnsureCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(priv->outputStream, EVENTID_SUSPEND_TOUCH); + Stream_Write_UINT32(priv->outputStream, RDPINPUT_HEADER_LENGTH); + + const size_t pos = Stream_GetPosition(priv->outputStream); + + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), + (ULONG)pos, &written)) + { + WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); + return ERROR_INTERNAL_ERROR; + } + + priv->automataState = STATE_SUSPENDED; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT rdpei_server_resume(RdpeiServerContext* context) +{ + ULONG written = 0; + RdpeiServerPrivate* priv = context->priv; + + switch (priv->automataState) + { + case STATE_WAITING_FRAME: + WLog_ERR(TAG, "not suspended"); + return CHANNEL_RC_OK; + case STATE_SUSPENDED: + break; + default: + WLog_ERR(TAG, "called from unexpected state %d", priv->automataState); + return ERROR_INVALID_STATE; + } + + Stream_SetPosition(priv->outputStream, 0); + if (!Stream_EnsureCapacity(priv->outputStream, RDPINPUT_HEADER_LENGTH)) + { + WLog_ERR(TAG, "Stream_EnsureCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write_UINT16(priv->outputStream, EVENTID_RESUME_TOUCH); + Stream_Write_UINT32(priv->outputStream, RDPINPUT_HEADER_LENGTH); + + const size_t pos = Stream_GetPosition(priv->outputStream); + + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), + (ULONG)pos, &written)) + { + WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); + return ERROR_INTERNAL_ERROR; + } + + priv->automataState = STATE_WAITING_FRAME; + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.h new file mode 100644 index 0000000000000000000000000000000000000000..cf3e3cbb4282aaba063d7e2795e52fc4d1b32937 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpei/server/rdpei_main.h @@ -0,0 +1,32 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Extended Input channel server-side implementation + * + * Copyright 2014 David Fort + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_RDPEI_SERVER_MAIN_H +#define FREERDP_CHANNEL_RDPEI_SERVER_MAIN_H + +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("rdpei.server") + +#endif /* FREERDP_CHANNEL_RDPEI_SERVER_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..760f82694c9ccf5d973159b2823e4ea632f54fa2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/CMakeLists.txt @@ -0,0 +1,58 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client("rdpsnd") + +set(${MODULE_PREFIX}_SRCS rdpsnd_main.c rdpsnd_main.h) + +set(${MODULE_PREFIX}_LIBS winpr freerdp ${CMAKE_THREAD_LIBS_INIT} rdpsnd-common) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntryEx;DVCPluginEntry") + +if(WITH_OSS) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "oss" "") +endif() + +if(WITH_ALSA) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "alsa" "") +endif() + +if(WITH_IOSAUDIO) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "ios" "") +endif() + +if(WITH_PULSE) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "pulse" "") +endif() + +if(WITH_MACAUDIO) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "mac" "") +endif() + +if(WITH_WINMM) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "winmm" "") +endif() + +if(WITH_OPENSLES) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "opensles" "") +endif() + +if(WITH_SNDIO) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "sndio" "") +endif() + +add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "fake" "") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/rdpsnd_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/rdpsnd_main.h new file mode 100644 index 0000000000000000000000000000000000000000..33adfcdfca4e49c7b81d08a73dfcf03f2f018da6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/client/rdpsnd_main.h @@ -0,0 +1,41 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Audio Output Virtual Channel + * + * Copyright 2010-2011 Vic Lee + * Copyright 2012-2013 Marc-Andre Moreau + * + * 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 FREERDP_CHANNEL_RDPSND_CLIENT_MAIN_H +#define FREERDP_CHANNEL_RDPSND_CLIENT_MAIN_H + +#include +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("rdpsnd.client") + +#if defined(WITH_DEBUG_SND) +#define DEBUG_SND(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_SND(...) \ + do \ + { \ + } while (0) +#endif + +#endif /* FREERDP_CHANNEL_RDPSND_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/common/rdpsnd_common.c b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/common/rdpsnd_common.c new file mode 100644 index 0000000000000000000000000000000000000000..a420beb9679fe9f69b842fc77b95ab1c13b05262 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/common/rdpsnd_common.c @@ -0,0 +1,21 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Server Audio Virtual Channel + * + * Copyright 2018 Armin Novak + * Copyright 2018 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 "rdpsnd_common.h" diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0282c01b4732e99ef3ab69ae1b1121d370ca9e98 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/rdpsnd/server/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("rdpsnd") + +set(${MODULE_PREFIX}_SRCS rdpsnd_main.c rdpsnd_main.h) + +set(${MODULE_PREFIX}_LIBS rdpsnd-common) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..005b217448248bf38a72794f70c8475a51a8b546 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client("remdesk") + +set(${MODULE_PREFIX}_SRCS remdesk_main.c remdesk_main.h) + +set(${MODULE_PREFIX}_LIBS winpr freerdp remdesk-common) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntryEx") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8cfb27027a270c2b48ae9b8898cf6a6d4f6b3f9f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.c @@ -0,0 +1,1048 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include + +#include +#include + +#include +#include + +#include "remdesk_main.h" +#include "remdesk_common.h" + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_virtual_channel_write(remdeskPlugin* remdesk, wStream* s) +{ + UINT32 status = 0; + + if (!remdesk) + { + WLog_ERR(TAG, "remdesk was null!"); + Stream_Free(s, TRUE); + return CHANNEL_RC_INVALID_INSTANCE; + } + + WINPR_ASSERT(remdesk->channelEntryPoints.pVirtualChannelWriteEx); + status = remdesk->channelEntryPoints.pVirtualChannelWriteEx( + remdesk->InitHandle, remdesk->OpenHandle, Stream_Buffer(s), (UINT32)Stream_Length(s), s); + + if (status != CHANNEL_RC_OK) + { + Stream_Free(s, TRUE); + WLog_ERR(TAG, "pVirtualChannelWriteEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(status), status); + } + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_generate_expert_blob(remdeskPlugin* remdesk) +{ + const char* name = NULL; + char* pass = NULL; + const char* password = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(remdesk); + + WINPR_ASSERT(remdesk->rdpcontext); + settings = remdesk->rdpcontext->settings; + WINPR_ASSERT(settings); + + if (remdesk->ExpertBlob) + return CHANNEL_RC_OK; + + password = freerdp_settings_get_string(settings, FreeRDP_RemoteAssistancePassword); + if (!password) + password = freerdp_settings_get_string(settings, FreeRDP_Password); + + if (!password) + { + WLog_ERR(TAG, "password was not set!"); + return ERROR_INTERNAL_ERROR; + } + + name = freerdp_settings_get_string(settings, FreeRDP_Username); + + if (!name) + name = "Expert"; + + const char* stub = freerdp_settings_get_string(settings, FreeRDP_RemoteAssistancePassStub); + remdesk->EncryptedPassStub = + freerdp_assistance_encrypt_pass_stub(password, stub, &(remdesk->EncryptedPassStubSize)); + + if (!remdesk->EncryptedPassStub) + { + WLog_ERR(TAG, "freerdp_assistance_encrypt_pass_stub failed!"); + return ERROR_INTERNAL_ERROR; + } + + pass = freerdp_assistance_bin_to_hex_string(remdesk->EncryptedPassStub, + remdesk->EncryptedPassStubSize); + + if (!pass) + { + WLog_ERR(TAG, "freerdp_assistance_bin_to_hex_string failed!"); + return ERROR_INTERNAL_ERROR; + } + + remdesk->ExpertBlob = freerdp_assistance_construct_expert_blob(name, pass); + free(pass); + + if (!remdesk->ExpertBlob) + { + WLog_ERR(TAG, "freerdp_assistance_construct_expert_blob failed!"); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_server_announce_pdu(remdeskPlugin* remdesk, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + WINPR_ASSERT(remdesk); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_version_info_pdu(remdeskPlugin* remdesk, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + UINT32 versionMajor = 0; + UINT32 versionMinor = 0; + + WINPR_ASSERT(remdesk); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, versionMajor); /* versionMajor (4 bytes) */ + Stream_Read_UINT32(s, versionMinor); /* versionMinor (4 bytes) */ + + if ((versionMajor != 1) || (versionMinor > 2) || (versionMinor == 0)) + { + WLog_ERR(TAG, "Unsupported protocol version %" PRId32 ".%" PRId32, versionMajor, + versionMinor); + } + + remdesk->Version = versionMinor; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_version_info_pdu(remdeskPlugin* remdesk) +{ + REMDESK_CTL_VERSION_INFO_PDU pdu = { 0 }; + + WINPR_ASSERT(remdesk); + + UINT error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERSIONINFO, 8); + if (error) + return error; + + pdu.versionMajor = 1; + pdu.versionMinor = 2; + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + return error; + } + Stream_Write_UINT32(s, pdu.versionMajor); /* versionMajor (4 bytes) */ + Stream_Write_UINT32(s, pdu.versionMinor); /* versionMinor (4 bytes) */ + Stream_SealLength(s); + + if ((error = remdesk_virtual_channel_write(remdesk, s))) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_result_pdu(remdeskPlugin* remdesk, wStream* s, + REMDESK_CHANNEL_HEADER* header, UINT32* pResult) +{ + UINT32 result = 0; + + WINPR_ASSERT(remdesk); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + WINPR_ASSERT(pResult); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, result); /* result (4 bytes) */ + *pResult = result; + // WLog_DBG(TAG, "RemdeskRecvResult: 0x%08"PRIX32"", result); + switch (result) + { + case REMDESK_ERROR_HELPEESAIDNO: + WLog_DBG(TAG, "remote assistance connection request was denied"); + return ERROR_CONNECTION_REFUSED; + + default: + break; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_authenticate_pdu(remdeskPlugin* remdesk) +{ + UINT error = ERROR_INTERNAL_ERROR; + size_t cbExpertBlobW = 0; + WCHAR* expertBlobW = NULL; + size_t cbRaConnectionStringW = 0; + REMDESK_CTL_HEADER ctlHeader = { 0 }; + + WINPR_ASSERT(remdesk); + + if ((error = remdesk_generate_expert_blob(remdesk))) + { + WLog_ERR(TAG, "remdesk_generate_expert_blob failed with error %" PRIu32 "", error); + return error; + } + + const char* expertBlob = remdesk->ExpertBlob; + WINPR_ASSERT(remdesk->rdpcontext); + rdpSettings* settings = remdesk->rdpcontext->settings; + WINPR_ASSERT(settings); + + const char* raConnectionString = + freerdp_settings_get_string(settings, FreeRDP_RemoteAssistanceRCTicket); + WCHAR* raConnectionStringW = + ConvertUtf8ToWCharAlloc(raConnectionString, &cbRaConnectionStringW); + + if (!raConnectionStringW || (cbRaConnectionStringW > UINT32_MAX / sizeof(WCHAR))) + goto out; + + cbRaConnectionStringW = cbRaConnectionStringW * sizeof(WCHAR); + + expertBlobW = ConvertUtf8ToWCharAlloc(expertBlob, &cbExpertBlobW); + + if (!expertBlobW) + goto out; + + cbExpertBlobW = cbExpertBlobW * sizeof(WCHAR); + error = remdesk_prepare_ctl_header(&(ctlHeader), REMDESK_CTL_AUTHENTICATE, + cbRaConnectionStringW + cbExpertBlobW); + if (error) + goto out; + + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + error = remdesk_write_ctl_header(s, &ctlHeader); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } + Stream_Write(s, raConnectionStringW, cbRaConnectionStringW); + Stream_Write(s, expertBlobW, cbExpertBlobW); + Stream_SealLength(s); + + error = remdesk_virtual_channel_write(remdesk, s); + if (error) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + +out: + free(raConnectionStringW); + free(expertBlobW); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_remote_control_desktop_pdu(remdeskPlugin* remdesk) +{ + UINT error = 0; + size_t length = 0; + + WINPR_ASSERT(remdesk); + WINPR_ASSERT(remdesk->rdpcontext); + rdpSettings* settings = remdesk->rdpcontext->settings; + WINPR_ASSERT(settings); + + const char* raConnectionString = + freerdp_settings_get_string(settings, FreeRDP_RemoteAssistanceRCTicket); + WCHAR* raConnectionStringW = ConvertUtf8ToWCharAlloc(raConnectionString, &length); + size_t cbRaConnectionStringW = length * sizeof(WCHAR); + + if (!raConnectionStringW) + return ERROR_INTERNAL_ERROR; + + REMDESK_CTL_HEADER ctlHeader = { 0 }; + error = remdesk_prepare_ctl_header(&ctlHeader, REMDESK_CTL_REMOTE_CONTROL_DESKTOP, + cbRaConnectionStringW); + if (error != CHANNEL_RC_OK) + goto out; + + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + error = remdesk_write_ctl_header(s, &ctlHeader); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } + Stream_Write(s, raConnectionStringW, cbRaConnectionStringW); + Stream_SealLength(s); + + if ((error = remdesk_virtual_channel_write(remdesk, s))) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + +out: + free(raConnectionStringW); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_verify_password_pdu(remdeskPlugin* remdesk) +{ + size_t cbExpertBlobW = 0; + REMDESK_CTL_VERIFY_PASSWORD_PDU pdu = { 0 }; + + WINPR_ASSERT(remdesk); + + UINT error = remdesk_generate_expert_blob(remdesk); + if (error) + { + WLog_ERR(TAG, "remdesk_generate_expert_blob failed with error %" PRIu32 "!", error); + return error; + } + + pdu.expertBlob = remdesk->ExpertBlob; + WCHAR* expertBlobW = ConvertUtf8ToWCharAlloc(pdu.expertBlob, &cbExpertBlobW); + + if (!expertBlobW) + goto out; + + cbExpertBlobW = cbExpertBlobW * sizeof(WCHAR); + error = + remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERIFY_PASSWORD, cbExpertBlobW); + if (error) + goto out; + + wStream* s = Stream_New(NULL, 1ULL * REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } + Stream_Write(s, expertBlobW, cbExpertBlobW); + Stream_SealLength(s); + + error = remdesk_virtual_channel_write(remdesk, s); + if (error) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + +out: + free(expertBlobW); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_expert_on_vista_pdu(remdeskPlugin* remdesk) +{ + REMDESK_CTL_EXPERT_ON_VISTA_PDU pdu = { 0 }; + + WINPR_ASSERT(remdesk); + + UINT error = remdesk_generate_expert_blob(remdesk); + if (error) + { + WLog_ERR(TAG, "remdesk_generate_expert_blob failed with error %" PRIu32 "!", error); + return error; + } + if (remdesk->EncryptedPassStubSize > UINT32_MAX) + return ERROR_INTERNAL_ERROR; + + pdu.EncryptedPasswordLength = (UINT32)remdesk->EncryptedPassStubSize; + pdu.EncryptedPassword = remdesk->EncryptedPassStub; + error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_EXPERT_ON_VISTA, + pdu.EncryptedPasswordLength); + if (error) + return error; + + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + return error; + } + Stream_Write(s, pdu.EncryptedPassword, pdu.EncryptedPasswordLength); + Stream_SealLength(s); + return remdesk_virtual_channel_write(remdesk, s); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_pdu(remdeskPlugin* remdesk, wStream* s, REMDESK_CHANNEL_HEADER* header) +{ + UINT error = CHANNEL_RC_OK; + UINT32 msgType = 0; + UINT32 result = 0; + + WINPR_ASSERT(remdesk); + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, msgType); /* msgType (4 bytes) */ + + // WLog_DBG(TAG, "msgType: %"PRIu32"", msgType); + + switch (msgType) + { + case REMDESK_CTL_REMOTE_CONTROL_DESKTOP: + break; + + case REMDESK_CTL_RESULT: + if ((error = remdesk_recv_ctl_result_pdu(remdesk, s, header, &result))) + WLog_ERR(TAG, "remdesk_recv_ctl_result_pdu failed with error %" PRIu32 "", error); + + break; + + case REMDESK_CTL_AUTHENTICATE: + break; + + case REMDESK_CTL_SERVER_ANNOUNCE: + if ((error = remdesk_recv_ctl_server_announce_pdu(remdesk, s, header))) + WLog_ERR(TAG, "remdesk_recv_ctl_server_announce_pdu failed with error %" PRIu32 "", + error); + + break; + + case REMDESK_CTL_DISCONNECT: + break; + + case REMDESK_CTL_VERSIONINFO: + if ((error = remdesk_recv_ctl_version_info_pdu(remdesk, s, header))) + { + WLog_ERR(TAG, "remdesk_recv_ctl_version_info_pdu failed with error %" PRIu32 "", + error); + break; + } + + if (remdesk->Version == 1) + { + if ((error = remdesk_send_ctl_version_info_pdu(remdesk))) + { + WLog_ERR(TAG, "remdesk_send_ctl_version_info_pdu failed with error %" PRIu32 "", + error); + break; + } + + if ((error = remdesk_send_ctl_authenticate_pdu(remdesk))) + { + WLog_ERR(TAG, "remdesk_send_ctl_authenticate_pdu failed with error %" PRIu32 "", + error); + break; + } + + if ((error = remdesk_send_ctl_remote_control_desktop_pdu(remdesk))) + { + WLog_ERR( + TAG, + "remdesk_send_ctl_remote_control_desktop_pdu failed with error %" PRIu32 "", + error); + break; + } + } + else if (remdesk->Version == 2) + { + if ((error = remdesk_send_ctl_expert_on_vista_pdu(remdesk))) + { + WLog_ERR(TAG, + "remdesk_send_ctl_expert_on_vista_pdu failed with error %" PRIu32 "", + error); + break; + } + + if ((error = remdesk_send_ctl_verify_password_pdu(remdesk))) + { + WLog_ERR(TAG, + "remdesk_send_ctl_verify_password_pdu failed with error %" PRIu32 "", + error); + break; + } + } + + break; + + case REMDESK_CTL_ISCONNECTED: + break; + + case REMDESK_CTL_VERIFY_PASSWORD: + break; + + case REMDESK_CTL_EXPERT_ON_VISTA: + break; + + case REMDESK_CTL_RANOVICE_NAME: + break; + + case REMDESK_CTL_RAEXPERT_NAME: + break; + + case REMDESK_CTL_TOKEN: + break; + + default: + WLog_ERR(TAG, "unknown msgType: %" PRIu32 "", msgType); + error = ERROR_INVALID_DATA; + break; + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_process_receive(remdeskPlugin* remdesk, wStream* s) +{ + UINT status = 0; + REMDESK_CHANNEL_HEADER header; + + WINPR_ASSERT(remdesk); + WINPR_ASSERT(s); + +#if 0 + WLog_DBG(TAG, "RemdeskReceive: %"PRIuz"", Stream_GetRemainingLength(s)); + winpr_HexDump(Stream_ConstPointer(s), Stream_GetRemainingLength(s)); +#endif + + if ((status = remdesk_read_channel_header(s, &header))) + { + WLog_ERR(TAG, "remdesk_read_channel_header failed with error %" PRIu32 "", status); + return status; + } + + if (strcmp(header.ChannelName, "RC_CTL") == 0) + { + status = remdesk_recv_ctl_pdu(remdesk, s, &header); + } + else if (strcmp(header.ChannelName, "70") == 0) + { + } + else if (strcmp(header.ChannelName, "71") == 0) + { + } + else if (strcmp(header.ChannelName, ".") == 0) + { + } + else if (strcmp(header.ChannelName, "1000.") == 0) + { + } + else if (strcmp(header.ChannelName, "RA_FX") == 0) + { + } + else + { + } + + return status; +} + +static void remdesk_process_connect(remdeskPlugin* remdesk) +{ + WINPR_ASSERT(remdesk); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_virtual_channel_event_data_received(remdeskPlugin* remdesk, const void* pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + wStream* data_in = NULL; + + WINPR_ASSERT(remdesk); + + if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) + { + return CHANNEL_RC_OK; + } + + if (dataFlags & CHANNEL_FLAG_FIRST) + { + if (remdesk->data_in) + Stream_Free(remdesk->data_in, TRUE); + + remdesk->data_in = Stream_New(NULL, totalLength); + + if (!remdesk->data_in) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + } + + data_in = remdesk->data_in; + + if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write(data_in, pData, dataLength); + + if (dataFlags & CHANNEL_FLAG_LAST) + { + if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) + { + WLog_ERR(TAG, "read error"); + return ERROR_INTERNAL_ERROR; + } + + remdesk->data_in = NULL; + Stream_SealLength(data_in); + Stream_SetPosition(data_in, 0); + + if (!MessageQueue_Post(remdesk->queue, NULL, 0, (void*)data_in, NULL)) + { + WLog_ERR(TAG, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + } + + return CHANNEL_RC_OK; +} + +static VOID VCAPITYPE remdesk_virtual_channel_open_event_ex(LPVOID lpUserParam, DWORD openHandle, + UINT event, LPVOID pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags) +{ + UINT error = CHANNEL_RC_OK; + remdeskPlugin* remdesk = (remdeskPlugin*)lpUserParam; + + switch (event) + { + case CHANNEL_EVENT_INITIALIZED: + break; + + case CHANNEL_EVENT_DATA_RECEIVED: + if (!remdesk || (remdesk->OpenHandle != openHandle)) + { + WLog_ERR(TAG, "error no match"); + return; + } + if ((error = remdesk_virtual_channel_event_data_received(remdesk, pData, dataLength, + totalLength, dataFlags))) + WLog_ERR(TAG, + "remdesk_virtual_channel_event_data_received failed with error %" PRIu32 + "!", + error); + + break; + + case CHANNEL_EVENT_WRITE_CANCELLED: + case CHANNEL_EVENT_WRITE_COMPLETE: + { + wStream* s = (wStream*)pData; + Stream_Free(s, TRUE); + } + break; + + case CHANNEL_EVENT_USER: + break; + + default: + WLog_ERR(TAG, "unhandled event %" PRIu32 "!", event); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (error && remdesk && remdesk->rdpcontext) + setChannelError(remdesk->rdpcontext, error, + "remdesk_virtual_channel_open_event_ex reported an error"); +} + +static DWORD WINAPI remdesk_virtual_channel_client_thread(LPVOID arg) +{ + wStream* data = NULL; + wMessage message = { 0 }; + remdeskPlugin* remdesk = (remdeskPlugin*)arg; + UINT error = CHANNEL_RC_OK; + + WINPR_ASSERT(remdesk); + + remdesk_process_connect(remdesk); + + while (1) + { + if (!MessageQueue_Wait(remdesk->queue)) + { + WLog_ERR(TAG, "MessageQueue_Wait failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (!MessageQueue_Peek(remdesk->queue, &message, TRUE)) + { + WLog_ERR(TAG, "MessageQueue_Peek failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (message.id == WMQ_QUIT) + break; + + if (message.id == 0) + { + data = (wStream*)message.wParam; + + if ((error = remdesk_process_receive(remdesk, data))) + { + WLog_ERR(TAG, "remdesk_process_receive failed with error %" PRIu32 "!", error); + Stream_Free(data, TRUE); + break; + } + + Stream_Free(data, TRUE); + } + } + + if (error && remdesk->rdpcontext) + setChannelError(remdesk->rdpcontext, error, + "remdesk_virtual_channel_client_thread reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_virtual_channel_event_connected(remdeskPlugin* remdesk, LPVOID pData, + UINT32 dataLength) +{ + UINT error = 0; + + WINPR_ASSERT(remdesk); + + remdesk->queue = MessageQueue_New(NULL); + + if (!remdesk->queue) + { + WLog_ERR(TAG, "MessageQueue_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto error_out; + } + + remdesk->thread = + CreateThread(NULL, 0, remdesk_virtual_channel_client_thread, (void*)remdesk, 0, NULL); + + if (!remdesk->thread) + { + WLog_ERR(TAG, "CreateThread failed"); + error = ERROR_INTERNAL_ERROR; + goto error_out; + } + + return remdesk->channelEntryPoints.pVirtualChannelOpenEx( + remdesk->InitHandle, &remdesk->OpenHandle, remdesk->channelDef.name, + remdesk_virtual_channel_open_event_ex); +error_out: + MessageQueue_Free(remdesk->queue); + remdesk->queue = NULL; + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_virtual_channel_event_disconnected(remdeskPlugin* remdesk) +{ + UINT rc = CHANNEL_RC_OK; + + WINPR_ASSERT(remdesk); + + if (remdesk->queue && remdesk->thread) + { + if (MessageQueue_PostQuit(remdesk->queue, 0) && + (WaitForSingleObject(remdesk->thread, INFINITE) == WAIT_FAILED)) + { + rc = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", rc); + return rc; + } + } + + if (remdesk->OpenHandle != 0) + { + WINPR_ASSERT(remdesk->channelEntryPoints.pVirtualChannelCloseEx); + rc = remdesk->channelEntryPoints.pVirtualChannelCloseEx(remdesk->InitHandle, + remdesk->OpenHandle); + + if (CHANNEL_RC_OK != rc) + { + WLog_ERR(TAG, "pVirtualChannelCloseEx failed with %s [%08" PRIX32 "]", + WTSErrorToString(rc), rc); + } + + remdesk->OpenHandle = 0; + } + MessageQueue_Free(remdesk->queue); + (void)CloseHandle(remdesk->thread); + Stream_Free(remdesk->data_in, TRUE); + remdesk->data_in = NULL; + remdesk->queue = NULL; + remdesk->thread = NULL; + return rc; +} + +static void remdesk_virtual_channel_event_terminated(remdeskPlugin* remdesk) +{ + WINPR_ASSERT(remdesk); + + remdesk->InitHandle = 0; + free(remdesk->context); + free(remdesk); +} + +static VOID VCAPITYPE remdesk_virtual_channel_init_event_ex(LPVOID lpUserParam, LPVOID pInitHandle, + UINT event, LPVOID pData, + UINT dataLength) +{ + UINT error = CHANNEL_RC_OK; + remdeskPlugin* remdesk = (remdeskPlugin*)lpUserParam; + + if (!remdesk || (remdesk->InitHandle != pInitHandle)) + { + WLog_ERR(TAG, "error no match"); + return; + } + + switch (event) + { + case CHANNEL_EVENT_CONNECTED: + if ((error = remdesk_virtual_channel_event_connected(remdesk, pData, dataLength))) + WLog_ERR(TAG, + "remdesk_virtual_channel_event_connected failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_DISCONNECTED: + if ((error = remdesk_virtual_channel_event_disconnected(remdesk))) + WLog_ERR(TAG, + "remdesk_virtual_channel_event_disconnected failed with error %" PRIu32 "", + error); + + break; + + case CHANNEL_EVENT_TERMINATED: + remdesk_virtual_channel_event_terminated(remdesk); + break; + + case CHANNEL_EVENT_ATTACHED: + case CHANNEL_EVENT_DETACHED: + default: + break; + } + + if (error && remdesk->rdpcontext) + setChannelError(remdesk->rdpcontext, error, + "remdesk_virtual_channel_init_event reported an error"); +} + +/* remdesk is always built-in */ +#define VirtualChannelEntryEx remdesk_VirtualChannelEntryEx + +FREERDP_ENTRY_POINT(BOOL VCAPITYPE VirtualChannelEntryEx(PCHANNEL_ENTRY_POINTS pEntryPoints, + PVOID pInitHandle)) +{ + UINT rc = 0; + remdeskPlugin* remdesk = NULL; + RemdeskClientContext* context = NULL; + CHANNEL_ENTRY_POINTS_FREERDP_EX* pEntryPointsEx = NULL; + + if (!pEntryPoints) + { + return FALSE; + } + + remdesk = (remdeskPlugin*)calloc(1, sizeof(remdeskPlugin)); + + if (!remdesk) + { + WLog_ERR(TAG, "calloc failed!"); + return FALSE; + } + + remdesk->channelDef.options = CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | + CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL; + (void)sprintf_s(remdesk->channelDef.name, ARRAYSIZE(remdesk->channelDef.name), + REMDESK_SVC_CHANNEL_NAME); + remdesk->Version = 2; + pEntryPointsEx = (CHANNEL_ENTRY_POINTS_FREERDP_EX*)pEntryPoints; + + if ((pEntryPointsEx->cbSize >= sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)) && + (pEntryPointsEx->MagicNumber == FREERDP_CHANNEL_MAGIC_NUMBER)) + { + context = (RemdeskClientContext*)calloc(1, sizeof(RemdeskClientContext)); + + if (!context) + { + WLog_ERR(TAG, "calloc failed!"); + goto error_out; + } + + context->handle = (void*)remdesk; + remdesk->context = context; + remdesk->rdpcontext = pEntryPointsEx->context; + } + + CopyMemory(&(remdesk->channelEntryPoints), pEntryPoints, + sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)); + remdesk->InitHandle = pInitHandle; + rc = remdesk->channelEntryPoints.pVirtualChannelInitEx( + remdesk, context, pInitHandle, &remdesk->channelDef, 1, VIRTUAL_CHANNEL_VERSION_WIN2000, + remdesk_virtual_channel_init_event_ex); + + if (CHANNEL_RC_OK != rc) + { + WLog_ERR(TAG, "pVirtualChannelInitEx failed with %s [%08" PRIX32 "]", WTSErrorToString(rc), + rc); + goto error_out; + } + + remdesk->channelEntryPoints.pInterface = context; + return TRUE; +error_out: + free(remdesk); + free(context); + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.h new file mode 100644 index 0000000000000000000000000000000000000000..0d9c48d4bf53c336e9a0564e7adf1e1157c38c6e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/client/remdesk_main.h @@ -0,0 +1,61 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_REMDESK_CLIENT_MAIN_H +#define FREERDP_CHANNEL_REMDESK_CLIENT_MAIN_H + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#define TAG CHANNELS_TAG("remdesk.client") + +typedef struct +{ + CHANNEL_DEF channelDef; + CHANNEL_ENTRY_POINTS_FREERDP_EX channelEntryPoints; + + RemdeskClientContext* context; + + HANDLE thread; + wStream* data_in; + void* InitHandle; + DWORD OpenHandle; + wMessageQueue* queue; + + UINT32 Version; + char* ExpertBlob; + BYTE* EncryptedPassStub; + size_t EncryptedPassStubSize; + rdpContext* rdpcontext; +} remdeskPlugin; + +#endif /* FREERDP_CHANNEL_REMDESK_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..afd7b62bc6ea6bdfd7329099401268506f81bfa1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/CMakeLists.txt @@ -0,0 +1,23 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2024 Armin Novak +# 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. + +set(SRCS remdesk_common.h remdesk_common.c) + +add_library(remdesk-common STATIC ${SRCS}) + +channel_install(remdesk-common ${FREERDP_ADDIN_PATH} "FreeRDPTargets") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.c b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.c new file mode 100644 index 0000000000000000000000000000000000000000..a4600e764bbacbb09112ac7cf2b25e8874899c80 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.c @@ -0,0 +1,105 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel - common components + * + * Copyright 2024 Armin Novak + * 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 "remdesk_common.h" + +#include +#define TAG CHANNELS_TAG("remdesk.common") + +UINT remdesk_write_channel_header(wStream* s, const REMDESK_CHANNEL_HEADER* header) +{ + WCHAR ChannelNameW[32] = { 0 }; + + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + for (size_t index = 0; index < 32; index++) + { + ChannelNameW[index] = (WCHAR)header->ChannelName[index]; + } + + const size_t ChannelNameLen = + (strnlen(header->ChannelName, sizeof(header->ChannelName)) + 1) * 2; + WINPR_ASSERT(ChannelNameLen <= ARRAYSIZE(header->ChannelName)); + + Stream_Write_UINT32(s, (UINT32)ChannelNameLen); /* ChannelNameLen (4 bytes) */ + Stream_Write_UINT32(s, header->DataLength); /* DataLen (4 bytes) */ + Stream_Write(s, ChannelNameW, ChannelNameLen); /* ChannelName (variable) */ + return CHANNEL_RC_OK; +} + +UINT remdesk_write_ctl_header(wStream* s, const REMDESK_CTL_HEADER* ctlHeader) +{ + WINPR_ASSERT(ctlHeader); + const UINT error = remdesk_write_channel_header(s, &ctlHeader->ch); + + if (error != 0) + { + WLog_ERR(TAG, "remdesk_write_channel_header failed with error %" PRIu32 "!", error); + return error; + } + + Stream_Write_UINT32(s, ctlHeader->msgType); /* msgType (4 bytes) */ + return CHANNEL_RC_OK; +} + +UINT remdesk_read_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* header) +{ + UINT32 ChannelNameLen = 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return CHANNEL_RC_NO_MEMORY; + + Stream_Read_UINT32(s, ChannelNameLen); /* ChannelNameLen (4 bytes) */ + Stream_Read_UINT32(s, header->DataLength); /* DataLen (4 bytes) */ + + if (ChannelNameLen > 64) + { + WLog_ERR(TAG, "ChannelNameLen > 64!"); + return ERROR_INVALID_DATA; + } + + if ((ChannelNameLen % 2) != 0) + { + WLog_ERR(TAG, "(ChannelNameLen %% 2) != 0!"); + return ERROR_INVALID_DATA; + } + + if (Stream_Read_UTF16_String_As_UTF8_Buffer(s, ChannelNameLen / sizeof(WCHAR), + header->ChannelName, + ARRAYSIZE(header->ChannelName)) < 0) + return ERROR_INVALID_DATA; + + return CHANNEL_RC_OK; +} + +UINT remdesk_prepare_ctl_header(REMDESK_CTL_HEADER* ctlHeader, UINT32 msgType, size_t msgSize) +{ + WINPR_ASSERT(ctlHeader); + + if (msgSize > UINT32_MAX - 4) + return ERROR_INVALID_PARAMETER; + + ctlHeader->msgType = msgType; + (void)sprintf_s(ctlHeader->ch.ChannelName, ARRAYSIZE(ctlHeader->ch.ChannelName), + REMDESK_CHANNEL_CTL_NAME); + ctlHeader->ch.DataLength = (UINT32)(4UL + msgSize); + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.h b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.h new file mode 100644 index 0000000000000000000000000000000000000000..98bd26b8a1758fe441c9bf46e0d529c4aa265bca --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/common/remdesk_common.h @@ -0,0 +1,32 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel - common components + * + * Copyright 2024 Armin Novak + * 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 +#include + +#include + +FREERDP_LOCAL UINT remdesk_write_channel_header(wStream* s, const REMDESK_CHANNEL_HEADER* header); +FREERDP_LOCAL UINT remdesk_write_ctl_header(wStream* s, const REMDESK_CTL_HEADER* ctlHeader); +FREERDP_LOCAL UINT remdesk_read_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* header); +FREERDP_LOCAL UINT remdesk_prepare_ctl_header(REMDESK_CTL_HEADER* ctlHeader, UINT32 msgType, + size_t msgSize); diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7725e6677f573111eb69a8ce94a058bbe601feca --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/CMakeLists.txt @@ -0,0 +1,24 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_server("remdesk") + +set(${MODULE_PREFIX}_SRCS remdesk_main.c remdesk_main.h) + +set(${MODULE_PREFIX}_LIBS winpr remdesk-common) + +add_channel_server_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} FALSE "VirtualChannelEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.c new file mode 100644 index 0000000000000000000000000000000000000000..82ef3663ee178adc5604f4a2fd01bce008440927 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.c @@ -0,0 +1,650 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include + +#include + +#include "remdesk_main.h" +#include "remdesk_common.h" + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_virtual_channel_write(RemdeskServerContext* context, wStream* s) +{ + const size_t len = Stream_Length(s); + WINPR_ASSERT(len <= UINT32_MAX); + ULONG BytesWritten = 0; + BOOL status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (UINT32)len, &BytesWritten); + return (status) ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_result_pdu(RemdeskServerContext* context, UINT32 result) +{ + wStream* s = NULL; + REMDESK_CTL_RESULT_PDU pdu; + UINT error = 0; + pdu.result = result; + + if ((error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_RESULT, 4))) + { + WLog_ERR(TAG, "remdesk_prepare_ctl_header failed with error %" PRIu32 "!", error); + return error; + } + + s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if ((error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)))) + { + WLog_ERR(TAG, "remdesk_write_ctl_header failed with error %" PRIu32 "!", error); + goto out; + } + + Stream_Write_UINT32(s, pdu.result); /* result (4 bytes) */ + Stream_SealLength(s); + + if ((error = remdesk_virtual_channel_write(context, s))) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + +out: + Stream_Free(s, TRUE); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_send_ctl_version_info_pdu(RemdeskServerContext* context) +{ + wStream* s = NULL; + REMDESK_CTL_VERSION_INFO_PDU pdu; + UINT error = 0; + + if ((error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERSIONINFO, 8))) + { + WLog_ERR(TAG, "remdesk_prepare_ctl_header failed with error %" PRIu32 "!", error); + return error; + } + + pdu.versionMajor = 1; + pdu.versionMinor = 2; + s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + if ((error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)))) + { + WLog_ERR(TAG, "remdesk_write_ctl_header failed with error %" PRIu32 "!", error); + goto out; + } + + Stream_Write_UINT32(s, pdu.versionMajor); /* versionMajor (4 bytes) */ + Stream_Write_UINT32(s, pdu.versionMinor); /* versionMinor (4 bytes) */ + Stream_SealLength(s); + + if ((error = remdesk_virtual_channel_write(context, s))) + WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); + +out: + Stream_Free(s, TRUE); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_version_info_pdu(RemdeskServerContext* context, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + UINT32 versionMajor = 0; + UINT32 versionMinor = 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, versionMajor); /* versionMajor (4 bytes) */ + Stream_Read_UINT32(s, versionMinor); /* versionMinor (4 bytes) */ + if ((versionMajor != 1) || (versionMinor != 2)) + { + WLog_ERR(TAG, "REMOTEDESKTOP_CTL_VERSIONINFO_PACKET invalid version %" PRIu32 ".%" PRIu32, + versionMajor, versionMinor); + return ERROR_INVALID_DATA; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_remote_control_desktop_pdu(RemdeskServerContext* context, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + size_t cchStringW = 0; + REMDESK_CTL_REMOTE_CONTROL_DESKTOP_PDU pdu = { 0 }; + UINT error = 0; + UINT32 msgLength = header->DataLength - 4; + const WCHAR* pStringW = Stream_ConstPointer(s); + const WCHAR* raConnectionStringW = pStringW; + + while ((msgLength > 0) && pStringW[cchStringW]) + { + msgLength -= 2; + cchStringW++; + } + + if (pStringW[cchStringW] || !cchStringW) + return ERROR_INVALID_DATA; + + cchStringW++; + const size_t cbRaConnectionStringW = cchStringW * 2; + pdu.raConnectionString = + ConvertWCharNToUtf8Alloc(raConnectionStringW, cbRaConnectionStringW / sizeof(WCHAR), NULL); + if (!pdu.raConnectionString) + return ERROR_INTERNAL_ERROR; + + WLog_INFO(TAG, "RaConnectionString: %s", pdu.raConnectionString); + free(pdu.raConnectionString); + + if ((error = remdesk_send_ctl_result_pdu(context, 0))) + WLog_ERR(TAG, "remdesk_send_ctl_result_pdu failed with error %" PRIu32 "!", error); + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_authenticate_pdu(RemdeskServerContext* context, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + size_t cchTmpStringW = 0; + const WCHAR* expertBlobW = NULL; + REMDESK_CTL_AUTHENTICATE_PDU pdu = { 0 }; + UINT32 msgLength = header->DataLength - 4; + const WCHAR* pStringW = Stream_ConstPointer(s); + const WCHAR* raConnectionStringW = pStringW; + + while ((msgLength > 0) && pStringW[cchTmpStringW]) + { + msgLength -= 2; + cchTmpStringW++; + } + + if (pStringW[cchTmpStringW] || !cchTmpStringW) + return ERROR_INVALID_DATA; + + cchTmpStringW++; + const size_t cbRaConnectionStringW = cchTmpStringW * sizeof(WCHAR); + pStringW += cchTmpStringW; + expertBlobW = pStringW; + + size_t cchStringW = 0; + while ((msgLength > 0) && pStringW[cchStringW]) + { + msgLength -= 2; + cchStringW++; + } + + if (pStringW[cchStringW] || !cchStringW) + return ERROR_INVALID_DATA; + + cchStringW++; + const size_t cbExpertBlobW = cchStringW * 2; + pdu.raConnectionString = + ConvertWCharNToUtf8Alloc(raConnectionStringW, cbRaConnectionStringW / sizeof(WCHAR), NULL); + if (!pdu.raConnectionString) + return ERROR_INTERNAL_ERROR; + + pdu.expertBlob = ConvertWCharNToUtf8Alloc(expertBlobW, cbExpertBlobW / sizeof(WCHAR), NULL); + if (!pdu.expertBlob) + { + free(pdu.raConnectionString); + return ERROR_INTERNAL_ERROR; + } + + WLog_INFO(TAG, "RaConnectionString: %s ExpertBlob: %s", pdu.raConnectionString, pdu.expertBlob); + free(pdu.raConnectionString); + free(pdu.expertBlob); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_verify_password_pdu(RemdeskServerContext* context, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + REMDESK_CTL_VERIFY_PASSWORD_PDU pdu = { 0 }; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return ERROR_INVALID_DATA; + + const WCHAR* expertBlobW = Stream_ConstPointer(s); + if (header->DataLength < 4) + return ERROR_INVALID_PARAMETER; + + const size_t cbExpertBlobW = header->DataLength - 4; + + pdu.expertBlob = ConvertWCharNToUtf8Alloc(expertBlobW, cbExpertBlobW / sizeof(WCHAR), NULL); + if (!pdu.expertBlob) + return ERROR_INTERNAL_ERROR; + + WLog_INFO(TAG, "ExpertBlob: %s", pdu.expertBlob); + + // TODO: Callback? + + free(pdu.expertBlob); + return remdesk_send_ctl_result_pdu(context, 0); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_recv_ctl_pdu(RemdeskServerContext* context, wStream* s, + REMDESK_CHANNEL_HEADER* header) +{ + UINT error = CHANNEL_RC_OK; + UINT32 msgType = 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, msgType); /* msgType (4 bytes) */ + WLog_INFO(TAG, "msgType: %" PRIu32 "", msgType); + + switch (msgType) + { + case REMDESK_CTL_REMOTE_CONTROL_DESKTOP: + if ((error = remdesk_recv_ctl_remote_control_desktop_pdu(context, s, header))) + { + WLog_ERR(TAG, + "remdesk_recv_ctl_remote_control_desktop_pdu failed with error %" PRIu32 + "!", + error); + return error; + } + + break; + + case REMDESK_CTL_AUTHENTICATE: + if ((error = remdesk_recv_ctl_authenticate_pdu(context, s, header))) + { + WLog_ERR(TAG, "remdesk_recv_ctl_authenticate_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case REMDESK_CTL_DISCONNECT: + break; + + case REMDESK_CTL_VERSIONINFO: + if ((error = remdesk_recv_ctl_version_info_pdu(context, s, header))) + { + WLog_ERR(TAG, "remdesk_recv_ctl_version_info_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case REMDESK_CTL_ISCONNECTED: + break; + + case REMDESK_CTL_VERIFY_PASSWORD: + if ((error = remdesk_recv_ctl_verify_password_pdu(context, s, header))) + { + WLog_ERR(TAG, "remdesk_recv_ctl_verify_password_pdu failed with error %" PRIu32 "!", + error); + return error; + } + + break; + + case REMDESK_CTL_EXPERT_ON_VISTA: + break; + + case REMDESK_CTL_RANOVICE_NAME: + break; + + case REMDESK_CTL_RAEXPERT_NAME: + break; + + case REMDESK_CTL_TOKEN: + break; + + default: + WLog_ERR(TAG, "remdesk_recv_control_pdu: unknown msgType: %" PRIu32 "", msgType); + error = ERROR_INVALID_DATA; + break; + } + + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_server_receive_pdu(RemdeskServerContext* context, wStream* s) +{ + UINT error = CHANNEL_RC_OK; + REMDESK_CHANNEL_HEADER header; +#if 0 + WLog_INFO(TAG, "RemdeskReceive: %"PRIuz"", Stream_GetRemainingLength(s)); + winpr_HexDump(WCHAR* expertBlobW = NULL;(s), Stream_GetRemainingLength(s)); +#endif + + if ((error = remdesk_read_channel_header(s, &header))) + { + WLog_ERR(TAG, "remdesk_read_channel_header failed with error %" PRIu32 "!", error); + return error; + } + + if (strcmp(header.ChannelName, "RC_CTL") == 0) + { + if ((error = remdesk_recv_ctl_pdu(context, s, &header))) + { + WLog_ERR(TAG, "remdesk_recv_ctl_pdu failed with error %" PRIu32 "!", error); + return error; + } + } + else if (strcmp(header.ChannelName, "70") == 0) + { + } + else if (strcmp(header.ChannelName, "71") == 0) + { + } + else if (strcmp(header.ChannelName, ".") == 0) + { + } + else if (strcmp(header.ChannelName, "1000.") == 0) + { + } + else if (strcmp(header.ChannelName, "RA_FX") == 0) + { + } + else + { + } + + return error; +} + +static DWORD WINAPI remdesk_server_thread(LPVOID arg) +{ + wStream* s = NULL; + DWORD status = 0; + DWORD nCount = 0; + void* buffer = NULL; + UINT32* pHeader = NULL; + UINT32 PduLength = 0; + HANDLE events[8]; + HANDLE ChannelEvent = NULL; + DWORD BytesReturned = 0; + RemdeskServerContext* context = NULL; + UINT error = 0; + context = (RemdeskServerContext*)arg; + buffer = NULL; + BytesReturned = 0; + ChannelEvent = NULL; + s = Stream_New(NULL, 4096); + + if (!s) + { + WLog_ERR(TAG, "Stream_New failed!"); + error = CHANNEL_RC_NO_MEMORY; + goto out; + } + + if (WTSVirtualChannelQuery(context->priv->ChannelHandle, WTSVirtualEventHandle, &buffer, + &BytesReturned) == TRUE) + { + if (BytesReturned == sizeof(HANDLE)) + ChannelEvent = *(HANDLE*)buffer; + + WTSFreeMemory(buffer); + } + else + { + WLog_ERR(TAG, "WTSVirtualChannelQuery failed!"); + error = ERROR_INTERNAL_ERROR; + goto out; + } + + nCount = 0; + events[nCount++] = ChannelEvent; + events[nCount++] = context->priv->StopEvent; + + if ((error = remdesk_send_ctl_version_info_pdu(context))) + { + WLog_ERR(TAG, "remdesk_send_ctl_version_info_pdu failed with error %" PRIu32 "!", error); + goto out; + } + + while (1) + { + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "", error); + break; + } + + status = WaitForSingleObject(context->priv->StopEvent, 0); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); + break; + } + + if (status == WAIT_OBJECT_0) + { + break; + } + + const size_t len = Stream_Capacity(s); + if (len > UINT32_MAX) + { + error = ERROR_INTERNAL_ERROR; + break; + } + if (WTSVirtualChannelRead(context->priv->ChannelHandle, 0, Stream_BufferAs(s, char), + (UINT32)len, &BytesReturned)) + { + if (BytesReturned) + Stream_Seek(s, BytesReturned); + } + else + { + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + { + WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); + error = CHANNEL_RC_NO_MEMORY; + break; + } + } + + if (Stream_GetPosition(s) >= 8) + { + pHeader = Stream_BufferAs(s, UINT32); + PduLength = pHeader[0] + pHeader[1] + 8; + + if (PduLength >= Stream_GetPosition(s)) + { + Stream_SealLength(s); + Stream_SetPosition(s, 0); + + if ((error = remdesk_server_receive_pdu(context, s))) + { + WLog_ERR(TAG, "remdesk_server_receive_pdu failed with error %" PRIu32 "!", + error); + break; + } + + Stream_SetPosition(s, 0); + } + } + } + + Stream_Free(s, TRUE); +out: + + if (error && context->rdpcontext) + setChannelError(context->rdpcontext, error, "remdesk_server_thread reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_server_start(RemdeskServerContext* context) +{ + context->priv->ChannelHandle = + WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, REMDESK_SVC_CHANNEL_NAME); + + if (!context->priv->ChannelHandle) + { + WLog_ERR(TAG, "WTSVirtualChannelOpen failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (!(context->priv->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + WLog_ERR(TAG, "CreateEvent failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (!(context->priv->Thread = + CreateThread(NULL, 0, remdesk_server_thread, (void*)context, 0, NULL))) + { + WLog_ERR(TAG, "CreateThread failed!"); + (void)CloseHandle(context->priv->StopEvent); + context->priv->StopEvent = NULL; + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT remdesk_server_stop(RemdeskServerContext* context) +{ + UINT error = 0; + (void)SetEvent(context->priv->StopEvent); + + if (WaitForSingleObject(context->priv->Thread, INFINITE) == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error); + return error; + } + + (void)CloseHandle(context->priv->Thread); + (void)CloseHandle(context->priv->StopEvent); + return CHANNEL_RC_OK; +} + +RemdeskServerContext* remdesk_server_context_new(HANDLE vcm) +{ + RemdeskServerContext* context = NULL; + context = (RemdeskServerContext*)calloc(1, sizeof(RemdeskServerContext)); + + if (context) + { + context->vcm = vcm; + context->Start = remdesk_server_start; + context->Stop = remdesk_server_stop; + context->priv = (RemdeskServerPrivate*)calloc(1, sizeof(RemdeskServerPrivate)); + + if (!context->priv) + { + free(context); + return NULL; + } + + context->priv->Version = 1; + } + + return context; +} + +void remdesk_server_context_free(RemdeskServerContext* context) +{ + if (context) + { + if (context->priv->ChannelHandle != INVALID_HANDLE_VALUE) + (void)WTSVirtualChannelClose(context->priv->ChannelHandle); + + free(context->priv); + free(context); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.h new file mode 100644 index 0000000000000000000000000000000000000000..4268e4ed1d74c8b8a0a224417718ccac25b6c20e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/remdesk/server/remdesk_main.h @@ -0,0 +1,41 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Assistance Virtual Channel + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_CHANNEL_REMDESK_SERVER_MAIN_H +#define FREERDP_CHANNEL_REMDESK_SERVER_MAIN_H + +#include +#include +#include + +#include +#include + +#define TAG CHANNELS_TAG("remdesk.server") + +struct s_remdesk_server_private +{ + HANDLE Thread; + HANDLE StopEvent; + void* ChannelHandle; + + UINT32 Version; +}; + +#endif /* FREERDP_CHANNEL_REMDESK_SERVER_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ccdb6ba4cea2b732f5d55aada6a21a92629a26a3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.c @@ -0,0 +1,721 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Smartcard Device Service Virtual Channel + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2011 Anthony Tong + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "smartcard_main.h" + +#define CAST_FROM_DEVICE(device) cast_device_from(device, __func__, __FILE__, __LINE__) + +typedef struct +{ + SMARTCARD_OPERATION operation; + IRP* irp; +} scard_irp_queue_element; + +static SMARTCARD_DEVICE* sSmartcard = NULL; + +static void smartcard_context_free(void* pCtx); + +static UINT smartcard_complete_irp(SMARTCARD_DEVICE* smartcard, IRP* irp, BOOL* handled); + +static SMARTCARD_DEVICE* cast_device_from(DEVICE* device, const char* fkt, const char* file, + size_t line) +{ + if (!device) + { + WLog_ERR(TAG, "%s [%s:%" PRIuz "] Called smartcard channel with NULL device", fkt, file, + line); + return NULL; + } + + if (device->type != RDPDR_DTYP_SMARTCARD) + { + WLog_ERR(TAG, + "%s [%s:%" PRIuz "] Called smartcard channel with invalid device of type %" PRIx32, + fkt, file, line, device->type); + return NULL; + } + + return (SMARTCARD_DEVICE*)device; +} + +static DWORD WINAPI smartcard_context_thread(LPVOID arg) +{ + SMARTCARD_CONTEXT* pContext = (SMARTCARD_CONTEXT*)arg; + DWORD nCount = 0; + LONG status = 0; + DWORD waitStatus = 0; + HANDLE hEvents[2] = { 0 }; + wMessage message = { 0 }; + SMARTCARD_DEVICE* smartcard = NULL; + UINT error = CHANNEL_RC_OK; + smartcard = pContext->smartcard; + + hEvents[nCount++] = MessageQueue_Event(pContext->IrpQueue); + + while (1) + { + waitStatus = WaitForMultipleObjects(nCount, hEvents, FALSE, INFINITE); + + if (waitStatus == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "!", error); + break; + } + + waitStatus = WaitForSingleObject(MessageQueue_Event(pContext->IrpQueue), 0); + + if (waitStatus == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error); + break; + } + + if (waitStatus == WAIT_OBJECT_0) + { + scard_irp_queue_element* element = NULL; + + if (!MessageQueue_Peek(pContext->IrpQueue, &message, TRUE)) + { + WLog_ERR(TAG, "MessageQueue_Peek failed!"); + status = ERROR_INTERNAL_ERROR; + break; + } + + if (message.id == WMQ_QUIT) + break; + + element = (scard_irp_queue_element*)message.wParam; + + if (element) + { + BOOL handled = FALSE; + WINPR_ASSERT(smartcard); + + if ((status = smartcard_irp_device_control_call( + smartcard->callctx, element->irp->output, &element->irp->IoStatus, + &element->operation))) + { + element->irp->Discard(element->irp); + smartcard_operation_free(&element->operation, TRUE); + WLog_ERR(TAG, "smartcard_irp_device_control_call failed with error %" PRIu32 "", + status); + break; + } + + error = smartcard_complete_irp(smartcard, element->irp, &handled); + if (!handled) + element->irp->Discard(element->irp); + smartcard_operation_free(&element->operation, TRUE); + + if (error) + { + WLog_ERR(TAG, "Queue_Enqueue failed!"); + break; + } + } + } + } + + if (status && smartcard->rdpcontext) + setChannelError(smartcard->rdpcontext, error, "smartcard_context_thread reported an error"); + + ExitThread((uint32_t)status); + return error; +} + +static void smartcard_operation_queue_free(void* obj) +{ + wMessage* msg = obj; + if (!msg) + return; + if (msg->id != 0) + return; + + scard_irp_queue_element* element = (scard_irp_queue_element*)msg->wParam; + if (!element) + return; + WINPR_ASSERT(element->irp); + WINPR_ASSERT(element->irp->Discard); + element->irp->Discard(element->irp); + smartcard_operation_free(&element->operation, TRUE); +} + +static void* smartcard_context_new(void* smartcard, SCARDCONTEXT hContext) +{ + SMARTCARD_CONTEXT* pContext = NULL; + pContext = (SMARTCARD_CONTEXT*)calloc(1, sizeof(SMARTCARD_CONTEXT)); + + if (!pContext) + { + WLog_ERR(TAG, "calloc failed!"); + return pContext; + } + + pContext->smartcard = smartcard; + pContext->hContext = hContext; + pContext->IrpQueue = MessageQueue_New(NULL); + + if (!pContext->IrpQueue) + { + WLog_ERR(TAG, "MessageQueue_New failed!"); + goto fail; + } + wObject* obj = MessageQueue_Object(pContext->IrpQueue); + WINPR_ASSERT(obj); + obj->fnObjectFree = smartcard_operation_queue_free; + + pContext->thread = CreateThread(NULL, 0, smartcard_context_thread, pContext, 0, NULL); + + if (!pContext->thread) + { + WLog_ERR(TAG, "CreateThread failed!"); + goto fail; + } + + return pContext; +fail: + smartcard_context_free(pContext); + return NULL; +} + +void smartcard_context_free(void* pCtx) +{ + SMARTCARD_CONTEXT* pContext = pCtx; + + if (!pContext) + return; + + /* cancel blocking calls like SCardGetStatusChange */ + WINPR_ASSERT(pContext->smartcard); + smartcard_call_cancel_context(pContext->smartcard->callctx, pContext->hContext); + + if (pContext->IrpQueue) + { + if (MessageQueue_PostQuit(pContext->IrpQueue, 0)) + { + if (WaitForSingleObject(pContext->thread, INFINITE) == WAIT_FAILED) + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", GetLastError()); + + (void)CloseHandle(pContext->thread); + } + MessageQueue_Free(pContext->IrpQueue); + } + smartcard_call_release_context(pContext->smartcard->callctx, pContext->hContext); + free(pContext); +} + +static void smartcard_release_all_contexts(SMARTCARD_DEVICE* smartcard) +{ + smartcard_call_cancel_all_context(smartcard->callctx); +} + +static UINT smartcard_free_(SMARTCARD_DEVICE* smartcard) +{ + if (!smartcard) + return CHANNEL_RC_OK; + + if (smartcard->IrpQueue) + { + MessageQueue_Free(smartcard->IrpQueue); + (void)CloseHandle(smartcard->thread); + } + + Stream_Free(smartcard->device.data, TRUE); + ListDictionary_Free(smartcard->rgOutstandingMessages); + + smartcard_call_context_free(smartcard->callctx); + + free(smartcard); + return CHANNEL_RC_OK; +} +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT smartcard_free(DEVICE* device) +{ + SMARTCARD_DEVICE* smartcard = CAST_FROM_DEVICE(device); + + if (!smartcard) + return ERROR_INVALID_PARAMETER; + + /** + * Calling smartcard_release_all_contexts to unblock all operations waiting for transactions + * to unlock. + */ + smartcard_release_all_contexts(smartcard); + + /* Stopping all threads and cancelling all IRPs */ + + if (smartcard->IrpQueue) + { + if (MessageQueue_PostQuit(smartcard->IrpQueue, 0) && + (WaitForSingleObject(smartcard->thread, INFINITE) == WAIT_FAILED)) + { + DWORD error = GetLastError(); + WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error); + return error; + } + } + + if (sSmartcard == smartcard) + sSmartcard = NULL; + + return smartcard_free_(smartcard); +} + +/** + * Initialization occurs when the protocol server sends a device announce message. + * At that time, we need to cancel all outstanding IRPs. + */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT smartcard_init(DEVICE* device) +{ + SMARTCARD_DEVICE* smartcard = CAST_FROM_DEVICE(device); + + if (!smartcard) + return ERROR_INVALID_PARAMETER; + + smartcard_release_all_contexts(smartcard); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +UINT smartcard_complete_irp(SMARTCARD_DEVICE* smartcard, IRP* irp, BOOL* handled) +{ + WINPR_ASSERT(smartcard); + WINPR_ASSERT(irp); + WINPR_ASSERT(handled); + + uintptr_t key = (uintptr_t)irp->CompletionId + 1; + ListDictionary_Remove(smartcard->rgOutstandingMessages, (void*)key); + + WINPR_ASSERT(irp->Complete); + *handled = TRUE; + return irp->Complete(irp); +} + +/** + * Multiple threads and SCardGetStatusChange: + * http://musclecard.996296.n3.nabble.com/Multiple-threads-and-SCardGetStatusChange-td4430.html + */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT smartcard_process_irp(SMARTCARD_DEVICE* smartcard, IRP* irp, BOOL* handled) +{ + LONG status = 0; + BOOL asyncIrp = FALSE; + SMARTCARD_CONTEXT* pContext = NULL; + + WINPR_ASSERT(smartcard); + WINPR_ASSERT(handled); + WINPR_ASSERT(irp); + WINPR_ASSERT(irp->Complete); + + uintptr_t key = (uintptr_t)irp->CompletionId + 1; + + if (!ListDictionary_Add(smartcard->rgOutstandingMessages, (void*)key, irp)) + { + WLog_ERR(TAG, "ListDictionary_Add failed!"); + return ERROR_INTERNAL_ERROR; + } + + if (irp->MajorFunction == IRP_MJ_DEVICE_CONTROL) + { + scard_irp_queue_element* element = calloc(1, sizeof(scard_irp_queue_element)); + if (!element) + return ERROR_OUTOFMEMORY; + + element->irp = irp; + element->operation.completionID = irp->CompletionId; + + status = smartcard_irp_device_control_decode(irp->input, irp->CompletionId, irp->FileId, + &element->operation); + + if (status != SCARD_S_SUCCESS) + { + UINT error = 0; + + smartcard_operation_free(&element->operation, TRUE); + irp->IoStatus = STATUS_UNSUCCESSFUL; + + if ((error = smartcard_complete_irp(smartcard, irp, handled))) + { + WLog_ERR(TAG, "Queue_Enqueue failed!"); + return error; + } + + return CHANNEL_RC_OK; + } + + asyncIrp = TRUE; + + switch (element->operation.ioControlCode) + { + case SCARD_IOCTL_ESTABLISHCONTEXT: + case SCARD_IOCTL_RELEASECONTEXT: + case SCARD_IOCTL_ISVALIDCONTEXT: + case SCARD_IOCTL_CANCEL: + case SCARD_IOCTL_ACCESSSTARTEDEVENT: + case SCARD_IOCTL_RELEASETARTEDEVENT: + asyncIrp = FALSE; + break; + + case SCARD_IOCTL_LISTREADERGROUPSA: + case SCARD_IOCTL_LISTREADERGROUPSW: + case SCARD_IOCTL_LISTREADERSA: + case SCARD_IOCTL_LISTREADERSW: + case SCARD_IOCTL_INTRODUCEREADERGROUPA: + case SCARD_IOCTL_INTRODUCEREADERGROUPW: + case SCARD_IOCTL_FORGETREADERGROUPA: + case SCARD_IOCTL_FORGETREADERGROUPW: + case SCARD_IOCTL_INTRODUCEREADERA: + case SCARD_IOCTL_INTRODUCEREADERW: + case SCARD_IOCTL_FORGETREADERA: + case SCARD_IOCTL_FORGETREADERW: + case SCARD_IOCTL_ADDREADERTOGROUPA: + case SCARD_IOCTL_ADDREADERTOGROUPW: + case SCARD_IOCTL_REMOVEREADERFROMGROUPA: + case SCARD_IOCTL_REMOVEREADERFROMGROUPW: + case SCARD_IOCTL_LOCATECARDSA: + case SCARD_IOCTL_LOCATECARDSW: + case SCARD_IOCTL_LOCATECARDSBYATRA: + case SCARD_IOCTL_LOCATECARDSBYATRW: + case SCARD_IOCTL_READCACHEA: + case SCARD_IOCTL_READCACHEW: + case SCARD_IOCTL_WRITECACHEA: + case SCARD_IOCTL_WRITECACHEW: + case SCARD_IOCTL_GETREADERICON: + case SCARD_IOCTL_GETDEVICETYPEID: + case SCARD_IOCTL_GETSTATUSCHANGEA: + case SCARD_IOCTL_GETSTATUSCHANGEW: + case SCARD_IOCTL_CONNECTA: + case SCARD_IOCTL_CONNECTW: + case SCARD_IOCTL_RECONNECT: + case SCARD_IOCTL_DISCONNECT: + case SCARD_IOCTL_BEGINTRANSACTION: + case SCARD_IOCTL_ENDTRANSACTION: + case SCARD_IOCTL_STATE: + case SCARD_IOCTL_STATUSA: + case SCARD_IOCTL_STATUSW: + case SCARD_IOCTL_TRANSMIT: + case SCARD_IOCTL_CONTROL: + case SCARD_IOCTL_GETATTRIB: + case SCARD_IOCTL_SETATTRIB: + case SCARD_IOCTL_GETTRANSMITCOUNT: + asyncIrp = TRUE; + break; + default: + break; + } + + pContext = smartcard_call_get_context(smartcard->callctx, element->operation.hContext); + + if (!pContext) + asyncIrp = FALSE; + + if (!asyncIrp) + { + UINT error = 0; + + status = + smartcard_irp_device_control_call(smartcard->callctx, element->irp->output, + &element->irp->IoStatus, &element->operation); + smartcard_operation_free(&element->operation, TRUE); + + if (status) + { + WLog_ERR(TAG, "smartcard_irp_device_control_call failed with error %" PRId32 "!", + status); + return (UINT32)status; + } + + if ((error = smartcard_complete_irp(smartcard, irp, handled))) + { + WLog_ERR(TAG, "Queue_Enqueue failed!"); + return error; + } + } + else + { + if (pContext) + { + if (!MessageQueue_Post(pContext->IrpQueue, NULL, 0, (void*)element, NULL)) + { + smartcard_operation_free(&element->operation, TRUE); + WLog_ERR(TAG, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + *handled = TRUE; + } + } + } + else + { + UINT ustatus = 0; + WLog_ERR(TAG, "Unexpected SmartCard IRP: MajorFunction %s, MinorFunction: 0x%08" PRIX32 "", + rdpdr_irp_string(irp->MajorFunction), irp->MinorFunction); + irp->IoStatus = STATUS_NOT_SUPPORTED; + + if ((ustatus = smartcard_complete_irp(smartcard, irp, handled))) + { + WLog_ERR(TAG, "Queue_Enqueue failed!"); + return ustatus; + } + } + + return CHANNEL_RC_OK; +} + +static DWORD WINAPI smartcard_thread_func(LPVOID arg) +{ + IRP* irp = NULL; + DWORD nCount = 0; + DWORD status = 0; + HANDLE hEvents[1] = { 0 }; + wMessage message = { 0 }; + UINT error = CHANNEL_RC_OK; + SMARTCARD_DEVICE* smartcard = CAST_FROM_DEVICE(arg); + + if (!smartcard) + return ERROR_INVALID_PARAMETER; + + hEvents[nCount++] = MessageQueue_Event(smartcard->IrpQueue); + + while (1) + { + status = WaitForMultipleObjects(nCount, hEvents, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + error = GetLastError(); + WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "!", error); + break; + } + + if (status == WAIT_OBJECT_0) + { + if (!MessageQueue_Peek(smartcard->IrpQueue, &message, TRUE)) + { + WLog_ERR(TAG, "MessageQueue_Peek failed!"); + error = ERROR_INTERNAL_ERROR; + break; + } + + if (message.id == WMQ_QUIT) + break; + + irp = (IRP*)message.wParam; + + if (irp) + { + BOOL handled = FALSE; + if ((error = smartcard_process_irp(smartcard, irp, &handled))) + { + WLog_ERR(TAG, "smartcard_process_irp failed with error %" PRIu32 "!", error); + goto out; + } + if (!handled) + { + WINPR_ASSERT(irp->Discard); + irp->Discard(irp); + } + } + } + } + +out: + + if (error && smartcard->rdpcontext) + setChannelError(smartcard->rdpcontext, error, "smartcard_thread_func reported an error"); + + ExitThread(error); + return error; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT smartcard_irp_request(DEVICE* device, IRP* irp) +{ + SMARTCARD_DEVICE* smartcard = CAST_FROM_DEVICE(device); + + if (!smartcard) + return ERROR_INVALID_PARAMETER; + + if (!MessageQueue_Post(smartcard->IrpQueue, NULL, 0, (void*)irp, NULL)) + { + WLog_ERR(TAG, "MessageQueue_Post failed!"); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +static void smartcard_free_irp(void* obj) +{ + wMessage* msg = obj; + if (!msg) + return; + if (msg->id != 0) + return; + + IRP* irp = (IRP*)msg->wParam; + if (!irp) + return; + WINPR_ASSERT(irp->Discard); + irp->Discard(irp); +} + +/* smartcard is always built-in */ +#define DeviceServiceEntry smartcard_DeviceServiceEntry + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)) +{ + SMARTCARD_DEVICE* smartcard = NULL; + size_t length = 0; + UINT error = CHANNEL_RC_NO_MEMORY; + + if (!sSmartcard) + { + smartcard = (SMARTCARD_DEVICE*)calloc(1, sizeof(SMARTCARD_DEVICE)); + + if (!smartcard) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + smartcard->device.type = RDPDR_DTYP_SMARTCARD; + smartcard->device.name = "SCARD"; + smartcard->device.IRPRequest = smartcard_irp_request; + smartcard->device.Init = smartcard_init; + smartcard->device.Free = smartcard_free; + smartcard->rdpcontext = pEntryPoints->rdpcontext; + length = strlen(smartcard->device.name); + smartcard->device.data = Stream_New(NULL, length + 1); + + if (!smartcard->device.data) + { + WLog_ERR(TAG, "Stream_New failed!"); + goto fail; + } + + Stream_Write(smartcard->device.data, "SCARD", 6); + smartcard->IrpQueue = MessageQueue_New(NULL); + + if (!smartcard->IrpQueue) + { + WLog_ERR(TAG, "MessageQueue_New failed!"); + goto fail; + } + + wObject* obj = MessageQueue_Object(smartcard->IrpQueue); + WINPR_ASSERT(obj); + obj->fnObjectFree = smartcard_free_irp; + + smartcard->rgOutstandingMessages = ListDictionary_New(TRUE); + + if (!smartcard->rgOutstandingMessages) + { + WLog_ERR(TAG, "ListDictionary_New failed!"); + goto fail; + } + + smartcard->callctx = smartcard_call_context_new(smartcard->rdpcontext->settings); + if (!smartcard->callctx) + goto fail; + + if (!smarcard_call_set_callbacks(smartcard->callctx, smartcard, smartcard_context_new, + smartcard_context_free)) + goto fail; + + if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, &smartcard->device))) + { + WLog_ERR(TAG, "RegisterDevice failed!"); + goto fail; + } + + smartcard->thread = + CreateThread(NULL, 0, smartcard_thread_func, smartcard, CREATE_SUSPENDED, NULL); + + if (!smartcard->thread) + { + WLog_ERR(TAG, "ListDictionary_New failed!"); + error = ERROR_INTERNAL_ERROR; + goto fail; + } + + ResumeThread(smartcard->thread); + } + else + smartcard = sSmartcard; + + if (pEntryPoints->device->Name) + { + smartcard_call_context_add(smartcard->callctx, pEntryPoints->device->Name); + } + + sSmartcard = smartcard; + return CHANNEL_RC_OK; +fail: + smartcard_free_(smartcard); + return error; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.h new file mode 100644 index 0000000000000000000000000000000000000000..c58858810a3e16f0b504e3117b1e40b936daa005 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/smartcard/client/smartcard_main.h @@ -0,0 +1,59 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Smartcard Device Service Virtual Channel + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 FREERDP_CHANNEL_SMARTCARD_CLIENT_MAIN_H +#define FREERDP_CHANNEL_SMARTCARD_CLIENT_MAIN_H + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#define TAG CHANNELS_TAG("smartcard.client") + +typedef struct +{ + DEVICE device; + + HANDLE thread; + scard_call_context* callctx; + wMessageQueue* IrpQueue; + wListDictionary* rgOutstandingMessages; + rdpContext* rdpcontext; +} SMARTCARD_DEVICE; + +typedef struct +{ + HANDLE thread; + SCARDCONTEXT hContext; + wMessageQueue* IrpQueue; + SMARTCARD_DEVICE* smartcard; +} SMARTCARD_CONTEXT; + +#endif /* FREERDP_CHANNEL_SMARTCARD_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..51ae4c5fcd98d7350608bce5cec6b10245bdea3b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/CMakeLists.txt @@ -0,0 +1,81 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2012 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. + +define_channel_client("tsmf") + +message(DEPRECATION "TSMF channel is no longer maintained. Use [MS-RDPEVOR] (/video) instead.") + +find_package(PkgConfig) +if(PkgConfig_FOUND) + pkg_check_modules(gstreamer gstreamer-1.0) +endif() + +if(WITH_GSTREAMER_1_0) + if(gstreamer_FOUND) + add_compile_definitions(WITH_GSTREAMER_1_0) + else() + message(WARNING "gstreamer not detected, disabling support") + endif() +endif() + +set(${MODULE_PREFIX}_SRCS + tsmf_audio.c + tsmf_audio.h + tsmf_codec.c + tsmf_codec.h + tsmf_constants.h + tsmf_decoder.c + tsmf_decoder.h + tsmf_ifman.c + tsmf_ifman.h + tsmf_main.c + tsmf_main.h + tsmf_media.c + tsmf_media.h + tsmf_types.h +) + +set(${MODULE_PREFIX}_LIBS winpr freerdp) +include_directories(..) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DVCPluginEntry") + +if(WITH_VIDEO_FFMPEG) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "ffmpeg" "decoder") +endif() + +if(WITH_GSTREAMER_1_0) + find_package(X11) + if(X11_Xrandr_FOUND) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "gstreamer" "decoder") + else() + message(WARNING "Disabling tsmf gstreamer because XRandR wasn't found") + endif() +endif() + +if(WITH_OSS) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "oss" "audio") +endif() + +if(WITH_ALSA) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "alsa" "audio") +endif() + +if(WITH_PULSE) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "pulse" "audio") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/alsa/tsmf_alsa.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/alsa/tsmf_alsa.c new file mode 100644 index 0000000000000000000000000000000000000000..125acc291f977a02681d673f30558f0a9d8f0f8f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/alsa/tsmf_alsa.c @@ -0,0 +1,238 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - ALSA Audio Device + * + * Copyright 2010-2011 Vic Lee + * + * 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 + +#include +#include +#include +#include + +#include + +#include + +#include +#include + +#include "tsmf_audio.h" + +typedef struct +{ + ITSMFAudioDevice iface; + + char device[32]; + snd_pcm_t* out_handle; + UINT32 source_rate; + UINT32 actual_rate; + UINT32 source_channels; + UINT32 actual_channels; + UINT32 bytes_per_sample; +} TSMFAlsaAudioDevice; + +static BOOL tsmf_alsa_open_device(TSMFAlsaAudioDevice* alsa) +{ + int error = 0; + error = snd_pcm_open(&alsa->out_handle, alsa->device, SND_PCM_STREAM_PLAYBACK, 0); + + if (error < 0) + { + WLog_ERR(TAG, "failed to open device %s", alsa->device); + return FALSE; + } + + DEBUG_TSMF("open device %s", alsa->device); + return TRUE; +} + +static BOOL tsmf_alsa_open(ITSMFAudioDevice* audio, const char* device) +{ + TSMFAlsaAudioDevice* alsa = (TSMFAlsaAudioDevice*)audio; + + if (!device) + { + strncpy(alsa->device, "default", sizeof(alsa->device)); + } + else + { + strncpy(alsa->device, device, sizeof(alsa->device) - 1); + } + + return tsmf_alsa_open_device(alsa); +} + +static BOOL tsmf_alsa_set_format(ITSMFAudioDevice* audio, UINT32 sample_rate, UINT32 channels, + UINT32 bits_per_sample) +{ + int error = 0; + snd_pcm_uframes_t frames = 0; + snd_pcm_hw_params_t* hw_params = NULL; + snd_pcm_sw_params_t* sw_params = NULL; + TSMFAlsaAudioDevice* alsa = (TSMFAlsaAudioDevice*)audio; + + if (!alsa->out_handle) + return FALSE; + + snd_pcm_drop(alsa->out_handle); + alsa->actual_rate = alsa->source_rate = sample_rate; + alsa->actual_channels = alsa->source_channels = channels; + alsa->bytes_per_sample = bits_per_sample / 8; + error = snd_pcm_hw_params_malloc(&hw_params); + + if (error < 0) + { + WLog_ERR(TAG, "snd_pcm_hw_params_malloc failed"); + return FALSE; + } + + snd_pcm_hw_params_any(alsa->out_handle, hw_params); + snd_pcm_hw_params_set_access(alsa->out_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); + snd_pcm_hw_params_set_format(alsa->out_handle, hw_params, SND_PCM_FORMAT_S16_LE); + snd_pcm_hw_params_set_rate_near(alsa->out_handle, hw_params, &alsa->actual_rate, NULL); + snd_pcm_hw_params_set_channels_near(alsa->out_handle, hw_params, &alsa->actual_channels); + frames = sample_rate; + snd_pcm_hw_params_set_buffer_size_near(alsa->out_handle, hw_params, &frames); + snd_pcm_hw_params(alsa->out_handle, hw_params); + snd_pcm_hw_params_free(hw_params); + error = snd_pcm_sw_params_malloc(&sw_params); + + if (error < 0) + { + WLog_ERR(TAG, "snd_pcm_sw_params_malloc"); + return FALSE; + } + + snd_pcm_sw_params_current(alsa->out_handle, sw_params); + snd_pcm_sw_params_set_start_threshold(alsa->out_handle, sw_params, frames / 2); + snd_pcm_sw_params(alsa->out_handle, sw_params); + snd_pcm_sw_params_free(sw_params); + snd_pcm_prepare(alsa->out_handle); + DEBUG_TSMF("sample_rate %" PRIu32 " channels %" PRIu32 " bits_per_sample %" PRIu32 "", + sample_rate, channels, bits_per_sample); + DEBUG_TSMF("hardware buffer %lu frames", frames); + + if ((alsa->actual_rate != alsa->source_rate) || + (alsa->actual_channels != alsa->source_channels)) + { + DEBUG_TSMF("actual rate %" PRIu32 " / channel %" PRIu32 " is different " + "from source rate %" PRIu32 " / channel %" PRIu32 ", resampling required.", + alsa->actual_rate, alsa->actual_channels, alsa->source_rate, + alsa->source_channels); + } + + return TRUE; +} + +static BOOL tsmf_alsa_play(ITSMFAudioDevice* audio, const BYTE* src, UINT32 data_size) +{ + const BYTE* pindex = NULL; + TSMFAlsaAudioDevice* alsa = (TSMFAlsaAudioDevice*)audio; + DEBUG_TSMF("data_size %" PRIu32 "", data_size); + + if (alsa->out_handle) + { + const size_t rbytes_per_frame = 1ULL * alsa->actual_channels * alsa->bytes_per_sample; + pindex = src; + const BYTE* end = pindex + data_size; + + while (pindex < end) + { + const size_t len = (size_t)(end - pindex); + const size_t frames = len / rbytes_per_frame; + snd_pcm_sframes_t error = snd_pcm_writei(alsa->out_handle, pindex, frames); + + if (error == -EPIPE) + { + snd_pcm_recover(alsa->out_handle, -EPIPE, 0); + error = 0; + } + else if (error < 0) + { + DEBUG_TSMF("error len %ld", error); + snd_pcm_close(alsa->out_handle); + alsa->out_handle = 0; + tsmf_alsa_open_device(alsa); + break; + } + + DEBUG_TSMF("%d frames played.", error); + + if (error == 0) + break; + + pindex += (size_t)error * rbytes_per_frame; + } + } + + return TRUE; +} + +static UINT64 tsmf_alsa_get_latency(ITSMFAudioDevice* audio) +{ + UINT64 latency = 0; + snd_pcm_sframes_t frames = 0; + TSMFAlsaAudioDevice* alsa = (TSMFAlsaAudioDevice*)audio; + + if (alsa->out_handle && alsa->actual_rate > 0 && + snd_pcm_delay(alsa->out_handle, &frames) == 0 && frames > 0) + { + latency = ((UINT64)frames) * 10000000LL / (UINT64)alsa->actual_rate; + } + + return latency; +} + +static BOOL tsmf_alsa_flush(ITSMFAudioDevice* audio) +{ + return TRUE; +} + +static void tsmf_alsa_free(ITSMFAudioDevice* audio) +{ + TSMFAlsaAudioDevice* alsa = (TSMFAlsaAudioDevice*)audio; + DEBUG_TSMF(""); + + if (alsa->out_handle) + { + snd_pcm_drain(alsa->out_handle); + snd_pcm_close(alsa->out_handle); + } + + free(alsa); +} + +FREERDP_ENTRY_POINT(UINT VCAPITYPE alsa_freerdp_tsmf_client_audio_subsystem_entry(void* ptr)) +{ + ITSMFAudioDevice** sptr = (ITSMFAudioDevice**)ptr; + WINPR_ASSERT(sptr); + *sptr = NULL; + + TSMFAlsaAudioDevice* alsa = calloc(1, sizeof(TSMFAlsaAudioDevice)); + if (!alsa) + return ERROR_OUTOFMEMORY; + + alsa->iface.Open = tsmf_alsa_open; + alsa->iface.SetFormat = tsmf_alsa_set_format; + alsa->iface.Play = tsmf_alsa_play; + alsa->iface.GetLatency = tsmf_alsa_get_latency; + alsa->iface.Flush = tsmf_alsa_flush; + alsa->iface.Free = tsmf_alsa_free; + *sptr = &alsa->iface; + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_X11.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_X11.c new file mode 100644 index 0000000000000000000000000000000000000000..987e69b28622231531c1e2c7ebd5f7de89c5f041 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_X11.c @@ -0,0 +1,500 @@ +/* + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - GStreamer Decoder X11 specifics + * + * (C) Copyright 2014 Thincast Technologies GmbH + * (C) Copyright 2014 Armin Novak + * + * 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 +#include +#include +#ifndef __CYGWIN__ +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if GST_VERSION_MAJOR > 0 +#include +#else +#include +#endif + +#include +#include +#include + +#include + +#include "tsmf_platform.h" +#include "tsmf_constants.h" +#include "tsmf_decoder.h" + +#if !defined(WITH_XEXT) +#warning "Building TSMF without shape extension support" +#endif + +struct X11Handle +{ + int shmid; + int* xfwin; +#if defined(WITH_XEXT) + BOOL has_shape; +#endif + Display* disp; + Window subwin; + BOOL subwinMapped; +#if GST_VERSION_MAJOR > 0 + GstVideoOverlay* overlay; +#else + GstXOverlay* overlay; +#endif + int subwinWidth; + int subwinHeight; + int subwinX; + int subwinY; +}; + +static const char* get_shm_id() +{ + static char shm_id[128]; + sprintf_s(shm_id, sizeof(shm_id), "/com.freerdp.xfreerdp.tsmf_%016X", GetCurrentProcessId()); + return shm_id; +} + +static GstBusSyncReply tsmf_platform_bus_sync_handler(GstBus* bus, GstMessage* message, + gpointer user_data) +{ + struct X11Handle* hdl; + + TSMFGstreamerDecoder* decoder = user_data; + + if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT) + return GST_BUS_PASS; + +#if GST_VERSION_MAJOR > 0 + if (!gst_is_video_overlay_prepare_window_handle_message(message)) + return GST_BUS_PASS; +#else + if (!gst_structure_has_name(message->structure, "prepare-xwindow-id")) + return GST_BUS_PASS; +#endif + + hdl = (struct X11Handle*)decoder->platform; + + if (hdl->subwin) + { +#if GST_VERSION_MAJOR > 0 + hdl->overlay = GST_VIDEO_OVERLAY(GST_MESSAGE_SRC(message)); + gst_video_overlay_set_window_handle(hdl->overlay, hdl->subwin); + gst_video_overlay_handle_events(hdl->overlay, FALSE); +#else + hdl->overlay = GST_X_OVERLAY(GST_MESSAGE_SRC(message)); +#if GST_CHECK_VERSION(0, 10, 31) + gst_x_overlay_set_window_handle(hdl->overlay, hdl->subwin); +#else + gst_x_overlay_set_xwindow_id(hdl->overlay, hdl->subwin); +#endif + gst_x_overlay_handle_events(hdl->overlay, TRUE); +#endif + + if (hdl->subwinWidth != -1 && hdl->subwinHeight != -1 && hdl->subwinX != -1 && + hdl->subwinY != -1) + { +#if GST_VERSION_MAJOR > 0 + if (!gst_video_overlay_set_render_rectangle(hdl->overlay, 0, 0, hdl->subwinWidth, + hdl->subwinHeight)) + { + WLog_ERR(TAG, "Could not resize overlay!"); + } + + gst_video_overlay_expose(hdl->overlay); +#else + if (!gst_x_overlay_set_render_rectangle(hdl->overlay, 0, 0, hdl->subwinWidth, + hdl->subwinHeight)) + { + WLog_ERR(TAG, "Could not resize overlay!"); + } + + gst_x_overlay_expose(hdl->overlay); +#endif + XLockDisplay(hdl->disp); + XMoveResizeWindow(hdl->disp, hdl->subwin, hdl->subwinX, hdl->subwinY, hdl->subwinWidth, + hdl->subwinHeight); + XSync(hdl->disp, FALSE); + XUnlockDisplay(hdl->disp); + } + } + else + { + g_warning("Window was not available before retrieving the overlay!"); + } + + gst_message_unref(message); + + return GST_BUS_DROP; +} + +const char* tsmf_platform_get_video_sink(void) +{ + return "autovideosink"; +} + +const char* tsmf_platform_get_audio_sink(void) +{ + return "autoaudiosink"; +} + +int tsmf_platform_create(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl; + + if (!decoder) + return -1; + + if (decoder->platform) + return -1; + + hdl = calloc(1, sizeof(struct X11Handle)); + if (!hdl) + { + WLog_ERR(TAG, "Could not allocate handle."); + return -1; + } + + decoder->platform = hdl; + hdl->shmid = shm_open(get_shm_id(), (O_RDWR | O_CREAT), (PROT_READ | PROT_WRITE)); + if (hdl->shmid == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "failed to get access to shared memory - shmget(%s): %i - %s", get_shm_id(), + errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return -2; + } + + hdl->xfwin = mmap(0, sizeof(void*), PROT_READ | PROT_WRITE, MAP_SHARED, hdl->shmid, 0); + if (hdl->xfwin == MAP_FAILED) + { + WLog_ERR(TAG, "shmat failed!"); + return -3; + } + + hdl->disp = XOpenDisplay(NULL); + if (!hdl->disp) + { + WLog_ERR(TAG, "Failed to open display"); + return -4; + } + + hdl->subwinMapped = FALSE; + hdl->subwinX = -1; + hdl->subwinY = -1; + hdl->subwinWidth = -1; + hdl->subwinHeight = -1; + + return 0; +} + +int tsmf_platform_set_format(TSMFGstreamerDecoder* decoder) +{ + if (!decoder) + return -1; + + if (decoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + { + } + + return 0; +} + +int tsmf_platform_register_handler(TSMFGstreamerDecoder* decoder) +{ + GstBus* bus; + + if (!decoder) + return -1; + + if (!decoder->pipe) + return -1; + + bus = gst_pipeline_get_bus(GST_PIPELINE(decoder->pipe)); + +#if GST_VERSION_MAJOR > 0 + gst_bus_set_sync_handler(bus, (GstBusSyncHandler)tsmf_platform_bus_sync_handler, decoder, NULL); +#else + gst_bus_set_sync_handler(bus, (GstBusSyncHandler)tsmf_platform_bus_sync_handler, decoder); +#endif + + if (!bus) + { + WLog_ERR(TAG, "gst_pipeline_get_bus failed!"); + return 1; + } + + gst_object_unref(bus); + + return 0; +} + +int tsmf_platform_free(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl = decoder->platform; + + if (!hdl) + return -1; + + if (hdl->disp) + XCloseDisplay(hdl->disp); + + if (hdl->xfwin) + munmap(0, sizeof(void*)); + + if (hdl->shmid >= 0) + close(hdl->shmid); + + free(hdl); + decoder->platform = NULL; + + return 0; +} + +int tsmf_window_create(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl; + + if (decoder->media_type != TSMF_MAJOR_TYPE_VIDEO) + { + decoder->ready = TRUE; + return -3; + } + else + { + if (!decoder) + return -1; + + if (!decoder->platform) + return -1; + + hdl = (struct X11Handle*)decoder->platform; + + if (!hdl->subwin) + { + XLockDisplay(hdl->disp); + hdl->subwin = XCreateSimpleWindow(hdl->disp, *(int*)hdl->xfwin, 0, 0, 1, 1, 0, 0, 0); + XUnlockDisplay(hdl->disp); + + if (!hdl->subwin) + { + WLog_ERR(TAG, "Could not create subwindow!"); + } + } + + tsmf_window_map(decoder); + + decoder->ready = TRUE; +#if defined(WITH_XEXT) + int event, error; + XLockDisplay(hdl->disp); + hdl->has_shape = XShapeQueryExtension(hdl->disp, &event, &error); + XUnlockDisplay(hdl->disp); +#endif + } + + return 0; +} + +int tsmf_window_resize(TSMFGstreamerDecoder* decoder, int x, int y, int width, int height, + int nr_rects, RDP_RECT* rects) +{ + struct X11Handle* hdl; + + if (!decoder) + return -1; + + if (decoder->media_type != TSMF_MAJOR_TYPE_VIDEO) + { + return -3; + } + + if (!decoder->platform) + return -1; + + hdl = (struct X11Handle*)decoder->platform; + DEBUG_TSMF("resize: x=%d, y=%d, w=%d, h=%d", x, y, width, height); + + if (hdl->overlay) + { +#if GST_VERSION_MAJOR > 0 + + if (!gst_video_overlay_set_render_rectangle(hdl->overlay, 0, 0, width, height)) + { + WLog_ERR(TAG, "Could not resize overlay!"); + } + + gst_video_overlay_expose(hdl->overlay); +#else + if (!gst_x_overlay_set_render_rectangle(hdl->overlay, 0, 0, width, height)) + { + WLog_ERR(TAG, "Could not resize overlay!"); + } + + gst_x_overlay_expose(hdl->overlay); +#endif + } + + if (hdl->subwin) + { + hdl->subwinX = x; + hdl->subwinY = y; + hdl->subwinWidth = width; + hdl->subwinHeight = height; + + XLockDisplay(hdl->disp); + XMoveResizeWindow(hdl->disp, hdl->subwin, hdl->subwinX, hdl->subwinY, hdl->subwinWidth, + hdl->subwinHeight); + + /* Unmap the window if there are no visibility rects */ + if (nr_rects == 0) + tsmf_window_unmap(decoder); + else + tsmf_window_map(decoder); + +#if defined(WITH_XEXT) + if (hdl->has_shape) + { + XRectangle* xrects = NULL; + + if (nr_rects == 0) + { + xrects = calloc(1, sizeof(XRectangle)); + xrects->x = x; + xrects->y = y; + xrects->width = width; + xrects->height = height; + } + else + { + xrects = calloc(nr_rects, sizeof(XRectangle)); + } + + if (xrects) + { + for (int i = 0; i < nr_rects; i++) + { + xrects[i].x = rects[i].x - x; + xrects[i].y = rects[i].y - y; + xrects[i].width = rects[i].width; + xrects[i].height = rects[i].height; + } + + XShapeCombineRectangles(hdl->disp, hdl->subwin, ShapeBounding, x, y, xrects, + nr_rects, ShapeSet, 0); + free(xrects); + } + } +#endif + XSync(hdl->disp, FALSE); + XUnlockDisplay(hdl->disp); + } + + return 0; +} + +int tsmf_window_map(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl; + if (!decoder) + return -1; + + hdl = (struct X11Handle*)decoder->platform; + + /* Only need to map the window if it is not currently mapped */ + if ((hdl->subwin) && (!hdl->subwinMapped)) + { + XLockDisplay(hdl->disp); + XMapWindow(hdl->disp, hdl->subwin); + hdl->subwinMapped = TRUE; + XSync(hdl->disp, FALSE); + XUnlockDisplay(hdl->disp); + } + + return 0; +} + +int tsmf_window_unmap(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl; + if (!decoder) + return -1; + + hdl = (struct X11Handle*)decoder->platform; + + /* only need to unmap window if it is currently mapped */ + if ((hdl->subwin) && (hdl->subwinMapped)) + { + XLockDisplay(hdl->disp); + XUnmapWindow(hdl->disp, hdl->subwin); + hdl->subwinMapped = FALSE; + XSync(hdl->disp, FALSE); + XUnlockDisplay(hdl->disp); + } + + return 0; +} + +int tsmf_window_destroy(TSMFGstreamerDecoder* decoder) +{ + struct X11Handle* hdl; + + if (!decoder) + return -1; + + decoder->ready = FALSE; + + if (decoder->media_type != TSMF_MAJOR_TYPE_VIDEO) + return -3; + + if (!decoder->platform) + return -1; + + hdl = (struct X11Handle*)decoder->platform; + + if (hdl->subwin) + { + XLockDisplay(hdl->disp); + XDestroyWindow(hdl->disp, hdl->subwin); + XSync(hdl->disp, FALSE); + XUnlockDisplay(hdl->disp); + } + + hdl->overlay = NULL; + hdl->subwin = 0; + hdl->subwinMapped = FALSE; + hdl->subwinX = -1; + hdl->subwinY = -1; + hdl->subwinWidth = -1; + hdl->subwinHeight = -1; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_gstreamer.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_gstreamer.c new file mode 100644 index 0000000000000000000000000000000000000000..13847eef9890e8ec831aa2727840db445a6fb25d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/gstreamer/tsmf_gstreamer.c @@ -0,0 +1,1058 @@ +/* + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - GStreamer Decoder + * + * (C) Copyright 2012 HP Development Company, LLC + * (C) Copyright 2014 Thincast Technologies GmbH + * (C) Copyright 2014 Armin Novak + * + * 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 + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include "tsmf_constants.h" +#include "tsmf_decoder.h" +#include "tsmf_platform.h" + +/* 1 second = 10,000,000 100ns units*/ +#define SEEK_TOLERANCE 10 * 1000 * 1000 + +static BOOL tsmf_gstreamer_pipeline_build(TSMFGstreamerDecoder* mdecoder); +static void tsmf_gstreamer_clean_up(TSMFGstreamerDecoder* mdecoder); +static int tsmf_gstreamer_pipeline_set_state(TSMFGstreamerDecoder* mdecoder, + GstState desired_state); +static BOOL tsmf_gstreamer_buffer_level(ITSMFDecoder* decoder); + +static const char* get_type(TSMFGstreamerDecoder* mdecoder) +{ + if (!mdecoder) + return NULL; + + switch (mdecoder->media_type) + { + case TSMF_MAJOR_TYPE_VIDEO: + return "VIDEO"; + case TSMF_MAJOR_TYPE_AUDIO: + return "AUDIO"; + default: + return "UNKNOWN"; + } +} + +static void cb_child_added(GstChildProxy* child_proxy, GObject* object, + TSMFGstreamerDecoder* mdecoder) +{ + DEBUG_TSMF("NAME: %s", G_OBJECT_TYPE_NAME(object)); + + if (!g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstXvImageSink") || + !g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstXImageSink") || + !g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstFluVAAutoSink")) + { + gst_base_sink_set_max_lateness((GstBaseSink*)object, 10000000); /* nanoseconds */ + g_object_set(G_OBJECT(object), "sync", TRUE, NULL); /* synchronize on the clock */ + g_object_set(G_OBJECT(object), "async", TRUE, NULL); /* no async state changes */ + } + + else if (!g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstAlsaSink") || + !g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstPulseSink")) + { + gst_base_sink_set_max_lateness((GstBaseSink*)object, 10000000); /* nanoseconds */ + g_object_set(G_OBJECT(object), "slave-method", 1, NULL); + g_object_set(G_OBJECT(object), "buffer-time", (gint64)20000, NULL); /* microseconds */ + g_object_set(G_OBJECT(object), "drift-tolerance", (gint64)20000, NULL); /* microseconds */ + g_object_set(G_OBJECT(object), "latency-time", (gint64)10000, NULL); /* microseconds */ + g_object_set(G_OBJECT(object), "sync", TRUE, NULL); /* synchronize on the clock */ + g_object_set(G_OBJECT(object), "async", TRUE, NULL); /* no async state changes */ + } +} + +static void tsmf_gstreamer_enough_data(GstAppSrc* src, gpointer user_data) +{ + TSMFGstreamerDecoder* mdecoder = user_data; + (void)mdecoder; + DEBUG_TSMF("%s", get_type(mdecoder)); +} + +static void tsmf_gstreamer_need_data(GstAppSrc* src, guint length, gpointer user_data) +{ + TSMFGstreamerDecoder* mdecoder = user_data; + (void)mdecoder; + DEBUG_TSMF("%s length=%u", get_type(mdecoder), length); +} + +static gboolean tsmf_gstreamer_seek_data(GstAppSrc* src, guint64 offset, gpointer user_data) +{ + TSMFGstreamerDecoder* mdecoder = user_data; + (void)mdecoder; + DEBUG_TSMF("%s offset=%" PRIu64 "", get_type(mdecoder), offset); + + return TRUE; +} + +static BOOL tsmf_gstreamer_change_volume(ITSMFDecoder* decoder, UINT32 newVolume, UINT32 muted) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + + if (!mdecoder || !mdecoder->pipe) + return TRUE; + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + return TRUE; + + mdecoder->gstMuted = (BOOL)muted; + DEBUG_TSMF("mute=[%" PRId32 "]", mdecoder->gstMuted); + mdecoder->gstVolume = (double)newVolume / (double)10000; + DEBUG_TSMF("gst_new_vol=[%f]", mdecoder->gstVolume); + + if (!mdecoder->volume) + return TRUE; + + if (!G_IS_OBJECT(mdecoder->volume)) + return TRUE; + + g_object_set(mdecoder->volume, "mute", mdecoder->gstMuted, NULL); + g_object_set(mdecoder->volume, "volume", mdecoder->gstVolume, NULL); + + return TRUE; +} + +static inline GstClockTime tsmf_gstreamer_timestamp_ms_to_gst(UINT64 ms_timestamp) +{ + /* + * Convert Microsoft 100ns timestamps to Gstreamer 1ns units. + */ + return (GstClockTime)(ms_timestamp * 100); +} + +int tsmf_gstreamer_pipeline_set_state(TSMFGstreamerDecoder* mdecoder, GstState desired_state) +{ + GstStateChangeReturn state_change; + const char* name; + const char* sname = get_type(mdecoder); + + if (!mdecoder) + return 0; + + if (!mdecoder->pipe) + return 0; /* Just in case this is called during startup or shutdown when we don't expect it + */ + + if (desired_state == mdecoder->state) + return 0; /* Redundant request - Nothing to do */ + + name = gst_element_state_get_name(desired_state); /* For debug */ + DEBUG_TSMF("%s to %s", sname, name); + state_change = gst_element_set_state(mdecoder->pipe, desired_state); + + if (state_change == GST_STATE_CHANGE_FAILURE) + { + WLog_ERR(TAG, "%s: (%s) GST_STATE_CHANGE_FAILURE.", sname, name); + } + else if (state_change == GST_STATE_CHANGE_ASYNC) + { + WLog_ERR(TAG, "%s: (%s) GST_STATE_CHANGE_ASYNC.", sname, name); + mdecoder->state = desired_state; + } + else + { + mdecoder->state = desired_state; + } + + return 0; +} + +static GstBuffer* tsmf_get_buffer_from_data(const void* raw_data, gsize size) +{ + GstBuffer* buffer; + gpointer data; + + if (!raw_data) + return NULL; + + if (size < 1) + return NULL; + + data = g_malloc(size); + + if (!data) + { + WLog_ERR(TAG, "Could not allocate %" G_GSIZE_FORMAT " bytes of data.", size); + return NULL; + } + + CopyMemory(data, raw_data, size); + +#if GST_VERSION_MAJOR > 0 + buffer = gst_buffer_new_wrapped(data, size); +#else + buffer = gst_buffer_new(); + + if (!buffer) + { + WLog_ERR(TAG, "Could not create GstBuffer"); + free(data); + return NULL; + } + + GST_BUFFER_MALLOCDATA(buffer) = data; + GST_BUFFER_SIZE(buffer) = size; + GST_BUFFER_DATA(buffer) = GST_BUFFER_MALLOCDATA(buffer); +#endif + + return buffer; +} + +static BOOL tsmf_gstreamer_set_format(ITSMFDecoder* decoder, TS_AM_MEDIA_TYPE* media_type) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + + if (!mdecoder) + return FALSE; + + DEBUG_TSMF(""); + + switch (media_type->MajorType) + { + case TSMF_MAJOR_TYPE_VIDEO: + mdecoder->media_type = TSMF_MAJOR_TYPE_VIDEO; + break; + case TSMF_MAJOR_TYPE_AUDIO: + mdecoder->media_type = TSMF_MAJOR_TYPE_AUDIO; + break; + default: + return FALSE; + } + + switch (media_type->SubType) + { + case TSMF_SUB_TYPE_WVC1: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-wmv", "bitrate", G_TYPE_UINT, media_type->BitRate, "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, "wmvversion", + G_TYPE_INT, 3, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "WVC1", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('W', 'V', 'C', '1'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, "pixel-aspect-ratio", GST_TYPE_FRACTION, + 1, 1, NULL); + break; + case TSMF_SUB_TYPE_MP4S: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-divx", "divxversion", G_TYPE_INT, 5, "bitrate", G_TYPE_UINT, + media_type->BitRate, "width", G_TYPE_INT, media_type->Width, "height", G_TYPE_INT, + media_type->Height, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "MP42", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('M', 'P', '4', '2'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); + break; + case TSMF_SUB_TYPE_MP42: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-msmpeg", "msmpegversion", G_TYPE_INT, 42, "bitrate", G_TYPE_UINT, + media_type->BitRate, "width", G_TYPE_INT, media_type->Width, "height", G_TYPE_INT, + media_type->Height, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "MP42", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('M', 'P', '4', '2'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); + break; + case TSMF_SUB_TYPE_MP43: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-msmpeg", "msmpegversion", G_TYPE_INT, 43, "bitrate", G_TYPE_UINT, + media_type->BitRate, "width", G_TYPE_INT, media_type->Width, "height", G_TYPE_INT, + media_type->Height, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "MP43", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('M', 'P', '4', '3'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); + break; + case TSMF_SUB_TYPE_M4S2: + mdecoder->gst_caps = gst_caps_new_simple( + "video/mpeg", "mpegversion", G_TYPE_INT, 4, "width", G_TYPE_INT, media_type->Width, + "height", G_TYPE_INT, media_type->Height, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "M4S2", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('M', '4', 'S', '2'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); + break; + case TSMF_SUB_TYPE_WMA9: + mdecoder->gst_caps = gst_caps_new_simple( + "audio/x-wma", "wmaversion", G_TYPE_INT, 3, "rate", G_TYPE_INT, + media_type->SamplesPerSecond.Numerator, "channels", G_TYPE_INT, + media_type->Channels, "bitrate", G_TYPE_INT, media_type->BitRate, "depth", + G_TYPE_INT, media_type->BitsPerSample, "width", G_TYPE_INT, + media_type->BitsPerSample, "block_align", G_TYPE_INT, media_type->BlockAlign, NULL); + break; + case TSMF_SUB_TYPE_WMA1: + mdecoder->gst_caps = gst_caps_new_simple( + "audio/x-wma", "wmaversion", G_TYPE_INT, 1, "rate", G_TYPE_INT, + media_type->SamplesPerSecond.Numerator, "channels", G_TYPE_INT, + media_type->Channels, "bitrate", G_TYPE_INT, media_type->BitRate, "depth", + G_TYPE_INT, media_type->BitsPerSample, "width", G_TYPE_INT, + media_type->BitsPerSample, "block_align", G_TYPE_INT, media_type->BlockAlign, NULL); + break; + case TSMF_SUB_TYPE_WMA2: + mdecoder->gst_caps = gst_caps_new_simple( + "audio/x-wma", "wmaversion", G_TYPE_INT, 2, "rate", G_TYPE_INT, + media_type->SamplesPerSecond.Numerator, "channels", G_TYPE_INT, + media_type->Channels, "bitrate", G_TYPE_INT, media_type->BitRate, "depth", + G_TYPE_INT, media_type->BitsPerSample, "width", G_TYPE_INT, + media_type->BitsPerSample, "block_align", G_TYPE_INT, media_type->BlockAlign, NULL); + break; + case TSMF_SUB_TYPE_MP3: + mdecoder->gst_caps = + gst_caps_new_simple("audio/mpeg", "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, + 3, "rate", G_TYPE_INT, media_type->SamplesPerSecond.Numerator, + "channels", G_TYPE_INT, media_type->Channels, NULL); + break; + case TSMF_SUB_TYPE_WMV1: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-wmv", "bitrate", G_TYPE_UINT, media_type->BitRate, "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, "wmvversion", + G_TYPE_INT, 1, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "WMV1", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('W', 'M', 'V', '1'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); + break; + case TSMF_SUB_TYPE_WMV2: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-wmv", "width", G_TYPE_INT, media_type->Width, "height", G_TYPE_INT, + media_type->Height, "wmvversion", G_TYPE_INT, 2, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "WMV2", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('W', 'M', 'V', '2'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, "pixel-aspect-ratio", GST_TYPE_FRACTION, + 1, 1, NULL); + break; + case TSMF_SUB_TYPE_WMV3: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-wmv", "bitrate", G_TYPE_UINT, media_type->BitRate, "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, "wmvversion", + G_TYPE_INT, 3, +#if GST_VERSION_MAJOR > 0 + "format", G_TYPE_STRING, "WMV3", +#else + "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('W', 'M', 'V', '3'), +#endif + "framerate", GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, "pixel-aspect-ratio", GST_TYPE_FRACTION, + 1, 1, NULL); + break; + case TSMF_SUB_TYPE_AVC1: + case TSMF_SUB_TYPE_H264: + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-h264", "width", G_TYPE_INT, media_type->Width, "height", G_TYPE_INT, + media_type->Height, "framerate", GST_TYPE_FRACTION, + media_type->SamplesPerSecond.Numerator, media_type->SamplesPerSecond.Denominator, + "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, "stream-format", G_TYPE_STRING, + "byte-stream", "alignment", G_TYPE_STRING, "nal", NULL); + break; + case TSMF_SUB_TYPE_AC3: + mdecoder->gst_caps = gst_caps_new_simple( + "audio/x-ac3", "rate", G_TYPE_INT, media_type->SamplesPerSecond.Numerator, + "channels", G_TYPE_INT, media_type->Channels, NULL); + break; + case TSMF_SUB_TYPE_AAC: + + /* For AAC the pFormat is a HEAACWAVEINFO struct, and the codec data + is at the end of it. See + http://msdn.microsoft.com/en-us/library/dd757806.aspx */ + if (media_type->ExtraData) + { + if (media_type->ExtraDataSize < 12) + return FALSE; + media_type->ExtraData += 12; + media_type->ExtraDataSize -= 12; + } + + mdecoder->gst_caps = gst_caps_new_simple( + "audio/mpeg", "rate", G_TYPE_INT, media_type->SamplesPerSecond.Numerator, + "channels", G_TYPE_INT, media_type->Channels, "mpegversion", G_TYPE_INT, 4, + "framed", G_TYPE_BOOLEAN, TRUE, "stream-format", G_TYPE_STRING, "raw", NULL); + break; + case TSMF_SUB_TYPE_MP1A: + mdecoder->gst_caps = + gst_caps_new_simple("audio/mpeg", "mpegversion", G_TYPE_INT, 1, "channels", + G_TYPE_INT, media_type->Channels, NULL); + break; + case TSMF_SUB_TYPE_MP1V: + mdecoder->gst_caps = + gst_caps_new_simple("video/mpeg", "mpegversion", G_TYPE_INT, 1, "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, + "systemstream", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case TSMF_SUB_TYPE_YUY2: +#if GST_VERSION_MAJOR > 0 + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-raw", "format", G_TYPE_STRING, "YUY2", "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, NULL); +#else + mdecoder->gst_caps = gst_caps_new_simple( + "video/x-raw-yuv", "format", G_TYPE_STRING, "YUY2", "width", G_TYPE_INT, + media_type->Width, "height", G_TYPE_INT, media_type->Height, "framerate", + GST_TYPE_FRACTION, media_type->SamplesPerSecond.Numerator, + media_type->SamplesPerSecond.Denominator, NULL); +#endif + break; + case TSMF_SUB_TYPE_MP2V: + mdecoder->gst_caps = gst_caps_new_simple("video/mpeg", "mpegversion", G_TYPE_INT, 2, + "systemstream", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case TSMF_SUB_TYPE_MP2A: + mdecoder->gst_caps = + gst_caps_new_simple("audio/mpeg", "mpegversion", G_TYPE_INT, 1, "rate", G_TYPE_INT, + media_type->SamplesPerSecond.Numerator, "channels", G_TYPE_INT, + media_type->Channels, NULL); + break; + case TSMF_SUB_TYPE_FLAC: + mdecoder->gst_caps = gst_caps_new_simple("audio/x-flac", "", NULL); + break; + default: + WLog_ERR(TAG, "unknown format:(%d).", media_type->SubType); + return FALSE; + } + + if (media_type->ExtraDataSize > 0) + { + GstBuffer* buffer; + DEBUG_TSMF("Extra data available (%" PRIu32 ")", media_type->ExtraDataSize); + buffer = tsmf_get_buffer_from_data(media_type->ExtraData, media_type->ExtraDataSize); + + if (!buffer) + { + WLog_ERR(TAG, "could not allocate GstBuffer!"); + return FALSE; + } + + gst_caps_set_simple(mdecoder->gst_caps, "codec_data", GST_TYPE_BUFFER, buffer, NULL); + } + + DEBUG_TSMF("%p format '%s'", (void*)mdecoder, gst_caps_to_string(mdecoder->gst_caps)); + tsmf_platform_set_format(mdecoder); + + /* Create the pipeline... */ + if (!tsmf_gstreamer_pipeline_build(mdecoder)) + return FALSE; + + return TRUE; +} + +void tsmf_gstreamer_clean_up(TSMFGstreamerDecoder* mdecoder) +{ + if (!mdecoder || !mdecoder->pipe) + return; + + if (mdecoder->pipe && GST_OBJECT_REFCOUNT_VALUE(mdecoder->pipe) > 0) + { + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_NULL); + gst_object_unref(mdecoder->pipe); + } + + mdecoder->ready = FALSE; + mdecoder->paused = FALSE; + + mdecoder->pipe = NULL; + mdecoder->src = NULL; + mdecoder->queue = NULL; +} + +BOOL tsmf_gstreamer_pipeline_build(TSMFGstreamerDecoder* mdecoder) +{ +#if GST_VERSION_MAJOR > 0 + const char* video = + "appsrc name=videosource ! queue2 name=videoqueue ! decodebin name=videodecoder !"; + const char* audio = + "appsrc name=audiosource ! queue2 name=audioqueue ! decodebin name=audiodecoder ! " + "audioconvert ! audiorate ! audioresample ! volume name=audiovolume !"; +#else + const char* video = + "appsrc name=videosource ! queue2 name=videoqueue ! decodebin2 name=videodecoder !"; + const char* audio = + "appsrc name=audiosource ! queue2 name=audioqueue ! decodebin2 name=audiodecoder ! " + "audioconvert ! audiorate ! audioresample ! volume name=audiovolume !"; +#endif + char pipeline[1024]; + + if (!mdecoder) + return FALSE; + + /* TODO: Construction of the pipeline from a string allows easy overwrite with arguments. + * The only fixed elements necessary are appsrc and the volume element for audio streams. + * The rest could easily be provided in gstreamer pipeline notation from command line. */ + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + sprintf_s(pipeline, sizeof(pipeline), "%s %s name=videosink", video, + tsmf_platform_get_video_sink()); + else + sprintf_s(pipeline, sizeof(pipeline), "%s %s name=audiosink", audio, + tsmf_platform_get_audio_sink()); + + DEBUG_TSMF("pipeline=%s", pipeline); + mdecoder->pipe = gst_parse_launch(pipeline, NULL); + + if (!mdecoder->pipe) + { + WLog_ERR(TAG, "Failed to create new pipe"); + return FALSE; + } + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + mdecoder->src = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "videosource"); + else + mdecoder->src = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "audiosource"); + + if (!mdecoder->src) + { + WLog_ERR(TAG, "Failed to get appsrc"); + return FALSE; + } + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + mdecoder->queue = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "videoqueue"); + else + mdecoder->queue = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "audioqueue"); + + if (!mdecoder->queue) + { + WLog_ERR(TAG, "Failed to get queue"); + return FALSE; + } + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + mdecoder->outsink = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "videosink"); + else + mdecoder->outsink = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "audiosink"); + + if (!mdecoder->outsink) + { + WLog_ERR(TAG, "Failed to get sink"); + return FALSE; + } + + g_signal_connect(mdecoder->outsink, "child-added", G_CALLBACK(cb_child_added), mdecoder); + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_AUDIO) + { + mdecoder->volume = gst_bin_get_by_name(GST_BIN(mdecoder->pipe), "audiovolume"); + + if (!mdecoder->volume) + { + WLog_ERR(TAG, "Failed to get volume"); + return FALSE; + } + + tsmf_gstreamer_change_volume((ITSMFDecoder*)mdecoder, mdecoder->gstVolume * ((double)10000), + mdecoder->gstMuted); + } + + tsmf_platform_register_handler(mdecoder); + /* AppSrc settings */ + GstAppSrcCallbacks callbacks = { + tsmf_gstreamer_need_data, tsmf_gstreamer_enough_data, tsmf_gstreamer_seek_data, { NULL } + }; + g_object_set(mdecoder->src, "format", GST_FORMAT_TIME, NULL); + g_object_set(mdecoder->src, "is-live", FALSE, NULL); + g_object_set(mdecoder->src, "block", FALSE, NULL); + g_object_set(mdecoder->src, "blocksize", 1024, NULL); + gst_app_src_set_caps((GstAppSrc*)mdecoder->src, mdecoder->gst_caps); + gst_app_src_set_callbacks((GstAppSrc*)mdecoder->src, &callbacks, mdecoder, NULL); + gst_app_src_set_stream_type((GstAppSrc*)mdecoder->src, GST_APP_STREAM_TYPE_SEEKABLE); + gst_app_src_set_latency((GstAppSrc*)mdecoder->src, 0, -1); + gst_app_src_set_max_bytes((GstAppSrc*)mdecoder->src, (guint64)0); // unlimited + g_object_set(G_OBJECT(mdecoder->queue), "use-buffering", FALSE, NULL); + g_object_set(G_OBJECT(mdecoder->queue), "use-rate-estimate", FALSE, NULL); + g_object_set(G_OBJECT(mdecoder->queue), "max-size-buffers", 0, NULL); + g_object_set(G_OBJECT(mdecoder->queue), "max-size-bytes", 0, NULL); + g_object_set(G_OBJECT(mdecoder->queue), "max-size-time", (guint64)0, NULL); + + /* Only set these properties if not an autosink, otherwise we will set properties when real + * sinks are added */ + if (!g_strcmp0(G_OBJECT_TYPE_NAME(mdecoder->outsink), "GstAutoVideoSink") && + !g_strcmp0(G_OBJECT_TYPE_NAME(mdecoder->outsink), "GstAutoAudioSink")) + { + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + { + gst_base_sink_set_max_lateness((GstBaseSink*)mdecoder->outsink, + 10000000); /* nanoseconds */ + } + else + { + gst_base_sink_set_max_lateness((GstBaseSink*)mdecoder->outsink, + 10000000); /* nanoseconds */ + g_object_set(G_OBJECT(mdecoder->outsink), "buffer-time", (gint64)20000, + NULL); /* microseconds */ + g_object_set(G_OBJECT(mdecoder->outsink), "drift-tolerance", (gint64)20000, + NULL); /* microseconds */ + g_object_set(G_OBJECT(mdecoder->outsink), "latency-time", (gint64)10000, + NULL); /* microseconds */ + g_object_set(G_OBJECT(mdecoder->outsink), "slave-method", 1, NULL); + } + g_object_set(G_OBJECT(mdecoder->outsink), "sync", TRUE, + NULL); /* synchronize on the clock */ + g_object_set(G_OBJECT(mdecoder->outsink), "async", TRUE, NULL); /* no async state changes */ + } + + tsmf_window_create(mdecoder); + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_READY); + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_PLAYING); + mdecoder->pipeline_start_time_valid = 0; + mdecoder->shutdown = 0; + mdecoder->paused = FALSE; + + GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(mdecoder->pipe), GST_DEBUG_GRAPH_SHOW_ALL, + get_type(mdecoder)); + + return TRUE; +} + +static BOOL tsmf_gstreamer_decodeEx(ITSMFDecoder* decoder, const BYTE* data, UINT32 data_size, + UINT32 extensions, UINT64 start_time, UINT64 end_time, + UINT64 duration) +{ + GstBuffer* gst_buf; + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + UINT64 sample_time = tsmf_gstreamer_timestamp_ms_to_gst(start_time); + BOOL useTimestamps = TRUE; + + if (!mdecoder) + { + WLog_ERR(TAG, "Decoder not initialized!"); + return FALSE; + } + + /* + * This function is always called from a stream-specific thread. + * It should be alright to block here if necessary. + * We don't expect to block here often, since the pipeline should + * have more than enough buffering. + */ + DEBUG_TSMF( + "%s. Start:(%" PRIu64 ") End:(%" PRIu64 ") Duration:(%" PRIu64 ") Last Start:(%" PRIu64 ")", + get_type(mdecoder), start_time, end_time, duration, mdecoder->last_sample_start_time); + + if (mdecoder->shutdown) + { + WLog_ERR(TAG, "decodeEx called on shutdown decoder"); + return TRUE; + } + + if (mdecoder->gst_caps == NULL) + { + WLog_ERR(TAG, "tsmf_gstreamer_set_format not called or invalid format."); + return FALSE; + } + + if (!mdecoder->pipe) + tsmf_gstreamer_pipeline_build(mdecoder); + + if (!mdecoder->src) + { + WLog_ERR( + TAG, + "failed to construct pipeline correctly. Unable to push buffer to source element."); + return FALSE; + } + + gst_buf = tsmf_get_buffer_from_data(data, data_size); + + if (gst_buf == NULL) + { + WLog_ERR(TAG, "tsmf_get_buffer_from_data(%p, %" PRIu32 ") failed.", (void*)data, data_size); + return FALSE; + } + + /* Relative timestamping will sometimes be set to 0 + * so we ignore these timestamps just to be safe(bit 8) + */ + if (extensions & 0x00000080) + { + DEBUG_TSMF("Ignoring the timestamps - relative - bit 8"); + useTimestamps = FALSE; + } + + /* If no timestamps exist then we dont want to look at the timestamp values (bit 7) */ + if (extensions & 0x00000040) + { + DEBUG_TSMF("Ignoring the timestamps - none - bit 7"); + useTimestamps = FALSE; + } + + /* If performing a seek */ + if (mdecoder->seeking) + { + mdecoder->seeking = FALSE; + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_PAUSED); + mdecoder->pipeline_start_time_valid = 0; + } + + if (mdecoder->pipeline_start_time_valid) + { + DEBUG_TSMF("%s start time %" PRIu64 "", get_type(mdecoder), start_time); + + /* Adjusted the condition for a seek to be based on start time only + * WMV1 and WMV2 files in particular have bad end time and duration values + * there seems to be no real side effects of just using the start time instead + */ + UINT64 minTime = mdecoder->last_sample_start_time - (UINT64)SEEK_TOLERANCE; + UINT64 maxTime = mdecoder->last_sample_start_time + (UINT64)SEEK_TOLERANCE; + + /* Make sure the minTime stops at 0 , should we be at the beginning of the stream */ + if (mdecoder->last_sample_start_time < (UINT64)SEEK_TOLERANCE) + minTime = 0; + + /* If the start_time is valid and different from the previous start time by more than the + * seek tolerance, then we have a seek condition */ + if (((start_time > maxTime) || (start_time < minTime)) && useTimestamps) + { + DEBUG_TSMF("tsmf_gstreamer_decodeEx: start_time=[%" PRIu64 + "] > last_sample_start_time=[%" PRIu64 "] OR ", + start_time, mdecoder->last_sample_start_time); + DEBUG_TSMF("tsmf_gstreamer_decodeEx: start_time=[%" PRIu64 + "] < last_sample_start_time=[%" PRIu64 "] with", + start_time, mdecoder->last_sample_start_time); + DEBUG_TSMF( + "tsmf_gstreamer_decodeEX: a tolerance of more than [%lu] from the last sample", + SEEK_TOLERANCE); + DEBUG_TSMF("tsmf_gstreamer_decodeEX: minTime=[%" PRIu64 "] maxTime=[%" PRIu64 "]", + minTime, maxTime); + + mdecoder->seeking = TRUE; + + /* since we can't make the gstreamer pipeline jump to the new start time after a seek - + * we just maintain an offset between realtime and gstreamer time + */ + mdecoder->seek_offset = start_time; + } + } + else + { + DEBUG_TSMF("%s start time %" PRIu64 "", get_type(mdecoder), start_time); + /* Always set base/start time to 0. Will use seek offset to translate real buffer times + * back to 0. This allows the video to be started from anywhere and the ability to handle + * seeks without rebuilding the pipeline, etc. since that is costly + */ + gst_element_set_base_time(mdecoder->pipe, tsmf_gstreamer_timestamp_ms_to_gst(0)); + gst_element_set_start_time(mdecoder->pipe, tsmf_gstreamer_timestamp_ms_to_gst(0)); + mdecoder->pipeline_start_time_valid = 1; + + /* Set the seek offset if buffer has valid timestamps. */ + if (useTimestamps) + mdecoder->seek_offset = start_time; + + if (!gst_element_seek(mdecoder->pipe, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, + GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) + { + WLog_ERR(TAG, "seek failed"); + } + } + +#if GST_VERSION_MAJOR > 0 + if (useTimestamps) + GST_BUFFER_PTS(gst_buf) = + sample_time - tsmf_gstreamer_timestamp_ms_to_gst(mdecoder->seek_offset); + else + GST_BUFFER_PTS(gst_buf) = GST_CLOCK_TIME_NONE; +#else + if (useTimestamps) + GST_BUFFER_TIMESTAMP(gst_buf) = + sample_time - tsmf_gstreamer_timestamp_ms_to_gst(mdecoder->seek_offset); + else + GST_BUFFER_TIMESTAMP(gst_buf) = GST_CLOCK_TIME_NONE; +#endif + GST_BUFFER_DURATION(gst_buf) = GST_CLOCK_TIME_NONE; + GST_BUFFER_OFFSET(gst_buf) = GST_BUFFER_OFFSET_NONE; +#if GST_VERSION_MAJOR > 0 +#else + gst_buffer_set_caps(gst_buf, mdecoder->gst_caps); +#endif + gst_app_src_push_buffer(GST_APP_SRC(mdecoder->src), gst_buf); + + /* Should only update the last timestamps if the current ones are valid */ + if (useTimestamps) + { + mdecoder->last_sample_start_time = start_time; + mdecoder->last_sample_end_time = end_time; + } + + if (mdecoder->pipe && (GST_STATE(mdecoder->pipe) != GST_STATE_PLAYING)) + { + DEBUG_TSMF("%s: state=%s", get_type(mdecoder), + gst_element_state_get_name(GST_STATE(mdecoder->pipe))); + + DEBUG_TSMF("%s Paused: %" PRIi32 " Shutdown: %i Ready: %" PRIi32 "", get_type(mdecoder), + mdecoder->paused, mdecoder->shutdown, mdecoder->ready); + if (!mdecoder->paused && !mdecoder->shutdown && mdecoder->ready) + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_PLAYING); + } + + return TRUE; +} + +static BOOL tsmf_gstreamer_control(ITSMFDecoder* decoder, ITSMFControlMsg control_msg, UINT32* arg) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + + if (!mdecoder) + { + WLog_ERR(TAG, "Control called with no decoder!"); + return TRUE; + } + + if (control_msg == Control_Pause) + { + DEBUG_TSMF("Control_Pause %s", get_type(mdecoder)); + + if (mdecoder->paused) + { + WLog_ERR(TAG, "%s: Ignoring Control_Pause, already received!", get_type(mdecoder)); + return TRUE; + } + + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_PAUSED); + mdecoder->shutdown = 0; + mdecoder->paused = TRUE; + } + else if (control_msg == Control_Resume) + { + DEBUG_TSMF("Control_Resume %s", get_type(mdecoder)); + + if (!mdecoder->paused && !mdecoder->shutdown) + { + WLog_ERR(TAG, "%s: Ignoring Control_Resume, already received!", get_type(mdecoder)); + return TRUE; + } + + mdecoder->shutdown = 0; + mdecoder->paused = FALSE; + } + else if (control_msg == Control_Stop) + { + DEBUG_TSMF("Control_Stop %s", get_type(mdecoder)); + + if (mdecoder->shutdown) + { + WLog_ERR(TAG, "%s: Ignoring Control_Stop, already received!", get_type(mdecoder)); + return TRUE; + } + + /* Reset stamps, flush buffers, etc */ + if (mdecoder->pipe) + { + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_NULL); + tsmf_window_destroy(mdecoder); + tsmf_gstreamer_clean_up(mdecoder); + } + mdecoder->seek_offset = 0; + mdecoder->pipeline_start_time_valid = 0; + mdecoder->shutdown = 1; + } + else if (control_msg == Control_Restart) + { + DEBUG_TSMF("Control_Restart %s", get_type(mdecoder)); + mdecoder->shutdown = 0; + mdecoder->paused = FALSE; + + if (mdecoder->pipeline_start_time_valid) + tsmf_gstreamer_pipeline_set_state(mdecoder, GST_STATE_PLAYING); + } + else + WLog_ERR(TAG, "Unknown control message %08x", control_msg); + + return TRUE; +} + +static BOOL tsmf_gstreamer_buffer_level(ITSMFDecoder* decoder) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + DEBUG_TSMF(""); + + if (!mdecoder) + return FALSE; + + guint clbuff = 0; + + if (G_IS_OBJECT(mdecoder->queue)) + g_object_get(mdecoder->queue, "current-level-buffers", &clbuff, NULL); + + DEBUG_TSMF("%s buffer level %u", get_type(mdecoder), clbuff); + return clbuff; +} + +static void tsmf_gstreamer_free(ITSMFDecoder* decoder) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + DEBUG_TSMF("%s", get_type(mdecoder)); + + if (mdecoder) + { + tsmf_window_destroy(mdecoder); + tsmf_gstreamer_clean_up(mdecoder); + + if (mdecoder->gst_caps) + gst_caps_unref(mdecoder->gst_caps); + + tsmf_platform_free(mdecoder); + ZeroMemory(mdecoder, sizeof(TSMFGstreamerDecoder)); + free(mdecoder); + mdecoder = NULL; + } +} + +static UINT64 tsmf_gstreamer_get_running_time(ITSMFDecoder* decoder) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + + if (!mdecoder) + return 0; + + if (!mdecoder->outsink) + return mdecoder->last_sample_start_time; + + if (!mdecoder->pipe) + return 0; + + GstFormat fmt = GST_FORMAT_TIME; + gint64 pos = 0; +#if GST_VERSION_MAJOR > 0 + gst_element_query_position(mdecoder->pipe, fmt, &pos); +#else + gst_element_query_position(mdecoder->pipe, &fmt, &pos); +#endif + return (UINT64)(pos / 100 + mdecoder->seek_offset); +} + +static BOOL tsmf_gstreamer_update_rendering_area(ITSMFDecoder* decoder, int newX, int newY, + int newWidth, int newHeight, int numRectangles, + RDP_RECT* rectangles) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + DEBUG_TSMF("x=%d, y=%d, w=%d, h=%d, rect=%d", newX, newY, newWidth, newHeight, numRectangles); + + if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) + { + return tsmf_window_resize(mdecoder, newX, newY, newWidth, newHeight, numRectangles, + rectangles) == 0; + } + + return TRUE; +} + +static BOOL tsmf_gstreamer_ack(ITSMFDecoder* decoder, BOOL (*cb)(void*, BOOL), void* stream) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + DEBUG_TSMF(""); + mdecoder->ack_cb = NULL; + mdecoder->stream = stream; + return TRUE; +} + +static BOOL tsmf_gstreamer_sync(ITSMFDecoder* decoder, void (*cb)(void*), void* stream) +{ + TSMFGstreamerDecoder* mdecoder = (TSMFGstreamerDecoder*)decoder; + DEBUG_TSMF(""); + mdecoder->sync_cb = NULL; + mdecoder->stream = stream; + return TRUE; +} + +FREERDP_ENTRY_POINT(UINT VCAPITYPE gstreamer_freerdp_tsmf_client_decoder_subsystem_entry(void* ptr)) +{ + ITSMFDecoder** sptr = (ITSMFDecoder**)ptr; + WINPR_ASSERT(sptr); + *sptr = NULL; + +#if GST_CHECK_VERSION(0, 10, 31) + if (!gst_is_initialized()) + { + gst_init(NULL, NULL); + } +#else + gst_init(NULL, NULL); +#endif + + TSMFGstreamerDecoder* decoder; + decoder = calloc(1, sizeof(TSMFGstreamerDecoder)); + + if (!decoder) + return ERROR_OUTOFMEMORY; + + decoder->iface.SetFormat = tsmf_gstreamer_set_format; + decoder->iface.Decode = NULL; + decoder->iface.GetDecodedData = NULL; + decoder->iface.GetDecodedFormat = NULL; + decoder->iface.GetDecodedDimension = NULL; + decoder->iface.GetRunningTime = tsmf_gstreamer_get_running_time; + decoder->iface.UpdateRenderingArea = tsmf_gstreamer_update_rendering_area; + decoder->iface.Free = tsmf_gstreamer_free; + decoder->iface.Control = tsmf_gstreamer_control; + decoder->iface.DecodeEx = tsmf_gstreamer_decodeEx; + decoder->iface.ChangeVolume = tsmf_gstreamer_change_volume; + decoder->iface.BufferLevel = tsmf_gstreamer_buffer_level; + decoder->iface.SetAckFunc = tsmf_gstreamer_ack; + decoder->iface.SetSyncFunc = tsmf_gstreamer_sync; + decoder->paused = FALSE; + decoder->gstVolume = 0.5; + decoder->gstMuted = FALSE; + decoder->state = GST_STATE_VOID_PENDING; /* No real state yet */ + decoder->last_sample_start_time = 0; + decoder->last_sample_end_time = 0; + decoder->seek_offset = 0; + decoder->seeking = FALSE; + + if (tsmf_platform_create(decoder) < 0) + { + free(decoder); + return ERROR_INTERNAL_ERROR; + } + + *sptr = &decoder->iface; + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/oss/tsmf_oss.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/oss/tsmf_oss.c new file mode 100644 index 0000000000000000000000000000000000000000..721620ebedf97fb4a201c0d1681e8c93aa32f440 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/oss/tsmf_oss.c @@ -0,0 +1,252 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - OSS Audio Device + * + * Copyright (c) 2015 Rozhuk Ivan + * + * 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 + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#if defined(__OpenBSD__) +#include +#else +#include +#endif +#include + +#include +#include + +#include "tsmf_audio.h" + +typedef struct +{ + ITSMFAudioDevice iface; + + char dev_name[PATH_MAX]; + int pcm_handle; + + UINT32 sample_rate; + UINT32 channels; + UINT32 bits_per_sample; + + UINT32 data_size_last; +} TSMFOssAudioDevice; + +#define OSS_LOG_ERR(_text, _error) \ + do \ + { \ + if ((_error) != 0) \ + { \ + char ebuffer[256] = { 0 }; \ + WLog_ERR(TAG, "%s: %i - %s", (_text), (_error), \ + winpr_strerror((_error), ebuffer, sizeof(ebuffer))); \ + } \ + } while (0) + +static BOOL tsmf_oss_open(ITSMFAudioDevice* audio, const char* device) +{ + int tmp = 0; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL || oss->pcm_handle != -1) + return FALSE; + + if (device == NULL) /* Default device. */ + { + strncpy(oss->dev_name, "/dev/dsp", sizeof(oss->dev_name)); + } + else + { + strncpy(oss->dev_name, device, sizeof(oss->dev_name) - 1); + } + + if ((oss->pcm_handle = open(oss->dev_name, O_WRONLY)) < 0) + { + OSS_LOG_ERR("sound dev open failed", errno); + oss->pcm_handle = -1; + return FALSE; + } + +#if 0 /* FreeBSD OSS implementation at this moment (2015.03) does not set PCM_CAP_OUTPUT flag. */ + if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETCAPS, &mask) == -1) + { + OSS_LOG_ERR("SNDCTL_DSP_GETCAPS failed, try ignored", errno); + } + else if ((mask & PCM_CAP_OUTPUT) == 0) + { + OSS_LOG_ERR("Device does not supports playback", EOPNOTSUPP); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + +#endif + const int rc = ioctl(oss->pcm_handle, SNDCTL_DSP_GETFMTS, &tmp); + if (rc == -1) + { + OSS_LOG_ERR("SNDCTL_DSP_GETFMTS failed", errno); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + + if ((AFMT_S16_LE & tmp) == 0) + { + OSS_LOG_ERR("SNDCTL_DSP_GETFMTS - AFMT_S16_LE", EOPNOTSUPP); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + + WLog_INFO(TAG, "open: %s", oss->dev_name); + return TRUE; +} + +static BOOL tsmf_oss_set_format(ITSMFAudioDevice* audio, UINT32 sample_rate, UINT32 channels, + UINT32 bits_per_sample) +{ + int tmp = 0; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL || oss->pcm_handle == -1) + return FALSE; + + oss->sample_rate = sample_rate; + oss->channels = channels; + oss->bits_per_sample = bits_per_sample; + tmp = AFMT_S16_LE; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFMT, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SETFMT failed", errno); + + tmp = channels; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_CHANNELS, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_CHANNELS failed", errno); + + tmp = sample_rate; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SPEED, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SPEED failed", errno); + + tmp = ((bits_per_sample / 8) * channels * sample_rate); + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFRAGMENT, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SETFRAGMENT failed", errno); + + DEBUG_TSMF("sample_rate %" PRIu32 " channels %" PRIu32 " bits_per_sample %" PRIu32 "", + sample_rate, channels, bits_per_sample); + return TRUE; +} + +static BOOL tsmf_oss_play(ITSMFAudioDevice* audio, const BYTE* data, UINT32 data_size) +{ + UINT32 offset = 0; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + DEBUG_TSMF("tsmf_oss_play: data_size %" PRIu32 "", data_size); + + if (oss == NULL || oss->pcm_handle == -1) + return FALSE; + + if (data == NULL || data_size == 0) + return TRUE; + + offset = 0; + oss->data_size_last = data_size; + + while (offset < data_size) + { + const ssize_t status = write(oss->pcm_handle, &data[offset], (data_size - offset)); + + if (status < 0) + { + OSS_LOG_ERR("write fail", errno); + return FALSE; + } + + offset += status; + } + + return TRUE; +} + +static UINT64 tsmf_oss_get_latency(ITSMFAudioDevice* audio) +{ + UINT64 latency = 0; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL) + return 0; + + // latency = ((oss->data_size_last / (oss->bits_per_sample / 8)) * oss->sample_rate); + // WLog_INFO(TAG, "latency: %zu", latency); + return latency; +} + +static BOOL tsmf_oss_flush(ITSMFAudioDevice* audio) +{ + return TRUE; +} + +static void tsmf_oss_free(ITSMFAudioDevice* audio) +{ + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL) + return; + + if (oss->pcm_handle != -1) + { + WLog_INFO(TAG, "close: %s", oss->dev_name); + close(oss->pcm_handle); + } + + free(oss); +} + +FREERDP_ENTRY_POINT(UINT VCAPITYPE oss_freerdp_tsmf_client_audio_subsystem_entry(void* ptr)) +{ + ITSMFAudioDevice** sptr = (ITSMFAudioDevice**)ptr; + WINPR_ASSERT(sptr); + *sptr = NULL; + + TSMFOssAudioDevice* oss = calloc(1, sizeof(TSMFOssAudioDevice)); + if (!oss) + return ERROR_OUTOFMEMORY; + + oss->iface.Open = tsmf_oss_open; + oss->iface.SetFormat = tsmf_oss_set_format; + oss->iface.Play = tsmf_oss_play; + oss->iface.GetLatency = tsmf_oss_get_latency; + oss->iface.Flush = tsmf_oss_flush; + oss->iface.Free = tsmf_oss_free; + oss->pcm_handle = -1; + *sptr = &oss->iface; + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9f54c28a3fd6356afd9c64cb3e2ea29d2a44a5e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/CMakeLists.txt @@ -0,0 +1,29 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +define_channel_client_subsystem("tsmf" "pulse" "audio") + +find_package(PulseAudio REQUIRED) + +set(${MODULE_PREFIX}_SRCS tsmf_pulse.c) + +set(${MODULE_PREFIX}_LIBS winpr ${PULSEAUDIO_LIBRARY} ${PULSEAUDIO_MAINLOOP_LIBRARY}) + +include_directories(..) +include_directories(SYSTEM ${PULSEAUDIO_INCLUDE_DIR}) + +add_channel_client_subsystem_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} "" TRUE "") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/tsmf_pulse.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/tsmf_pulse.c new file mode 100644 index 0000000000000000000000000000000000000000..b5b9f033facb00a2ff475cadf5e52b8d9289035d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/pulse/tsmf_pulse.c @@ -0,0 +1,422 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - PulseAudio Device + * + * Copyright 2010-2011 Vic Lee + * + * 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 + +#include +#include +#include +#include + +#include + +#include + +#include "tsmf_audio.h" + +typedef struct +{ + ITSMFAudioDevice iface; + + char device[32]; + pa_threaded_mainloop* mainloop; + pa_context* context; + pa_sample_spec sample_spec; + pa_stream* stream; +} TSMFPulseAudioDevice; + +static void tsmf_pulse_context_state_callback(pa_context* context, void* userdata) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)userdata; + pa_context_state_t state = pa_context_get_state(context); + + switch (state) + { + case PA_CONTEXT_READY: + DEBUG_TSMF("PA_CONTEXT_READY"); + pa_threaded_mainloop_signal(pulse->mainloop, 0); + break; + + case PA_CONTEXT_FAILED: + case PA_CONTEXT_TERMINATED: + DEBUG_TSMF("state %d", state); + pa_threaded_mainloop_signal(pulse->mainloop, 0); + break; + + default: + DEBUG_TSMF("state %d", state); + break; + } +} + +static BOOL tsmf_pulse_connect(TSMFPulseAudioDevice* pulse) +{ + pa_context_state_t state = PA_CONTEXT_FAILED; + + if (!pulse->context) + return FALSE; + + if (pa_context_connect(pulse->context, NULL, 0, NULL)) + { + WLog_ERR(TAG, "pa_context_connect failed (%d)", pa_context_errno(pulse->context)); + return FALSE; + } + + pa_threaded_mainloop_lock(pulse->mainloop); + + if (pa_threaded_mainloop_start(pulse->mainloop) < 0) + { + pa_threaded_mainloop_unlock(pulse->mainloop); + WLog_ERR(TAG, "pa_threaded_mainloop_start failed (%d)", pa_context_errno(pulse->context)); + return FALSE; + } + + for (;;) + { + state = pa_context_get_state(pulse->context); + + if (state == PA_CONTEXT_READY) + break; + + if (!PA_CONTEXT_IS_GOOD(state)) + { + DEBUG_TSMF("bad context state (%d)", pa_context_errno(pulse->context)); + break; + } + + pa_threaded_mainloop_wait(pulse->mainloop); + } + + pa_threaded_mainloop_unlock(pulse->mainloop); + + if (state == PA_CONTEXT_READY) + { + DEBUG_TSMF("connected"); + return TRUE; + } + else + { + pa_context_disconnect(pulse->context); + return FALSE; + } +} + +static BOOL tsmf_pulse_open(ITSMFAudioDevice* audio, const char* device) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + + if (device) + { + strncpy(pulse->device, device, sizeof(pulse->device) - 1); + } + + pulse->mainloop = pa_threaded_mainloop_new(); + + if (!pulse->mainloop) + { + WLog_ERR(TAG, "pa_threaded_mainloop_new failed"); + return FALSE; + } + + pulse->context = pa_context_new(pa_threaded_mainloop_get_api(pulse->mainloop), "freerdp"); + + if (!pulse->context) + { + WLog_ERR(TAG, "pa_context_new failed"); + return FALSE; + } + + pa_context_set_state_callback(pulse->context, tsmf_pulse_context_state_callback, pulse); + + if (!tsmf_pulse_connect(pulse)) + { + WLog_ERR(TAG, "tsmf_pulse_connect failed"); + return FALSE; + } + + DEBUG_TSMF("open device %s", pulse->device); + return TRUE; +} + +static void tsmf_pulse_stream_success_callback(pa_stream* stream, int success, void* userdata) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)userdata; + pa_threaded_mainloop_signal(pulse->mainloop, 0); +} + +static void tsmf_pulse_wait_for_operation(TSMFPulseAudioDevice* pulse, pa_operation* operation) +{ + if (operation == NULL) + return; + + while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) + { + pa_threaded_mainloop_wait(pulse->mainloop); + } + + pa_operation_unref(operation); +} + +static void tsmf_pulse_stream_state_callback(pa_stream* stream, void* userdata) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)userdata; + WINPR_ASSERT(pulse); + + pa_stream_state_t state = pa_stream_get_state(stream); + + switch (state) + { + case PA_STREAM_READY: + DEBUG_TSMF("PA_STREAM_READY"); + pa_threaded_mainloop_signal(pulse->mainloop, 0); + break; + + case PA_STREAM_FAILED: + case PA_STREAM_TERMINATED: + DEBUG_TSMF("state %d", state); + pa_threaded_mainloop_signal(pulse->mainloop, 0); + break; + + default: + DEBUG_TSMF("state %d", state); + break; + } +} + +static void tsmf_pulse_stream_request_callback(pa_stream* stream, size_t length, void* userdata) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)userdata; + DEBUG_TSMF("%" PRIdz "", length); + pa_threaded_mainloop_signal(pulse->mainloop, 0); +} + +static BOOL tsmf_pulse_close_stream(TSMFPulseAudioDevice* pulse) +{ + if (!pulse->context || !pulse->stream) + return FALSE; + + DEBUG_TSMF(""); + pa_threaded_mainloop_lock(pulse->mainloop); + pa_stream_set_write_callback(pulse->stream, NULL, NULL); + tsmf_pulse_wait_for_operation( + pulse, pa_stream_drain(pulse->stream, tsmf_pulse_stream_success_callback, pulse)); + pa_stream_disconnect(pulse->stream); + pa_stream_unref(pulse->stream); + pulse->stream = NULL; + pa_threaded_mainloop_unlock(pulse->mainloop); + return TRUE; +} + +static BOOL tsmf_pulse_open_stream(TSMFPulseAudioDevice* pulse) +{ + pa_stream_state_t state = PA_STREAM_FAILED; + pa_buffer_attr buffer_attr = { 0 }; + + if (!pulse->context) + return FALSE; + + DEBUG_TSMF(""); + pa_threaded_mainloop_lock(pulse->mainloop); + pulse->stream = pa_stream_new(pulse->context, "freerdp", &pulse->sample_spec, NULL); + + if (!pulse->stream) + { + pa_threaded_mainloop_unlock(pulse->mainloop); + WLog_ERR(TAG, "pa_stream_new failed (%d)", pa_context_errno(pulse->context)); + return FALSE; + } + + pa_stream_set_state_callback(pulse->stream, tsmf_pulse_stream_state_callback, pulse); + pa_stream_set_write_callback(pulse->stream, tsmf_pulse_stream_request_callback, pulse); + buffer_attr.maxlength = (uint32_t)pa_usec_to_bytes(500000, &pulse->sample_spec); + buffer_attr.tlength = (uint32_t)pa_usec_to_bytes(250000, &pulse->sample_spec); + buffer_attr.prebuf = (UINT32)-1; + buffer_attr.minreq = (UINT32)-1; + buffer_attr.fragsize = (UINT32)-1; + + if (pa_stream_connect_playback( + pulse->stream, pulse->device[0] ? pulse->device : NULL, &buffer_attr, + PA_STREAM_ADJUST_LATENCY | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE, + NULL, NULL) < 0) + { + pa_threaded_mainloop_unlock(pulse->mainloop); + WLog_ERR(TAG, "pa_stream_connect_playback failed (%d)", pa_context_errno(pulse->context)); + return FALSE; + } + + for (;;) + { + state = pa_stream_get_state(pulse->stream); + + if (state == PA_STREAM_READY) + break; + + if (!PA_STREAM_IS_GOOD(state)) + { + WLog_ERR(TAG, "bad stream state (%d)", pa_context_errno(pulse->context)); + break; + } + + pa_threaded_mainloop_wait(pulse->mainloop); + } + + pa_threaded_mainloop_unlock(pulse->mainloop); + + if (state == PA_STREAM_READY) + { + DEBUG_TSMF("connected"); + return TRUE; + } + else + { + tsmf_pulse_close_stream(pulse); + return FALSE; + } +} + +static BOOL tsmf_pulse_set_format(ITSMFAudioDevice* audio, UINT32 sample_rate, UINT32 channels, + UINT32 bits_per_sample) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + DEBUG_TSMF("sample_rate %" PRIu32 " channels %" PRIu32 " bits_per_sample %" PRIu32 "", + sample_rate, channels, bits_per_sample); + pulse->sample_spec.rate = sample_rate; + + WINPR_ASSERT(channels <= UINT8_MAX); + pulse->sample_spec.channels = (uint8_t)channels; + pulse->sample_spec.format = PA_SAMPLE_S16LE; + return tsmf_pulse_open_stream(pulse); +} + +static BOOL tsmf_pulse_play(ITSMFAudioDevice* audio, const BYTE* data, UINT32 data_size) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + const BYTE* src = NULL; + size_t len = 0; + int ret = 0; + DEBUG_TSMF("data_size %" PRIu32 "", data_size); + + if (pulse->stream) + { + pa_threaded_mainloop_lock(pulse->mainloop); + src = data; + + while (data_size > 0) + { + while ((len = pa_stream_writable_size(pulse->stream)) == 0) + { + DEBUG_TSMF("waiting"); + pa_threaded_mainloop_wait(pulse->mainloop); + } + + if (len == (size_t)-1) + break; + + if (len > data_size) + len = data_size; + + ret = pa_stream_write(pulse->stream, src, len, NULL, 0LL, PA_SEEK_RELATIVE); + + if (ret < 0) + { + DEBUG_TSMF("pa_stream_write failed (%d)", pa_context_errno(pulse->context)); + break; + } + + src += len; + data_size -= len; + } + + pa_threaded_mainloop_unlock(pulse->mainloop); + } + + return TRUE; +} + +static UINT64 tsmf_pulse_get_latency(ITSMFAudioDevice* audio) +{ + pa_usec_t usec = 0; + UINT64 latency = 0; + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + + if (pulse->stream && pa_stream_get_latency(pulse->stream, &usec, NULL) == 0) + { + latency = ((UINT64)usec) * 10LL; + } + + return latency; +} + +static BOOL tsmf_pulse_flush(ITSMFAudioDevice* audio) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + pa_threaded_mainloop_lock(pulse->mainloop); + tsmf_pulse_wait_for_operation( + pulse, pa_stream_flush(pulse->stream, tsmf_pulse_stream_success_callback, pulse)); + pa_threaded_mainloop_unlock(pulse->mainloop); + return TRUE; +} + +static void tsmf_pulse_free(ITSMFAudioDevice* audio) +{ + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)audio; + DEBUG_TSMF(""); + tsmf_pulse_close_stream(pulse); + + if (pulse->mainloop) + { + pa_threaded_mainloop_stop(pulse->mainloop); + } + + if (pulse->context) + { + pa_context_disconnect(pulse->context); + pa_context_unref(pulse->context); + pulse->context = NULL; + } + + if (pulse->mainloop) + { + pa_threaded_mainloop_free(pulse->mainloop); + pulse->mainloop = NULL; + } + + free(pulse); +} + +FREERDP_ENTRY_POINT(UINT VCAPITYPE pulse_freerdp_tsmf_client_audio_subsystem_entry(void* ptr)) +{ + ITSMFAudioDevice** sptr = (ITSMFAudioDevice**)ptr; + WINPR_ASSERT(sptr); + *sptr = NULL; + + TSMFPulseAudioDevice* pulse = (TSMFPulseAudioDevice*)calloc(1, sizeof(TSMFPulseAudioDevice)); + + if (!pulse) + return ERROR_OUTOFMEMORY; + + pulse->iface.Open = tsmf_pulse_open; + pulse->iface.SetFormat = tsmf_pulse_set_format; + pulse->iface.Play = tsmf_pulse_play; + pulse->iface.GetLatency = tsmf_pulse_get_latency; + pulse->iface.Flush = tsmf_pulse_flush; + pulse->iface.Free = tsmf_pulse_free; + *sptr = &pulse->iface; + return CHANNEL_RC_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/tsmf_decoder.c b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/tsmf_decoder.c new file mode 100644 index 0000000000000000000000000000000000000000..b5dd108e1a2cd2e56855778d2581ec9ad97fef7b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/tsmf/client/tsmf_decoder.c @@ -0,0 +1,121 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - Decoder + * + * Copyright 2010-2011 Vic Lee + * + * 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 + +#include +#include +#include + +#include +#include + +#include "tsmf_types.h" +#include "tsmf_constants.h" +#include "tsmf_decoder.h" + +static ITSMFDecoder* tsmf_load_decoder_by_name(const char* name) +{ + ITSMFDecoder* decoder = NULL; + union + { + PVIRTUALCHANNELENTRY pvce; + TSMF_DECODER_ENTRY entry; + } cnv; + cnv.pvce = freerdp_load_channel_addin_entry("tsmf", name, "decoder", 0); + + if (!cnv.entry) + return NULL; + + const UINT rc = cnv.entry(&decoder); + + if ((rc != CHANNEL_RC_OK) || !decoder) + { + WLog_ERR(TAG, "failed to call export function in %s", name); + return NULL; + } + + return decoder; +} + +static BOOL tsmf_decoder_set_format(ITSMFDecoder* decoder, TS_AM_MEDIA_TYPE* media_type) +{ + if (decoder->SetFormat(decoder, media_type)) + return TRUE; + else + return FALSE; +} + +ITSMFDecoder* tsmf_load_decoder(const char* name, TS_AM_MEDIA_TYPE* media_type) +{ + ITSMFDecoder* decoder = NULL; + + if (name) + decoder = tsmf_load_decoder_by_name(name); + +#if defined(WITH_GSTREAMER_1_0) + if (!decoder) + decoder = tsmf_load_decoder_by_name("gstreamer"); +#endif + +#if defined(WITH_VIDEO_FFMPEG) + if (!decoder) + decoder = tsmf_load_decoder_by_name("ffmpeg"); +#endif + + if (decoder) + { + if (!tsmf_decoder_set_format(decoder, media_type)) + { + decoder->Free(decoder); + decoder = NULL; + } + } + + return decoder; +} + +BOOL tsmf_check_decoder_available(const char* name) +{ + ITSMFDecoder* decoder = NULL; + BOOL retValue = FALSE; + + if (name) + { + decoder = tsmf_load_decoder_by_name(name); + } +#if defined(WITH_GSTREAMER_1_0) + if (!decoder) + decoder = tsmf_load_decoder_by_name("gstreamer"); +#endif + +#if defined(WITH_VIDEO_FFMPEG) + if (!decoder) + decoder = tsmf_load_decoder_by_name("ffmpeg"); +#endif + + if (decoder) + { + decoder->Free(decoder); + decoder = NULL; + retValue = TRUE; + } + + return retValue; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..41e371deaafa505da69b582efd1594fa3d40787f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/CMakeLists.txt @@ -0,0 +1,25 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2018 David Fort +# +# 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. + +define_channel_client("video") + +set(${MODULE_PREFIX}_SRCS video_main.c video_main.h) + +set(${MODULE_PREFIX}_LIBS winpr) +include_directories(..) + +add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE "DVCPluginEntry") diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.c b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.c new file mode 100644 index 0000000000000000000000000000000000000000..eae5a93fff838a0389d14ec9ec830d4e2f8e1355 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.c @@ -0,0 +1,1243 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Optimized Remoting Virtual Channel Extension + * + * Copyright 2017 David Fort + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define TAG CHANNELS_TAG("video") + +#include "video_main.h" + +typedef struct +{ + IWTSPlugin wtsPlugin; + + IWTSListener* controlListener; + IWTSListener* dataListener; + GENERIC_LISTENER_CALLBACK* control_callback; + GENERIC_LISTENER_CALLBACK* data_callback; + + VideoClientContext* context; + BOOL initialized; +} VIDEO_PLUGIN; + +#define XF_VIDEO_UNLIMITED_RATE 31 + +static const BYTE MFVideoFormat_H264[] = { 'H', '2', '6', '4', 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 }; + +typedef struct +{ + VideoClientContext* video; + BYTE PresentationId; + UINT32 ScaledWidth, ScaledHeight; + MAPPED_GEOMETRY* geometry; + + UINT64 startTimeStamp; + UINT64 publishOffset; + H264_CONTEXT* h264; + wStream* currentSample; + UINT64 lastPublishTime, nextPublishTime; + volatile LONG refCounter; + VideoSurface* surface; +} PresentationContext; + +typedef struct +{ + UINT64 publishTime; + UINT64 hnsDuration; + MAPPED_GEOMETRY* geometry; + UINT32 w, h; + UINT32 scanline; + BYTE* surfaceData; + PresentationContext* presentation; +} VideoFrame; + +/** @brief private data for the channel */ +struct s_VideoClientContextPriv +{ + VideoClientContext* video; + GeometryClientContext* geometry; + wQueue* frames; + CRITICAL_SECTION framesLock; + wBufferPool* surfacePool; + UINT32 publishedFrames; + UINT32 droppedFrames; + UINT32 lastSentRate; + UINT64 nextFeedbackTime; + PresentationContext* currentPresentation; +}; + +static void PresentationContext_unref(PresentationContext** presentation); +static void VideoClientContextPriv_free(VideoClientContextPriv* priv); + +static const char* video_command_name(BYTE cmd) +{ + switch (cmd) + { + case TSMM_START_PRESENTATION: + return "start"; + case TSMM_STOP_PRESENTATION: + return "stop"; + default: + return ""; + } +} + +static void video_client_context_set_geometry(VideoClientContext* video, + GeometryClientContext* geometry) +{ + WINPR_ASSERT(video); + WINPR_ASSERT(video->priv); + video->priv->geometry = geometry; +} + +static VideoClientContextPriv* VideoClientContextPriv_new(VideoClientContext* video) +{ + VideoClientContextPriv* ret = NULL; + + WINPR_ASSERT(video); + ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->frames = Queue_New(TRUE, 10, 2); + if (!ret->frames) + { + WLog_ERR(TAG, "unable to allocate frames queue"); + goto fail; + } + + ret->surfacePool = BufferPool_New(FALSE, 0, 16); + if (!ret->surfacePool) + { + WLog_ERR(TAG, "unable to create surface pool"); + goto fail; + } + + if (!InitializeCriticalSectionAndSpinCount(&ret->framesLock, 4 * 1000)) + { + WLog_ERR(TAG, "unable to initialize frames lock"); + goto fail; + } + + ret->video = video; + + /* don't set to unlimited so that we have the chance to send a feedback in + * the first second (for servers that want feedback directly) + */ + ret->lastSentRate = 30; + return ret; + +fail: + VideoClientContextPriv_free(ret); + return NULL; +} + +static BOOL PresentationContext_ref(PresentationContext* presentation) +{ + WINPR_ASSERT(presentation); + + InterlockedIncrement(&presentation->refCounter); + return TRUE; +} + +static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, + UINT32 x, UINT32 y, UINT32 width, UINT32 height) +{ + size_t s = 4ULL * width * height; + PresentationContext* ret = NULL; + + WINPR_ASSERT(video); + + if (s > INT32_MAX) + return NULL; + + ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->video = video; + ret->PresentationId = PresentationId; + + ret->h264 = h264_context_new(FALSE); + if (!ret->h264) + { + WLog_ERR(TAG, "unable to create a h264 context"); + goto fail; + } + if (!h264_context_reset(ret->h264, width, height)) + goto fail; + + ret->currentSample = Stream_New(NULL, 4096); + if (!ret->currentSample) + { + WLog_ERR(TAG, "unable to create current packet stream"); + goto fail; + } + + ret->surface = video->createSurface(video, x, y, width, height); + if (!ret->surface) + { + WLog_ERR(TAG, "unable to create surface"); + goto fail; + } + + if (!PresentationContext_ref(ret)) + goto fail; + + return ret; + +fail: + PresentationContext_unref(&ret); + return NULL; +} + +static void PresentationContext_unref(PresentationContext** ppresentation) +{ + PresentationContext* presentation = NULL; + MAPPED_GEOMETRY* geometry = NULL; + + WINPR_ASSERT(ppresentation); + + presentation = *ppresentation; + if (!presentation) + return; + + if (InterlockedDecrement(&presentation->refCounter) > 0) + return; + + geometry = presentation->geometry; + if (geometry) + { + geometry->MappedGeometryUpdate = NULL; + geometry->MappedGeometryClear = NULL; + geometry->custom = NULL; + mappedGeometryUnref(geometry); + } + + h264_context_free(presentation->h264); + Stream_Free(presentation->currentSample, TRUE); + presentation->video->deleteSurface(presentation->video, presentation->surface); + free(presentation); + *ppresentation = NULL; +} + +static void VideoFrame_free(VideoFrame** pframe) +{ + VideoFrame* frame = NULL; + + WINPR_ASSERT(pframe); + frame = *pframe; + if (!frame) + return; + + mappedGeometryUnref(frame->geometry); + + WINPR_ASSERT(frame->presentation); + WINPR_ASSERT(frame->presentation->video); + WINPR_ASSERT(frame->presentation->video->priv); + BufferPool_Return(frame->presentation->video->priv->surfacePool, frame->surfaceData); + PresentationContext_unref(&frame->presentation); + free(frame); + *pframe = NULL; +} + +static VideoFrame* VideoFrame_new(VideoClientContextPriv* priv, PresentationContext* presentation, + MAPPED_GEOMETRY* geom) +{ + VideoFrame* frame = NULL; + const VideoSurface* surface = NULL; + + WINPR_ASSERT(priv); + WINPR_ASSERT(presentation); + WINPR_ASSERT(geom); + + surface = presentation->surface; + WINPR_ASSERT(surface); + + frame = calloc(1, sizeof(VideoFrame)); + if (!frame) + goto fail; + + mappedGeometryRef(geom); + + frame->publishTime = presentation->lastPublishTime; + frame->geometry = geom; + frame->w = surface->alignedWidth; + frame->h = surface->alignedHeight; + frame->scanline = surface->scanline; + + frame->surfaceData = BufferPool_Take(priv->surfacePool, 1ll * frame->scanline * frame->h); + if (!frame->surfaceData) + goto fail; + + frame->presentation = presentation; + if (!PresentationContext_ref(frame->presentation)) + goto fail; + + return frame; + +fail: + VideoFrame_free(&frame); + return NULL; +} + +void VideoClientContextPriv_free(VideoClientContextPriv* priv) +{ + if (!priv) + return; + + EnterCriticalSection(&priv->framesLock); + + if (priv->frames) + { + while (Queue_Count(priv->frames)) + { + VideoFrame* frame = Queue_Dequeue(priv->frames); + if (frame) + VideoFrame_free(&frame); + } + } + + Queue_Free(priv->frames); + LeaveCriticalSection(&priv->framesLock); + + DeleteCriticalSection(&priv->framesLock); + + if (priv->currentPresentation) + PresentationContext_unref(&priv->currentPresentation); + + BufferPool_Free(priv->surfacePool); + free(priv); +} + +static UINT video_control_send_presentation_response(VideoClientContext* context, + TSMM_PRESENTATION_RESPONSE* resp) +{ + BYTE buf[12] = { 0 }; + wStream* s = NULL; + VIDEO_PLUGIN* video = NULL; + IWTSVirtualChannel* channel = NULL; + UINT ret = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(resp); + + video = (VIDEO_PLUGIN*)context->handle; + WINPR_ASSERT(video); + + s = Stream_New(buf, 12); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT32(s, 12); /* cbSize */ + Stream_Write_UINT32(s, TSMM_PACKET_TYPE_PRESENTATION_RESPONSE); /* PacketType */ + Stream_Write_UINT8(s, resp->PresentationId); + Stream_Zero(s, 3); + Stream_SealLength(s); + + channel = video->control_callback->channel_callback->channel; + ret = channel->Write(channel, 12, buf, NULL); + Stream_Free(s, FALSE); + + return ret; +} + +static BOOL video_onMappedGeometryUpdate(MAPPED_GEOMETRY* geometry) +{ + PresentationContext* presentation = NULL; + RDP_RECT* r = NULL; + + WINPR_ASSERT(geometry); + + presentation = (PresentationContext*)geometry->custom; + WINPR_ASSERT(presentation); + + r = &geometry->geometry.boundingRect; + WLog_DBG(TAG, + "geometry updated topGeom=(%" PRId32 ",%" PRId32 "-%" PRId32 "x%" PRId32 + ") geom=(%" PRId32 ",%" PRId32 "-%" PRId32 "x%" PRId32 ") rects=(%" PRId16 ",%" PRId16 + "-%" PRId16 "x%" PRId16 ")", + geometry->topLevelLeft, geometry->topLevelTop, + geometry->topLevelRight - geometry->topLevelLeft, + geometry->topLevelBottom - geometry->topLevelTop, + + geometry->left, geometry->top, geometry->right - geometry->left, + geometry->bottom - geometry->top, + + r->x, r->y, r->width, r->height); + + presentation->surface->x = + WINPR_ASSERTING_INT_CAST(uint32_t, geometry->topLevelLeft + geometry->left); + presentation->surface->y = + WINPR_ASSERTING_INT_CAST(uint32_t, geometry->topLevelTop + geometry->top); + + return TRUE; +} + +static BOOL video_onMappedGeometryClear(MAPPED_GEOMETRY* geometry) +{ + PresentationContext* presentation = NULL; + + WINPR_ASSERT(geometry); + + presentation = (PresentationContext*)geometry->custom; + WINPR_ASSERT(presentation); + + mappedGeometryUnref(presentation->geometry); + presentation->geometry = NULL; + return TRUE; +} + +static UINT video_PresentationRequest(VideoClientContext* video, + const TSMM_PRESENTATION_REQUEST* req) +{ + UINT ret = CHANNEL_RC_OK; + + WINPR_ASSERT(video); + WINPR_ASSERT(req); + + VideoClientContextPriv* priv = video->priv; + WINPR_ASSERT(priv); + + if (req->Command == TSMM_START_PRESENTATION) + { + MAPPED_GEOMETRY* geom = NULL; + TSMM_PRESENTATION_RESPONSE resp; + + if (memcmp(req->VideoSubtypeId, MFVideoFormat_H264, 16) != 0) + { + WLog_ERR(TAG, "not a H264 video, ignoring request"); + return CHANNEL_RC_OK; + } + + if (priv->currentPresentation) + { + if (priv->currentPresentation->PresentationId == req->PresentationId) + { + WLog_ERR(TAG, "ignoring start request for existing presentation %" PRIu8, + req->PresentationId); + return CHANNEL_RC_OK; + } + + WLog_ERR(TAG, "releasing current presentation %" PRIu8, req->PresentationId); + PresentationContext_unref(&priv->currentPresentation); + } + + if (!priv->geometry) + { + WLog_ERR(TAG, "geometry channel not ready, ignoring request"); + return CHANNEL_RC_OK; + } + + geom = HashTable_GetItemValue(priv->geometry->geometries, &(req->GeometryMappingId)); + if (!geom) + { + WLog_ERR(TAG, "geometry mapping 0x%" PRIx64 " not registered", req->GeometryMappingId); + return CHANNEL_RC_OK; + } + + WLog_DBG(TAG, "creating presentation 0x%x", req->PresentationId); + priv->currentPresentation = PresentationContext_new( + video, req->PresentationId, + WINPR_ASSERTING_INT_CAST(uint32_t, geom->topLevelLeft + geom->left), + WINPR_ASSERTING_INT_CAST(uint32_t, geom->topLevelTop + geom->top), req->SourceWidth, + req->SourceHeight); + if (!priv->currentPresentation) + { + WLog_ERR(TAG, "unable to create presentation video"); + return CHANNEL_RC_NO_MEMORY; + } + + mappedGeometryRef(geom); + priv->currentPresentation->geometry = geom; + + priv->currentPresentation->video = video; + priv->currentPresentation->ScaledWidth = req->ScaledWidth; + priv->currentPresentation->ScaledHeight = req->ScaledHeight; + + geom->custom = priv->currentPresentation; + geom->MappedGeometryUpdate = video_onMappedGeometryUpdate; + geom->MappedGeometryClear = video_onMappedGeometryClear; + + /* send back response */ + resp.PresentationId = req->PresentationId; + ret = video_control_send_presentation_response(video, &resp); + } + else if (req->Command == TSMM_STOP_PRESENTATION) + { + WLog_DBG(TAG, "stopping presentation 0x%x", req->PresentationId); + if (!priv->currentPresentation) + { + WLog_ERR(TAG, "unknown presentation to stop %" PRIu8, req->PresentationId); + return CHANNEL_RC_OK; + } + + priv->droppedFrames = 0; + priv->publishedFrames = 0; + PresentationContext_unref(&priv->currentPresentation); + } + + return ret; +} + +static UINT video_read_tsmm_presentation_req(VideoClientContext* context, wStream* s) +{ + TSMM_PRESENTATION_REQUEST req = { 0 }; + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 60)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, req.PresentationId); + Stream_Read_UINT8(s, req.Version); + Stream_Read_UINT8(s, req.Command); + Stream_Read_UINT8(s, req.FrameRate); /* FrameRate - reserved and ignored */ + + Stream_Seek_UINT16(s); /* AverageBitrateKbps reserved and ignored */ + Stream_Seek_UINT16(s); /* reserved */ + + Stream_Read_UINT32(s, req.SourceWidth); + Stream_Read_UINT32(s, req.SourceHeight); + Stream_Read_UINT32(s, req.ScaledWidth); + Stream_Read_UINT32(s, req.ScaledHeight); + Stream_Read_UINT64(s, req.hnsTimestampOffset); + Stream_Read_UINT64(s, req.GeometryMappingId); + Stream_Read(s, req.VideoSubtypeId, 16); + + Stream_Read_UINT32(s, req.cbExtra); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, req.cbExtra)) + return ERROR_INVALID_DATA; + + req.pExtraData = Stream_Pointer(s); + + WLog_DBG(TAG, + "presentationReq: id:%" PRIu8 " version:%" PRIu8 + " command:%s srcWidth/srcHeight=%" PRIu32 "x%" PRIu32 " scaled Width/Height=%" PRIu32 + "x%" PRIu32 " timestamp=%" PRIu64 " mappingId=%" PRIx64 "", + req.PresentationId, req.Version, video_command_name(req.Command), req.SourceWidth, + req.SourceHeight, req.ScaledWidth, req.ScaledHeight, req.hnsTimestampOffset, + req.GeometryMappingId); + + return video_PresentationRequest(context, &req); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT video_control_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* s) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + VIDEO_PLUGIN* video = NULL; + VideoClientContext* context = NULL; + UINT ret = CHANNEL_RC_OK; + UINT32 cbSize = 0; + UINT32 packetType = 0; + + WINPR_ASSERT(callback); + WINPR_ASSERT(s); + + video = (VIDEO_PLUGIN*)callback->plugin; + WINPR_ASSERT(video); + + context = (VideoClientContext*)video->wtsPlugin.pInterface; + WINPR_ASSERT(context); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, cbSize); + if (cbSize < 8) + { + WLog_ERR(TAG, "invalid cbSize %" PRIu32 ", expected 8", cbSize); + return ERROR_INVALID_DATA; + } + if (!Stream_CheckAndLogRequiredLength(TAG, s, cbSize - 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, packetType); + switch (packetType) + { + case TSMM_PACKET_TYPE_PRESENTATION_REQUEST: + ret = video_read_tsmm_presentation_req(context, s); + break; + default: + WLog_ERR(TAG, "not expecting packet type %" PRIu32 "", packetType); + ret = ERROR_UNSUPPORTED_TYPE; + break; + } + + return ret; +} + +static UINT video_control_send_client_notification(VideoClientContext* context, + const TSMM_CLIENT_NOTIFICATION* notif) +{ + BYTE buf[100]; + wStream* s = NULL; + VIDEO_PLUGIN* video = NULL; + IWTSVirtualChannel* channel = NULL; + UINT ret = 0; + UINT32 cbSize = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(notif); + + video = (VIDEO_PLUGIN*)context->handle; + WINPR_ASSERT(video); + + s = Stream_New(buf, 32); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + cbSize = 16; + Stream_Seek_UINT32(s); /* cbSize */ + Stream_Write_UINT32(s, TSMM_PACKET_TYPE_CLIENT_NOTIFICATION); /* PacketType */ + Stream_Write_UINT8(s, notif->PresentationId); + Stream_Write_UINT8(s, notif->NotificationType); + Stream_Zero(s, 2); + if (notif->NotificationType == TSMM_CLIENT_NOTIFICATION_TYPE_FRAMERATE_OVERRIDE) + { + Stream_Write_UINT32(s, 16); /* cbData */ + + /* TSMM_CLIENT_NOTIFICATION_FRAMERATE_OVERRIDE */ + Stream_Write_UINT32(s, notif->FramerateOverride.Flags); + Stream_Write_UINT32(s, notif->FramerateOverride.DesiredFrameRate); + Stream_Zero(s, 4ULL * 2ULL); + + cbSize += 4UL * 4UL; + } + else + { + Stream_Write_UINT32(s, 0); /* cbData */ + } + + Stream_SealLength(s); + Stream_SetPosition(s, 0); + Stream_Write_UINT32(s, cbSize); + Stream_Free(s, FALSE); + + WINPR_ASSERT(video->control_callback); + WINPR_ASSERT(video->control_callback->channel_callback); + + channel = video->control_callback->channel_callback->channel; + WINPR_ASSERT(channel); + WINPR_ASSERT(channel->Write); + + ret = channel->Write(channel, cbSize, buf, NULL); + + return ret; +} + +static void video_timer(VideoClientContext* video, UINT64 now) +{ + PresentationContext* presentation = NULL; + VideoClientContextPriv* priv = NULL; + VideoFrame* peekFrame = NULL; + VideoFrame* frame = NULL; + + WINPR_ASSERT(video); + + priv = video->priv; + WINPR_ASSERT(priv); + + EnterCriticalSection(&priv->framesLock); + do + { + peekFrame = (VideoFrame*)Queue_Peek(priv->frames); + if (!peekFrame) + break; + + if (peekFrame->publishTime > now) + break; + + if (frame) + { + WLog_DBG(TAG, "dropping frame @%" PRIu64, frame->publishTime); + priv->droppedFrames++; + VideoFrame_free(&frame); + } + frame = peekFrame; + Queue_Dequeue(priv->frames); + } while (1); + LeaveCriticalSection(&priv->framesLock); + + if (!frame) + goto treat_feedback; + + presentation = frame->presentation; + + priv->publishedFrames++; + memcpy(presentation->surface->data, frame->surfaceData, 1ull * frame->scanline * frame->h); + + WINPR_ASSERT(video->showSurface); + video->showSurface(video, presentation->surface, presentation->ScaledWidth, + presentation->ScaledHeight); + + VideoFrame_free(&frame); + +treat_feedback: + if (priv->nextFeedbackTime < now) + { + /* we can compute some feedback only if we have some published frames and + * a current presentation + */ + if (priv->publishedFrames && priv->currentPresentation) + { + UINT32 computedRate = 0; + + PresentationContext_ref(priv->currentPresentation); + + if (priv->droppedFrames) + { + /** + * some dropped frames, looks like we're asking too many frames per seconds, + * try lowering rate. We go directly from unlimited rate to 24 frames/seconds + * otherwise we lower rate by 2 frames by seconds + */ + if (priv->lastSentRate == XF_VIDEO_UNLIMITED_RATE) + computedRate = 24; + else + { + computedRate = priv->lastSentRate - 2; + if (!computedRate) + computedRate = 2; + } + } + else + { + /** + * we treat all frames ok, so either ask the server to send more, + * or stay unlimited + */ + if (priv->lastSentRate == XF_VIDEO_UNLIMITED_RATE) + computedRate = XF_VIDEO_UNLIMITED_RATE; /* stay unlimited */ + else + { + computedRate = priv->lastSentRate + 2; + if (computedRate > XF_VIDEO_UNLIMITED_RATE) + computedRate = XF_VIDEO_UNLIMITED_RATE; + } + } + + if (computedRate != priv->lastSentRate) + { + TSMM_CLIENT_NOTIFICATION notif; + + WINPR_ASSERT(priv->currentPresentation); + notif.PresentationId = priv->currentPresentation->PresentationId; + notif.NotificationType = TSMM_CLIENT_NOTIFICATION_TYPE_FRAMERATE_OVERRIDE; + if (computedRate == XF_VIDEO_UNLIMITED_RATE) + { + notif.FramerateOverride.Flags = 0x01; + notif.FramerateOverride.DesiredFrameRate = 0x00; + } + else + { + notif.FramerateOverride.Flags = 0x02; + notif.FramerateOverride.DesiredFrameRate = computedRate; + } + + video_control_send_client_notification(video, ¬if); + priv->lastSentRate = computedRate; + + WLog_DBG(TAG, + "server notified with rate %" PRIu32 " published=%" PRIu32 + " dropped=%" PRIu32, + priv->lastSentRate, priv->publishedFrames, priv->droppedFrames); + } + + PresentationContext_unref(&priv->currentPresentation); + } + + WLog_DBG(TAG, "currentRate=%" PRIu32 " published=%" PRIu32 " dropped=%" PRIu32, + priv->lastSentRate, priv->publishedFrames, priv->droppedFrames); + + priv->droppedFrames = 0; + priv->publishedFrames = 0; + priv->nextFeedbackTime = now + 1000; + } +} + +static UINT video_VideoData(VideoClientContext* context, const TSMM_VIDEO_DATA* data) +{ + VideoClientContextPriv* priv = NULL; + PresentationContext* presentation = NULL; + int status = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(data); + + priv = context->priv; + WINPR_ASSERT(priv); + + presentation = priv->currentPresentation; + if (!presentation) + { + WLog_ERR(TAG, "no current presentation"); + return CHANNEL_RC_OK; + } + + if (presentation->PresentationId != data->PresentationId) + { + WLog_ERR(TAG, "current presentation id=%" PRIu8 " doesn't match data id=%" PRIu8, + presentation->PresentationId, data->PresentationId); + return CHANNEL_RC_OK; + } + + if (!Stream_EnsureRemainingCapacity(presentation->currentSample, data->cbSample)) + { + WLog_ERR(TAG, "unable to expand the current packet"); + return CHANNEL_RC_NO_MEMORY; + } + + Stream_Write(presentation->currentSample, data->pSample, data->cbSample); + + if (data->CurrentPacketIndex == data->PacketsInSample) + { + VideoSurface* surface = presentation->surface; + H264_CONTEXT* h264 = presentation->h264; + UINT64 startTime = GetTickCount64(); + UINT64 timeAfterH264 = 0; + MAPPED_GEOMETRY* geom = presentation->geometry; + + const RECTANGLE_16 rect = { 0, 0, WINPR_ASSERTING_INT_CAST(UINT16, surface->alignedWidth), + WINPR_ASSERTING_INT_CAST(UINT16, surface->alignedHeight) }; + Stream_SealLength(presentation->currentSample); + Stream_SetPosition(presentation->currentSample, 0); + + timeAfterH264 = GetTickCount64(); + if (data->SampleNumber == 1) + { + presentation->lastPublishTime = startTime; + } + + presentation->lastPublishTime += (data->hnsDuration / 10000); + if (presentation->lastPublishTime <= timeAfterH264 + 10) + { + int dropped = 0; + + const size_t len = Stream_Length(presentation->currentSample); + if (len > UINT32_MAX) + return CHANNEL_RC_OK; + + /* if the frame is to be published in less than 10 ms, let's consider it's now */ + status = + avc420_decompress(h264, Stream_Pointer(presentation->currentSample), (UINT32)len, + surface->data, surface->format, surface->scanline, + surface->alignedWidth, surface->alignedHeight, &rect, 1); + + if (status < 0) + return CHANNEL_RC_OK; + + WINPR_ASSERT(context->showSurface); + context->showSurface(context, presentation->surface, presentation->ScaledWidth, + presentation->ScaledHeight); + + priv->publishedFrames++; + + /* cleanup previously scheduled frames */ + EnterCriticalSection(&priv->framesLock); + while (Queue_Count(priv->frames) > 0) + { + VideoFrame* frame = Queue_Dequeue(priv->frames); + if (frame) + { + priv->droppedFrames++; + VideoFrame_free(&frame); + dropped++; + } + } + LeaveCriticalSection(&priv->framesLock); + + if (dropped) + WLog_DBG(TAG, "showing frame (%d dropped)", dropped); + } + else + { + const size_t len = Stream_Length(presentation->currentSample); + if (len > UINT32_MAX) + return CHANNEL_RC_OK; + + BOOL enqueueResult = 0; + VideoFrame* frame = VideoFrame_new(priv, presentation, geom); + if (!frame) + { + WLog_ERR(TAG, "unable to create frame"); + return CHANNEL_RC_NO_MEMORY; + } + + status = + avc420_decompress(h264, Stream_Pointer(presentation->currentSample), (UINT32)len, + frame->surfaceData, surface->format, surface->scanline, + surface->alignedWidth, surface->alignedHeight, &rect, 1); + if (status < 0) + { + VideoFrame_free(&frame); + return CHANNEL_RC_OK; + } + + EnterCriticalSection(&priv->framesLock); + enqueueResult = Queue_Enqueue(priv->frames, frame); + LeaveCriticalSection(&priv->framesLock); + + if (!enqueueResult) + { + WLog_ERR(TAG, "unable to enqueue frame"); + VideoFrame_free(&frame); + return CHANNEL_RC_NO_MEMORY; + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): Queue_Enqueue owns frame + WLog_DBG(TAG, "scheduling frame in %" PRIu32 " ms", (frame->publishTime - startTime)); + } + } + + return CHANNEL_RC_OK; +} + +static UINT video_data_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* s) +{ + GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback; + VIDEO_PLUGIN* video = NULL; + VideoClientContext* context = NULL; + UINT32 cbSize = 0; + UINT32 packetType = 0; + TSMM_VIDEO_DATA data; + + video = (VIDEO_PLUGIN*)callback->plugin; + context = (VideoClientContext*)video->wtsPlugin.pInterface; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, cbSize); + if (cbSize < 8) + { + WLog_ERR(TAG, "invalid cbSize %" PRIu32 ", expected >= 8", cbSize); + return ERROR_INVALID_DATA; + } + + if (!Stream_CheckAndLogRequiredLength(TAG, s, cbSize - 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, packetType); + if (packetType != TSMM_PACKET_TYPE_VIDEO_DATA) + { + WLog_ERR(TAG, "only expecting VIDEO_DATA on the data channel"); + return ERROR_INVALID_DATA; + } + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 32)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT8(s, data.PresentationId); + Stream_Read_UINT8(s, data.Version); + Stream_Read_UINT8(s, data.Flags); + Stream_Seek_UINT8(s); /* reserved */ + Stream_Read_UINT64(s, data.hnsTimestamp); + Stream_Read_UINT64(s, data.hnsDuration); + Stream_Read_UINT16(s, data.CurrentPacketIndex); + Stream_Read_UINT16(s, data.PacketsInSample); + Stream_Read_UINT32(s, data.SampleNumber); + Stream_Read_UINT32(s, data.cbSample); + if (!Stream_CheckAndLogRequiredLength(TAG, s, data.cbSample)) + return ERROR_INVALID_DATA; + data.pSample = Stream_Pointer(s); + + /* + WLog_DBG(TAG, "videoData: id:%"PRIu8" version:%"PRIu8" flags:0x%"PRIx8" timestamp=%"PRIu64" + duration=%"PRIu64 " curPacketIndex:%"PRIu16" packetInSample:%"PRIu16" sampleNumber:%"PRIu32" + cbSample:%"PRIu32"", data.PresentationId, data.Version, data.Flags, data.hnsTimestamp, + data.hnsDuration, data.CurrentPacketIndex, data.PacketsInSample, data.SampleNumber, + data.cbSample); + */ + + return video_VideoData(context, &data); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT video_control_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + free(pChannelCallback); + return CHANNEL_RC_OK; +} + +static UINT video_data_on_close(IWTSVirtualChannelCallback* pChannelCallback) +{ + free(pChannelCallback); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +// NOLINTBEGIN(readability-non-const-parameter) +static UINT video_control_on_new_channel_connection(IWTSListenerCallback* listenerCallback, + IWTSVirtualChannel* channel, BYTE* Data, + BOOL* pbAccept, + IWTSVirtualChannelCallback** ppCallback) +// NOLINTEND(readability-non-const-parameter) +{ + GENERIC_CHANNEL_CALLBACK* callback = NULL; + GENERIC_LISTENER_CALLBACK* listener_callback = (GENERIC_LISTENER_CALLBACK*)listenerCallback; + + WINPR_UNUSED(Data); + WINPR_UNUSED(pbAccept); + + callback = (GENERIC_CHANNEL_CALLBACK*)calloc(1, sizeof(GENERIC_CHANNEL_CALLBACK)); + if (!callback) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + callback->iface.OnDataReceived = video_control_on_data_received; + callback->iface.OnClose = video_control_on_close; + callback->plugin = listener_callback->plugin; + callback->channel_mgr = listener_callback->channel_mgr; + callback->channel = channel; + listener_callback->channel_callback = callback; + + *ppCallback = (IWTSVirtualChannelCallback*)callback; + + return CHANNEL_RC_OK; +} + +// NOLINTBEGIN(readability-non-const-parameter) +static UINT video_data_on_new_channel_connection(IWTSListenerCallback* pListenerCallback, + IWTSVirtualChannel* pChannel, BYTE* Data, + BOOL* pbAccept, + IWTSVirtualChannelCallback** ppCallback) +// NOLINTEND(readability-non-const-parameter) +{ + GENERIC_CHANNEL_CALLBACK* callback = NULL; + GENERIC_LISTENER_CALLBACK* listener_callback = (GENERIC_LISTENER_CALLBACK*)pListenerCallback; + + WINPR_UNUSED(Data); + WINPR_UNUSED(pbAccept); + + callback = (GENERIC_CHANNEL_CALLBACK*)calloc(1, sizeof(GENERIC_CHANNEL_CALLBACK)); + if (!callback) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + callback->iface.OnDataReceived = video_data_on_data_received; + callback->iface.OnClose = video_data_on_close; + callback->plugin = listener_callback->plugin; + callback->channel_mgr = listener_callback->channel_mgr; + callback->channel = pChannel; + listener_callback->channel_callback = callback; + + *ppCallback = (IWTSVirtualChannelCallback*)callback; + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT video_plugin_initialize(IWTSPlugin* plugin, IWTSVirtualChannelManager* channelMgr) +{ + UINT status = 0; + VIDEO_PLUGIN* video = (VIDEO_PLUGIN*)plugin; + GENERIC_LISTENER_CALLBACK* callback = NULL; + + if (video->initialized) + { + WLog_ERR(TAG, "[%s] channel initialized twice, aborting", VIDEO_CONTROL_DVC_CHANNEL_NAME); + return ERROR_INVALID_DATA; + } + video->control_callback = callback = + (GENERIC_LISTENER_CALLBACK*)calloc(1, sizeof(GENERIC_LISTENER_CALLBACK)); + if (!callback) + { + WLog_ERR(TAG, "calloc for control callback failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + callback->iface.OnNewChannelConnection = video_control_on_new_channel_connection; + callback->plugin = plugin; + callback->channel_mgr = channelMgr; + + status = channelMgr->CreateListener(channelMgr, VIDEO_CONTROL_DVC_CHANNEL_NAME, 0, + &callback->iface, &(video->controlListener)); + + if (status != CHANNEL_RC_OK) + return status; + video->controlListener->pInterface = video->wtsPlugin.pInterface; + + video->data_callback = callback = + (GENERIC_LISTENER_CALLBACK*)calloc(1, sizeof(GENERIC_LISTENER_CALLBACK)); + if (!callback) + { + WLog_ERR(TAG, "calloc for data callback failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + callback->iface.OnNewChannelConnection = video_data_on_new_channel_connection; + callback->plugin = plugin; + callback->channel_mgr = channelMgr; + + status = channelMgr->CreateListener(channelMgr, VIDEO_DATA_DVC_CHANNEL_NAME, 0, + &callback->iface, &(video->dataListener)); + + if (status == CHANNEL_RC_OK) + video->dataListener->pInterface = video->wtsPlugin.pInterface; + + video->initialized = status == CHANNEL_RC_OK; + return status; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT video_plugin_terminated(IWTSPlugin* pPlugin) +{ + VIDEO_PLUGIN* video = (VIDEO_PLUGIN*)pPlugin; + + if (video->control_callback) + { + IWTSVirtualChannelManager* mgr = video->control_callback->channel_mgr; + if (mgr) + IFCALL(mgr->DestroyListener, mgr, video->controlListener); + } + if (video->data_callback) + { + IWTSVirtualChannelManager* mgr = video->data_callback->channel_mgr; + if (mgr) + IFCALL(mgr->DestroyListener, mgr, video->dataListener); + } + + if (video->context) + VideoClientContextPriv_free(video->context->priv); + + free(video->control_callback); + free(video->data_callback); + free(video->wtsPlugin.pInterface); + free(pPlugin); + return CHANNEL_RC_OK; +} + +/** + * Channel Client Interface + */ +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +FREERDP_ENTRY_POINT(UINT VCAPITYPE video_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)) +{ + UINT error = CHANNEL_RC_OK; + VIDEO_PLUGIN* videoPlugin = NULL; + VideoClientContext* videoContext = NULL; + VideoClientContextPriv* priv = NULL; + + videoPlugin = (VIDEO_PLUGIN*)pEntryPoints->GetPlugin(pEntryPoints, "video"); + if (!videoPlugin) + { + videoPlugin = (VIDEO_PLUGIN*)calloc(1, sizeof(VIDEO_PLUGIN)); + if (!videoPlugin) + { + WLog_ERR(TAG, "calloc failed!"); + return CHANNEL_RC_NO_MEMORY; + } + + videoPlugin->wtsPlugin.Initialize = video_plugin_initialize; + videoPlugin->wtsPlugin.Connected = NULL; + videoPlugin->wtsPlugin.Disconnected = NULL; + videoPlugin->wtsPlugin.Terminated = video_plugin_terminated; + + videoContext = (VideoClientContext*)calloc(1, sizeof(VideoClientContext)); + if (!videoContext) + { + WLog_ERR(TAG, "calloc failed!"); + free(videoPlugin); + return CHANNEL_RC_NO_MEMORY; + } + + priv = VideoClientContextPriv_new(videoContext); + if (!priv) + { + WLog_ERR(TAG, "VideoClientContextPriv_new failed!"); + free(videoContext); + free(videoPlugin); + return CHANNEL_RC_NO_MEMORY; + } + + videoContext->handle = (void*)videoPlugin; + videoContext->priv = priv; + videoContext->timer = video_timer; + videoContext->setGeometry = video_client_context_set_geometry; + + videoPlugin->wtsPlugin.pInterface = (void*)videoContext; + videoPlugin->context = videoContext; + + error = pEntryPoints->RegisterPlugin(pEntryPoints, "video", &videoPlugin->wtsPlugin); + } + else + { + WLog_ERR(TAG, "could not get video Plugin."); + return CHANNEL_RC_BAD_CHANNEL; + } + + return error; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.h b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.h new file mode 100644 index 0000000000000000000000000000000000000000..d09efabee8d455344c0c89550fa4e9678ce37779 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/channels/video/client/video_main.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Optimized Remoting Virtual Channel Extension + * + * Copyright 2017 David Fort + * + * 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 FREERDP_CHANNEL_VIDEO_CLIENT_MAIN_H +#define FREERDP_CHANNEL_VIDEO_CLIENT_MAIN_H + +#include + +#include +#include +#include + +#include + +#endif /* FREERDP_CHANNEL_GEOMETRY_CLIENT_MAIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-abi.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-abi.txt new file mode 100644 index 0000000000000000000000000000000000000000..b3ed0b5bc556e3276e367ed33984dcdf56f3c52b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-abi.txt @@ -0,0 +1,21 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WITH_MANPAGES OFF CACHE BOOL "preload") +set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "preload") +#set (UWAC_FORCE_STATIC_BUILD ON CACHE BOOL "preload") +#set (RDTK_FORCE_STATIC_BUILD ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_PNG ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_JPEG ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_WEBP ON CACHE BOOL "preload") +set(WITH_BINARY_VERSIONING ON CACHE BOOL "preload") +set(WITH_INTERNAL_RC4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD5 ON CACHE BOOL "preload") +set(WITH_SAMPLE ON CACHE BOOL "preload") +set(WITH_FFMPEG ON CACHE BOOL "preload") +set(WITH_SWSCALE ON CACHE BOOL "preload") +set(WITH_DSP_FFMPEG ON CACHE BOOL "preload") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "preload") +set(WITH_PULSE ON CACHE BOOL "preload") +set(WITH_OPAQUE_SETTINGS ON CACHE BOOL "preload") +set(WITH_VERBOSE_WINPR_ASSERT OFF CACHE BOOL "preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-android.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-android.txt new file mode 100644 index 0000000000000000000000000000000000000000..64b732432e6de22ede687451495d4f127620bffd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-android.txt @@ -0,0 +1,15 @@ +message("PRELOADING android cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(CMAKE_TOOLCHAIN_FILE "$ANDROID_NDK/build/cmake/android.toolchain.cmake" CACHE PATH "ToolChain file") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "build with address sanitizer") +set(FREERDP_EXTERNAL_SSL_PATH $ENV{ANDROID_SSL_PATH} CACHE PATH "android ssl") +# ANDROID_NDK and ANDROID_SDK must be set as environment variable +#set(ANDROID_NDK $ENV{ANDROID_SDK} CACHE PATH "Android NDK") +#set(ANDROID_SDK "${ANDROID_NDK}" CACHE PATH "android SDK") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "Enable deprecated command line options") +set(WITH_KRB5 OFF CACHE BOOL "Kerberos support") +set(WITH_CLIENT_SDL OFF CACHE BOOL "SDL client") +set(WITH_SERVER OFF CACHE BOOL "ci default") +set(WITH_X11 OFF CACHE BOOL "ci default") +set(WITH_MANPAGES OFF CACHE BOOL "ci default") +set(WITH_LIBRARY_VERSIONING OFF CACHE BOOL "ci default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-coverity.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-coverity.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2e025926beb477918e337455a260e89b44dbe82 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-coverity.txt @@ -0,0 +1,17 @@ +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_JPEG ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_WEBP ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_PNG ON CACHE BOOL "preload") +set(WITH_CAIRO ON CACHE BOOL "preload") +set(WITH_DSP_EXPERIMENTAL ON CACHE BOOL "preload") +set(WITH_DSP_FFMPEG ON CACHE BOOL "preload") +set(WITH_FFMPEG ON CACHE BOOL "preload") +set(WITH_INTERNAL_RC4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD5 ON CACHE BOOL "preload") +set(WITH_OPUS ON CACHE BOOL "preload") +set(WITH_PROXY_EMULATE_SMARTCARD ON CACHE BOOL "preload") +set(WITH_PULSE ON CACHE BOOL "preload") +set(WITH_SMARTCARD_INSPECT ON CACHE BOOL "preload") +set(WITH_SOXR ON CACHE BOOL "preload") +set(WITH_UNICODE_BUILTIN ON CACHE BOOL "preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-freebsd.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-freebsd.txt new file mode 100644 index 0000000000000000000000000000000000000000..3714fdc5a32bcd69d6d08237800379dbc02d8f26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-freebsd.txt @@ -0,0 +1,48 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "preload") +set(WITH_MANPAGES ON CACHE BOOL "preload") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "preload") +set(WITH_CAIRO ON CACHE BOOL "preload") +set(WITH_ALSA ON CACHE BOOL "preload") +set(WITH_PULSE ON CACHE BOOL "preload") +set(WITH_CHANNELS ON CACHE BOOL "preload") +set(WITH_CUPS ON CACHE BOOL "preload") +set(WITH_LIBRESSL OFF CACHE BOOL "preload") +set(WITH_GSM OFF CACHE BOOL "preload") +set(WITH_CLIENT_SDL3 OFF CACHE BOOL "preload") +set(WITH_SDL_IMAGE_DIALOGS ON CACHE BOOL "preload") +set(WITH_WAYLAND ON CACHE BOOL "preload") +set(WITH_KRB5 ON CACHE BOOL "preload") +set(WITH_PCSC ON CACHE BOOL "preload") +set(WITH_JPEG ON CACHE BOOL "preload") +set(WITH_GSM ON CACHE BOOL "preload") +set(WITH_INTERNAL_RC4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD4 ON CACHE BOOL "preload") +set(WITH_INTERNAL_MD5 ON CACHE BOOL "preload") +set(CHANNEL_SSHAGENT ON CACHE BOOL "preload") +set(CHANNEL_RDPECAM ON CACHE BOOL "preload") +set(CHANNEL_RDPECAM_CLIENT ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_JPEG ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_PNG ON CACHE BOOL "preload") +set(WINPR_UTILS_IMAGE_WEBP ON CACHE BOOL "preload") +set(CHANNEL_URBDRC ON CACHE BOOL "preload") +set(CHANNEL_URBDRC_CLIENT ON CACHE BOOL "preload") +set(WITH_SERVER ON CACHE BOOL "preload") +set(WITH_SAMPLE ON CACHE BOOL "preload") +set(WITH_FAAC ON CACHE BOOL "preload") +set(WITH_FAAD ON CACHE BOOL "preload") +set(WITH_LAME ON CACHE BOOL "preload") +set(WITH_OPENCL ON CACHE BOOL "preload") +set(WITH_OPUS ON CACHE BOOL "preload") +set(WITH_SOXR ON CACHE BOOL "preload") +set(WITH_OPENH264 ON CACHE BOOL "preload") +set(WITH_FDK_AAC ON CACHE BOOL "preload") +set(WITH_NO_UNDEFINED OFF CACHE BOOL "preload") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "preload") +set(WITH_FFMPEG ON CACHE BOOL "preload") +set(WITH_SWSCALE ON CACHE BOOL "preload") +set(WITH_DSP_FFMPEG ON CACHE BOOL "preload") +set(WITH_PROXY ON CACHE BOOL "preload") +set(WITH_PROXY_MODULES ON CACHE BOOL "preload") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios-shared.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios-shared.txt new file mode 100644 index 0000000000000000000000000000000000000000..41ca459f9477d40fc219f99aa56a640782715396 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios-shared.txt @@ -0,0 +1,19 @@ +message("PRELOADING iOS cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(CMAKE_TOOLCHAIN_FILE "${CMAKE_SOURCE_DIR}/cmake/ios.toolchain.cmake" CACHE PATH "cmake toolchain file") +set(CMAKE_BUILD_TYPE "Release" CACHE STRING "build type") +set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "iOS platform to build") +set(CMAKE_OSX_DEPLOYMENT_TARGET "10.0" CACHE STRING "iOS minimum target") +set(ENABLE_BITCODE OFF CACHE BOOL "iOS default") +set(BUILD_TESTING ON CACHE BOOL "iOS default") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "build with address sanitizer") +set(WITH_CLIENT OFF CACHE BOOL "disable iOS client") +set(WITH_SERVER OFF CACHE BOOL "disable iOS server") +set(WITH_KRB5 OFF CACHE BOOL "Kerberos support") +set(WITH_CLIENT_SDL OFF CACHE BOOL "iOS preload") +set(WITH_FFMPEG OFF CACHE BOOL "iOS preload") +set(WITH_SWSCALE OFF CACHE BOOL "iOS preload") +set(WITH_SIMD ON CACHE BOOL "iOS preload") +set(WITH_OPUS OFF CACHE BOOL "iOS preload") +set(WITH_MANPAGES OFF CACHE BOOL "iOS preload") +set(BUILD_SHARED_LIBS ON CACHE BOOL "iOS preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios.txt new file mode 100644 index 0000000000000000000000000000000000000000..37dae19b66299520d9d2e9ba2999f6266f995893 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ios.txt @@ -0,0 +1,19 @@ +message("PRELOADING iOS cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(CMAKE_TOOLCHAIN_FILE "${CMAKE_SOURCE_DIR}/cmake/ios.toolchain.cmake" CACHE PATH "cmake toolchain file") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "build type") +set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "iOS platform to build") +set(CMAKE_OSX_DEPLOYMENT_TARGET "10.0" CACHE STRING "iOS minimum target") +set(ENABLE_BITCODE OFF CACHE BOOL "iOS default") +set(BUILD_TESTING ON CACHE BOOL "iOS default") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "build with address sanitizer") +set(WITH_CLIENT OFF CACHE BOOL "disable iOS client") +set(WITH_SERVER OFF CACHE BOOL "disable iOS server") +set(WITH_KRB5 OFF CACHE BOOL "Kerberos support") +set(WITH_CLIENT_SDL OFF CACHE BOOL "iOS preload") +set(WITH_FFMPEG OFF CACHE BOOL "iOS preload") +set(WITH_SWSCALE OFF CACHE BOOL "iOS preload") +set(WITH_SIMD ON CACHE BOOL "iOS preload") +set(WITH_OPUS OFF CACHE BOOL "iOS preload") +set(WITH_MANPAGES OFF CACHE BOOL "iOS preload") +set(BUILD_SHARED_LIBS OFF CACHE BOOL "iOS preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-linux-all.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-linux-all.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a0563cda29f3c7d01f4caa6dc2af416f3fc6d8f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-linux-all.txt @@ -0,0 +1,55 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "preload") +set(WITH_MANPAGES ON CACHE BOOL "preload") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "preload") +set(WITH_PULSE ON CACHE BOOL "preload") +set(WITH_CHANNELS ON CACHE BOOL "preload") +set(WITH_CUPS ON CACHE BOOL "preload") +set(WITH_WAYLAND ON CACHE BOOL "preload") +set(WITH_KRB5 ON CACHE BOOL "preload") +set(WITH_PCSC ON CACHE BOOL "preload") +set(WITH_JPEG ON CACHE BOOL "preload") +set(WITH_GSM ON CACHE BOOL "preload") +set(CHANNEL_URBDRC ON CACHE BOOL "preload") +set(CHANNEL_URBDRC_CLIENT ON CACHE BOOL "preload") +set(WITH_SERVER ON CACHE BOOL "preload") +set(WITH_DEBUG_ALL OFF CACHE BOOL "preload") +set(WITH_DEBUG_CAPABILITIES OFF CACHE BOOL "preload") +set(WITH_DEBUG_CERTIFICATE OFF CACHE BOOL "preload") +set(WITH_DEBUG_CHANNELS OFF CACHE BOOL "preload") +set(WITH_DEBUG_CLIPRDR OFF CACHE BOOL "preload") +set(WITH_DEBUG_RDPGFX OFF CACHE BOOL "preload") +set(WITH_DEBUG_DVC OFF CACHE BOOL "preload") +set(WITH_DEBUG_KBD OFF CACHE BOOL "preload") +set(WITH_DEBUG_LICENSE OFF CACHE BOOL "preload") +set(WITH_DEBUG_NEGO OFF CACHE BOOL "preload") +set(WITH_DEBUG_NLA OFF CACHE BOOL "preload") +set(WITH_DEBUG_NTLM OFF CACHE BOOL "preload") +set(WITH_DEBUG_RAIL OFF CACHE BOOL "preload") +set(WITH_DEBUG_RDP OFF CACHE BOOL "preload") +set(WITH_DEBUG_RDPEI OFF CACHE BOOL "preload") +set(WITH_DEBUG_REDIR OFF CACHE BOOL "preload") +set(WITH_DEBUG_RDPDR OFF CACHE BOOL "preload") +set(WITH_DEBUG_RFX OFF CACHE BOOL "preload") +set(WITH_DEBUG_SCARD OFF CACHE BOOL "preload") +set(WITH_DEBUG_SND OFF CACHE BOOL "preload") +set(WITH_DEBUG_SVC OFF CACHE BOOL "preload") +set(WITH_DEBUG_THREADS OFF CACHE BOOL "preload") +set(WITH_DEBUG_TIMEZONE OFF CACHE BOOL "preload") +set(WITH_DEBUG_TRANSPORT OFF CACHE BOOL "preload") +set(WITH_DEBUG_TSG OFF CACHE BOOL "preload") +set(WITH_DEBUG_TSMF OFF CACHE BOOL "preload") +set(WITH_DEBUG_WND OFF CACHE BOOL "preload") +set(WITH_DEBUG_X11 OFF CACHE BOOL "preload") +set(WITH_DEBUG_X11_LOCAL_MOVESIZE OFF CACHE BOOL "preload") +set(WITH_DEBUG_XV OFF CACHE BOOL "preload") +set(WITH_SAMPLE ON CACHE BOOL "preload") +set(WITH_NO_UNDEFINED ON CACHE BOOL "preload") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "preload") +set(WITH_FFMPEG ON CACHE BOOL "preload") +set(WITH_SWSCALE ON CACHE BOOL "preload") +set(WITH_DSP_FFMPEG ON CACHE BOOL "preload") +set(WITH_PROXY ON CACHE BOOL "preload") +set(WITH_PROXY_MODULES ON CACHE BOOL "preload") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "preload") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-macosx.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-macosx.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5b19f5e8ab2e499394a329b182c6ee8a10aa513 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-macosx.txt @@ -0,0 +1,17 @@ +message("PRELOADING mac cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WITH_MANPAGES OFF CACHE BOOL "man pages") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "build type") +set(WITH_CUPS ON CACHE BOOL "CUPS printing") +set(CHANNEL_URBDRC OFF CACHE BOOL "USB redirection") +set(WITH_X11 ON CACHE BOOL "Enable X11") +set(WITH_SERVER ON CACHE BOOL "build with server") +set(WITH_SAMPLE ON CACHE BOOL "build with sample") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "build testing") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "build with address sanitizer") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "Enable deprecated command line options") +set(WITH_KRB5 OFF CACHE BOOL "Kerberos support") +set(WITH_WEBVIEW OFF CACHE BOOL "ci default") +set(WITH_FFMPEG OFF CACHE BOOL "ci default") +set(WITH_OPUS OFF CACHE BOOL "ci default") +set(WITH_SWSCALE OFF CACHE BOOL "ci default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-oss-fuzz.cmake b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-oss-fuzz.cmake new file mode 100644 index 0000000000000000000000000000000000000000..4b9f3171294d5b327abe549c3a8fc03300894512 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-oss-fuzz.cmake @@ -0,0 +1,29 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WITH_VERBOSE_WINPR_ASSERT ON CACHE BOOL "oss fuzz") + +set(WITH_SERVER ON CACHE BOOL "oss fuzz") +set(WITH_SAMPLE OFF CACHE BOOL "oss fuzz") +set(WITH_PROXY OFF CACHE BOOL "oss fuzz") +set(WITH_SHADOW OFF CACHE BOOL "oss fuzz") +set(WITH_CLIENT OFF CACHE BOOL "oss fuzz") +set(WITH_ALSA OFF CACHE BOOL "oss fuzz") +set(WITH_X11 OFF CACHE BOOL "oss fuzz") +set(WITH_FUSE OFF CACHE BOOL "oss fuzz") +set(WITH_AAD OFF CACHE BOOL "oss fuzz") +set(WITH_FFMPEG OFF CACHE BOOL "oss fuzz") +set(CHANNEL_RDPECAM_CLIENT OFF CACHE BOOL "oss fuzz") +set(WITH_SWSCALE OFF CACHE BOOL "oss fuzz") +set(WITH_LIBSYSTEMD OFF CACHE BOOL "oss fuzz") +set(WITH_UNICODE_BUILTIN ON CACHE BOOL "oss fuzz") +set(WITH_OPUS OFF CACHE BOOL "oss fuzz") +set(WITH_CUPS OFF CACHE BOOL "oss fuzz") +set(CHANNEL_URBDRC OFF CACHE BOOL "oss fuzz") + +set(BUILD_SHARED_LIBS OFF CACHE BOOL "oss fuzz") + +set(BUILD_WITH_CLANG_TIDY OFF CACHE BOOL "oss fuzz") +set(OSS_FUZZ ON CACHE BOOL "oss fuzz") +set(BUILD_FUZZERS ON CACHE BOOL "oss fuzz") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "oss fuzz") +set(WITH_STREAMPOOL_DEBUG ON CACHE BOOL "oss fuzz") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa-static.cmake b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa-static.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ba945b4a5467e42b0a9594448b0acf330d3873c3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa-static.cmake @@ -0,0 +1,22 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WITH_SERVER ON CACHE BOOL "qa default") +set(WITH_SAMPLE ON CACHE BOOL "qa default") +set(WITH_SIMD ON CACHE BOOL "qa default") +set(WITH_STREAMPOOL_DEBUG ON CACHE BOOL "preload") +set(WITH_VERBOSE_WINPR_ASSERT OFF CACHE BOOL "qa default") +set(ENABLE_WARNING_VERBOSE ON CACHE BOOL "preload") +set(BUILD_SHARED_LIBS OFF CACHE BOOL "qa default") +set(CHANNEL_GFXREDIR ON CACHE BOOL "qa default") +set(CHANNEL_RDP2TCP ON CACHE BOOL "qa default") +set(CHANNEL_SSHAGENT ON CACHE BOOL "qa default") + +set(BUILD_WITH_CLANG_TIDY OFF CACHE BOOL "qa default") + +include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/ClangDetectTool.cmake) +clang_detect_tool(CLANG_EXE clang REQUIRED) +clang_detect_tool(CLANG_XX_EXE clang++ REQUIRED) + +set(CMAKE_C_COMPILER "${CLANG_EXE}" CACHE STRING "qa default") +set(CMAKE_CXX_COMPILER "${CLANG_XX_EXE}" CACHE STRING "qa default") +set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "qa-default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa.cmake b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e1c95e031a6daed48e3cbb3fbf4ce0b838e59a0d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-qa.cmake @@ -0,0 +1,41 @@ +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "qa default") +set(WITH_STREAMPOOL_DEBUG ON CACHE BOOL "preload") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(ENABLE_WARNING_VERBOSE ON CACHE BOOL "preload") +set(WITH_MANPAGES ON CACHE BOOL "qa default") +set(WITH_SAMPLE ON CACHE BOOL "qa default") +set(WITH_SERVER ON CACHE BOOL "qa default") +set(WITH_SHADOW ON CACHE BOOL "qa default") +set(WITH_PROXY ON CACHE BOOL "qa default") +set(WITH_PULSE ON CACHE BOOL "qa default") +set(WITH_CUPS ON CACHE BOOL "qa default") +set(WITH_OPENCL ON CACHE BOOL "qa default") +set(WITH_PCSC ON CACHE BOOL "qa default") +set(WITH_SOXR ON CACHE BOOL "qa default") +set(WITH_SIMD ON CACHE BOOL "qa default") +set(WITH_SWSCALE ON CACHE BOOL "qa default") +set(WITH_DSP_FFMPEG ON CACHE BOOL "qa default") +set(WITH_FFMPEG ON CACHE BOOL "qa default") +set(WITH_SANITIZE_ADDRESS ON CACHE BOOL "qa default") +set(WITH_WINPR_UTILS_IMAGE_JPEG ON CACHE BOOL "qa default") +set(WITH_WINPR_UTILS_IMAGE_WEBP ON CACHE BOOL "qa default") +set(WITH_WINPR_UTILS_IMAGE_PNG ON CACHE BOOL "qa default") +set(WITH_INTERNAL_RC4 ON CACHE BOOL "qa default") +set(WITH_INTERNAL_MD4 ON CACHE BOOL "qa default") +set(WITH_INTERNAL_MD5 ON CACHE BOOL "qa default") +set(CHANNEL_RDPECAM ON CACHE BOOL "qa default") +set(CHANNEL_RDPECAM_CLIENT ON CACHE BOOL "qa default") +set(CHANNEL_RDPEAR ON CACHE BOOL "qa default") +set(CHANNEL_RDPEAR_CLIENT ON CACHE BOOL "qa default") +set(CHANNEL_GFXREDIR ON CACHE BOOL "qa default") +set(CHANNEL_RDP2TCP ON CACHE BOOL "qa default") +set(CHANNEL_SSHAGENT ON CACHE BOOL "qa default") + +set(BUILD_WITH_CLANG_TIDY ON CACHE BOOL "qa default") + +include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/ClangDetectTool.cmake) +clang_detect_tool(CLANG_EXE clang REQUIRED) +clang_detect_tool(CLANG_XX_EXE clang++ REQUIRED) + +set(CMAKE_C_COMPILER "${CLANG_EXE}" CACHE STRING "qa default") +set(CMAKE_CXX_COMPILER "${CLANG_XX_EXE}" CACHE STRING "qa default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ubuntu-1204.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ubuntu-1204.txt new file mode 100644 index 0000000000000000000000000000000000000000..7e2050049cdd772696c61b6df72818e505a70875 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-ubuntu-1204.txt @@ -0,0 +1,15 @@ +message("PRELOADING cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(WITH_MANPAGES ON CACHE BOOL "man pages") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "build type") +set(WITH_CUPS OFF CACHE BOOL "CUPS printing") +set(WITH_KRB5 ON CACHE BOOL "Kerberos support") +set(WITH_ALSA OFF CACHE BOOL "alsa audio") +set(WITH_FFMPEG OFF CACHE BOOL "ffmepg support") +set(WITH_XV OFF CACHE BOOL "xvideo support") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "build testing") +set(WITH_XSHM OFF CACHE BOOL "build with xshm support") +set(WITH_SERVER ON CACHE BOOL "build with server") +set(WITH_SAMPLE ON CACHE BOOL "build with sample") +set(WITH_SANITIZE_ADDRESS ON) +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "Enable deprecated command line options") diff --git a/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-windows.txt b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-windows.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ee05f10a7db256121378013ac8f4f0dfaea6ce2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/ci/cmake-preloads/config-windows.txt @@ -0,0 +1,21 @@ +message("PRELOADING windows cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "preload") +set(CMAKE_WINDOWS_VERSION "WIN7" CACHE STRING "windows build version") +set(BUILD_SHARED_LIBS OFF CACHE BOOL "build static linked executable") +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded" CACHE STRING "MSVC runtime to use") +set(OPENSSL_USE_STATIC_LIBS ON CACHE BOOL "link OpenSSL static") +set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "build type") +set(WITH_SERVER ON CACHE BOOL "build with server") +set(WITH_SAMPLE ON CACHE BOOL "build with sample") +set(WITH_SHADOW OFF CACHE BOOL "Do not build shadow server") +set(WITH_PLATFORM_SERVER OFF CACHE BOOL "Do not build platform server") +set(WITH_CLIENT_SDL ON CACHE BOOL "build with SDL client") +set(WITH_PROXY_MODULES "ON" CACHE BOOL "build proxy modules") +set(CHANNEL_URBDRC OFF CACHE BOOL "USB redirection") +set(BUILD_TESTING_INTERNAL ON CACHE BOOL "build testing") +set(WITH_FFMPEG OFF CACHE BOOL "ci default") +set(WITH_SWSCALE OFF CACHE BOOL "ci default") +set(WITH_WEBVIEW ON CACHE BOOL "ci default") +set(ZLIB_USE_STATIC_LIBS ON CACHE BOOL "ci default") +set(WITH_FREERDP_DEPRECATED_COMMANDLINE ON CACHE BOOL "Enable deprecated command line options") +set(WITH_SDL_LINK_SHARED OFF CACHE BOOL "ci default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/Dockerfile b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acddf56d069fce7781649fbf74eeaa9d3f1c5422 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/Dockerfile @@ -0,0 +1,160 @@ +FROM ubuntu:22.04 as builder +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update -qq +RUN apt-get install -y xz-utils wget make nasm git ninja-build autoconf automake libtool texinfo help2man yasm gcc pkg-config + +# SETUP WORKSPACE +WORKDIR /tmp +# RUN wget https://github.com/mstorsjo/llvm-mingw/releases/download/20230320/llvm-mingw-20230320-ucrt-ubuntu-18.04-x86_64.tar.xz -O llvm.tar.xz && \ +RUN wget https://github.com/mstorsjo/llvm-mingw/releases/download/20230320/llvm-mingw-20230320-msvcrt-ubuntu-18.04-x86_64.tar.xz -O llvm.tar.xz && \ + tar -xf llvm.tar.xz && \ + cp -a /tmp/llvm-mingw-20230320-msvcrt-ubuntu-18.04-x86_64/* /usr/ && \ + rm -rf /tmp/* + +RUN mkdir /src +WORKDIR /src + +# SETUP TOOLCHAIN +RUN mkdir /src/patch +ARG ARCH +ENV TOOLCHAIN_ARCH=$ARCH + +FROM builder as cmake-builder +RUN apt-get install -y cmake +COPY toolchain/cmake /src/toolchain/cmake +ENV TOOLCHAIN_NAME=$TOOLCHAIN_ARCH-w64-mingw32 +ENV TOOLCHAIN_CMAKE=/src/toolchain/cmake/$TOOLCHAIN_NAME-toolchain.cmake + +FROM builder as meson-builder +RUN apt-get install -y meson +COPY toolchain/meson /src/toolchain/meson +ENV TOOLCHAIN_MESON=/src/toolchain/meson/$TOOLCHAIN_ARCH.txt + +# BUILD ZLIB +FROM cmake-builder AS zlib-build +RUN git clone https://github.com/madler/zlib.git /src/zlib +WORKDIR /src/zlib +RUN git fetch; git checkout 04f42ceca40f73e2978b50e93806c2a18c1281fc +RUN mkdir /src/zlib/build +WORKDIR /src/zlib/build +RUN cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_CMAKE -G Ninja -Wno-dev -DCMAKE_INSTALL_PREFIX=/build -DCMAKE_BUILD_TYPE=Release +RUN cmake --build . -j `nproc` +RUN cmake --install . + +# BUILD OPENSSL +FROM cmake-builder AS openssl-build +RUN git clone https://github.com/janbar/openssl-cmake.git /src/openssl +WORKDIR /src/openssl +RUN mkdir /src/openssl/build +WORKDIR /src/openssl/build +RUN cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_CMAKE -G Ninja -Wno-dev -DCMAKE_INSTALL_PREFIX=/build \ + -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF +RUN cmake --build . -j `nproc` +RUN cmake --install . + +# BUILD OPENH264 +FROM meson-builder AS openh264-build +RUN git clone https://github.com/cisco/openh264 /src/openh264 +WORKDIR /src/openh264 +RUN git fetch; git checkout 0a48f4d2e9be2abb4fb01b4c3be83cf44ce91a6e +RUN mkdir /src/openh264/out +WORKDIR /src/openh264/out +RUN meson .. . --cross-file $TOOLCHAIN_MESON --prefix=/build +RUN ninja -j `nproc` +RUN ninja install + +# # BUILD LIBUSB +FROM cmake-builder AS libusb-build +RUN git clone https://github.com/libusb/libusb.git /src/libusb +WORKDIR /src/libusb +RUN git fetch; git checkout 4239bc3a50014b8e6a5a2a59df1fff3b7469543b +RUN mkdir m4; autoreconf -ivf +RUN sed -i.bak "s/-mwin32//g" ./configure +RUN sed -i.bak "s/--add-stdcall-alias//g" ./configure +RUN ./configure --host=$TOOLCHAIN_NAME --prefix=/build +RUN make -j `nproc` && make install + +# BUILD FAAC +FROM cmake-builder AS faac-build +RUN git clone https://github.com/knik0/faac.git /src/faac +WORKDIR /src/faac +RUN git fetch; git checkout 78d8e0141600ac006a94ac6fd5601f599fa5b65b +RUN sed -i.bak "s/-Wl,--add-stdcall-alias//g" ./libfaac/Makefile.am +RUN mkdir m4; autoreconf -ivf +RUN sed -i.bak "s/-mwin32//g" ./configure +RUN ./configure --host=$TOOLCHAIN_NAME --prefix=/build +RUN make -j `nproc` && make install + +# BUILD FAAD2 +FROM cmake-builder AS faad2-build +RUN git clone https://github.com/knik0/faad2.git /src/faad2 +WORKDIR /src/faad2 +RUN git fetch; git checkout 3918dee56063500d0aa23d6c3c94b211ac471a8c +RUN sed -i.bak "s/-Wl,--add-stdcall-alias//g" ./libfaad/Makefile.am +RUN mkdir m4; autoreconf -ivf +RUN sed -i.bak "s/-mwin32//g" ./configure +RUN ./configure --host=$TOOLCHAIN_NAME --prefix=/build +RUN make -j `nproc` && make install + +# BUILD OPENCL-HEADERS +FROM cmake-builder AS opencl-headers +RUN git clone https://github.com/KhronosGroup/OpenCL-Headers.git /src/opencl-headers +WORKDIR /src/opencl-headers +RUN git fetch; git checkout 4fdcfb0ae675f2f63a9add9552e0af62c2b4ed30 +RUN mkdir /src/opencl-headers/build +WORKDIR /src/opencl-headers/build +RUN cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_CMAKE -G Ninja -Wno-dev -DCMAKE_INSTALL_PREFIX=/build \ + -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF +RUN cmake --build . -j `nproc` +RUN cmake --install . + +# BUILD OPENCL +FROM cmake-builder AS opencl-build +COPY --from=opencl-headers /build /build +RUN git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader.git /src/opencl +WORKDIR /src/opencl +RUN git fetch; git checkout b1bce7c3c580a8345205cf65fc1a5f55ba9cdb01 +RUN echo 'set_target_properties (OpenCL PROPERTIES PREFIX "")' >> CMakeLists.txt +RUN mkdir /src/opencl/build +WORKDIR /src/opencl/build +RUN cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_CMAKE -G Ninja -Wno-dev -DCMAKE_INSTALL_PREFIX=/build \ + -DBUILD_SHARED_LIBS=OFF -DOPENCL_ICD_LOADER_DISABLE_OPENCLON12=ON \ + -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF \ + -DCMAKE_C_FLAGS="${CMAKE_C_FLAGS} -I/build/include/" \ + -DCMAKE_CXX_FLAGS="${CMAKE_CXX_FLAGS} -I/build/include/" +RUN cmake --build . -j `nproc` +RUN cmake --install . + +# BUILD FREERDP +FROM cmake-builder AS freerdp-build +COPY --from=zlib-build /build /build +COPY --from=openssl-build /build /build +COPY --from=openh264-build /build /build +COPY --from=libusb-build /build /build +COPY --from=faac-build /build /build +COPY --from=faad2-build /build /build +COPY --from=opencl-build /build /build +RUN git clone https://github.com/FreeRDP/FreeRDP.git /src/FreeRDP +RUN mkdir /src/FreeRDP/build +WORKDIR /src/FreeRDP/build + +ARG ARCH +RUN /bin/bash -c "( [[ $ARCH == aarch64 ]] && printf 'arm64' || printf $ARCH ) > arch.txt" + +RUN bash -c "cmake .. -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_CMAKE -G Ninja -Wno-dev -DCMAKE_INSTALL_PREFIX=/build \ + -DWITH_X11=OFF -DWITH_MEDIA_FOUNDATION=OFF -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release \ + -DUSE_UNWIND=OFF \ + -DWITH_ZLIB=ON -DZLIB_INCLUDE_DIR=/build \ + -DWITH_OPENH264=ON -DOPENH264_INCLUDE_DIR=/build/include -DOPENH264_LIBRARY=/build/lib/libopenh264.dll.a \ + -DOPENSSL_INCLUDE_DIR=/build/include \ + -DWITH_OPENCL=ON -DOpenCL_INCLUDE_DIR=/build/include -DOpenCL_LIBRARIES=/build/lib/OpenCL.a \ + -DLIBUSB_1_INCLUDE_DIRS=/build/include/libusb-1.0 -DLIBUSB_1_LIBRARIES=/build/lib/libusb-1.0.a \ + -DWITH_WINPR_TOOLS=OFF -DWITH_WIN_CONSOLE=ON -DWITH_PROGRESS_BAR=OFF \ + -DWITH_FAAD2=ON -DFAAD2_INCLUDE_DIR=/build/include -DFAAD2_LIBRARY=/build/lib/libfaad.a \ + -DWITH_FAAC=ON -DFAAC_INCLUDE_DIR=/build/include -DFAAC_LIBRARY=/build/lib/libfaac.a \ + -DCMAKE_SYSTEM_PROCESSOR=$( cat arch.txt ) \ + -DCMAKE_C_FLAGS=\"${CMAKE_C_FLAGS} -static -Wno-error=incompatible-function-pointer-types -DERROR_OPERATION_IN_PROGRESS=0x00000149\" \ + " +RUN cmake --build . -j `nproc` +RUN cmake --install . +RUN cp -a /usr/$ARCH-w64-mingw32/bin/* /build/bin; \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/_build.sh b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/_build.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a74819d188cd169756d6e68dba1401b6e594b69 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/_build.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +rm -rf $(pwd)/build/$TARGET_ARCH +mkdir -p $(pwd)/build/$TARGET_ARCH +docker build -t win32-builder --build-arg ARCH . +docker compose up dist-builder \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_arm64.sh b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_arm64.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae63a6852c971103463c7bb7697702c78b9328a1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_arm64.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +export ARCH=aarch64 +. ./_build.sh \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_ia32.sh b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_ia32.sh new file mode 100644 index 0000000000000000000000000000000000000000..efcfacc5216b03918d91fd408e3a90616c13fc2f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_ia32.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +export ARCH=i686 +. ./_build.sh diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_x64.sh b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_x64.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9918690ca875a40728d15c89d5d127a32856c4c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/build_x64.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +export ARCH=x86_64 +. ./_build.sh \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/docker-compose.yml b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dec42155527961cccc511385db4a154d3960bc4d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/docker-compose.yml @@ -0,0 +1,8 @@ +version: '3' + +services: + dist-builder: + image: win32-builder + volumes: + - ./build:/out + command: bash -c "rm -rf /out/*; cp -a /build/bin/. /out/;" \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/aarch64-w64-mingw32-toolchain.cmake b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/aarch64-w64-mingw32-toolchain.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d892195966977d282d146966f8ef06d20bf06bbd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/aarch64-w64-mingw32-toolchain.cmake @@ -0,0 +1,15 @@ +set(CMAKE_C_COMPILER aarch64-w64-mingw32-gcc) +set(CMAKE_CXX_COMPILER aarch64-w64-mingw32-g++) +set(CMAKE_FIND_ROOT_PATH /usr/aarch64-w64-mingw32) + +execute_process(COMMAND which aarch64-w64-mingw32-windres OUTPUT_VARIABLE TOOLCHAIN_RC_COMPILER) +execute_process(COMMAND which aarch64-w64-mingw32-dlltool OUTPUT_VARIABLE TOOLCHAIN_DLLTOOL) + +string(STRIP ${TOOLCHAIN_RC_COMPILER} TOOLCHAIN_RC_COMPILER) +set(CMAKE_RC_COMPILER ${TOOLCHAIN_RC_COMPILER}) + +string(STRIP ${TOOLCHAIN_DLLTOOL} TOOLCHAIN_DLLTOOL) +set(DLLTOOL ${TOOLCHAIN_DLLTOOL}) + +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_SYSTEM_NAME Windows) diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/i686-w64-mingw32-toolchain.cmake b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/i686-w64-mingw32-toolchain.cmake new file mode 100644 index 0000000000000000000000000000000000000000..85ea20f640b451e9559abb15a2c1302c95381bae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/i686-w64-mingw32-toolchain.cmake @@ -0,0 +1,15 @@ +set(CMAKE_C_COMPILER i686-w64-mingw32-gcc) +set(CMAKE_CXX_COMPILER i686-w64-mingw32-g++) +set(CMAKE_FIND_ROOT_PATH /usr/i686-w64-mingw32) + +execute_process(COMMAND which i686-w64-mingw32-windres OUTPUT_VARIABLE TOOLCHAIN_RC_COMPILER) +execute_process(COMMAND which i686-w64-mingw32-dlltool OUTPUT_VARIABLE TOOLCHAIN_DLLTOOL) + +string(STRIP ${TOOLCHAIN_RC_COMPILER} TOOLCHAIN_RC_COMPILER) +set(CMAKE_RC_COMPILER ${TOOLCHAIN_RC_COMPILER}) + +string(STRIP ${TOOLCHAIN_DLLTOOL} TOOLCHAIN_DLLTOOL) +set(DLLTOOL ${TOOLCHAIN_DLLTOOL}) + +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_SYSTEM_NAME Windows) diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/x86_64-w64-mingw32-toolchain.cmake b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/x86_64-w64-mingw32-toolchain.cmake new file mode 100644 index 0000000000000000000000000000000000000000..15bb9797fbe5f374591c9069d39cdacd580ebe41 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/cmake/x86_64-w64-mingw32-toolchain.cmake @@ -0,0 +1,15 @@ +set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) +set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++) +set(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32) + +execute_process(COMMAND which x86_64-w64-mingw32-windres OUTPUT_VARIABLE TOOLCHAIN_RC_COMPILER) +execute_process(COMMAND which x86_64-w64-mingw32-dlltool OUTPUT_VARIABLE TOOLCHAIN_DLLTOOL) + +string(STRIP ${TOOLCHAIN_RC_COMPILER} TOOLCHAIN_RC_COMPILER) +set(CMAKE_RC_COMPILER ${TOOLCHAIN_RC_COMPILER}) + +string(STRIP ${TOOLCHAIN_DLLTOOL} TOOLCHAIN_DLLTOOL) +set(DLLTOOL ${TOOLCHAIN_DLLTOOL}) + +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_SYSTEM_NAME Windows) diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/aarch64.txt b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/aarch64.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1f9c3c194f017b19e51dd637e24ba5fec749fa1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/aarch64.txt @@ -0,0 +1,15 @@ +[binaries] +c = 'aarch64-w64-mingw32-gcc' +cpp = 'aarch64-w64-mingw32-g++' +ar = 'aarch64-w64-mingw32-ar' +ld = 'aarch64-w64-mingw32-ld' +strip = 'aarch64-w64-mingw32-strip' + +[host_machine] +system = 'windows' +cpu_family = 'aarch64' +cpu = 'native' +endian = 'little' + +[properties] +platform = 'generic_aarch64' \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/i686.txt b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/i686.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dfeef14d4685b0b5cbf4f8ecb284ce13f2bfbee --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/i686.txt @@ -0,0 +1,16 @@ +[binaries] +c = 'i686-w64-mingw32-gcc' +cpp = 'i686-w64-mingw32-g++' +ar = 'i686-w64-mingw32-ar' +ld = 'i686-w64-mingw32-ld' +strip = 'i686-w64-mingw32-strip' + +[host_machine] +system = 'windows' +cpu_family = 'x86' +cpu = 'native' +endian = 'little' + +[properties] +c_args = '-mno-avx512f' +cpp_args = '-mno-avx512f' \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/x86_64.txt b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/x86_64.txt new file mode 100644 index 0000000000000000000000000000000000000000..587f34ba671328b61a8289081438b1567e203698 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/docs/mingw-example/toolchain/meson/x86_64.txt @@ -0,0 +1,16 @@ +[binaries] +c = 'x86_64-w64-mingw32-gcc' +cpp = 'x86_64-w64-mingw32-g++' +ar = 'x86_64-w64-mingw32-ar' +ld = 'x86_64-w64-mingw32-ld' +strip = 'x86_64-w64-mingw32-strip' + +[host_machine] +system = 'windows' +cpu_family = 'x86_64' +cpu = 'native' +endian = 'little' + +[properties] +c_args = '-mno-avx512f' +cpp_args = '-mno-avx512f' \ No newline at end of file diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/changelog b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/changelog new file mode 100644 index 0000000000000000000000000000000000000000..d5e2101281ce79391bcc6a9445bbc982d363908b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/changelog @@ -0,0 +1,24 @@ +freerdp-nightly (3.0.0) unstable; urgency=low + + * Update version to 3.0.0 + + -- FreeRDP Tue, 29 Jun 2020 10:26:12 +0100 + + +freerdp-nightly (2.0.0) unstable; urgency=low + + * Update version to 2.0.0 + + -- FreeRDP Tue, 17 Nov 2015 23:26:12 +0100 + +freerdp-nightly (1.2.1) unstable; urgency=low + + * Update version to 1.2.1 + + -- FreeRDP Tue, 03 Feb 2015 13:44:33 +0100 + +freerdp-nightly (1.2.0) unstable; urgency=medium + + * Initial version of freerdp-nightly + + -- FreeRDP Wed, 07 Jan 2015 10:09:32 +0100 diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/compat b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/compat new file mode 100644 index 0000000000000000000000000000000000000000..f599e28b8ab0d8c9c57a486c89c4a5132dcbd3b2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/compat @@ -0,0 +1 @@ +10 diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/control b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/control new file mode 100644 index 0000000000000000000000000000000000000000..d410a3ec5a261fd1691a3aa48507ab5c26a84a94 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/control @@ -0,0 +1,110 @@ +Source: freerdp-nightly +Section: x11 +Priority: optional +Maintainer: FreeRDP +Build-Depends: + debhelper (>= 9), + cdbs, + dpkg-dev, + autotools-dev, + cmake, + pkg-config, + libssl-dev, + ninja-build, + libkrb5-dev | krb5-multidev | heimdal-multidev, + libxkbcommon-dev, + libxkbfile-dev, + libx11-dev, + libwayland-dev, + libxrandr-dev, + libxi-dev, + libxrender-dev, + libxext-dev, + libxinerama-dev, + libxfixes-dev, + libxcursor-dev, + libxv-dev, + libxdamage-dev, + libxtst-dev, + libcups2-dev, + libcairo2-dev, + libpcsclite-dev, + libasound2-dev, + libswscale-dev, + libpulse-dev, + libavformat-dev, + libavcodec-dev, + libavutil-dev, + libfuse3-dev, + libswresample-dev | libavresample-dev, + libusb-1.0-0-dev, + libudev-dev, + libfdk-aac-dev | libfaad-dev, + libsoxr-dev, + libdbus-glib-1-dev, + libpam0g-dev, + uuid-dev, + libjson-c-dev | libcjson-dev, + libsdl3-0 | libsdl2-2.0-0, + libsdl3-dev | libsdl2-dev, + libsdl3-ttf-dev | libsdl2-ttf-dev, + libsdl3-image-dev | libsdl2-image-dev, + libsystemd-dev, + libwebkit2gtk-4.1-dev | libwebkit2gtk-4.0-dev, + liburiparser-dev, + libopus-dev, + libwebp-dev, + libpng-dev, + libjpeg-dev, + opensc-pkcs11, + libv4l-dev, + libasan5 | libasan6 | libasan8 +Standards-Version: 3.9.5 +Homepage: http://www.freerdp.com/ +Vcs-Browser: http://github.com/FreeRDP/FreeRDP.git +Vcs-Git: git://github.com/FreeRDP/FreeRDP.git + +Package: freerdp-nightly +Architecture: any +Depends: ${misc:Depends}, ${shlibs:Depends} +Provides: freerdp +Description: RDP client for Windows Terminal Services (X11 client) + FreeRDP is a libre client/server implementation of the Remote + Desktop Protocol (RDP). + . + Currently, the FreeRDP client supports the following Windows Versions: + . + * Windows NT Server + * Windows 2000 Terminal Server + * Windows XP + * Windows 2003 Server + * Windows Vista + * Windows 2008/2008r2/2011SBS Server + * Windows 7 + * Windows 2012 Server + * Windows 8 + . + This package contains the X11 based client. + +Package: freerdp-nightly-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Depends: freerdp-nightly (= ${binary:Version}), ${misc:Depends} +Description: Free Remote Desktop Protocol library (development files) + FreeRDP is a libre client/server implementation of the Remote + Desktop Protocol (RDP). + . + This package contains the FreeRDP development files. + +Package: freerdp-nightly-dbg +Section: debug +Priority: extra +Architecture: any +Depends: + freerdp-nightly (= ${binary:Version}), ${misc:Depends}, +Description: RDP client for Windows Terminal Services (X11 client, debug symbols) + FreeRDP is a libre client/server implementation of the Remote + Desktop Protocol (RDP). + . + This package contains the debug symbols of the xfreerdp executable. diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/copyright b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/copyright new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dbg.lintian-overrides b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dbg.lintian-overrides new file mode 100644 index 0000000000000000000000000000000000000000..8108c1ed1d0557533431ac12f47c324d0dda2a0b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dbg.lintian-overrides @@ -0,0 +1 @@ +freerdp-nightly-dbg: no-copyright-file new-package-should-close-itp-bug dir-or-file-in-opt package-name-doesnt-match-sonames diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.install b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.install new file mode 100644 index 0000000000000000000000000000000000000000..65f1c68c725560976145d0ff3d28607406c41643 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.install @@ -0,0 +1,3 @@ +opt/freerdp-nightly/lib/pkgconfig +opt/freerdp-nightly/lib/cmake +opt/freerdp-nightly/include diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.lintian-overrides b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.lintian-overrides new file mode 100644 index 0000000000000000000000000000000000000000..0f6ac7a2beedb002234d9ebdbc1be91b820fb8ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly-dev.lintian-overrides @@ -0,0 +1 @@ +freerdp-nightly-dev: no-copyright-file dir-or-file-in-opt diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.install b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.install new file mode 100644 index 0000000000000000000000000000000000000000..d979dc05dc5f1c77841ea1ca574e34f00fe4fd2b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.install @@ -0,0 +1,6 @@ +opt/freerdp-nightly/lib/*.so* +opt/freerdp-nightly/lib/freerdp3/proxy/*.so* +opt/freerdp-nightly/bin +opt/freerdp-nightly/share/man/man1/* +opt/freerdp-nightly/share/man/man7/* +opt/freerdp-nightly/share/FreeRDP/FreeRDP3/* diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.lintian-overrides b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.lintian-overrides new file mode 100644 index 0000000000000000000000000000000000000000..62263e0473b1ca33f5f4221d84e12d45ed3dd6d2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/freerdp-nightly.lintian-overrides @@ -0,0 +1 @@ +freerdp-nightly: no-copyright-file new-package-should-close-itp-bug dir-or-file-in-opt package-name-doesnt-match-sonames diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/lintian-overrides b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/lintian-overrides new file mode 100644 index 0000000000000000000000000000000000000000..d583c69f28c665dc1cf605d1cf58392572922979 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/lintian-overrides @@ -0,0 +1 @@ +freerdp-nightly source: no-debian-copyright diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/rules b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/rules new file mode 100644 index 0000000000000000000000000000000000000000..f699e625691a37fc8aa6ea2641180ab61a73398f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/rules @@ -0,0 +1,85 @@ +#!/usr/bin/make -f + +NULL = + +DEB_HOST_ARCH=$(shell dpkg-architecture -qDEB_HOST_ARCH) +DEB_FDK_SUPPORT=$(shell dpkg-query -s libfdk-aac-dev 2>&1 >/dev/null; echo $$?) + +ifeq ($(DEB_FDK_SUPPORT),0) + AAC_SUPPORT = -DWITH_FDK_AAC=ON +endif +SANITIZE_ADDRESS = -DWITH_SANITIZE_ADDRESS=ON + +DEB_CMAKE_EXTRA_FLAGS := -GNinja \ + -DCMAKE_SKIP_RPATH=FALSE \ + -DCMAKE_SKIP_INSTALL_RPATH=FALSE \ + -DWITH_PULSE=ON \ + -DWITH_CHANNELS=ON \ + -DWITH_AAD=ON \ + -DWITH_CUPS=ON \ + -DWITH_KRB5=ON \ + -DWITH_PCSC=ON \ + -DWITH_FFMPEG=ON \ + -DWITH_OPUS=ON \ + -DWITH_DSP_FFMPEG=ON \ + -DWITH_FREERDP_DEPRECATED_COMMANDLINE=ON \ + -DWITH_SERVER=ON \ + -DWITH_WAYLAND=ON \ + -DWITH_CAIRO=ON \ + -DWITH_URIPARSER=ON \ + -DWITH_WINPR_UTILS_IMAGE_PNG=ON \ + -DWITH_WINPR_UTILS_IMAGE_WEBP=ON \ + -DWITH_WINPR_UTILS_IMAGE_JPEG=ON \ + -DWITH_INTERNAL_RC4=ON \ + -DWITH_INTERNAL_MD4=ON \ + -DWITH_INTERNAL_MD5=ON \ + -DBUILD_TESTING=ON \ + -DWITH_KEYBOARD_LAYOUT_FROM_FILE=ON \ + -DWITH_TIMEZONE_FROM_FILE=ON \ + -DSDL_USE_COMPILED_RESOURCES=OFF \ + -DWITH_SDL_IMAGE_DIALOGS=ON \ + -DRDTK_FORCE_STATIC_BUILD=ON \ + -DUWAC_FORCE_STATIC_BUILD=ON \ + -DWITH_BINARY_VERSIONING=ON \ + -DWITH_RESOURCE_VERSIONING=ON \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DCMAKE_INSTALL_PREFIX=/opt/freerdp-nightly/ \ + -DCMAKE_INSTALL_INCLUDEDIR=include \ + -DCMAKE_INSTALL_LIBDIR=lib \ + -DNO_CMAKE_PACKAGE_REGISTRY=ON \ + -DWINPR_USE_LEGACY_RESOURCE_DIR=OFF \ + -DWINPR_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DFREERDP_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DSAMPLE_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DSDL_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + $(AAC_SUPPORT) \ + $(SANITIZE_ADDRESS) \ + $(NULL) + +%: + dh $@ --parallel + +override_dh_auto_configure: + dh_auto_configure -- $(DEB_CMAKE_EXTRA_FLAGS) + +override_dh_shlibdeps: + dh_shlibdeps -l /opt/freerdp-nightly/lib/ + +override_dh_strip: + dh_strip --dbg-package=freerdp-nightly-dbg + +override_dh_missing: + dh_missing --fail-missing + +override_dh_install: + mkdir -p debian/tmp/opt/freerdp-nightly/lib/cmake/ + rm -rf debian/tmp/opt/freerdp-nightly/lib/freerdp3/*.a + + dh_install + +override_dh_auto_test: + dh_auto_test + +override_dh_clean: + rm -f config.h + dh_clean diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/source/format b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/source/format new file mode 100644 index 0000000000000000000000000000000000000000..89ae9db8f88b823b6a7eabf55e203658739da122 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/deb/freerdp-nightly/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/build-bundle.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/build-bundle.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed4b5a8aa45edf8b24847ec0f4514f0ace36cc5c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/build-bundle.sh @@ -0,0 +1,33 @@ +#!/bin/bash -xe +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +MANIFEST=com.freerdp.FreeRDP + +BUILD_BASE=$(mktemp -d) +if [ $# -gt 0 ]; +then + BUILD_BASE=$1 +fi + +echo "Using $BUILD_BASE as temporary build directory" +REPO=$BUILD_BASE/repo +BUILD=$BUILD_BASE/build +STATE=$BUILD_BASE/state + +BUILDER=$(which flatpak-builder) +if [ ! -x "$BUILDER" ]; +then + echo "command 'flatpak-builder' could not be found, please install and add to PATH" + exit 1 +fi + +FLATPAK=$(which flatpak) +if [ ! -x "$FLATPAK" ]; +then + echo "command 'flatpak' could not be found, please install and add to PATH" + exit 1 +fi + +flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo --user +flatpak-builder -v --repo=$REPO --state-dir=$STATE $BUILD $SCRIPT_DIR/$MANIFEST.json --force-clean --user --install-deps-from=flathub +flatpak build-bundle -v $REPO $MANIFEST.flatpak $MANIFEST --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/freerdp.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/freerdp.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b6a7dbe9d25f4bdde95eb957172caa5475798f0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/flatpak/freerdp.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +if [ -z ${FREERDP_SDL_OFF} ]; +then + echo "SDL $(which sdl-freerdp)" + sdl-freerdp $@ + exit $rc +else + if [ -z $XDG_SESSION_TYPE ]; + then + echo "XDG_SESSION_TYPE undefined" + exit -1 + elif [ "$XDG_SESSION_TYPE" = "wayland" ]; + then + if [ -z $FREERDP_WAYLAND_OFF ]; + then + echo "wayland $(which wlfreerdp)" + wlfreerdp $@ + exit $rc + else + echo "X11 $(which xfreerdp)" + xfreerdp $@ + exit $rc + fi + elif [ "$XDG_SESSION_TYPE" = "x11" ]; + then + echo "X11 $(which xfreerdp)" + xfreerdp $@ + exit $rc + else + echo "XDG_SESSION_TYPE $XDG_SESSION_TYPE not handled" + exit -1 + fi +fi diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly-rpmlintrc b/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly-rpmlintrc new file mode 100644 index 0000000000000000000000000000000000000000..d747a310606f8e4f60ac51cdfc2927858a2ca5d7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly-rpmlintrc @@ -0,0 +1,13 @@ +# files are on purpose in /opt - vendor package +addFilter("dir-or-file-in-opt") +# required in this case that the binaries work +addFilter("binary-or-shlib-defines-rpath") +# ldconfig run not required +addFilter("library-without-ldconfig-postin") +addFilter("library-without-ldconfig-postun") +# keep debug symbols and so directly in the package +addFilter("unstripped-binary-or-object /opt/freerdp-nightly/lib64/*") +addFilter("unstripped-binary-or-object /opt/freerdp-nightly/bin/*") +addFilter("no-documentation") +addFilter("manpage-not-compressed") +addFilter("suse-filelist-forbidden-opt") diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly.spec b/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly.spec new file mode 100644 index 0000000000000000000000000000000000000000..8abead6b53f0c7d31eee43873786fc262409c470 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/rpm/freerdp-nightly.spec @@ -0,0 +1,281 @@ +# +# spec file for package freerdp-nightly +# +# Copyright (c) 2015 Bernhard Miklautz +# +# Bugs and comments https://github.com/FreeRDP/FreeRDP/issues + +%define _build_id_links none +%define INSTALL_PREFIX /opt/freerdp-nightly/ + +# do not add provides for libs provided by this package +# or it could possibly mess with system provided packages +# which depend on freerdp libs +%global __provides_exclude_from ^%{INSTALL_PREFIX}.*$ + +# do not require our own libs +%global __requires_exclude ^(libfreerdp.*|libwinpr.*|librdtk.*|libuwac.*).*$ + +# no debug package +%global debug_package %{nil} + +Name: freerdp-nightly +Version: 3.0 +Release: 0 +License: ASL 2.0 +Summary: Free implementation of the Remote Desktop Protocol (RDP) +Url: http://www.freerdp.com +Group: Productivity/Networking/Other +Source0: %{name}-%{version}.tar.bz2 +Source1: source_version +BuildRequires: clang +BuildRequires: cmake >= 3.13.0 +BuildRequires: libxkbfile-devel +BuildRequires: libX11-devel +BuildRequires: libXrandr-devel +BuildRequires: libXi-devel +BuildRequires: libXrender-devel +BuildRequires: libXext-devel +BuildRequires: libXinerama-devel +BuildRequires: libXfixes-devel +BuildRequires: libXcursor-devel +BuildRequires: libXv-devel +BuildRequires: libXdamage-devel +BuildRequires: libXtst-devel +BuildRequires: cups-devel +BuildRequires: cairo-devel +BuildRequires: pcsc-lite-devel +BuildRequires: zlib-devel +BuildRequires: krb5-devel +BuildRequires: uriparser-devel +BuildRequires: libpng-devel +BuildRequires: libwebp-devel +BuildRequires: fuse3-devel +BuildRequires: pam-devel +BuildRequires: libicu-devel +BuildRequires: libv4l-devel + +# (Open)Suse +%if %{defined suse_version} +BuildRequires: libswscale-devel +BuildRequires: cJSON-devel +BuildRequires: uuid-devel +BuildRequires: libSDL2-devel +BuildRequires: libSDL2_ttf-devel +BuildRequires: libSDL2_image-devel +BuildRequires: pkg-config +BuildRequires: libopenssl-devel +BuildRequires: alsa-devel +BuildRequires: libpulse-devel +BuildRequires: libusb-1_0-devel +BuildRequires: libudev-devel +BuildRequires: dbus-1-glib-devel +BuildRequires: wayland-devel +BuildRequires: libavutil-devel +BuildRequires: libavcodec-devel +BuildRequires: libavformat-devel +BuildRequires: libswresample-devel +BuildRequires: libopus-devel +BuildRequires: libjpeg62-devel +%endif + +%if 0%{defined rhel} +BuildRequires: cjson-devel +BuildRequires: uuid-devel +BuildRequires: opus-devel +BuildRequires: SDL2-devel +BuildRequires: SDL2_ttf-devel +BuildRequires: SDL2_image-devel +BuildRequires: pkgconfig +BuildRequires: openssl-devel +BuildRequires: alsa-lib-devel +BuildRequires: pulseaudio-libs-devel +BuildRequires: libusbx-devel +BuildRequires: systemd-devel +BuildRequires: dbus-glib-devel +BuildRequires: libjpeg-turbo-devel +BuildRequires: libasan +BuildRequires: libjpeg-turbo-devel +BuildRequires: wayland-devel +%endif + +# fedora 21+ +%if 0%{?fedora} >= 37 +BuildRequires: cjson-devel +BuildRequires: uuid-devel +BuildRequires: opus-devel +BuildRequires: SDL2-devel +BuildRequires: SDL2_ttf-devel +BuildRequires: SDL2_image-devel +BuildRequires: pkgconfig +BuildRequires: openssl-devel +BuildRequires: alsa-lib-devel +BuildRequires: pulseaudio-libs-devel +BuildRequires: libusbx-devel +BuildRequires: systemd-devel +BuildRequires: dbus-glib-devel +BuildRequires: libjpeg-turbo-devel +BuildRequires: libasan +BuildRequires: webkit2gtk4.0-devel +BuildRequires: libjpeg-turbo-devel +BuildRequires: wayland-devel +%endif + +%if 0%{?fedora} || 0%{?rhel} > 8 +BuildRequires: (fdk-aac-devel or fdk-aac-free-devel) +BuildRequires: (noopenh264-devel or openh264-devel) +%endif + +%if 0%{?fedora} >= 36 || 0%{?rhel} >= 8 +BuildRequires: (ffmpeg-free-devel or ffmpeg-devel) +%endif + +BuildRoot: %{_tmppath}/%{name}-%{version}-build + +%description +FreeRDP is a open and free implementation of the Remote Desktop Protocol (RDP). +This package provides nightly master builds of all components. + +%package devel +Summary: Development Files for %{name} +Group: Development/Libraries/C and C++ +Requires: %{name} = %{version} + +%description devel +This package contains development files necessary for developing applications +based on freerdp and winpr. + +%prep +%setup -q +cd %{_topdir}/BUILD +%if 0%{?fedora} >= 41 +cp %{_topdir}/SOURCES/source_version freerdp-nightly-%{version}-build/.source_version +%else +cp %{_topdir}/SOURCES/source_version freerdp-nightly-%{version}/.source_version +%endif + +%build + +%cmake \ + -DCMAKE_SKIP_RPATH=FALSE \ + -DCMAKE_SKIP_INSTALL_RPATH=FALSE \ + -DWITH_FREERDP_DEPRECATED_COMMANDLINE=ON \ + -DWITH_PULSE=ON \ + -DWITH_CHANNELS=ON \ + -DWITH_CUPS=ON \ + -DWITH_PCSC=ON \ + -DWITH_JPEG=ON \ + -DWITH_OPUS=ON \ + -DWITH_OPENH264=ON \ + -DWITH_OPENH264_LOADING=ON \ + -DWITH_INTERNAL_RC4=ON \ + -DWITH_INTERNAL_MD4=ON \ + -DWITH_INTERNAL_MD5=ON \ + -DWITH_KEYBOARD_LAYOUT_FROM_FILE=ON \ + -DWITH_TIMEZONE_FROM_FILE=ON \ + -DSDL_USE_COMPILED_RESOURCES=OFF \ + -DWITH_SDL_IMAGE_DIALOGS=ON \ + -DWITH_BINARY_VERSIONING=ON \ + -DWITH_RESOURCE_VERSIONING=ON \ + -DWINPR_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DFREERDP_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DSAMPLE_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DSDL_USE_VENDOR_PRODUCT_CONFIG_DIR=ON \ + -DWINPR_USE_LEGACY_RESOURCE_DIR=OFF \ + -DRDTK_FORCE_STATIC_BUILD=ON \ + -DUWAC_FORCE_STATIC_BUILD=ON \ +%if 0%{?fedora} || 0%{?rhel} > 8 + -DWITH_FDK_AAC=ON \ +%endif +%if 0%{?fedora} >= 36 || 0%{?rhel} >= 9 || 0%{?suse_version} + -DWITH_FFMPEG=ON \ + -DWITH_DSP_FFMPEG=ON \ +%endif +%if 0%{?rhel} <= 8 + -DALLOW_IN_SOURCE_BUILD=ON \ +%endif +%if 0%{?rhel} >= 8 || 0%{defined suse_version} + -DWITH_WEBVIEW=OFF \ +%endif + -DCMAKE_C_COMPILER=clang \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DWITH_SANITIZE_ADDRESS=OFF \ + -DWITH_KRB5=ON \ + -DCHANNEL_URBDRC=ON \ + -DCHANNEL_URBDRC_CLIENT=ON \ + -DWITH_SERVER=ON \ + -DWITH_CAIRO=ON \ + -DBUILD_TESTING=ON \ + -DBUILD_TESTING_NO_H264=ON \ + -DCMAKE_CTEST_ARGUMENTS="-DExperimentalTest;--output-on-failure;--no-compress-output" \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DCMAKE_INSTALL_PREFIX=%{INSTALL_PREFIX} \ + -DCMAKE_INSTALL_LIBDIR=%{_lib} + +%cmake_build + +%check +%cmake_build --target test + +%install + +%cmake_install + +find %{buildroot} -name "*.a" -delete +export NO_BRP_CHECK_RPATH true + +%files +%defattr(-,root,root) +%dir %{INSTALL_PREFIX} +%dir %{INSTALL_PREFIX}/%{_lib} +%dir %{INSTALL_PREFIX}/bin +%dir %{INSTALL_PREFIX}/share/ +%dir %{INSTALL_PREFIX}/share/man/ +%dir %{INSTALL_PREFIX}/share/man/man1 +%dir %{INSTALL_PREFIX}/share/man/man7 +%dir %{INSTALL_PREFIX}/share/FreeRDP/FreeRDP3 +%dir %{INSTALL_PREFIX}/%{_lib}/freerdp3/proxy/ +%{INSTALL_PREFIX}/%{_lib}/*.so.* +%{INSTALL_PREFIX}/%{_lib}/freerdp3/proxy/*.so +%{INSTALL_PREFIX}/bin/* +%{INSTALL_PREFIX}/share/man/man1/* +%{INSTALL_PREFIX}/share/man/man7/* +%{INSTALL_PREFIX}/share/FreeRDP/FreeRDP3/* + +%files devel +%defattr(-,root,root) +%{INSTALL_PREFIX}/%{_lib}/*.so +%{INSTALL_PREFIX}/include/ +%{INSTALL_PREFIX}/%{_lib}/pkgconfig/ +%{INSTALL_PREFIX}/%{_lib}/cmake/ + +%post -p /sbin/ldconfig + +%postun -p /sbin/ldconfig + +%changelog +* Thu Oct 10 2024 FreeRDP Team - 3.10.0-1 +- update resource locations, utilize new settings +* Wed Apr 10 2024 FreeRDP Team - 3.0.0-5 +- Fix exclusion of libuwac and librdtk +* Fri Feb 09 2024 FreeRDP Team - 3.0.0-4 +- Deactivate ASAN due to issues with clang +* Fri Feb 09 2024 FreeRDP Team - 3.0.0-3 +- Fix dependencies for alma, suse and rhel +* Thu Dec 21 2023 FreeRDP Team - 3.0.0-2 +- Add new manpages +- Use new CMake options +* Wed Dec 20 2023 FreeRDP Team - 3.0.0-2 +- Exclude libuwac and librdtk +- Allow ffmpeg-devel or ffmpeg-free-devel as dependency +* Tue Dec 19 2023 FreeRDP Team - 3.0.0-1 +- Disable build-id +- Update build dependencies +* Wed Nov 15 2023 FreeRDP Team - 3.0.0-0 +- Update build dependencies +* Wed Feb 7 2018 FreeRDP Team - 2.0.0-0 +- Update version information and support for OpenSuse 42.1 +* Tue Feb 03 2015 FreeRDP Team - 1.2.1-0 +- Update version information +* Fri Jan 23 2015 Bernhard Miklautz - 1.2.0-0 +- Initial version diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_deb.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_deb.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d9dfb929b4799237ae71ea67ce383a9711de5a3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_deb.sh @@ -0,0 +1,24 @@ +#!/bin/bash -xe + +SCRIPT_PATH=$(dirname "${BASH_SOURCE[0]}") +SCRIPT_PATH=$(realpath "$SCRIPT_PATH") + +BUILD_DEPS=$(/usr/bin/which dpkg-checkbuilddeps) +BUILD_PKG=$(/usr/bin/which dpkg-buildpackage) + +if [ -z "$BUILD_DEPS" ] || [ -z "$BUILD_PKG" ]; +then + echo "dpkg-buildpackage [$BUILD_PKG] and dpkg-checkbuilddeps [$BUILD_DEPS] required" + echo "Install with 'sudo apt install dpkg-dev'" + exit 1 +fi + +# First create a link to the debian/control folder +cd "$SCRIPT_PATH/../.." +ln -sf "packaging/deb/freerdp-nightly" "debian" + +# Check all dependencies are installed +$BUILD_DEPS "debian/control" + +# And finally build the package +$BUILD_PKG diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_rpm.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_rpm.sh new file mode 100644 index 0000000000000000000000000000000000000000..384233d0581592628235dfa095ce442a9c065317 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/create_rpm.sh @@ -0,0 +1,11 @@ +#!/bin/bash -xe +# +# Create a RPM package +SCRIPT_PATH=$(dirname "${BASH_SOURCE[0]}") +SCRIPT_PATH=$(realpath "$SCRIPT_PATH") + +mkdir -p ~/rpmbuild/SOURCES/ +git archive --format=tar HEAD --output ~/rpmbuild/SOURCES/freerdp-nightly-3.0.tar.bz2 --prefix=freerdp-nightly-3.0/ +$SCRIPT_PATH/prepare_rpm_freerdp-nightly.sh +cp source_version ~/rpmbuild/SOURCES/ +rpmbuild -ba "$SCRIPT_PATH/../rpm/freerdp-nightly.spec" diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_deb_freerdp-nightly.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_deb_freerdp-nightly.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4654914afbb3ace33d6bbfdc34a2918aa3e0cdc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_deb_freerdp-nightly.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +ln -s packaging/deb/freerdp-nightly debian +git rev-parse --short HEAD > .source_version diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_rpm_freerdp-nightly.sh b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_rpm_freerdp-nightly.sh new file mode 100644 index 0000000000000000000000000000000000000000..5401a8186cfb3764e6029aab0102eb4695771d49 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/scripts/prepare_rpm_freerdp-nightly.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +git rev-parse --short HEAD > source_version diff --git a/local-test-freerdp-delta-01/afc-freerdp/packaging/windows/preload.cmake b/local-test-freerdp-delta-01/afc-freerdp/packaging/windows/preload.cmake new file mode 100644 index 0000000000000000000000000000000000000000..f91281cd272dec46bb6917434f68c6e9ce8b6ae7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/packaging/windows/preload.cmake @@ -0,0 +1,22 @@ +message("PRELOADING windows cache") +set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "nightly default") +set(CMAKE_WINDOWS_VERSION "WIN7" CACHE STRING "windows build version") +set(BUILD_SHARED_LIBS OFF CACHE BOOL "build static linked executable") +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded" CACHE STRING "MSVC runtime to use") +set(OPENSSL_USE_STATIC_LIBS ON CACHE BOOL "link OpenSSL static") +set(CHANNEL_URBDRC OFF CACHE BOOL "we do not build libusb support") +set(WITH_CLIENT_SDL ON CACHE BOOL "build with SDL client") +set(WITH_SERVER ON CACHE BOOL "Build with server support") +set(WITH_SHADOW OFF CACHE BOOL "Do not build shadow server") +set(WITH_PROXY ON CACHE BOOL "Build proxy server") +set(WITH_PLATFORM_SERVER OFF CACHE BOOL "Do not build platform server") +set(WITH_INTERNAL_MD4 ON CACHE BOOL "nightly default") +set(WITH_INTERNAL_MD5 ON CACHE BOOL "nightly default") +set(WITH_INTERNAL_RC4 ON CACHE BOOL "nightly default") +set(WITH_FFMPEG OFF CACHE BOOL "nightly default") +set(WITH_SWSCALE OFF CACHE BOOL "nightly default") +set(WITH_WEBVIEW ON CACHE BOOL "nightly default") +set(ZLIB_USE_STATIC_LIBS ON CACHE BOOL "ci default") +set(WITH_SDL_IMAGE_DIALOGS ON CACHE BOOL "nightly default") +set(SDL_USE_COMPILED_RESOURCES ON CACHE BOOL "nightly default") +set(WITH_SDL_LINK_SHARED OFF CACHE BOOL "nightly default") diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca8a7cb3c8bc2a4af593d33b11e12d664ebcf035 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/CMakeLists.txt @@ -0,0 +1,4 @@ +if(NOT RDTK_FORCE_STATIC_BUILD) + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${RDTK_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h") + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/rdtk DESTINATION ${RDTK_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/api.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/api.h new file mode 100644 index 0000000000000000000000000000000000000000..b5cee542ae621115fe3eebdbabe0068ef49d8d44 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/api.h @@ -0,0 +1,46 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_API_H +#define RDTK_API_H + +#include + +#if defined _WIN32 || defined __CYGWIN__ +#ifdef RDTK_EXPORTS +#ifdef __GNUC__ +#define RDTK_EXPORT __attribute__((dllexport)) +#else +#define RDTK_EXPORT __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define RDTK_EXPORT __attribute__((dllimport)) +#else +#define RDTK_EXPORT __declspec(dllimport) +#endif +#endif +#else +#if __GNUC__ >= 4 +#define RDTK_EXPORT __attribute__((visibility("default"))) +#else +#define RDTK_EXPORT +#endif +#endif + +#endif /* RDTK_API_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/rdtk.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/rdtk.h new file mode 100644 index 0000000000000000000000000000000000000000..4897ff9e355066b85e562dfc5fa62c02e8ad926f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/include/rdtk/rdtk.h @@ -0,0 +1,85 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_H +#define RDTK_H + +#include +#include + +#include +#include + +typedef struct rdtk_engine rdtkEngine; +typedef struct rdtk_font rdtkFont; +typedef struct rdtk_glyph rdtkGlyph; +typedef struct rdtk_surface rdtkSurface; +typedef struct rdtk_button rdtkButton; +typedef struct rdtk_label rdtkLabel; +typedef struct rdtk_text_field rdtkTextField; +typedef struct rdtk_nine_patch rdtkNinePatch; + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* Engine */ + + RDTK_EXPORT void rdtk_engine_free(rdtkEngine* engine); + + WINPR_ATTR_MALLOC(rdtk_engine_free, 1) + RDTK_EXPORT rdtkEngine* rdtk_engine_new(void); + + /* Surface */ + + RDTK_EXPORT int rdtk_surface_fill(rdtkSurface* surface, uint16_t x, uint16_t y, uint16_t width, + uint16_t height, uint32_t color); + + RDTK_EXPORT rdtkSurface* rdtk_surface_new(rdtkEngine* engine, uint8_t* data, uint16_t width, + uint16_t height, uint32_t scanline); + RDTK_EXPORT void rdtk_surface_free(rdtkSurface* surface); + + /* Font */ + + RDTK_EXPORT int rdtk_font_draw_text(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, + rdtkFont* font, const char* text); + + /* Button */ + + RDTK_EXPORT int rdtk_button_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, + uint16_t nWidth, uint16_t nHeight, rdtkButton* button, + const char* text); + + /* Label */ + + RDTK_EXPORT int rdtk_label_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, + uint16_t nWidth, uint16_t nHeight, rdtkLabel* label, + const char* text, uint16_t hAlign, uint16_t vAlign); + + /* TextField */ + + RDTK_EXPORT int rdtk_text_field_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, + uint16_t nWidth, uint16_t nHeight, + rdtkTextField* textField, const char* text); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..96ada15b2ce73fe1f9c57d2b3c1b50a8f4ce8d26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/CMakeLists.txt @@ -0,0 +1,56 @@ +# RdTk: Remote Desktop Toolkit +# +# Copyright 2014 Marc-Andre Moreau +# +# 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 "rdtk") +set(MODULE_PREFIX "RDTK") + +set(${MODULE_PREFIX}_SRCS + rdtk_resources.c + rdtk_resources.h + rdtk_surface.c + rdtk_surface.h + rdtk_font.c + rdtk_font.h + rdtk_button.c + rdtk_button.h + rdtk_label.c + rdtk_label.h + rdtk_nine_patch.c + rdtk_nine_patch.h + rdtk_text_field.c + rdtk_text_field.h + rdtk_engine.c + rdtk_engine.h +) + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${RDTK_VERSION}" ${MODULE_PREFIX}_SRCS) + +list(APPEND ${MODULE_PREFIX}_LIBS winpr) + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${${MODULE_PREFIX}_LIBS}) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "RdTk") + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() + +if(NOT RDTK_FORCE_STATIC_BUILD) + install(TARGETS ${MODULE_NAME} COMPONENT libraries EXPORT rdtk ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.c new file mode 100644 index 0000000000000000000000000000000000000000..3984fa9049c8b1bf882639d0e7a954cfc0bbdf54 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.c @@ -0,0 +1,130 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include + +#include "rdtk_font.h" + +#include "rdtk_button.h" + +int rdtk_button_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, uint16_t nWidth, + uint16_t nHeight, rdtkButton* button, const char* text) +{ + uint16_t textWidth = 0; + uint16_t textHeight = 0; + + WINPR_ASSERT(surface); + WINPR_ASSERT(button); + WINPR_ASSERT(text); + + rdtkEngine* engine = surface->engine; + rdtkFont* font = engine->font; + rdtkNinePatch* ninePatch = button->ninePatch; + + rdtk_font_text_draw_size(font, &textWidth, &textHeight, text); + + rdtk_nine_patch_draw(surface, nXDst, nYDst, nWidth, nHeight, ninePatch); + + if ((textWidth > 0) && (textHeight > 0)) + { + const int wd = (ninePatch->width - ninePatch->fillWidth); + const int hd = (ninePatch->height - ninePatch->fillHeight); + + const uint16_t fillWidth = nWidth - WINPR_ASSERTING_INT_CAST(uint16_t, wd); + const uint16_t fillHeight = nHeight - WINPR_ASSERTING_INT_CAST(uint16_t, hd); + uint16_t offsetX = WINPR_ASSERTING_INT_CAST(UINT16, ninePatch->fillLeft); + uint16_t offsetY = WINPR_ASSERTING_INT_CAST(UINT16, ninePatch->fillTop); + + if (textWidth < fillWidth) + { + const int twd = ((fillWidth - textWidth) / 2) + ninePatch->fillLeft; + offsetX = WINPR_ASSERTING_INT_CAST(uint16_t, twd); + } + else if (textWidth < ninePatch->width) + { + const int twd = ((ninePatch->width - textWidth) / 2); + offsetX = WINPR_ASSERTING_INT_CAST(uint16_t, twd); + } + + if (textHeight < fillHeight) + { + const int twd = ((fillHeight - textHeight) / 2) + ninePatch->fillTop; + offsetY = WINPR_ASSERTING_INT_CAST(uint16_t, twd); + } + else if (textHeight < ninePatch->height) + { + const int twd = ((ninePatch->height - textHeight) / 2); + offsetY = WINPR_ASSERTING_INT_CAST(uint16_t, twd); + } + + rdtk_font_draw_text(surface, nXDst + offsetX, nYDst + offsetY, font, text); + } + + return 1; +} + +rdtkButton* rdtk_button_new(rdtkEngine* engine, rdtkNinePatch* ninePatch) +{ + WINPR_ASSERT(engine); + WINPR_ASSERT(ninePatch); + + rdtkButton* button = (rdtkButton*)calloc(1, sizeof(rdtkButton)); + + if (!button) + return NULL; + + button->engine = engine; + button->ninePatch = ninePatch; + + return button; +} + +void rdtk_button_free(rdtkButton* button) +{ + free(button); +} + +int rdtk_button_engine_init(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + + if (!engine->button) + { + engine->button = rdtk_button_new(engine, engine->button9patch); + if (!engine->button) + return -1; + } + + return 1; +} + +int rdtk_button_engine_uninit(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + + if (engine->button) + { + rdtk_button_free(engine->button); + engine->button = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.h new file mode 100644 index 0000000000000000000000000000000000000000..691295943f0feaa15583d54dd2b7c3865eef826a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_button.h @@ -0,0 +1,50 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_BUTTON_PRIVATE_H +#define RDTK_BUTTON_PRIVATE_H + +#include + +#include "rdtk_surface.h" +#include "rdtk_nine_patch.h" + +#include "rdtk_engine.h" + +struct rdtk_button +{ + rdtkEngine* engine; + rdtkNinePatch* ninePatch; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int rdtk_button_engine_init(rdtkEngine* engine); + int rdtk_button_engine_uninit(rdtkEngine* engine); + + rdtkButton* rdtk_button_new(rdtkEngine* engine, rdtkNinePatch* ninePatch); + void rdtk_button_free(rdtkButton* button); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_BUTTON_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.c new file mode 100644 index 0000000000000000000000000000000000000000..726fa062afd7ee98432ecd5dfdb786c20e33b25e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.c @@ -0,0 +1,64 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "rdtk_font.h" +#include "rdtk_nine_patch.h" +#include "rdtk_button.h" +#include "rdtk_text_field.h" + +#include "rdtk_engine.h" + +rdtkEngine* rdtk_engine_new(void) +{ + rdtkEngine* engine = (rdtkEngine*)calloc(1, sizeof(rdtkEngine)); + + if (!engine) + return NULL; + + if (rdtk_font_engine_init(engine) < 0) + goto fail; + if (rdtk_nine_patch_engine_init(engine) < 0) + goto fail; + if (rdtk_button_engine_init(engine) < 0) + goto fail; + if (rdtk_text_field_engine_init(engine) < 0) + goto fail; + + return engine; + +fail: + rdtk_engine_free(engine); + return NULL; +} + +void rdtk_engine_free(rdtkEngine* engine) +{ + if (!engine) + return; + + rdtk_font_engine_uninit(engine); + rdtk_nine_patch_engine_uninit(engine); + rdtk_button_engine_uninit(engine); + rdtk_text_field_engine_uninit(engine); + + free(engine); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..7e3aed063f676e1c3e0e3bb53295ecfd04628e9f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_engine.h @@ -0,0 +1,46 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_ENGINE_PRIVATE_H +#define RDTK_ENGINE_PRIVATE_H + +#include + +struct rdtk_engine +{ + rdtkFont* font; + + rdtkLabel* label; + + rdtkButton* button; + rdtkNinePatch* button9patch; + + rdtkTextField* textField; + rdtkNinePatch* textField9patch; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_ENGINE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.c new file mode 100644 index 0000000000000000000000000000000000000000..deb09deb3f5eee0d6d7fe85a6164172012b2c49b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.c @@ -0,0 +1,760 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rdtk_engine.h" +#include "rdtk_resources.h" +#include "rdtk_surface.h" + +#include "rdtk_font.h" + +#if defined(WINPR_WITH_PNG) +#define FILE_EXT "png" +#else +#define FILE_EXT "bmp" +#endif + +static int rdtk_font_draw_glyph(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, + rdtkFont* font, rdtkGlyph* glyph) +{ + WINPR_ASSERT(surface); + WINPR_ASSERT(font); + WINPR_ASSERT(glyph); + + nXDst += glyph->offsetX; + nYDst += glyph->offsetY; + const size_t nXSrc = WINPR_ASSERTING_INT_CAST(size_t, glyph->rectX); + const size_t nYSrc = WINPR_ASSERTING_INT_CAST(size_t, glyph->rectY); + const size_t nWidth = WINPR_ASSERTING_INT_CAST(size_t, glyph->rectWidth); + const size_t nHeight = WINPR_ASSERTING_INT_CAST(size_t, glyph->rectHeight); + const uint32_t nSrcStep = font->image->scanline; + const uint8_t* pSrcData = font->image->data; + uint8_t* pDstData = surface->data; + const uint32_t nDstStep = surface->scanline; + + for (size_t y = 0; y < nHeight; y++) + { + const uint8_t* pSrcPixel = &pSrcData[((1ULL * nYSrc + y) * nSrcStep) + (4ULL * nXSrc)]; + uint8_t* pDstPixel = &pDstData[((1ULL * nYDst + y) * nDstStep) + (4ULL * nXDst)]; + + for (size_t x = 0; x < nWidth; x++) + { + uint8_t B = pSrcPixel[0]; + uint8_t G = pSrcPixel[1]; + uint8_t R = pSrcPixel[2]; + uint8_t A = pSrcPixel[3]; + pSrcPixel += 4; + + if (1) + { + /* tint black */ + R = 255 - R; + G = 255 - G; + B = 255 - B; + } + + if (A == 255) + { + pDstPixel[0] = B; + pDstPixel[1] = G; + pDstPixel[2] = R; + } + else + { + R = (R * A) / 255; + G = (G * A) / 255; + B = (B * A) / 255; + pDstPixel[0] = B + (pDstPixel[0] * (255 - A) + (255 / 2)) / 255; + pDstPixel[1] = G + (pDstPixel[1] * (255 - A) + (255 / 2)) / 255; + pDstPixel[2] = R + (pDstPixel[2] * (255 - A) + (255 / 2)) / 255; + } + + pDstPixel[3] = 0xFF; + pDstPixel += 4; + } + } + + return 1; +} + +int rdtk_font_draw_text(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, rdtkFont* font, + const char* text) +{ + WINPR_ASSERT(surface); + WINPR_ASSERT(font); + WINPR_ASSERT(text); + + const size_t length = strlen(text); + for (size_t index = 0; index < length; index++) + { + rdtkGlyph* glyph = &font->glyphs[text[index] - 32]; + rdtk_font_draw_glyph(surface, nXDst, nYDst, font, glyph); + nXDst += (glyph->width + 1); + } + + return 1; +} + +int rdtk_font_text_draw_size(rdtkFont* font, uint16_t* width, uint16_t* height, const char* text) +{ + WINPR_ASSERT(font); + WINPR_ASSERT(width); + WINPR_ASSERT(height); + WINPR_ASSERT(text); + + *width = 0; + *height = 0; + const size_t length = strlen(text); + for (size_t index = 0; index < length; index++) + { + const size_t glyphIndex = WINPR_ASSERTING_INT_CAST(size_t, text[index] - 32); + + if (glyphIndex < font->glyphCount) + { + rdtkGlyph* glyph = &font->glyphs[glyphIndex]; + *width += (glyph->width + 1); + } + } + + *height = font->height + 2; + return 1; +} + +WINPR_ATTR_MALLOC(free, 1) +static char* rdtk_font_load_descriptor_file(const char* filename, size_t* pSize) +{ + WINPR_ASSERT(filename); + WINPR_ASSERT(pSize); + + union + { + size_t s; + INT64 i64; + } fileSize; + FILE* fp = winpr_fopen(filename, "r"); + + if (!fp) + return NULL; + + if (_fseeki64(fp, 0, SEEK_END) != 0) + goto fail; + fileSize.i64 = _ftelli64(fp); + if (_fseeki64(fp, 0, SEEK_SET) != 0) + goto fail; + + if (fileSize.i64 < 1) + goto fail; + + char* buffer = (char*)calloc(fileSize.s + 4, sizeof(char)); + + if (!buffer) + goto fail; + + size_t readSize = fread(buffer, fileSize.s, 1, fp); + if (readSize == 0) + { + if (!ferror(fp)) + readSize = fileSize.s; + } + + (void)fclose(fp); + + if (readSize < 1) + { + free(buffer); + return NULL; + } + + buffer[fileSize.s] = '\0'; + buffer[fileSize.s + 1] = '\0'; + *pSize = fileSize.s; + return buffer; + +fail: + (void)fclose(fp); + return NULL; +} + +static int rdtk_font_convert_descriptor_code_to_utf8(const char* str, uint8_t* utf8) +{ + WINPR_ASSERT(str); + WINPR_ASSERT(utf8); + + const size_t len = strlen(str); + *((uint32_t*)utf8) = 0; + + if (len < 1) + return 1; + + if (len == 1) + { + if ((str[0] > 31) && (str[0] < 127)) + { + utf8[0] = WINPR_ASSERTING_INT_CAST(uint8_t, str[0] & 0xFF); + } + } + else + { + if (str[0] == '&') + { + const char* acc = &str[1]; + + if (strcmp(acc, "quot;") == 0) + utf8[0] = '"'; + else if (strcmp(acc, "amp;") == 0) + utf8[0] = '&'; + else if (strcmp(acc, "lt;") == 0) + utf8[0] = '<'; + else if (strcmp(acc, "gt;") == 0) + utf8[0] = '>'; + } + } + + return 1; +} + +static int rdtk_font_parse_descriptor_buffer(rdtkFont* font, char* buffer, size_t size) +{ + int rc = -1; + + WINPR_ASSERT(font); + + const char xmlversion[] = ""; + const char xmlfont[] = ""); + + if (!end) + goto fail; + + /* parse font size */ + p = strstr(p, "size=\""); + + if (!p) + goto fail; + + p += sizeof("size=\"") - 1; + char* q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + errno = 0; + { + long val = strtol(p, NULL, 0); + + if ((errno != 0) || (val == 0) || (val > UINT32_MAX)) + goto fail; + + font->size = (UINT32)val; + } + *q = '"'; + + if (font->size <= 0) + goto fail; + + p = q + 1; + /* parse font family */ + p = strstr(p, "family=\""); + + if (!p) + goto fail; + + p += sizeof("family=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + font->family = _strdup(p); + *q = '"'; + + if (!font->family) + goto fail; + + p = q + 1; + /* parse font height */ + p = strstr(p, "height=\""); + + if (!p) + goto fail; + + p += sizeof("height=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + errno = 0; + { + const unsigned long val = strtoul(p, NULL, 0); + + if ((errno != 0) || (val > UINT16_MAX)) + goto fail; + + font->height = (uint16_t)val; + } + *q = '"'; + + if (font->height <= 0) + goto fail; + + p = q + 1; + /* parse font style */ + p = strstr(p, "style=\""); + + if (!p) + goto fail; + + p += sizeof("style=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + font->style = _strdup(p); + *q = '"'; + + if (!font->style) + goto fail; + + p = q + 1; + // printf("size: %d family: %s height: %d style: %s\n", + // font->size, font->family, font->height, font->style); + char* beg = p; + size_t count = 0; + + while (p < end) + { + p = strstr(p, ""); + + if (!r) + goto fail; + + *r = '\0'; + p = r + sizeof("/>"); + *r = '/'; + count++; + } + + if (count > UINT16_MAX) + goto fail; + + font->glyphCount = (uint16_t)count; + font->glyphs = NULL; + + if (count > 0) + font->glyphs = (rdtkGlyph*)calloc(font->glyphCount, sizeof(rdtkGlyph)); + + if (!font->glyphs) + goto fail; + + p = beg; + size_t index = 0; + + while (p < end) + { + p = strstr(p, ""); + + if (!r) + goto fail; + + *r = '\0'; + /* start parsing glyph */ + if (index >= font->glyphCount) + goto fail; + + rdtkGlyph* glyph = &font->glyphs[index]; + /* parse glyph width */ + p = strstr(p, "width=\""); + + if (!p) + goto fail; + + p += sizeof("width=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + errno = 0; + { + long val = strtol(p, NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->width = (INT32)val; + } + *q = '"'; + + if (glyph->width < 0) + goto fail; + + p = q + 1; + /* parse glyph offset x,y */ + p = strstr(p, "offset=\""); + + if (!p) + goto fail; + + p += sizeof("offset=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + char* tok[4] = { 0 }; + *q = '\0'; + tok[0] = p; + p = strchr(tok[0] + 1, ' '); + + if (!p) + goto fail; + + *p = 0; + tok[1] = p + 1; + errno = 0; + { + long val = strtol(tok[0], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->offsetX = (INT32)val; + } + { + long val = strtol(tok[1], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->offsetY = (INT32)val; + } + *q = '"'; + p = q + 1; + /* parse glyph rect x,y,w,h */ + p = strstr(p, "rect=\""); + + if (!p) + goto fail; + + p += sizeof("rect=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + tok[0] = p; + p = strchr(tok[0] + 1, ' '); + + if (!p) + goto fail; + + *p = 0; + tok[1] = p + 1; + p = strchr(tok[1] + 1, ' '); + + if (!p) + goto fail; + + *p = 0; + tok[2] = p + 1; + p = strchr(tok[2] + 1, ' '); + + if (!p) + goto fail; + + *p = 0; + tok[3] = p + 1; + errno = 0; + { + long val = strtol(tok[0], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->rectX = (INT32)val; + } + { + long val = strtol(tok[1], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->rectY = (INT32)val; + } + { + long val = strtol(tok[2], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->rectWidth = (INT32)val; + } + { + long val = strtol(tok[3], NULL, 0); + + if ((errno != 0) || (val < INT32_MIN) || (val > INT32_MAX)) + goto fail; + + glyph->rectHeight = (INT32)val; + } + *q = '"'; + p = q + 1; + /* parse code */ + p = strstr(p, "code=\""); + + if (!p) + goto fail; + + p += sizeof("code=\"") - 1; + q = strchr(p, '"'); + + if (!q) + goto fail; + + *q = '\0'; + rdtk_font_convert_descriptor_code_to_utf8(p, glyph->code); + *q = '"'; + /* finish parsing glyph */ + p = r + sizeof("/>"); + *r = '/'; + index++; + } + + rc = 1; + +fail: + free(buffer); + return rc; +} + +static int rdtk_font_load_descriptor(rdtkFont* font, const char* filename) +{ + size_t size = 0; + + WINPR_ASSERT(font); + char* buffer = rdtk_font_load_descriptor_file(filename, &size); + + if (!buffer) + return -1; + + return rdtk_font_parse_descriptor_buffer(font, buffer, size); +} + +rdtkFont* rdtk_font_new(rdtkEngine* engine, const char* path, const char* file) +{ + size_t length = 0; + rdtkFont* font = NULL; + char* fontImageFile = NULL; + char* fontDescriptorFile = NULL; + + WINPR_ASSERT(engine); + WINPR_ASSERT(path); + WINPR_ASSERT(file); + + char* fontBaseFile = GetCombinedPath(path, file); + if (!fontBaseFile) + goto cleanup; + + winpr_asprintf(&fontImageFile, &length, "%s." FILE_EXT, fontBaseFile); + if (!fontImageFile) + goto cleanup; + + winpr_asprintf(&fontDescriptorFile, &length, "%s.xml", fontBaseFile); + if (!fontDescriptorFile) + goto cleanup; + + if (!winpr_PathFileExists(fontImageFile)) + goto cleanup; + + if (!winpr_PathFileExists(fontDescriptorFile)) + goto cleanup; + + font = (rdtkFont*)calloc(1, sizeof(rdtkFont)); + + if (!font) + goto cleanup; + + font->engine = engine; + font->image = winpr_image_new(); + + if (!font->image) + goto cleanup; + + const int status = winpr_image_read(font->image, fontImageFile); + if (status < 0) + goto cleanup; + + const int status2 = rdtk_font_load_descriptor(font, fontDescriptorFile); + if (status2 < 0) + goto cleanup; + + free(fontBaseFile); + free(fontImageFile); + free(fontDescriptorFile); + return font; +cleanup: + free(fontBaseFile); + free(fontImageFile); + free(fontDescriptorFile); + + rdtk_font_free(font); + return NULL; +} + +static rdtkFont* rdtk_embedded_font_new(rdtkEngine* engine, const uint8_t* imageData, + size_t imageSize, const uint8_t* descriptorData, + size_t descriptorSize) +{ + size_t size = 0; + + WINPR_ASSERT(engine); + + rdtkFont* font = (rdtkFont*)calloc(1, sizeof(rdtkFont)); + + if (!font) + return NULL; + + font->engine = engine; + font->image = winpr_image_new(); + + if (!font->image) + { + free(font); + return NULL; + } + + const int status = winpr_image_read_buffer(font->image, imageData, imageSize); + if (status < 0) + { + winpr_image_free(font->image, TRUE); + free(font); + return NULL; + } + + size = descriptorSize; + char* buffer = (char*)calloc(size + 4, sizeof(char)); + + if (!buffer) + goto fail; + + CopyMemory(buffer, descriptorData, size); + const int status2 = rdtk_font_parse_descriptor_buffer(font, buffer, size); + + if (status2 < 0) + goto fail; + + return font; + +fail: + rdtk_font_free(font); + return NULL; +} + +void rdtk_font_free(rdtkFont* font) +{ + if (font) + { + free(font->family); + free(font->style); + winpr_image_free(font->image, TRUE); + free(font->glyphs); + free(font); + } +} +int rdtk_font_engine_init(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (!engine->font) + { + const uint8_t* imageData = NULL; + const uint8_t* descriptorData = NULL; + const SSIZE_T imageSize = + rdtk_get_embedded_resource_file("source_serif_pro_regular_12." FILE_EXT, &imageData); + const SSIZE_T descriptorSize = + rdtk_get_embedded_resource_file("source_serif_pro_regular_12.xml", &descriptorData); + + if ((imageSize < 0) || (descriptorSize < 0)) + return -1; + + engine->font = rdtk_embedded_font_new(engine, imageData, (size_t)imageSize, descriptorData, + (size_t)descriptorSize); + if (!engine->font) + return -1; + } + + return 1; +} + +int rdtk_font_engine_uninit(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (engine->font) + { + rdtk_font_free(engine->font); + engine->font = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.h new file mode 100644 index 0000000000000000000000000000000000000000..bf40e67cb8c5b160a3ffd9882ef0f50c648cc266 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_font.h @@ -0,0 +1,73 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_FONT_PRIVATE_H +#define RDTK_FONT_PRIVATE_H + +#include + +#include + +#include + +#include "rdtk_engine.h" + +struct rdtk_glyph +{ + int width; + int offsetX; + int offsetY; + int rectX; + int rectY; + int rectWidth; + int rectHeight; + uint8_t code[4]; +}; + +struct rdtk_font +{ + rdtkEngine* engine; + + uint32_t size; + uint16_t height; + char* family; + char* style; + wImage* image; + uint16_t glyphCount; + rdtkGlyph* glyphs; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int rdtk_font_text_draw_size(rdtkFont* font, uint16_t* width, uint16_t* height, + const char* text); + + int rdtk_font_engine_init(rdtkEngine* engine); + int rdtk_font_engine_uninit(rdtkEngine* engine); + + rdtkFont* rdtk_font_new(rdtkEngine* engine, const char* path, const char* file); + void rdtk_font_free(rdtkFont* font); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_FONT_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.c new file mode 100644 index 0000000000000000000000000000000000000000..298bf1711a9729a57c5360f3ecdaecb2e5161863 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.c @@ -0,0 +1,99 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "rdtk_font.h" + +#include "rdtk_label.h" + +int rdtk_label_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, uint16_t nWidth, + uint16_t nHeight, rdtkLabel* label, const char* text, uint16_t hAlign, + uint16_t vAlign) +{ + uint16_t offsetX = 0; + uint16_t offsetY = 0; + uint16_t textWidth = 0; + uint16_t textHeight = 0; + + WINPR_ASSERT(surface); + + rdtkEngine* engine = surface->engine; + rdtkFont* font = engine->font; + + rdtk_font_text_draw_size(font, &textWidth, &textHeight, text); + + if ((textWidth > 0) && (textHeight > 0)) + { + offsetX = 0; + offsetY = 0; + + if (textWidth < nWidth) + offsetX = ((nWidth - textWidth) / 2); + + if (textHeight < nHeight) + offsetY = ((nHeight - textHeight) / 2); + + rdtk_font_draw_text(surface, nXDst + offsetX, nYDst + offsetY, font, text); + } + + return 1; +} + +rdtkLabel* rdtk_label_new(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + rdtkLabel* label = (rdtkLabel*)calloc(1, sizeof(rdtkLabel)); + + if (!label) + return NULL; + + label->engine = engine; + + return label; +} + +void rdtk_label_free(rdtkLabel* label) +{ + free(label); +} + +int rdtk_label_engine_init(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (!engine->label) + { + engine->label = rdtk_label_new(engine); + } + + return 1; +} + +int rdtk_label_engine_uninit(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (engine->label) + { + rdtk_label_free(engine->label); + engine->label = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.h new file mode 100644 index 0000000000000000000000000000000000000000..eefe67aeca8b1760a4466c045c67edcf7885f9f4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_label.h @@ -0,0 +1,48 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_LABEL_PRIVATE_H +#define RDTK_LABEL_PRIVATE_H + +#include + +#include "rdtk_surface.h" + +#include "rdtk_engine.h" + +struct rdtk_label +{ + rdtkEngine* engine; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int rdtk_label_engine_init(rdtkEngine* engine); + int rdtk_label_engine_uninit(rdtkEngine* engine); + + rdtkLabel* rdtk_label_new(rdtkEngine* engine); + void rdtk_label_free(rdtkLabel* label); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_LABEL_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.c new file mode 100644 index 0000000000000000000000000000000000000000..d070b253326045e60c01830d5f19959296531917 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.c @@ -0,0 +1,524 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include + +#include "rdtk_resources.h" + +#include "rdtk_nine_patch.h" + +#if defined(WINPR_WITH_PNG) +#define FILE_EXT "png" +#else +#define FILE_EXT "bmp" +#endif + +static int rdtk_image_copy_alpha_blend(uint8_t* pDstData, int nDstStep, int nXDst, int nYDst, + int nWidth, int nHeight, const uint8_t* pSrcData, + int nSrcStep, int nXSrc, int nYSrc) +{ + WINPR_ASSERT(pDstData); + WINPR_ASSERT(pSrcData); + + for (int y = 0; y < nHeight; y++) + { + const uint8_t* pSrcPixel = &pSrcData[((nYSrc + y) * nSrcStep) + (nXSrc * 4)]; + uint8_t* pDstPixel = &pDstData[((nYDst + y) * nDstStep) + (nXDst * 4)]; + + for (int x = 0; x < nWidth; x++) + { + uint8_t B = pSrcPixel[0]; + uint8_t G = pSrcPixel[1]; + uint8_t R = pSrcPixel[2]; + uint8_t A = pSrcPixel[3]; + pSrcPixel += 4; + + if (A == 255) + { + pDstPixel[0] = B; + pDstPixel[1] = G; + pDstPixel[2] = R; + } + else + { + R = (R * A) / 255; + G = (G * A) / 255; + B = (B * A) / 255; + pDstPixel[0] = B + (pDstPixel[0] * (255 - A) + (255 / 2)) / 255; + pDstPixel[1] = G + (pDstPixel[1] * (255 - A) + (255 / 2)) / 255; + pDstPixel[2] = R + (pDstPixel[2] * (255 - A) + (255 / 2)) / 255; + } + + pDstPixel[3] = 0xFF; + pDstPixel += 4; + } + } + + return 1; +} + +int rdtk_nine_patch_draw(rdtkSurface* surface, int nXDst, int nYDst, int nWidth, int nHeight, + rdtkNinePatch* ninePatch) +{ + WINPR_ASSERT(surface); + WINPR_ASSERT(ninePatch); + + if (nWidth < ninePatch->width) + nWidth = ninePatch->width; + + if (nHeight < ninePatch->height) + nHeight = ninePatch->height; + + WINPR_UNUSED(nHeight); + + int scaleWidth = nWidth - (ninePatch->width - ninePatch->scaleWidth); + int nSrcStep = ninePatch->scanline; + const uint8_t* pSrcData = ninePatch->data; + uint8_t* pDstData = surface->data; + WINPR_ASSERT(surface->scanline <= INT_MAX); + int nDstStep = (int)surface->scanline; + /* top */ + int x = 0; + int y = 0; + /* top left */ + int nXSrc = 0; + int nYSrc = 0; + int width = ninePatch->scaleLeft; + int height = ninePatch->scaleTop; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + x += width; + /* top middle (scalable) */ + nXSrc = ninePatch->scaleLeft; + nYSrc = 0; + height = ninePatch->scaleTop; + + while (x < (nXSrc + scaleWidth)) + { + width = (nXSrc + scaleWidth) - x; + + if (width > ninePatch->scaleWidth) + width = ninePatch->scaleWidth; + + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, + pSrcData, nSrcStep, nXSrc, nYSrc); + x += width; + } + + /* top right */ + nXSrc = ninePatch->scaleRight; + nYSrc = 0; + width = ninePatch->width - ninePatch->scaleRight; + height = ninePatch->scaleTop; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + /* middle */ + x = 0; + y = ninePatch->scaleTop; + /* middle left */ + nXSrc = 0; + nYSrc = ninePatch->scaleTop; + width = ninePatch->scaleLeft; + height = ninePatch->scaleHeight; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + x += width; + /* middle (scalable) */ + nXSrc = ninePatch->scaleLeft; + nYSrc = ninePatch->scaleTop; + height = ninePatch->scaleHeight; + + while (x < (nXSrc + scaleWidth)) + { + width = (nXSrc + scaleWidth) - x; + + if (width > ninePatch->scaleWidth) + width = ninePatch->scaleWidth; + + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, + pSrcData, nSrcStep, nXSrc, nYSrc); + x += width; + } + + /* middle right */ + nXSrc = ninePatch->scaleRight; + nYSrc = ninePatch->scaleTop; + width = ninePatch->width - ninePatch->scaleRight; + height = ninePatch->scaleHeight; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + /* bottom */ + x = 0; + y = ninePatch->scaleBottom; + /* bottom left */ + nXSrc = 0; + nYSrc = ninePatch->scaleBottom; + width = ninePatch->scaleLeft; + height = ninePatch->height - ninePatch->scaleBottom; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + x += width; + /* bottom middle (scalable) */ + nXSrc = ninePatch->scaleLeft; + nYSrc = ninePatch->scaleBottom; + height = ninePatch->height - ninePatch->scaleBottom; + + while (x < (nXSrc + scaleWidth)) + { + width = (nXSrc + scaleWidth) - x; + + if (width > ninePatch->scaleWidth) + width = ninePatch->scaleWidth; + + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, + pSrcData, nSrcStep, nXSrc, nYSrc); + x += width; + } + + /* bottom right */ + nXSrc = ninePatch->scaleRight; + nYSrc = ninePatch->scaleBottom; + width = ninePatch->width - ninePatch->scaleRight; + height = ninePatch->height - ninePatch->scaleBottom; + rdtk_image_copy_alpha_blend(pDstData, nDstStep, nXDst + x, nYDst + y, width, height, pSrcData, + nSrcStep, nXSrc, nYSrc); + return 1; +} + +static BOOL rdtk_nine_patch_get_scale_lr(rdtkNinePatch* ninePatch, wImage* image) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(ninePatch); + + WINPR_ASSERT(image->data); + WINPR_ASSERT(image->width > 0); + + int64_t beg = -1; + int64_t end = -1; + + for (uint32_t x = 1; x < image->width - 1; x++) + { + const uint32_t* pixel = (const uint32_t*)&image->data[sizeof(uint32_t) * x]; /* (1, 0) */ + if (beg < 0) + { + if (*pixel) + beg = x; + } + else if (end < 0) + { + if (!(*pixel)) + { + end = x; + break; + } + } + } + + if ((beg <= 0) || (end <= 0)) + return FALSE; + + WINPR_ASSERT(beg <= INT32_MAX); + WINPR_ASSERT(end <= INT32_MAX); + ninePatch->scaleLeft = (int32_t)beg - 1; + ninePatch->scaleRight = (int32_t)end - 1; + ninePatch->scaleWidth = ninePatch->scaleRight - ninePatch->scaleLeft; + + return TRUE; +} + +static BOOL rdtk_nine_patch_get_scale_ht(rdtkNinePatch* ninePatch, wImage* image) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(ninePatch); + + WINPR_ASSERT(image->data); + WINPR_ASSERT(image->height > 0); + WINPR_ASSERT(image->scanline > 0); + + int64_t beg = -1; + int64_t end = -1; + + for (uint32_t y = 1; y < image->height - 1; y++) + { + const uint32_t* pixel = + (const uint32_t*)&image->data[1ULL * image->scanline * y]; /* (1, 0) */ + if (beg < 0) + { + if (*pixel) + beg = y; + } + else if (end < 0) + { + if (!(*pixel)) + { + end = y; + break; + } + } + } + + if ((beg <= 0) || (end <= 0)) + return FALSE; + + WINPR_ASSERT(beg <= INT32_MAX); + WINPR_ASSERT(end <= INT32_MAX); + ninePatch->scaleTop = (int32_t)beg - 1; + ninePatch->scaleBottom = (int32_t)end - 1; + ninePatch->scaleHeight = ninePatch->scaleBottom - ninePatch->scaleTop; + + return TRUE; +} + +static BOOL rdtk_nine_patch_get_fill_lr(rdtkNinePatch* ninePatch, wImage* image) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(ninePatch); + + WINPR_ASSERT(image->data); + WINPR_ASSERT(image->width > 0); + WINPR_ASSERT(image->height > 0); + WINPR_ASSERT(image->scanline > 0); + + int64_t beg = -1; + int64_t end = -1; + + for (uint32_t x = 1; x < image->width - 1; x++) + { + const uint32_t* pixel = + (uint32_t*)&image->data[((1ULL * image->height - 1ULL) * image->scanline) + + x * sizeof(uint32_t)]; /* (1, height - 1) */ + if (beg < 0) + { + if (*pixel) + beg = x; + } + else if (end < 0) + { + if (!(*pixel)) + { + end = x; + break; + } + } + } + + if ((beg <= 0) || (end <= 0)) + return FALSE; + + WINPR_ASSERT(beg <= INT32_MAX); + WINPR_ASSERT(end <= INT32_MAX); + + ninePatch->fillLeft = (int32_t)beg - 1; + ninePatch->fillRight = (int32_t)end - 1; + ninePatch->fillWidth = ninePatch->fillRight - ninePatch->fillLeft; + + return TRUE; +} + +static BOOL rdtk_nine_patch_get_fill_ht(rdtkNinePatch* ninePatch, wImage* image) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(ninePatch); + + WINPR_ASSERT(image->data); + WINPR_ASSERT(image->width > 0); + WINPR_ASSERT(image->height > 0); + WINPR_ASSERT(image->scanline > 0); + + int64_t beg = -1; + int64_t end = -1; + + for (uint32_t y = 1; y < image->height - 1; y++) + { + const uint32_t* pixel = + (uint32_t*)&image->data[((image->width - 1) * sizeof(uint32_t)) + + 1ull * image->scanline * y]; /* (width - 1, 1) */ + if (beg < 0) + { + if (*pixel) + beg = y; + } + else if (end < 0) + { + if (!(*pixel)) + { + end = y; + break; + } + } + } + + if ((beg <= 0) || (end <= 0)) + return FALSE; + + WINPR_ASSERT(beg <= INT32_MAX); + WINPR_ASSERT(end <= INT32_MAX); + ninePatch->scaleTop = (int32_t)beg - 1; + ninePatch->scaleBottom = (int32_t)end - 1; + ninePatch->scaleHeight = ninePatch->scaleBottom - ninePatch->scaleTop; + + return TRUE; +} + +int rdtk_nine_patch_set_image(rdtkNinePatch* ninePatch, wImage* image) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(ninePatch); + + ninePatch->image = image; + + /* parse scalable area */ + if (!rdtk_nine_patch_get_scale_lr(ninePatch, image)) + return -1; + + if (!rdtk_nine_patch_get_scale_ht(ninePatch, image)) + return -1; + + /* parse fillable area */ + if (!rdtk_nine_patch_get_fill_lr(ninePatch, image)) + return -1; + + if (!rdtk_nine_patch_get_fill_ht(ninePatch, image)) + return -1; + + /* cut out borders from image */ + WINPR_ASSERT(image->width >= 2); + WINPR_ASSERT(image->height >= 2); + WINPR_ASSERT(image->scanline > 0); + WINPR_ASSERT(image->width <= INT32_MAX); + WINPR_ASSERT(image->height <= INT32_MAX); + WINPR_ASSERT(image->scanline <= INT32_MAX); + WINPR_ASSERT(image->data); + + ninePatch->width = (int32_t)image->width - 2; + ninePatch->height = (int32_t)image->height - 2; + ninePatch->data = &image->data[image->scanline + 4]; /* (1, 1) */ + ninePatch->scanline = (int32_t)image->scanline; + + return 1; +} + +rdtkNinePatch* rdtk_nine_patch_new(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + rdtkNinePatch* ninePatch = (rdtkNinePatch*)calloc(1, sizeof(rdtkNinePatch)); + + if (!ninePatch) + return NULL; + + ninePatch->engine = engine; + return ninePatch; +} + +void rdtk_nine_patch_free(rdtkNinePatch* ninePatch) +{ + if (!ninePatch) + return; + + winpr_image_free(ninePatch->image, TRUE); + free(ninePatch); +} + +int rdtk_nine_patch_engine_init(rdtkEngine* engine) +{ + int status = 0; + wImage* image = NULL; + rdtkNinePatch* ninePatch = NULL; + + WINPR_ASSERT(engine); + + if (!engine->button9patch) + { + SSIZE_T size = 0; + const uint8_t* data = NULL; + status = -1; + size = rdtk_get_embedded_resource_file("btn_default_normal.9." FILE_EXT, &data); + + if (size > 0) + { + image = winpr_image_new(); + + if (image) + status = winpr_image_read_buffer(image, data, (size_t)size); + } + + if (status > 0) + { + ninePatch = engine->button9patch = rdtk_nine_patch_new(engine); + + if (ninePatch) + rdtk_nine_patch_set_image(ninePatch, image); + else + winpr_image_free(image, TRUE); + } + else + winpr_image_free(image, TRUE); + } + + if (!engine->textField9patch) + { + SSIZE_T size = 0; + const uint8_t* data = NULL; + status = -1; + size = rdtk_get_embedded_resource_file("textfield_default.9." FILE_EXT, &data); + image = NULL; + + if (size > 0) + { + image = winpr_image_new(); + + if (image) + status = winpr_image_read_buffer(image, data, (size_t)size); + } + + if (status > 0) + { + ninePatch = engine->textField9patch = rdtk_nine_patch_new(engine); + + if (ninePatch) + rdtk_nine_patch_set_image(ninePatch, image); + else + winpr_image_free(image, TRUE); + } + else + winpr_image_free(image, TRUE); + } + + return 1; +} + +int rdtk_nine_patch_engine_uninit(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (engine->button9patch) + { + rdtk_nine_patch_free(engine->button9patch); + engine->button9patch = NULL; + } + + if (engine->textField9patch) + { + rdtk_nine_patch_free(engine->textField9patch); + engine->textField9patch = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.h new file mode 100644 index 0000000000000000000000000000000000000000..a236233140bbbc5b6ebe2947d452b555a41e335b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_nine_patch.h @@ -0,0 +1,76 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_NINE_PATCH_PRIVATE_H +#define RDTK_NINE_PATCH_PRIVATE_H + +#include +#include + +#include + +#include "rdtk_surface.h" + +#include "rdtk_engine.h" + +struct rdtk_nine_patch +{ + rdtkEngine* engine; + + wImage* image; + + int width; + int height; + int scanline; + uint8_t* data; + + int scaleLeft; + int scaleRight; + int scaleWidth; + int scaleTop; + int scaleBottom; + int scaleHeight; + + int fillLeft; + int fillRight; + int fillWidth; + int fillTop; + int fillBottom; + int fillHeight; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int rdtk_nine_patch_set_image(rdtkNinePatch* ninePatch, wImage* image); + int rdtk_nine_patch_draw(rdtkSurface* surface, int nXDst, int nYDst, int nWidth, int nHeight, + rdtkNinePatch* ninePatch); + + int rdtk_nine_patch_engine_init(rdtkEngine* engine); + int rdtk_nine_patch_engine_uninit(rdtkEngine* engine); + + rdtkNinePatch* rdtk_nine_patch_new(rdtkEngine* engine); + void rdtk_nine_patch_free(rdtkNinePatch* ninePatch); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_NINE_PATCH_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.c new file mode 100644 index 0000000000000000000000000000000000000000..dd9364ea9e684b6d1cd9ed613f618577d20d12ff --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.c @@ -0,0 +1,3935 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include "rdtk_resources.h" + +/* Nine Patches */ +#if defined(WINPR_WITH_PNG) +static const uint8_t btn_default_normal_9_png[] = { + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06, 0x00, 0x00, 0x00, 0x42, 0xb5, 0xcb, + 0x95, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x89, 0x00, 0x00, 0x0b, + 0x89, 0x01, 0x37, 0xc9, 0xcb, 0xad, 0x00, 0x00, 0x02, 0x5d, 0x49, 0x44, 0x41, 0x54, 0x58, 0x85, + 0xed, 0x58, 0x41, 0xae, 0xd3, 0x40, 0x0c, 0x7d, 0x9e, 0x52, 0x84, 0x10, 0x69, 0xd5, 0x05, 0x57, + 0xe8, 0x8e, 0x4d, 0x51, 0x57, 0xdc, 0x80, 0x43, 0xf4, 0x08, 0x1c, 0xaa, 0x87, 0xe0, 0x02, 0x88, + 0x13, 0xb0, 0xeb, 0x0d, 0x10, 0x8b, 0x4a, 0x5f, 0x15, 0x42, 0xe4, 0x63, 0xb3, 0xa0, 0x53, 0x39, + 0x8e, 0x3d, 0x33, 0x49, 0xbf, 0xf4, 0x37, 0x58, 0x8a, 0x32, 0x3f, 0x99, 0xf1, 0xf3, 0x1b, 0x3f, + 0x7b, 0xd2, 0x4f, 0x22, 0x02, 0x22, 0x82, 0x63, 0xe2, 0x3d, 0x6c, 0xb0, 0x91, 0x33, 0x91, 0xb9, + 0xae, 0x9e, 0x02, 0x1d, 0xc0, 0xeb, 0xe3, 0xf1, 0xf8, 0x71, 0xbb, 0xdd, 0x7e, 0x00, 0x40, 0x44, + 0x74, 0x63, 0x6c, 0x99, 0xe7, 0x48, 0x45, 0x24, 0x8f, 0xe5, 0x74, 0x3a, 0x7d, 0x3d, 0x1c, 0x0e, + 0x9f, 0x01, 0xfc, 0xd4, 0x73, 0x5f, 0x38, 0x40, 0xdd, 0x7e, 0xbf, 0xff, 0xb4, 0xd9, 0x6c, 0x76, + 0x44, 0x84, 0x94, 0x52, 0x13, 0x10, 0x33, 0x43, 0x44, 0xb0, 0x5e, 0xaf, 0xdf, 0x03, 0xf8, 0xd2, + 0x02, 0xb4, 0xea, 0xba, 0x6e, 0xd7, 0xf7, 0xbd, 0xa4, 0x94, 0x6e, 0x40, 0x16, 0xcc, 0xb2, 0x61, + 0x66, 0x30, 0x33, 0xba, 0xae, 0xdb, 0x01, 0x58, 0x01, 0xf8, 0xae, 0x9d, 0x26, 0x8c, 0x93, 0xbe, + 0x64, 0xe6, 0x41, 0xd4, 0x3a, 0x99, 0xb5, 0xbf, 0xaf, 0x6b, 0x97, 0x36, 0x7a, 0x8f, 0xd1, 0x20, + 0xda, 0xcc, 0x42, 0x8f, 0xf5, 0x3b, 0x0d, 0x66, 0x41, 0x2d, 0x23, 0x6b, 0xe4, 0x2d, 0x72, 0x12, + 0x1f, 0x82, 0xc1, 0x11, 0x99, 0x07, 0x14, 0x32, 0x9c, 0xfa, 0x4e, 0x4f, 0xf3, 0xb6, 0x6e, 0x10, + 0x4d, 0x0d, 0x24, 0xd8, 0xae, 0x36, 0x46, 0x59, 0xaa, 0xf9, 0x1e, 0x6d, 0x65, 0x74, 0x79, 0xe6, + 0x32, 0xca, 0x0b, 0xb4, 0x08, 0x22, 0x86, 0x01, 0xd0, 0x88, 0x91, 0xab, 0x3a, 0xed, 0x00, 0x88, + 0x55, 0x67, 0x05, 0x32, 0x8b, 0x91, 0x8e, 0x9e, 0x99, 0x5d, 0x59, 0xe7, 0x77, 0x16, 0xcc, 0x63, + 0x54, 0x55, 0x5d, 0x8b, 0xe2, 0x5a, 0x94, 0x57, 0xcc, 0x11, 0x00, 0xa4, 0x94, 0x06, 0x0e, 0x4b, + 0x2d, 0x68, 0x32, 0xa3, 0x28, 0xe1, 0x76, 0x6c, 0xe7, 0x96, 0x98, 0x85, 0x75, 0xa4, 0x23, 0xd5, + 0x2c, 0x22, 0x46, 0x26, 0x80, 0x76, 0xd5, 0x45, 0x36, 0xf7, 0xb4, 0x2c, 0x32, 0xca, 0x6c, 0xf4, + 0x65, 0x41, 0xed, 0x75, 0x9d, 0xd3, 0x94, 0x23, 0x8a, 0xa2, 0x8e, 0x1a, 0x6a, 0x14, 0x6c, 0x8d, + 0xd1, 0x28, 0xc1, 0x59, 0x79, 0x5e, 0x7e, 0x74, 0x00, 0x93, 0x0b, 0x36, 0x2f, 0xce, 0x8e, 0xb5, + 0x20, 0xac, 0xd9, 0x43, 0x32, 0xda, 0xba, 0x62, 0x1d, 0x79, 0x2c, 0x22, 0x33, 0x2c, 0xa7, 0xd5, + 0x51, 0xa9, 0xa1, 0x96, 0xba, 0xb9, 0x67, 0xc5, 0x5e, 0x07, 0x60, 0xa0, 0xbc, 0x08, 0xbc, 0xa5, + 0x8e, 0x5c, 0xd5, 0xd5, 0xa2, 0xaf, 0x3d, 0xf7, 0x80, 0x8a, 0x05, 0x5b, 0xcb, 0x91, 0xc7, 0x2e, + 0x12, 0x8d, 0xbb, 0x75, 0x5a, 0x49, 0x79, 0xec, 0x39, 0x28, 0xc8, 0xfb, 0xbe, 0x16, 0xd4, 0xc2, + 0x2a, 0xb2, 0xb0, 0x8e, 0x98, 0x19, 0x29, 0xfd, 0x4b, 0xa1, 0x77, 0xa4, 0x5b, 0xb0, 0x5a, 0x0b, + 0x6a, 0xfa, 0x80, 0xb4, 0x7b, 0xaf, 0x81, 0xa3, 0xe3, 0xc3, 0x5a, 0x73, 0xaf, 0x6b, 0x3d, 0x77, + 0x9e, 0xe4, 0x28, 0x8f, 0x24, 0x7f, 0xf7, 0x51, 0x9e, 0x73, 0x64, 0xc7, 0x36, 0x10, 0xe7, 0x23, + 0x66, 0x7e, 0x1d, 0x79, 0x8d, 0xb5, 0x75, 0x3b, 0x43, 0x46, 0x76, 0x71, 0xad, 0xb1, 0x3a, 0x42, + 0x78, 0xb6, 0x8f, 0xfc, 0xb8, 0xd7, 0x59, 0x47, 0x25, 0x25, 0x3a, 0xef, 0x2c, 0x23, 0xba, 0xbb, + 0x33, 0xb4, 0x5a, 0x53, 0x1d, 0xcd, 0xd8, 0x3a, 0x57, 0x75, 0xa3, 0x87, 0xcc, 0x8c, 0xbe, 0xef, + 0x5d, 0x27, 0x25, 0x61, 0x10, 0x11, 0x96, 0xcb, 0xd1, 0xcf, 0xd7, 0x1b, 0x90, 0xb5, 0xc7, 0xf3, + 0xf9, 0xfc, 0xb0, 0x58, 0x2c, 0x56, 0x53, 0xb7, 0x8a, 0x88, 0x70, 0xb9, 0x5c, 0x1e, 0x00, 0x3c, + 0x8e, 0xde, 0x39, 0xf3, 0xdf, 0x02, 0x78, 0x77, 0xbd, 0x2f, 0x26, 0x21, 0x01, 0x7f, 0x00, 0xfc, + 0x00, 0xf0, 0xed, 0x7a, 0x2f, 0x02, 0xbd, 0x04, 0xf0, 0x06, 0xc0, 0x2b, 0x34, 0xca, 0x5f, 0x19, + 0x03, 0xf8, 0x05, 0xe0, 0x02, 0xe0, 0xf7, 0xc4, 0xb5, 0xff, 0xed, 0xb9, 0x6d, 0x46, 0xb5, 0x0b, + 0x26, 0xfe, 0xd3, 0x50, 0x44, 0xf0, 0x17, 0xa0, 0xb1, 0xe0, 0x73, 0xc3, 0xe6, 0x24, 0xdb, 0x00, + 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 +}; +#else +static const uint8_t btn_default_normal_9_bmp[] = { + 0x42, 0x4d, 0x2a, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x7c, 0x00, + 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xa0, 0x0f, 0x00, 0x00, 0x89, 0x0b, 0x00, 0x00, 0x89, 0x0b, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x42, 0x47, 0x52, 0x73, 0x80, 0xc2, 0xf5, 0x28, 0x60, 0xb8, + 0x1e, 0x15, 0x20, 0x85, 0xeb, 0x01, 0x40, 0x33, 0x33, 0x13, 0x80, 0x66, 0x66, 0x26, 0x40, 0x66, + 0x66, 0x06, 0xa0, 0x99, 0x99, 0x09, 0x3c, 0x0a, 0xd7, 0x03, 0x24, 0x5c, 0x8f, 0x32, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbc, 0xbc, 0xbc, 0xbf, 0xbf, 0xbf, 0xbe, + 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, + 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, 0xbe, + 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xbc, 0xbc, 0xbc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xcd, 0xcd, 0xc8, 0xc8, 0xc8, 0xc7, + 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc8, 0xc8, + 0xc8, 0xc8, 0xc8, 0xc8, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, 0xc7, + 0xc7, 0xc7, 0xc7, 0xc8, 0xc8, 0xc8, 0xcd, 0xcd, 0xcd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, + 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, + 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, + 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, + 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, 0xd0, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xcf, + 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, + 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd0, 0xd0, 0xd0, + 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xd0, + 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, + 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, + 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf, 0xd1, + 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, + 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, + 0xd1, 0xd1, 0xd1, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd2, + 0xd2, 0xd2, 0xd2, 0xd2, 0xd2, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, + 0xd4, 0xd4, 0xd4, 0xd4, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd2, 0xd2, 0xd2, + 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd2, + 0xd2, 0xd2, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, + 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, + 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, 0xd2, + 0xd2, 0xd2, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, + 0xd4, 0xd5, 0xd5, 0xd5, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd4, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, + 0xd2, 0xd2, 0xd2, 0xd1, 0xd1, 0xd1, 0xd2, 0xd2, 0xd2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd3, 0xd3, 0xd3, 0xd1, 0xd1, 0xd1, 0xd3, + 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, + 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd4, 0xd4, 0xd4, + 0xd3, 0xd3, 0xd3, 0xd2, 0xd2, 0xd2, 0xd3, 0xd3, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, + 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, + 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, + 0xd4, 0xd4, 0xd4, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd4, + 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, + 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd5, 0xd5, 0xd5, + 0xd4, 0xd4, 0xd4, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0xd5, 0xd5, 0xd4, 0xd4, 0xd4, 0xd5, + 0xd5, 0xd5, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, + 0xd6, 0xd6, 0xd6, 0xd4, 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0xd5, 0xd5, 0xd4, 0xd4, 0xd4, 0xd6, + 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, + 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd8, 0xd8, 0xd8, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, + 0xd6, 0xd6, 0xd6, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd6, + 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, + 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd8, 0xd8, 0xd8, 0xd7, 0xd7, 0xd7, + 0xd6, 0xd6, 0xd6, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd7, + 0xd7, 0xd7, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, + 0xda, 0xda, 0xda, 0xda, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, + 0xd7, 0xd7, 0xd7, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd7, 0xd7, 0xd7, 0xd6, 0xd6, 0xd6, 0xd8, + 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xda, 0xda, + 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, + 0xd8, 0xd8, 0xd8, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0xd8, 0xd8, 0xd7, 0xd7, 0xd7, 0xd9, + 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, + 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, + 0xd9, 0xd9, 0xd9, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd9, + 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, + 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xda, 0xda, 0xda, + 0xd9, 0xd9, 0xd9, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xd9, 0xda, + 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, + 0xdd, 0xde, 0xde, 0xde, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdc, 0xdc, 0xdc, 0xdb, 0xdb, 0xdb, + 0xda, 0xda, 0xda, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xda, 0xda, 0xda, 0xd9, 0xd9, 0xd9, 0xda, + 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xde, 0xde, + 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xde, 0xdd, 0xdd, 0xdd, 0xdc, 0xdc, 0xdc, 0xdb, 0xdb, 0xdb, + 0xda, 0xda, 0xda, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdc, + 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, + 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xde, 0xde, 0xde, 0xdd, 0xdd, 0xdd, + 0xdc, 0xdc, 0xdc, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0xdc, + 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, + 0xe0, 0xe0, 0xe0, 0xe0, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xde, 0xde, 0xde, 0xdd, 0xdd, 0xdd, + 0xdc, 0xdc, 0xdc, 0xda, 0xda, 0xda, 0xda, 0xda, 0xda, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdd, + 0xdd, 0xdd, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, + 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, + 0xdd, 0xdd, 0xdd, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdd, + 0xdd, 0xdd, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, + 0xe2, 0xe2, 0xe2, 0xe2, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe0, 0xe0, 0xe0, 0xdf, 0xdf, 0xdf, + 0xdd, 0xdd, 0xdd, 0xdc, 0xdc, 0xdc, 0xdb, 0xdb, 0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xdf, + 0xdf, 0xdf, 0xdf, 0xdf, 0xdf, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, + 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe2, 0xe2, 0xe2, 0xe1, 0xe1, 0xe1, 0xe0, 0xe0, 0xe0, + 0xdf, 0xdf, 0xdf, 0xdd, 0xdd, 0xdd, 0xdc, 0xdc, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xdf, + 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, + 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, 0xe1, + 0xdf, 0xdf, 0xdf, 0xdd, 0xdd, 0xdd, 0xdc, 0xdc, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xe0, + 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, + 0xe5, 0xe5, 0xe5, 0xe5, 0xe4, 0xe4, 0xe4, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe1, 0xe1, 0xe1, + 0xe0, 0xe0, 0xe0, 0xde, 0xde, 0xde, 0xdd, 0xdd, 0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdd, 0xdd, 0xdd, 0xdf, 0xdf, 0xdf, 0xe1, + 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, + 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe3, 0xe3, 0xe3, 0xe2, 0xe2, 0xe2, + 0xe1, 0xe1, 0xe1, 0xdf, 0xdf, 0xdf, 0xde, 0xde, 0xde, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0xde, 0xde, 0xe0, 0xe0, 0xe0, 0xe1, + 0xe1, 0xe1, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe6, 0xe6, 0xe6, 0xe5, 0xe5, 0xe5, 0xe4, 0xe4, 0xe4, 0xe3, 0xe3, 0xe3, + 0xe2, 0xe2, 0xe2, 0xe0, 0xe0, 0xe0, 0xdf, 0xdf, 0xdf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe3, + 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe6, 0xe6, 0xe6, 0xe5, 0xe5, 0xe5, 0xe4, 0xe4, 0xe4, + 0xe3, 0xe3, 0xe3, 0xe1, 0xe1, 0xe1, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe3, + 0xe3, 0xe3, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, + 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe7, 0xe7, 0xe7, 0xe6, 0xe6, 0xe6, 0xe5, 0xe5, 0xe5, + 0xe3, 0xe3, 0xe3, 0xe1, 0xe1, 0xe1, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe3, + 0xe3, 0xe3, 0xe5, 0xe5, 0xe5, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, + 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe5, 0xe5, 0xe5, + 0xe3, 0xe3, 0xe3, 0xe1, 0xe1, 0xe1, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe4, + 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, + 0xe9, 0xe9, 0xe9, 0xe9, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe8, 0xe7, 0xe7, 0xe7, 0xe5, 0xe5, 0xe5, + 0xe4, 0xe4, 0xe4, 0xe2, 0xe2, 0xe2, 0xe1, 0xe1, 0xe1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe5, + 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, + 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe7, 0xe7, 0xe7, 0xe6, 0xe6, 0xe6, + 0xe5, 0xe5, 0xe5, 0xe3, 0xe3, 0xe3, 0xe2, 0xe2, 0xe2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0xe4, 0xe4, 0xe3, 0xe3, 0xe3, 0xe5, + 0xe5, 0xe5, 0xe7, 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xea, 0xea, + 0xea, 0xea, 0xea, 0xea, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe8, 0xe8, 0xe8, 0xe7, 0xe7, 0xe7, + 0xe5, 0xe5, 0xe5, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd7, 0xd7, 0xd7, 0xe8, 0xe8, 0xe8, 0xe9, + 0xe9, 0xe9, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, + 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, + 0xe9, 0xe9, 0xe9, 0xe8, 0xe8, 0xe8, 0xd7, 0xd7, 0xd7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa2, 0xa2, 0xa2, 0xc8, 0xc8, 0xc8, 0xc8, + 0xc8, 0xc8, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, + 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xcb, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xc9, 0xc9, 0xc9, + 0xc8, 0xc8, 0xc8, 0xc8, 0xc8, 0xc8, 0xa2, 0xa2, 0xa2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00 +}; +#endif + +#if defined(WINPR_WITH_PNG) +static const uint8_t textfield_default_9_png[] = { + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06, 0x00, 0x00, 0x00, 0x46, 0x40, 0x1b, + 0xa8, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x89, 0x00, 0x00, 0x0b, + 0x89, 0x01, 0x37, 0xc9, 0xcb, 0xad, 0x00, 0x00, 0x01, 0x53, 0x49, 0x44, 0x41, 0x54, 0x58, 0x85, + 0xed, 0x98, 0x4b, 0x6e, 0x83, 0x30, 0x10, 0x86, 0x67, 0xc6, 0xa8, 0x8a, 0x58, 0xb1, 0x45, 0xa2, + 0x9b, 0x8a, 0x83, 0xf4, 0x28, 0xbd, 0x03, 0xea, 0x71, 0xb8, 0x0b, 0xf7, 0x60, 0x55, 0xa9, 0x97, + 0x60, 0x51, 0x4f, 0x17, 0xcd, 0x44, 0x7e, 0x76, 0x30, 0x09, 0x52, 0xa9, 0xf8, 0x25, 0x0b, 0x3f, + 0x26, 0xf3, 0xf9, 0xb7, 0xad, 0x10, 0x07, 0x98, 0x19, 0x0a, 0x54, 0x16, 0xcc, 0x0c, 0x18, 0xf4, + 0x3d, 0x03, 0x44, 0x7d, 0xa5, 0xb2, 0x00, 0xf0, 0x29, 0x8d, 0xca, 0x1d, 0x99, 0xa6, 0xe9, 0xbd, + 0xef, 0xfb, 0x37, 0x71, 0x85, 0xa8, 0xb3, 0xdc, 0x15, 0xa8, 0xaa, 0x0a, 0xda, 0xb6, 0x7d, 0xcd, + 0x02, 0x2e, 0x97, 0x0b, 0xd7, 0x75, 0xfd, 0x63, 0xcd, 0x49, 0x9e, 0x02, 0xb9, 0x89, 0x83, 0x09, + 0x7d, 0xb9, 0x71, 0x1e, 0xc0, 0x18, 0xc3, 0xc6, 0x18, 0x40, 0xc4, 0x5b, 0x59, 0xeb, 0x80, 0x99, + 0xa5, 0x6e, 0xb3, 0x00, 0x22, 0x62, 0x22, 0x8a, 0x00, 0x39, 0x50, 0x98, 0xfc, 0xda, 0xf6, 0x0e, + 0x82, 0x07, 0x90, 0xa4, 0x2e, 0x24, 0x07, 0x90, 0x65, 0x94, 0xa7, 0xb5, 0x16, 0x52, 0x27, 0x32, + 0x02, 0x48, 0x72, 0x79, 0x6a, 0x0e, 0xa4, 0x10, 0x51, 0x32, 0x46, 0x75, 0xb0, 0x66, 0x1f, 0xc4, + 0x41, 0x22, 0x96, 0x93, 0x00, 0xb7, 0x9e, 0x83, 0xb8, 0x27, 0x47, 0x92, 0xa7, 0xe2, 0x92, 0xbe, + 0xb4, 0xe4, 0xa9, 0xc9, 0xe4, 0x54, 0x85, 0x1d, 0xa9, 0xe4, 0xbf, 0x6d, 0x72, 0x0a, 0xa8, 0x3a, + 0x08, 0x81, 0x25, 0xfd, 0xc5, 0x80, 0x7b, 0x75, 0x38, 0x40, 0xb4, 0x6e, 0x87, 0x73, 0xa0, 0x02, + 0xee, 0x7d, 0xd9, 0xa8, 0x80, 0x87, 0xeb, 0x7f, 0x00, 0x8a, 0x7e, 0x29, 0x6c, 0x01, 0x3c, 0x7c, + 0x63, 0x43, 0xc0, 0xae, 0xf2, 0x00, 0x6b, 0xbf, 0xc0, 0x36, 0x03, 0xf6, 0xd0, 0x09, 0x38, 0x01, + 0x27, 0xe0, 0x04, 0xfc, 0x01, 0x00, 0xaa, 0x80, 0xc2, 0x6b, 0x6e, 0xa4, 0xcd, 0x0e, 0xd6, 0x82, + 0xa3, 0xfb, 0x41, 0x70, 0xdf, 0x52, 0x21, 0x5a, 0xac, 0xe7, 0x80, 0x88, 0x10, 0x11, 0x09, 0x11, + 0xe9, 0x3a, 0xe6, 0xd5, 0x53, 0x45, 0xc6, 0xe5, 0x73, 0x4d, 0xd3, 0x78, 0x6f, 0x2d, 0xaf, 0x31, + 0x0c, 0xc3, 0x4b, 0xd7, 0x75, 0x4f, 0xea, 0xd4, 0x33, 0x5a, 0x96, 0xc5, 0xce, 0xf3, 0xbc, 0x8c, + 0xe3, 0xf8, 0xb1, 0x35, 0xc7, 0xa9, 0x23, 0x6a, 0xef, 0x3f, 0xa4, 0xbe, 0x01, 0x9f, 0x91, 0x87, + 0x71, 0x3a, 0x69, 0xd1, 0x87, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, + 0x82 +}; +#else +static const uint8_t textfield_default_9_bmp[] = { + 0x42, 0x4d, 0x9a, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x7c, 0x00, + 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x0e, 0x00, 0x00, 0x89, 0x0b, 0x00, 0x00, 0x89, 0x0b, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x42, 0x47, 0x52, 0x73, 0x80, 0xc2, 0xf5, 0x28, 0x60, 0xb8, + 0x1e, 0x15, 0x20, 0x85, 0xeb, 0x01, 0x40, 0x33, 0x33, 0x13, 0x80, 0x66, 0x66, 0x26, 0x40, 0x66, + 0x66, 0x06, 0xa0, 0x99, 0x99, 0x09, 0x3c, 0x0a, 0xd7, 0x03, 0x24, 0x5c, 0x8f, 0x32, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, + 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x73, 0x73, 0x73, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, + 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, + 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, 0x8f, + 0x8f, 0x8f, 0x8f, 0x88, 0x88, 0x88, 0x63, 0x63, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0xd5, 0xd5, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, + 0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xf9, 0xf9, 0xf9, 0x10, 0x10, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd3, 0xd3, 0xd3, 0xf8, 0xf8, 0xf8, 0xfa, 0xfa, 0xfa, 0xfc, 0xfc, 0xfc, 0xfd, + 0xfd, 0xfd, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfb, 0xfb, 0xfb, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd2, 0xd2, 0xd2, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, + 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfd, 0xfd, 0xfd, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, + 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf8, 0xf8, + 0xf8, 0xfa, 0xfa, 0xfa, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, + 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfb, 0xfb, 0xfb, 0xf9, 0xf9, 0xf9, 0xf7, 0xf7, 0xf7, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xd1, 0xd1, 0xd1, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xfb, 0xfb, 0xfb, 0xfc, + 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfa, 0xfa, 0xfa, + 0xf9, 0xf9, 0xf9, 0xf7, 0xf7, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xd0, 0xd0, 0xf7, 0xf7, + 0xf7, 0xf9, 0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, + 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfc, 0xfb, + 0xfb, 0xfb, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xf8, 0xf8, 0xf8, 0xf6, 0xf6, 0xf6, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xcf, 0xcf, 0xcf, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf9, 0xf9, 0xf9, 0xfa, + 0xfa, 0xfa, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, + 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfa, 0xfa, 0xfa, 0xf9, 0xf9, 0xf9, 0xf8, 0xf8, 0xf8, + 0xf7, 0xf7, 0xf7, 0xf5, 0xf5, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xce, 0xce, 0xce, 0xf4, 0xf4, + 0xf4, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, + 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf9, 0xf8, 0xf8, 0xf8, 0xf8, + 0xf8, 0xf8, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf5, 0xf5, 0xf5, 0xf3, 0xf3, 0xf3, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xcd, 0xcd, 0xcd, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf6, + 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, + 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, + 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcb, 0xcb, 0xcb, 0xf1, 0xf1, + 0xf1, 0xf2, 0xf2, 0xf2, 0xf3, 0xf3, 0xf3, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, + 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, + 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xc8, 0xc8, 0xc8, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, + 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, + 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, + 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xe4, 0xe4, + 0xe4, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, + 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, + 0xe4, 0xe4, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xe7, 0xe7, 0xe7, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff +}; +#endif +/* Fonts */ + +#if defined(WINPR_WITH_PNG) +static const uint8_t source_serif_pro_regular_12_png[] = { + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x02, 0xe7, 0x00, 0x00, 0x00, 0x11, 0x08, 0x06, 0x00, 0x00, 0x00, 0x7e, 0x53, 0x02, + 0xe5, 0x00, 0x00, 0x00, 0x04, 0x73, 0x42, 0x49, 0x54, 0x08, 0x08, 0x08, 0x08, 0x7c, 0x08, 0x64, + 0x88, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0e, 0xc4, 0x00, 0x00, 0x0e, + 0xc4, 0x01, 0x95, 0x2b, 0x0e, 0x1b, 0x00, 0x00, 0x20, 0x00, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, + 0xed, 0x9d, 0x77, 0xd8, 0x55, 0xc5, 0xb5, 0xc6, 0x7f, 0x14, 0x15, 0xb1, 0xa2, 0x62, 0x12, 0x8d, + 0x0d, 0x1b, 0x26, 0xf6, 0x86, 0x1a, 0x13, 0x10, 0x7b, 0xb0, 0xc4, 0x28, 0x18, 0x4b, 0x14, 0x31, + 0x17, 0x15, 0x8d, 0xc6, 0x42, 0xbc, 0x26, 0x16, 0xbc, 0x46, 0x63, 0xbc, 0x26, 0xd8, 0x35, 0x09, + 0x0a, 0x51, 0xb1, 0x44, 0x63, 0x8f, 0x1d, 0xf9, 0x00, 0x1b, 0x62, 0x45, 0xc4, 0xd8, 0x51, 0x11, + 0x8d, 0x8a, 0x60, 0x45, 0x41, 0x7c, 0xef, 0x1f, 0xef, 0xcc, 0xdd, 0x73, 0xf6, 0xd9, 0xfb, 0x9c, + 0xf3, 0x7d, 0x7c, 0x60, 0xd4, 0xef, 0x7d, 0x9e, 0x79, 0xce, 0xd9, 0xb3, 0x67, 0x66, 0xcf, 0x9e, + 0xb2, 0x66, 0xcd, 0x5a, 0x6b, 0xd6, 0x6e, 0x27, 0x89, 0xaf, 0x19, 0x3a, 0x01, 0x5f, 0x00, 0x9f, + 0x87, 0xdf, 0x36, 0xb4, 0xa1, 0x0d, 0x6d, 0x68, 0x43, 0x1b, 0xda, 0xd0, 0x86, 0x79, 0x45, 0x07, + 0x60, 0x71, 0xe0, 0xfd, 0x2f, 0xbb, 0x22, 0x6d, 0xf8, 0x7a, 0xa3, 0x7d, 0xf2, 0xff, 0x5f, 0xc0, + 0x7e, 0x05, 0xff, 0x9b, 0x83, 0x29, 0xf3, 0x5a, 0xa1, 0x66, 0x22, 0x5f, 0xcf, 0x8d, 0x80, 0xbf, + 0x01, 0x9b, 0x00, 0x7f, 0xa9, 0x91, 0x6f, 0x10, 0xf0, 0xe6, 0x7c, 0xac, 0x57, 0x11, 0x9e, 0x03, + 0x56, 0x58, 0xc0, 0xcf, 0x9c, 0x1f, 0xe8, 0x04, 0x74, 0xfe, 0xb2, 0x2b, 0x31, 0x1f, 0xd0, 0x11, + 0xf8, 0x01, 0xb0, 0xd4, 0x97, 0x5d, 0x91, 0x36, 0xb4, 0xa1, 0x0d, 0x5f, 0x6b, 0x08, 0x78, 0x1b, + 0x18, 0x8d, 0xd7, 0xaa, 0x27, 0x81, 0x55, 0x0a, 0xd2, 0x9d, 0x0d, 0x3c, 0x16, 0xd2, 0x0f, 0x99, + 0x87, 0xe7, 0xfd, 0x1e, 0xb8, 0xb9, 0x99, 0x79, 0x96, 0x00, 0x0e, 0x00, 0xae, 0x06, 0x0e, 0x9b, + 0x87, 0x67, 0x47, 0x6c, 0x0a, 0xfc, 0x0f, 0xf0, 0x40, 0x0b, 0xf2, 0xfe, 0x04, 0x78, 0x0a, 0x98, + 0x0d, 0x34, 0x01, 0x0b, 0x35, 0x90, 0x27, 0xd6, 0xff, 0x1a, 0xea, 0xd7, 0x7f, 0x0c, 0x5e, 0x9f, + 0x17, 0xad, 0x11, 0xbf, 0x06, 0x70, 0x2d, 0xf0, 0x0e, 0x70, 0x74, 0x9d, 0xe7, 0xfe, 0x1c, 0xb8, + 0xaa, 0x81, 0xe7, 0xb6, 0xe1, 0xeb, 0x8b, 0x01, 0x78, 0x5e, 0x5f, 0x40, 0x36, 0x7f, 0xcf, 0x05, + 0x5e, 0x00, 0xfe, 0x8e, 0x37, 0x78, 0x35, 0xd1, 0x1e, 0x78, 0x06, 0xd8, 0x07, 0x58, 0x0d, 0xf8, + 0x6e, 0x88, 0x4f, 0xff, 0x03, 0xac, 0x09, 0x9c, 0x11, 0xfe, 0x6f, 0x06, 0xfc, 0x36, 0x57, 0xce, + 0x2a, 0xc0, 0xaf, 0x81, 0x2e, 0x98, 0xf1, 0xed, 0x14, 0xe2, 0x57, 0x06, 0xc6, 0x03, 0x93, 0x0a, + 0xf2, 0xc4, 0xe7, 0x9f, 0x96, 0x8b, 0x5b, 0x1f, 0xb8, 0x2f, 0xe4, 0x9b, 0x02, 0x5c, 0x49, 0xf5, + 0xa4, 0x89, 0x48, 0xeb, 0xb9, 0x3c, 0x70, 0x13, 0x6e, 0x84, 0x87, 0x42, 0x1d, 0x7e, 0x93, 0x4b, + 0xbf, 0x74, 0xf8, 0x9d, 0x01, 0xbc, 0x1b, 0xfe, 0x77, 0x02, 0x16, 0x29, 0x29, 0xbf, 0xb5, 0xb0, + 0x0e, 0xde, 0x69, 0x4f, 0x0b, 0xd7, 0xbb, 0x00, 0x13, 0xf0, 0x3b, 0x5e, 0x01, 0x2c, 0x96, 0xa4, + 0x6d, 0x0f, 0x6c, 0x0c, 0x1c, 0x1b, 0xd2, 0xa5, 0x58, 0x16, 0xf8, 0x2b, 0x70, 0x1b, 0xf0, 0x3a, + 0x70, 0x07, 0xd9, 0xfb, 0xb7, 0xc3, 0x6d, 0x7c, 0x0f, 0xf0, 0x08, 0x30, 0x11, 0xd8, 0xab, 0xa4, + 0x3e, 0x07, 0xe3, 0x01, 0x13, 0xf1, 0x12, 0x26, 0x7a, 0x69, 0x48, 0xd1, 0x01, 0xf8, 0x45, 0x78, + 0xde, 0x9f, 0xa8, 0x1c, 0x1b, 0x65, 0xe8, 0x1f, 0xea, 0xf0, 0x28, 0x26, 0x72, 0xab, 0x27, 0xf7, + 0x06, 0xe1, 0x81, 0x3b, 0x36, 0xa4, 0xe9, 0xd7, 0x40, 0x79, 0xf3, 0x1b, 0x83, 0x80, 0xfb, 0x81, + 0xb7, 0x80, 0xa1, 0x64, 0x63, 0x38, 0xc5, 0x32, 0xc0, 0xa9, 0xb8, 0xde, 0xf7, 0xe1, 0x85, 0xe6, + 0x69, 0xe0, 0x2c, 0x3c, 0xfe, 0xca, 0xb0, 0x3b, 0xf0, 0x11, 0xc5, 0xe3, 0xb8, 0x2f, 0xf0, 0x30, + 0xee, 0x8f, 0x29, 0xb8, 0xad, 0x26, 0x85, 0xb8, 0x1d, 0x73, 0x69, 0x37, 0xc6, 0x8b, 0xcd, 0xf8, + 0x24, 0xdd, 0x4d, 0x78, 0x81, 0xef, 0x1b, 0xea, 0x13, 0xcb, 0x69, 0x02, 0x1e, 0xc4, 0xf3, 0x7b, + 0x28, 0xf0, 0xad, 0xa4, 0x9c, 0xdd, 0x70, 0x5f, 0xa6, 0x69, 0x63, 0x78, 0x1d, 0xcf, 0xa1, 0x5a, + 0x69, 0xde, 0xa2, 0x92, 0x59, 0x58, 0x07, 0xb8, 0x34, 0xd4, 0x6b, 0x34, 0xf0, 0x04, 0x66, 0x2a, + 0x62, 0x9a, 0x7d, 0x70, 0x7f, 0x0b, 0xcf, 0xbb, 0x3b, 0x92, 0xbc, 0xb7, 0x85, 0x38, 0x85, 0x34, + 0xfb, 0x00, 0x7b, 0xe3, 0x71, 0x13, 0x99, 0x98, 0x7b, 0x93, 0xf4, 0xa7, 0xe0, 0xb9, 0xa3, 0x50, + 0x8f, 0x7b, 0xf0, 0x9c, 0xc9, 0xe7, 0x19, 0x85, 0x17, 0xf1, 0x83, 0x80, 0xd7, 0xf0, 0x9c, 0xbf, + 0x1f, 0x58, 0xb1, 0x20, 0xed, 0x5d, 0x54, 0xa3, 0x77, 0x78, 0x9f, 0xb9, 0xc0, 0xad, 0x05, 0xf7, + 0x23, 0x8e, 0x0c, 0xe5, 0x3c, 0x0a, 0xec, 0x1b, 0xda, 0xe2, 0xa1, 0x10, 0x77, 0x55, 0x2e, 0xed, + 0x51, 0x98, 0xc9, 0xf8, 0x3c, 0xb4, 0xcf, 0xa6, 0xc9, 0xbd, 0x7e, 0xb8, 0x6d, 0xc7, 0x84, 0xe7, + 0x0e, 0x03, 0x56, 0x4a, 0xee, 0x17, 0x8d, 0x93, 0xc7, 0xc3, 0xb3, 0xf6, 0xcf, 0x3d, 0x67, 0xe7, + 0xf0, 0xfe, 0xb1, 0xac, 0x0b, 0x80, 0xae, 0xb9, 0xb2, 0xf2, 0x63, 0xe5, 0x7e, 0xdc, 0x6f, 0x43, + 0x80, 0x85, 0x93, 0xb4, 0xed, 0x31, 0x6d, 0x7f, 0x3c, 0xa4, 0x79, 0x0a, 0x33, 0x29, 0xdd, 0x42, + 0xda, 0xb7, 0xc8, 0xc6, 0x45, 0x5a, 0x5e, 0xac, 0xeb, 0x0f, 0x42, 0x3d, 0x62, 0x7f, 0xdd, 0x15, + 0xca, 0x6c, 0x1f, 0xea, 0x38, 0x3d, 0xdc, 0x7b, 0x08, 0xd8, 0x0e, 0x38, 0x27, 0xa4, 0x13, 0x66, + 0x8c, 0x8e, 0x09, 0xf5, 0x58, 0x2a, 0xd4, 0xe1, 0x23, 0xe0, 0x45, 0xe0, 0x57, 0x21, 0xed, 0xd4, + 0x90, 0xf6, 0x29, 0xe0, 0x50, 0x2c, 0x38, 0x18, 0x85, 0xfb, 0xf5, 0x43, 0x60, 0x1c, 0x5e, 0x53, + 0xb6, 0xc7, 0xe3, 0xe6, 0xb3, 0xd0, 0x26, 0xeb, 0x02, 0x27, 0x01, 0xcf, 0x86, 0xfc, 0x53, 0x81, + 0x8b, 0xc2, 0xb3, 0x2e, 0xc2, 0x4c, 0xd8, 0x9b, 0x98, 0x39, 0x05, 0x33, 0x5d, 0xa3, 0x81, 0x8f, + 0xb1, 0x46, 0xf6, 0x11, 0xa0, 0x4f, 0x78, 0xde, 0x18, 0x4c, 0xdf, 0x5f, 0x04, 0x7e, 0x99, 0x94, + 0xd7, 0x94, 0x0b, 0x9f, 0x85, 0xf7, 0x8d, 0xcf, 0xd8, 0x06, 0x8f, 0x83, 0x5b, 0xf1, 0x7c, 0xcb, + 0xe3, 0x38, 0x3c, 0xb7, 0xe7, 0x15, 0x57, 0x02, 0x3d, 0x30, 0xb3, 0xda, 0x28, 0xba, 0x02, 0xdf, + 0x07, 0x7e, 0x46, 0x25, 0xed, 0x68, 0x29, 0x36, 0x02, 0x76, 0x00, 0xb6, 0x6a, 0x66, 0xbe, 0x6d, + 0x80, 0x11, 0x78, 0x2d, 0x1b, 0x09, 0x7c, 0x8a, 0xd7, 0xba, 0x7a, 0x88, 0xf5, 0xdf, 0x9b, 0xfa, + 0xf5, 0xef, 0x8a, 0x69, 0x7b, 0xc7, 0x1a, 0xf1, 0x6f, 0xe1, 0x79, 0xd4, 0xa5, 0x81, 0xb2, 0xd6, + 0xc5, 0x74, 0xac, 0x35, 0xda, 0xad, 0x0d, 0x5f, 0x4d, 0xfc, 0x09, 0xd3, 0x9c, 0x23, 0x92, 0xb8, + 0xa3, 0xf0, 0xf8, 0xef, 0x8b, 0xd7, 0xa5, 0xda, 0x90, 0xf4, 0xb9, 0xa4, 0xdf, 0x4a, 0x7a, 0x49, + 0xd2, 0x7e, 0x92, 0x08, 0xff, 0xf7, 0x0d, 0xff, 0x91, 0xb4, 0x93, 0xa4, 0x83, 0xc3, 0xff, 0x7e, + 0x92, 0xf6, 0x49, 0xee, 0xfd, 0x58, 0xd2, 0x74, 0x49, 0x47, 0x48, 0x9a, 0x26, 0xe9, 0x77, 0x92, + 0xee, 0x0e, 0xf7, 0xae, 0x95, 0x74, 0xa3, 0xa4, 0xf5, 0x65, 0x7c, 0x3f, 0xc9, 0x87, 0xa4, 0xe3, + 0x25, 0xed, 0x92, 0x8b, 0x7b, 0x41, 0xd2, 0x15, 0xe1, 0xff, 0xda, 0x21, 0xdf, 0xe1, 0xb9, 0x34, + 0x31, 0xa4, 0x75, 0xbe, 0x46, 0xd2, 0xb0, 0xe4, 0xde, 0x6a, 0x92, 0x66, 0x49, 0x5a, 0x37, 0x5c, + 0x2f, 0x2a, 0xe9, 0x7d, 0x49, 0xf7, 0x84, 0xf2, 0x6e, 0x0b, 0x75, 0x9d, 0x21, 0xe9, 0xc8, 0x92, + 0xf2, 0x5b, 0x2b, 0x1c, 0x2f, 0xe9, 0xc4, 0xf0, 0xbf, 0x7b, 0xa8, 0x57, 0x6c, 0x8b, 0x1b, 0x24, + 0x0d, 0x0f, 0xff, 0x3b, 0x4b, 0xba, 0x2f, 0xd4, 0x51, 0x92, 0x86, 0xe4, 0xca, 0xb9, 0x5b, 0xd2, + 0xed, 0xe1, 0x7f, 0x17, 0x49, 0x53, 0x92, 0xeb, 0x5f, 0x84, 0x3c, 0x6b, 0x86, 0xeb, 0xff, 0x92, + 0x34, 0x57, 0xd2, 0x86, 0xb9, 0x32, 0x56, 0x95, 0x34, 0x33, 0xa4, 0x8d, 0x71, 0xd3, 0x6a, 0xd4, + 0x7d, 0x39, 0x49, 0xe3, 0x24, 0x9d, 0x2c, 0xa9, 0x53, 0x12, 0xdf, 0x54, 0x10, 0x1e, 0x94, 0x34, + 0x59, 0xd2, 0x16, 0xa1, 0xfc, 0x1f, 0x86, 0xb4, 0xa3, 0x24, 0x3d, 0x14, 0xfe, 0x1f, 0x1e, 0xfa, + 0x61, 0xf5, 0x70, 0xbd, 0xbd, 0xa4, 0x2f, 0xc2, 0x6f, 0x4b, 0xda, 0x76, 0x39, 0x49, 0x2b, 0x34, + 0x98, 0x76, 0x05, 0x49, 0x5d, 0x4b, 0xee, 0x75, 0x91, 0x74, 0x8c, 0xa4, 0x2b, 0x25, 0xbd, 0x28, + 0xe9, 0x2e, 0x49, 0xed, 0x93, 0xfb, 0x7b, 0x84, 0x76, 0x3a, 0x3a, 0xd7, 0x0e, 0xcb, 0x4a, 0xba, + 0x3c, 0xdc, 0x5b, 0xbb, 0xa4, 0xec, 0x91, 0xa1, 0x3d, 0xf6, 0xaa, 0x51, 0x37, 0xa9, 0xb2, 0xbf, + 0x7f, 0x29, 0x69, 0x8e, 0xa4, 0xf5, 0xc2, 0xf5, 0x00, 0x49, 0xff, 0x96, 0xe7, 0x5b, 0x4c, 0xd3, + 0x41, 0xd2, 0x1b, 0xb9, 0x7c, 0xf9, 0x72, 0x96, 0x96, 0xc7, 0xd7, 0x9b, 0x92, 0xd6, 0xaa, 0xf3, + 0x4c, 0x42, 0x1b, 0xd4, 0x2a, 0x0f, 0x79, 0xde, 0xc4, 0xb8, 0xfd, 0x24, 0xbd, 0x2d, 0xa9, 0xaf, + 0xa4, 0x76, 0x49, 0x9a, 0xe3, 0x43, 0xde, 0x7a, 0xcf, 0x23, 0xc4, 0xe5, 0xd3, 0xd6, 0x4a, 0x5f, + 0xeb, 0x5e, 0x3e, 0xbe, 0xb3, 0xa4, 0xb1, 0x05, 0xef, 0x5e, 0xaf, 0xfc, 0x18, 0x66, 0xca, 0x34, + 0x72, 0xa5, 0x82, 0x7b, 0xed, 0x24, 0xfd, 0xab, 0xa4, 0xee, 0x71, 0x8e, 0xed, 0x5b, 0x70, 0x6f, + 0x4a, 0xee, 0xfa, 0x34, 0x49, 0x8f, 0x4b, 0xfa, 0x4e, 0x12, 0x77, 0x98, 0xdc, 0xdf, 0xf9, 0x31, + 0x95, 0xaf, 0x73, 0x2f, 0x99, 0x9e, 0x44, 0x1a, 0x79, 0xb8, 0xa4, 0x67, 0x24, 0xad, 0x9c, 0xd4, + 0xf1, 0x38, 0x49, 0x2f, 0xe7, 0xca, 0x2f, 0x2a, 0xeb, 0x5b, 0x32, 0x4d, 0x1d, 0x91, 0xc4, 0xfd, + 0x41, 0xd2, 0xd3, 0xf2, 0x38, 0x47, 0x52, 0x47, 0x49, 0x9f, 0x48, 0x3a, 0x34, 0xe4, 0x3d, 0xab, + 0xa4, 0xbc, 0xce, 0xf2, 0xbc, 0x6e, 0x49, 0xdf, 0xef, 0x11, 0xe2, 0x76, 0x2c, 0x48, 0xff, 0xa4, + 0xa4, 0x25, 0x92, 0xeb, 0xed, 0x42, 0xda, 0x9d, 0x72, 0xe9, 0x6e, 0x91, 0xf4, 0x4a, 0x2e, 0x6e, + 0x19, 0x99, 0x16, 0xa5, 0x71, 0x0b, 0xc9, 0x7d, 0xf8, 0x90, 0xb2, 0xf1, 0xdb, 0x41, 0x1e, 0x33, + 0xdf, 0x2d, 0x78, 0xfe, 0xc9, 0xe1, 0x79, 0x9b, 0x24, 0x71, 0x1d, 0x25, 0x3d, 0x20, 0x69, 0xe1, + 0xe4, 0x5d, 0x7f, 0x95, 0xcb, 0xd7, 0x27, 0xc4, 0x1f, 0x54, 0xd0, 0x16, 0x9b, 0xc9, 0x34, 0xbf, + 0x6c, 0x0c, 0x96, 0xb5, 0x5d, 0x73, 0x42, 0xb7, 0x50, 0xc7, 0x2e, 0xcd, 0xcc, 0xd7, 0x1a, 0xcf, + 0xae, 0xd5, 0xd7, 0xf5, 0xc2, 0xf5, 0x92, 0xae, 0x9e, 0x87, 0x67, 0x36, 0x52, 0xff, 0x85, 0x65, + 0xfe, 0xa0, 0x91, 0xf8, 0x46, 0xdb, 0xa3, 0x35, 0xdb, 0xed, 0xeb, 0x10, 0xce, 0xfb, 0x86, 0xb5, + 0x87, 0x72, 0xff, 0x87, 0xd4, 0xb8, 0x2e, 0x0c, 0xed, 0x81, 0x99, 0x78, 0xd7, 0xff, 0x0a, 0x96, + 0xa0, 0x12, 0x7e, 0x5f, 0x4a, 0x78, 0xf8, 0xd5, 0x81, 0x97, 0xc3, 0xff, 0xd5, 0x42, 0xda, 0x88, + 0x73, 0xb1, 0x24, 0xe5, 0x02, 0xac, 0x76, 0x1a, 0x89, 0x25, 0x20, 0x2b, 0x02, 0xdb, 0x62, 0xe9, + 0xc7, 0xf3, 0x21, 0x6d, 0xaf, 0x24, 0xdf, 0x7a, 0x58, 0xb2, 0x7e, 0x5b, 0x6e, 0xbf, 0xb0, 0x34, + 0x99, 0xda, 0x6a, 0x66, 0xf8, 0xfd, 0xa4, 0x64, 0x6f, 0x11, 0xeb, 0xbc, 0x1e, 0x96, 0x3c, 0x9d, + 0x93, 0xbb, 0x77, 0x27, 0x96, 0xb4, 0x01, 0xcc, 0x02, 0x96, 0xc3, 0xbb, 0x97, 0x6d, 0x80, 0xef, + 0x61, 0x89, 0xdc, 0x3a, 0xc0, 0x79, 0x05, 0x65, 0xcf, 0xab, 0x2a, 0x31, 0xc5, 0x6e, 0x64, 0x6a, + 0xc5, 0xc3, 0xb1, 0x94, 0xe7, 0x99, 0x70, 0x7d, 0x19, 0x56, 0x83, 0x2d, 0x8f, 0xdf, 0xb3, 0x37, + 0xde, 0x71, 0xe5, 0xb1, 0x10, 0x6e, 0xbf, 0x7f, 0x86, 0xeb, 0x19, 0xc0, 0x0d, 0x64, 0x6d, 0xba, + 0x08, 0x96, 0xa2, 0xbe, 0x10, 0xae, 0xaf, 0xc0, 0xd2, 0xa9, 0x54, 0xfa, 0xda, 0x0e, 0xbf, 0xeb, + 0x8d, 0xb9, 0xb2, 0x67, 0x52, 0x8c, 0x8e, 0xa1, 0xde, 0x97, 0x62, 0x95, 0xe4, 0xa7, 0xc9, 0xbd, + 0x5e, 0x05, 0xe1, 0x66, 0x2c, 0x5d, 0x8b, 0x75, 0x7a, 0x38, 0xfc, 0x8e, 0xc7, 0x52, 0x5f, 0x70, + 0xfb, 0xdf, 0x40, 0x36, 0xbe, 0xee, 0xc1, 0x12, 0xad, 0xe3, 0x4a, 0xea, 0x50, 0x86, 0x0e, 0x58, + 0xda, 0x3d, 0x09, 0xf7, 0x67, 0x23, 0xd8, 0x06, 0x4b, 0xba, 0x8f, 0x08, 0xf9, 0x53, 0xcc, 0xc0, + 0xbb, 0xdd, 0xfd, 0x71, 0xfd, 0x77, 0xc0, 0x12, 0x6f, 0x80, 0x3d, 0xb0, 0xf4, 0xa9, 0x2f, 0x96, + 0x42, 0xa7, 0xed, 0x30, 0x1d, 0x38, 0x10, 0x98, 0x8c, 0xa5, 0x6c, 0x79, 0xa9, 0x4e, 0x27, 0x2c, + 0x01, 0x7d, 0x93, 0xe6, 0x69, 0x08, 0x86, 0xe1, 0xf6, 0xdf, 0x19, 0xd8, 0x00, 0xf8, 0x33, 0x96, + 0x7c, 0xdd, 0x9e, 0xa4, 0x99, 0x4b, 0x36, 0x8e, 0xca, 0x30, 0x13, 0xab, 0xd8, 0x9e, 0x0b, 0xef, + 0x50, 0x0f, 0x77, 0x63, 0xa9, 0x60, 0x2d, 0xdc, 0x12, 0xd2, 0xac, 0x07, 0x0c, 0xc7, 0x52, 0x80, + 0xeb, 0xa8, 0xd4, 0xc6, 0x3c, 0x1c, 0xea, 0xf7, 0x65, 0xe3, 0xaf, 0xc0, 0x99, 0x64, 0x34, 0xa8, + 0xb9, 0xf8, 0x04, 0x4b, 0x6b, 0x07, 0x16, 0xdc, 0xdb, 0x8e, 0x72, 0x8d, 0xc9, 0x87, 0x58, 0x9a, + 0x7e, 0x11, 0xa6, 0x73, 0x65, 0xf8, 0x11, 0x70, 0x02, 0x96, 0xb4, 0xa5, 0xa6, 0x76, 0x17, 0x63, + 0xfa, 0x34, 0xbc, 0x4e, 0xfd, 0x9a, 0xb0, 0x9a, 0xf4, 0x38, 0x4c, 0xd3, 0x86, 0xe2, 0xf1, 0xf8, + 0x5a, 0xb8, 0x2f, 0x6c, 0x1e, 0x31, 0x19, 0xb8, 0xb0, 0x4e, 0x59, 0xff, 0x06, 0xae, 0xc7, 0xe3, + 0x3c, 0x62, 0x20, 0xa6, 0x39, 0x51, 0xe2, 0xfb, 0x39, 0x1e, 0x23, 0xef, 0x03, 0xef, 0xe1, 0x77, + 0x2c, 0xc2, 0x27, 0x98, 0x16, 0xb4, 0x04, 0xf1, 0x79, 0x3f, 0xcb, 0xc5, 0xaf, 0x87, 0x25, 0xf3, + 0x1f, 0x26, 0x71, 0xe3, 0xb0, 0x34, 0x7b, 0xbb, 0x24, 0x6e, 0x09, 0xac, 0x95, 0x58, 0x15, 0x4b, + 0x6c, 0x23, 0xb6, 0xc3, 0x1a, 0xaf, 0x14, 0x73, 0xb0, 0x74, 0x7e, 0x0b, 0x32, 0x13, 0xc9, 0x23, + 0x70, 0x3b, 0x4c, 0x2d, 0xa8, 0xdb, 0xf9, 0xe1, 0xf9, 0xa9, 0x69, 0xc3, 0xcf, 0x80, 0x7f, 0xe0, + 0xf5, 0x0f, 0xe0, 0x55, 0xac, 0x09, 0x88, 0x58, 0x1c, 0x8f, 0x83, 0x51, 0x14, 0xf7, 0xe7, 0xa3, + 0x58, 0x3b, 0x3d, 0x3f, 0x4d, 0xea, 0x5e, 0xc6, 0x9a, 0xd8, 0x0f, 0xeb, 0x25, 0xfc, 0x0f, 0xc3, + 0xa6, 0x64, 0xbc, 0xc7, 0xfc, 0xc2, 0x6c, 0x8a, 0xcf, 0xa7, 0xcd, 0xa6, 0x31, 0x13, 0x9a, 0x36, + 0xd4, 0xc7, 0xe6, 0x5f, 0x76, 0x05, 0xbe, 0x6a, 0x68, 0x8f, 0xd5, 0x7f, 0xef, 0x60, 0xa6, 0x2e, + 0x32, 0x4c, 0x2f, 0x90, 0x4d, 0x88, 0x26, 0xcc, 0xe0, 0x9e, 0x12, 0xfe, 0x0f, 0xc6, 0x8b, 0x5d, + 0x53, 0xb8, 0xbf, 0x12, 0x95, 0xea, 0xfa, 0x67, 0x31, 0x03, 0xff, 0x06, 0x66, 0xb4, 0x3f, 0x0b, + 0x01, 0x32, 0x95, 0xd0, 0xc2, 0xd8, 0x9c, 0xe5, 0xbf, 0x0b, 0xea, 0x34, 0x18, 0x2f, 0x0e, 0xfd, + 0x31, 0x23, 0x79, 0x35, 0x66, 0x34, 0x7b, 0x61, 0x46, 0x64, 0x36, 0x56, 0x6f, 0x76, 0x49, 0xea, + 0xdc, 0x3f, 0xfc, 0x9f, 0x94, 0x2b, 0xeb, 0x06, 0x6c, 0xaf, 0x16, 0xcd, 0x59, 0xe6, 0x60, 0x62, + 0xdd, 0x15, 0xdb, 0xe1, 0xf5, 0xc6, 0xea, 0xaa, 0xf9, 0x89, 0xae, 0x58, 0xbd, 0xf5, 0x74, 0xb8, + 0xee, 0x85, 0x99, 0xf3, 0x88, 0xa7, 0x30, 0xa3, 0xb8, 0x75, 0x9d, 0x72, 0xe6, 0x60, 0x55, 0xf2, + 0xc5, 0x49, 0xdc, 0xdc, 0x10, 0x0f, 0x5e, 0x78, 0xf7, 0x48, 0xee, 0xc5, 0x77, 0x7e, 0x23, 0x89, + 0x3b, 0x0a, 0x9b, 0x14, 0xbc, 0x9a, 0x2b, 0xbb, 0xec, 0x70, 0xcb, 0x01, 0x98, 0xe9, 0x1f, 0x51, + 0xa7, 0x6e, 0x60, 0xd3, 0x9c, 0x63, 0x71, 0x9f, 0x45, 0xc6, 0xa0, 0x77, 0xf8, 0x5d, 0x15, 0x2f, + 0xa2, 0xf1, 0x7f, 0x7e, 0xd1, 0x7b, 0x0c, 0x9b, 0x4b, 0xdd, 0x8d, 0xc7, 0x4f, 0x6a, 0xd3, 0x5e, + 0x14, 0xb7, 0x35, 0x5e, 0xd0, 0x76, 0x0c, 0xff, 0x47, 0x62, 0x26, 0xa2, 0xa9, 0x46, 0xe8, 0x10, + 0xd2, 0x6d, 0x8d, 0x37, 0x3f, 0x8f, 0x51, 0xde, 0xe6, 0x91, 0x71, 0x5f, 0x03, 0x6f, 0xe8, 0x46, + 0xe0, 0x8d, 0xda, 0x03, 0xa1, 0x1e, 0x97, 0x60, 0xe6, 0xb3, 0x09, 0xab, 0xa4, 0x85, 0x4d, 0x5b, + 0x36, 0xc2, 0x8b, 0x7c, 0x8a, 0x9d, 0x31, 0x93, 0x75, 0x0b, 0x99, 0x1a, 0xbc, 0x11, 0xc4, 0x74, + 0xef, 0xe2, 0x39, 0xf1, 0x34, 0xc5, 0xe6, 0x17, 0x3b, 0xe1, 0x8d, 0x53, 0x2d, 0x08, 0x6f, 0x3c, + 0x36, 0xa3, 0xd2, 0x94, 0x22, 0x8f, 0x89, 0x78, 0x0e, 0xdd, 0x5e, 0x23, 0xcd, 0xe3, 0x98, 0x31, + 0xbf, 0x1d, 0x9b, 0x3b, 0x4c, 0x22, 0xdb, 0x30, 0xa6, 0x18, 0x43, 0xb5, 0x9a, 0x78, 0x41, 0xe3, + 0x58, 0xea, 0xbf, 0x4f, 0x3d, 0xcc, 0x06, 0x2e, 0xc7, 0xa6, 0x60, 0xf9, 0xf7, 0xf9, 0x05, 0x99, + 0xd9, 0x43, 0x1e, 0x73, 0x31, 0xc3, 0xdd, 0x9e, 0x6c, 0xa3, 0x5c, 0x84, 0xa3, 0x30, 0x23, 0xf7, + 0x5c, 0xc1, 0xbd, 0xe1, 0xc0, 0x96, 0xc0, 0x86, 0x75, 0xea, 0x38, 0x15, 0x9f, 0x67, 0x39, 0x12, + 0xcf, 0x95, 0x22, 0x86, 0xf9, 0x52, 0x4c, 0x0b, 0x8b, 0x6c, 0x9b, 0x53, 0x74, 0xa5, 0x9a, 0x1e, + 0x6c, 0x43, 0xa5, 0xa9, 0xcb, 0x4f, 0xf0, 0x7b, 0x9f, 0x87, 0x37, 0x06, 0x65, 0xf8, 0x51, 0x9d, + 0x67, 0x95, 0x61, 0x36, 0x36, 0xdf, 0xda, 0x83, 0x4a, 0x93, 0xc3, 0x7e, 0x05, 0xcf, 0xfb, 0x0c, + 0x33, 0xdc, 0xa9, 0x40, 0x63, 0x17, 0xbc, 0x21, 0x79, 0x0f, 0xf8, 0x69, 0x12, 0xbf, 0x03, 0x95, + 0x26, 0x52, 0x11, 0xb7, 0x87, 0x70, 0x26, 0x9e, 0xf3, 0xbb, 0x62, 0x61, 0x53, 0x11, 0x66, 0xe0, + 0xf9, 0xdf, 0x8f, 0xec, 0x0c, 0xd1, 0x00, 0x2a, 0xcf, 0x38, 0xad, 0x8a, 0x05, 0x12, 0x11, 0x67, + 0x60, 0x3a, 0x52, 0xb4, 0xc1, 0x03, 0xcf, 0xcf, 0xbb, 0x30, 0xad, 0x68, 0x04, 0x7f, 0xc4, 0x1b, + 0x92, 0x7a, 0x7d, 0x99, 0xc7, 0x0c, 0xbc, 0xb9, 0x02, 0x0b, 0x4b, 0x6e, 0xc4, 0xc2, 0x91, 0x29, + 0xa1, 0xcc, 0x32, 0x73, 0x91, 0x65, 0xf0, 0xe6, 0xe2, 0x6e, 0x4c, 0xdb, 0x8f, 0x4f, 0xee, 0x6d, + 0x8e, 0x37, 0x1d, 0x0f, 0xe1, 0x7e, 0xf8, 0x75, 0x72, 0x6f, 0x0f, 0x4c, 0xb7, 0xee, 0xc7, 0x82, + 0xa3, 0xef, 0x15, 0x94, 0xbd, 0x1e, 0x16, 0xea, 0x8c, 0xc6, 0x63, 0xf7, 0x22, 0x4c, 0xfb, 0x36, + 0xc4, 0x7d, 0xb2, 0x0a, 0xde, 0x34, 0x35, 0xe1, 0x35, 0x3b, 0xc5, 0x31, 0x78, 0xdd, 0x7f, 0x28, + 0xe4, 0x3f, 0x10, 0xcf, 0xd5, 0x23, 0x73, 0xe9, 0x3a, 0x63, 0x13, 0xa6, 0x6b, 0x30, 0xbf, 0x73, + 0x13, 0x19, 0xd3, 0xdd, 0x13, 0xcf, 0xcf, 0xf7, 0x72, 0x79, 0x76, 0x0f, 0xf5, 0x7a, 0x97, 0x72, + 0x5c, 0x8b, 0x37, 0xa1, 0xaf, 0x51, 0x3e, 0x5e, 0xc0, 0x66, 0xa0, 0xe7, 0x63, 0x01, 0xc1, 0x40, + 0xbc, 0x81, 0xbe, 0x0f, 0x0b, 0x4e, 0x06, 0x62, 0x81, 0xd0, 0xd5, 0xd8, 0xec, 0xf5, 0x4e, 0xb2, + 0x31, 0x9f, 0xe6, 0x1b, 0x00, 0xfc, 0x01, 0x6f, 0x1a, 0xdf, 0xc6, 0x9b, 0xc1, 0x74, 0xe3, 0xb0, + 0x15, 0x1e, 0xdb, 0x63, 0x31, 0x7d, 0x3e, 0x33, 0x29, 0xa7, 0x1b, 0x5e, 0x23, 0x26, 0x61, 0x7a, + 0x33, 0x02, 0xf7, 0xd9, 0x2b, 0xd8, 0x3c, 0x2c, 0xa2, 0x2f, 0xde, 0xc4, 0x8f, 0x0b, 0xcf, 0xd9, + 0x9d, 0x4a, 0x41, 0x4d, 0x47, 0x3c, 0xee, 0x1f, 0xc4, 0x63, 0xf5, 0xa0, 0xf0, 0x0e, 0x23, 0xb0, + 0x00, 0xf7, 0x5e, 0xdc, 0x17, 0x13, 0xc9, 0x04, 0xa5, 0x9b, 0xe0, 0xf5, 0xa1, 0x07, 0xe6, 0xd3, + 0x9a, 0x30, 0xdf, 0xd7, 0x19, 0x9b, 0x88, 0x5e, 0x4c, 0xc6, 0xb7, 0x2c, 0x1e, 0xe2, 0x2e, 0x49, + 0xe2, 0xc6, 0xe2, 0xf9, 0xf1, 0x6f, 0xdc, 0x4f, 0x4b, 0xe3, 0xf1, 0xf4, 0x19, 0x9e, 0x33, 0xf1, + 0xfe, 0x54, 0x3c, 0xf6, 0xb6, 0xc2, 0x63, 0x2e, 0x9a, 0x1a, 0xae, 0x1e, 0xea, 0xf7, 0x41, 0xa8, + 0xd7, 0xd2, 0x58, 0xa0, 0xfc, 0x01, 0x16, 0xb2, 0x9d, 0x84, 0x85, 0x27, 0x93, 0xf0, 0xc6, 0xf5, + 0xa4, 0xd0, 0xae, 0x0f, 0x27, 0xcf, 0x1d, 0x81, 0x85, 0xcd, 0xe3, 0xc3, 0x73, 0xa3, 0x49, 0xe0, + 0x13, 0x64, 0xfc, 0xc5, 0x4c, 0x2c, 0xc4, 0x69, 0x3d, 0x48, 0x1a, 0x2d, 0x69, 0x9b, 0x3a, 0x22, + 0xf6, 0x7f, 0x24, 0xff, 0x6f, 0xcc, 0xdd, 0xbb, 0x55, 0x56, 0xfb, 0x0e, 0x91, 0xf4, 0x7a, 0xee, + 0xde, 0x9b, 0xb2, 0xda, 0xb3, 0x73, 0x10, 0xe5, 0x1f, 0x12, 0xe2, 0x4f, 0x93, 0x55, 0x97, 0xd7, + 0xc9, 0xea, 0xc4, 0x9f, 0xe7, 0xf2, 0x9d, 0x13, 0xd2, 0xff, 0x2e, 0x17, 0xbf, 0xa8, 0x6c, 0x8e, + 0x92, 0xaf, 0xdf, 0x63, 0xca, 0x4c, 0x61, 0xd2, 0x10, 0xcd, 0x62, 0x52, 0xd3, 0x99, 0x97, 0x64, + 0x95, 0x64, 0x67, 0x49, 0x4f, 0xd4, 0x51, 0x4b, 0xb4, 0x86, 0x1a, 0xe6, 0x20, 0x49, 0xe7, 0x26, + 0xd7, 0x1f, 0x4a, 0x3a, 0x3d, 0xb9, 0x5e, 0x24, 0x3c, 0xeb, 0x98, 0x16, 0x3c, 0xff, 0x61, 0xd9, + 0x74, 0x28, 0x1f, 0xdf, 0x49, 0x56, 0x4d, 0x8f, 0x56, 0xa6, 0x6a, 0xed, 0x2e, 0xe9, 0x9f, 0xb2, + 0xea, 0x76, 0x48, 0x28, 0x3f, 0xa6, 0x7f, 0x47, 0x36, 0xe3, 0x78, 0x54, 0xd2, 0x9d, 0x92, 0x7e, + 0x12, 0xe2, 0x9b, 0x24, 0x5d, 0x26, 0xe9, 0x8f, 0xb2, 0x49, 0xcd, 0x04, 0x49, 0x83, 0x55, 0x69, + 0xee, 0x11, 0xc3, 0x60, 0xd9, 0x24, 0x27, 0xbe, 0xd3, 0xe3, 0xb2, 0x5a, 0x7e, 0x50, 0xa8, 0x67, + 0x34, 0x3d, 0xc9, 0xab, 0xcd, 0x91, 0xfb, 0x79, 0x8e, 0xa4, 0xe7, 0x64, 0x73, 0x80, 0xa5, 0x93, + 0x7b, 0x69, 0xdc, 0x77, 0xe4, 0x7e, 0x7e, 0x4a, 0xd2, 0xb6, 0xf3, 0xd8, 0x2f, 0xdb, 0x86, 0x72, + 0xae, 0x50, 0xa6, 0xee, 0xef, 0x2a, 0x8f, 0xcd, 0xb7, 0x42, 0x3f, 0x7d, 0x2f, 0xf4, 0xd5, 0x0c, + 0x79, 0xbc, 0xb4, 0x97, 0xcd, 0x88, 0xa2, 0x2a, 0x7f, 0x7f, 0x59, 0xed, 0x8a, 0xa4, 0xa5, 0x42, + 0x9b, 0xe6, 0x4d, 0xa4, 0xae, 0x96, 0xcd, 0xba, 0x76, 0x0a, 0xf7, 0xfb, 0x96, 0xd4, 0x47, 0xaa, + 0x34, 0x09, 0xb8, 0x28, 0xb4, 0x61, 0x67, 0xd9, 0x64, 0xe6, 0x82, 0x06, 0xdf, 0x2b, 0x2d, 0x27, + 0x0d, 0x5d, 0xc3, 0xbd, 0x41, 0x35, 0xd2, 0xce, 0x68, 0xa0, 0xbc, 0x77, 0x92, 0xff, 0x6f, 0x34, + 0xa3, 0x5e, 0xb5, 0xea, 0x96, 0x1f, 0x8f, 0x8d, 0xcc, 0x81, 0xb2, 0x7b, 0x31, 0x7e, 0x1b, 0x49, + 0x1f, 0xa9, 0xb6, 0x1a, 0xbf, 0x56, 0xf9, 0x31, 0x4c, 0x91, 0xc7, 0x81, 0x24, 0xfd, 0x34, 0x89, + 0x5f, 0x59, 0xd2, 0xdf, 0x6a, 0xd4, 0x7d, 0x4a, 0xf8, 0xfd, 0x79, 0xb8, 0x7f, 0x42, 0xc1, 0x3d, + 0xe4, 0x39, 0x72, 0x5e, 0xc9, 0xb3, 0x97, 0x0d, 0x79, 0x0f, 0xab, 0x53, 0xe7, 0x5b, 0x65, 0x3a, + 0xfa, 0xa2, 0xa4, 0xbf, 0x96, 0x94, 0xb5, 0x62, 0xc8, 0x7b, 0x40, 0x8d, 0xb2, 0x76, 0x93, 0xf4, + 0xa9, 0x2a, 0xc7, 0xf0, 0x69, 0x21, 0xdd, 0x64, 0xd9, 0x74, 0x6e, 0x89, 0x82, 0xb2, 0xe7, 0xa5, + 0xbf, 0xca, 0xda, 0x6f, 0xf3, 0x10, 0xbf, 0x47, 0x12, 0x97, 0x37, 0x69, 0x89, 0xe1, 0x50, 0xd9, + 0x84, 0x66, 0xf9, 0x70, 0x7d, 0x9d, 0xdc, 0x3f, 0x97, 0x4a, 0x9a, 0x94, 0xa4, 0x7b, 0x4a, 0x36, + 0x59, 0x29, 0xaa, 0xdf, 0x5a, 0x92, 0x66, 0xcb, 0x73, 0x3f, 0x6f, 0x0a, 0x98, 0x0f, 0xdf, 0x96, + 0x4d, 0x89, 0x4e, 0x97, 0xe7, 0xf5, 0xa9, 0x35, 0xd2, 0xf6, 0x90, 0xcd, 0x0b, 0x8f, 0xab, 0xd3, + 0x16, 0x7d, 0x24, 0x5d, 0xd5, 0x40, 0xdb, 0xad, 0x2b, 0xd3, 0xd0, 0xa3, 0x55, 0xbd, 0x16, 0x37, + 0x1a, 0xba, 0x48, 0x7a, 0x2f, 0xa9, 0x77, 0x8f, 0xf0, 0x8c, 0x3e, 0x25, 0xcf, 0x1e, 0xab, 0xcc, + 0x1c, 0x70, 0x53, 0x99, 0x56, 0xf7, 0x97, 0xd7, 0xd1, 0x4f, 0x94, 0xad, 0xaf, 0x2b, 0x84, 0xf4, + 0x07, 0xc9, 0xe6, 0x46, 0x73, 0x24, 0xf5, 0x0e, 0xf7, 0x3a, 0xcb, 0x6b, 0xb7, 0x92, 0xb2, 0xd7, + 0x95, 0x4d, 0x62, 0xb7, 0x08, 0xd7, 0x8b, 0xc9, 0x34, 0x2f, 0x1d, 0xc3, 0x45, 0x6d, 0x15, 0xdb, + 0x4b, 0x92, 0x76, 0x0e, 0xd7, 0xdb, 0xc8, 0xfd, 0xb7, 0xaf, 0x2a, 0xcd, 0x91, 0x24, 0x8f, 0x81, + 0x68, 0x1e, 0xb6, 0x59, 0x88, 0x8b, 0xe3, 0x6a, 0xb0, 0xbc, 0xae, 0xa5, 0xf5, 0x42, 0x36, 0xe3, + 0x1d, 0x53, 0x10, 0x9f, 0xd6, 0x67, 0x67, 0xd9, 0x9c, 0xb6, 0x68, 0x3d, 0x4c, 0xd3, 0x2d, 0xa9, + 0x8c, 0xfe, 0x3f, 0x2a, 0x9b, 0x8f, 0x21, 0x9b, 0x5e, 0xcd, 0x91, 0x4d, 0x16, 0x51, 0x66, 0xfe, + 0xbb, 0x77, 0x41, 0xbe, 0x27, 0x64, 0x53, 0x5d, 0x94, 0x99, 0x8d, 0xc6, 0x77, 0xe8, 0x21, 0xd3, + 0xba, 0x2d, 0xc3, 0xf5, 0x42, 0xa1, 0xec, 0x1b, 0x92, 0x77, 0x3e, 0x25, 0xe4, 0xb9, 0x47, 0xd9, + 0xfa, 0xda, 0x43, 0xe6, 0xdd, 0xf6, 0x93, 0xcd, 0x4a, 0xe7, 0x28, 0xe3, 0x05, 0x17, 0x97, 0xd7, + 0xfc, 0xf4, 0xfd, 0xf7, 0x97, 0x4d, 0xdc, 0x24, 0xd3, 0xfd, 0xe1, 0x72, 0x9f, 0x9e, 0x1e, 0xde, + 0x2b, 0x9a, 0x15, 0xaf, 0x2f, 0xd3, 0x91, 0x5a, 0xf3, 0xbf, 0x43, 0x78, 0x56, 0x1a, 0x5f, 0x14, + 0x87, 0xa4, 0x67, 0x55, 0xc9, 0xf7, 0x2d, 0x16, 0x9e, 0x17, 0xaf, 0xff, 0xa5, 0x4a, 0x93, 0xe6, + 0x03, 0x42, 0x19, 0x3f, 0x4c, 0xe2, 0x26, 0x84, 0x7c, 0xf1, 0x7a, 0xaf, 0xf0, 0xee, 0x9b, 0x86, + 0xeb, 0xf3, 0x25, 0xed, 0x9a, 0xab, 0xf3, 0x73, 0x72, 0xff, 0xc6, 0xeb, 0xc8, 0xd7, 0xc4, 0xf7, + 0x89, 0xfd, 0xb8, 0xbe, 0x3c, 0xf6, 0xe2, 0xda, 0xba, 0x84, 0xcc, 0x3f, 0x94, 0xbd, 0xfb, 0x7b, + 0x32, 0x4f, 0x85, 0x6c, 0xba, 0xf7, 0xa0, 0x3c, 0x97, 0x57, 0x49, 0xd2, 0x5c, 0xda, 0x3e, 0xec, + 0x0c, 0xde, 0xae, 0xc3, 0xc3, 0xa7, 0x3b, 0xea, 0xbc, 0xfa, 0xa7, 0x3f, 0x96, 0x0a, 0x9e, 0x82, + 0x77, 0x7a, 0xa3, 0xf1, 0x6e, 0x18, 0xbc, 0x63, 0xda, 0x00, 0x1f, 0xc8, 0x99, 0x8b, 0x77, 0xe9, + 0x3d, 0xb0, 0xa4, 0x7d, 0x27, 0xac, 0x7e, 0x3c, 0x12, 0x9b, 0x76, 0xac, 0x8a, 0xa5, 0x33, 0x23, + 0xf0, 0xee, 0xfe, 0x58, 0xac, 0x3a, 0xec, 0x99, 0x3c, 0xab, 0x2f, 0xde, 0xd1, 0xe5, 0xb1, 0x06, + 0xd9, 0x61, 0xcb, 0x14, 0x53, 0x93, 0xfb, 0x11, 0xab, 0x63, 0xa9, 0xe9, 0x27, 0x54, 0xaa, 0x3c, + 0x37, 0xa7, 0xfa, 0x40, 0x64, 0xff, 0xe4, 0xfa, 0x22, 0x5a, 0x86, 0xdd, 0x70, 0xfb, 0x44, 0x74, + 0x26, 0x93, 0x76, 0x43, 0xa6, 0x0a, 0x6d, 0xae, 0x07, 0x94, 0x1f, 0xe1, 0x76, 0x3e, 0x31, 0x17, + 0x7f, 0x33, 0x96, 0x26, 0x6c, 0x82, 0x0f, 0x27, 0xcd, 0xc6, 0x3b, 0xde, 0x8b, 0xc8, 0x0e, 0x2b, + 0xe5, 0xf1, 0x6d, 0x2c, 0x85, 0xde, 0x0c, 0x4b, 0x97, 0xaf, 0xc7, 0x3b, 0xf5, 0x0d, 0x80, 0xb5, + 0xf1, 0x4e, 0x73, 0x07, 0x6c, 0x7e, 0x73, 0x42, 0x08, 0x29, 0x3a, 0x63, 0xb5, 0x7a, 0x34, 0x0f, + 0xfa, 0x0c, 0x4b, 0x89, 0x3f, 0xc2, 0x3b, 0xff, 0xe7, 0xb0, 0x59, 0x11, 0x58, 0x82, 0xdb, 0x17, + 0x4b, 0x04, 0xc1, 0x63, 0x60, 0x03, 0xac, 0xbd, 0xd9, 0x08, 0x8f, 0x83, 0xd4, 0xcc, 0x26, 0x8d, + 0x7b, 0x2e, 0xfc, 0x6e, 0x8c, 0x77, 0xfe, 0xf3, 0x82, 0x51, 0xa1, 0x9c, 0xe9, 0x64, 0x52, 0xcb, + 0xe1, 0x58, 0xda, 0x39, 0x1c, 0x8f, 0xd9, 0xc9, 0x58, 0x8a, 0x76, 0x1f, 0x1e, 0x2f, 0x03, 0x43, + 0x5d, 0x63, 0x9b, 0xaf, 0x81, 0xc7, 0x12, 0x58, 0x92, 0x05, 0x95, 0x87, 0x7b, 0x17, 0xc5, 0xd2, + 0xa2, 0x89, 0xa1, 0x8c, 0x0f, 0xa9, 0x6d, 0xda, 0xd2, 0x1f, 0xef, 0xca, 0xa7, 0x61, 0xc9, 0x51, + 0xdf, 0xf0, 0xdc, 0xe5, 0x28, 0x37, 0x3d, 0x6a, 0x14, 0x33, 0xc2, 0xef, 0xd2, 0xb9, 0xf8, 0xfe, + 0x64, 0x63, 0xbc, 0x4c, 0xad, 0x9e, 0xa6, 0x59, 0x36, 0x89, 0xef, 0x5a, 0x50, 0xaf, 0x65, 0xb0, + 0xf9, 0x40, 0x1a, 0xca, 0xca, 0x8a, 0xa1, 0x7f, 0xad, 0x8a, 0xb7, 0x00, 0x2b, 0xe1, 0xc3, 0xe0, + 0xef, 0x53, 0x7d, 0x28, 0xbc, 0x25, 0x98, 0x8c, 0x35, 0x01, 0x87, 0x26, 0x71, 0x87, 0x51, 0xdb, + 0x23, 0x54, 0xc4, 0x15, 0xd8, 0x9c, 0xe8, 0x54, 0x8a, 0x0f, 0xf7, 0x2d, 0x43, 0xb9, 0xe6, 0x2a, + 0xb6, 0x6d, 0xd9, 0x21, 0xb4, 0x4e, 0x58, 0xab, 0xf2, 0x43, 0x2c, 0x11, 0xfb, 0x2e, 0xa6, 0xe7, + 0x45, 0x88, 0xf1, 0xdf, 0xc9, 0xc5, 0xf7, 0xc7, 0x92, 0xa8, 0xe9, 0x78, 0x9e, 0xef, 0x4e, 0xa5, + 0x99, 0xdf, 0xc9, 0xb8, 0x0d, 0x57, 0xc2, 0x26, 0x42, 0x53, 0xf1, 0xf8, 0xcf, 0x9b, 0x85, 0xb5, + 0x36, 0x1e, 0xc1, 0xde, 0xb8, 0xf6, 0x09, 0xd7, 0xeb, 0x61, 0x49, 0x5f, 0x91, 0x59, 0xc6, 0x1d, + 0x78, 0x8d, 0xda, 0x16, 0xd3, 0xa2, 0xef, 0x60, 0x69, 0xe6, 0x75, 0xf8, 0x50, 0xe0, 0x9a, 0x40, + 0x77, 0x7c, 0x60, 0xb3, 0xcc, 0xd4, 0xea, 0x79, 0xdc, 0x57, 0x5d, 0x4a, 0x9e, 0x91, 0xe2, 0x2d, + 0xbc, 0x66, 0x1d, 0x82, 0xd7, 0xa8, 0x22, 0xb3, 0x48, 0xb0, 0x04, 0x6e, 0x18, 0x96, 0xb0, 0x0d, + 0xad, 0x53, 0xe6, 0x28, 0x4c, 0xd3, 0xeb, 0x69, 0x9b, 0x2e, 0xc4, 0x6b, 0xe3, 0x39, 0x98, 0x6e, + 0xef, 0x54, 0x27, 0x7d, 0x11, 0x16, 0xc5, 0xa6, 0x84, 0x97, 0x87, 0xeb, 0xa8, 0x69, 0xd9, 0xa0, + 0x24, 0xfd, 0x7d, 0x98, 0x3e, 0xc7, 0xb4, 0x77, 0x60, 0x93, 0xc2, 0xdf, 0x61, 0xc9, 0x65, 0x34, + 0x4d, 0x9d, 0x86, 0xc7, 0xd0, 0x6c, 0x3c, 0x66, 0xee, 0x25, 0x33, 0x23, 0xfa, 0x84, 0x6a, 0x8d, + 0xce, 0x19, 0x58, 0xfa, 0x19, 0xcd, 0x1f, 0x3f, 0xc6, 0x63, 0xb1, 0x2f, 0xf5, 0xb1, 0x6e, 0xf8, + 0x6d, 0x0a, 0xbf, 0x0f, 0xe3, 0xf6, 0x5e, 0x89, 0x6a, 0xcd, 0xec, 0xf5, 0x64, 0x34, 0xfe, 0x89, + 0xf0, 0xdb, 0x3d, 0xfc, 0xfe, 0x2f, 0xc5, 0x9a, 0xbf, 0x4b, 0x31, 0x2f, 0x53, 0x86, 0x1e, 0x58, + 0x72, 0x7f, 0x20, 0xf5, 0x5d, 0x36, 0x7f, 0x80, 0x25, 0xe2, 0xe0, 0xb6, 0x8a, 0x73, 0x71, 0x22, + 0xee, 0xef, 0xcb, 0xc2, 0x75, 0x34, 0x51, 0x5c, 0xa3, 0x20, 0xdf, 0xcd, 0x64, 0xe6, 0xc4, 0xb1, + 0x1d, 0xe3, 0x3b, 0x9c, 0x4e, 0xa6, 0xbd, 0x00, 0xf3, 0x17, 0xa7, 0x62, 0xe9, 0xf3, 0x16, 0xb8, + 0xaf, 0x4f, 0x0d, 0xf7, 0x1e, 0x20, 0xa3, 0x2b, 0xe3, 0x43, 0xf9, 0x47, 0x91, 0xf5, 0x57, 0x7c, + 0xe7, 0x8f, 0xb0, 0x84, 0x3c, 0xc5, 0x95, 0x64, 0xbc, 0xdd, 0x76, 0x78, 0x3d, 0xdc, 0x05, 0x3b, + 0xa2, 0x58, 0x07, 0x5b, 0x4c, 0x74, 0xc6, 0xf4, 0xb2, 0x9e, 0x16, 0x68, 0x2e, 0xd5, 0xed, 0x5b, + 0x14, 0x07, 0x36, 0xe9, 0xdc, 0x91, 0xcc, 0x84, 0x70, 0x57, 0x2a, 0xf9, 0xc0, 0x91, 0x98, 0x6e, + 0xc5, 0xb9, 0xb3, 0x27, 0x6e, 0xdb, 0x78, 0x50, 0xbe, 0x1b, 0xb6, 0x16, 0xf8, 0x38, 0xc9, 0x73, + 0x3d, 0xd6, 0xa0, 0xfc, 0x25, 0xbc, 0x43, 0xd1, 0xc1, 0xff, 0xe1, 0x98, 0x7f, 0x5b, 0x22, 0x5c, + 0xef, 0x40, 0x36, 0x56, 0xce, 0xc2, 0xfd, 0xd8, 0x01, 0x8f, 0x95, 0xfb, 0xb1, 0x16, 0xa0, 0x2b, + 0xa6, 0x23, 0x23, 0x0a, 0xde, 0x23, 0xe2, 0x44, 0xcc, 0x07, 0xf4, 0xc3, 0x1a, 0xab, 0x7d, 0xf1, + 0x9c, 0x1e, 0x81, 0xfb, 0x7e, 0x65, 0x60, 0xb3, 0xf6, 0x58, 0x6d, 0xf3, 0x4e, 0x71, 0x19, 0xff, + 0x8f, 0x94, 0x39, 0xcf, 0x33, 0x77, 0xd3, 0xb1, 0xea, 0x70, 0x6d, 0xdc, 0xe9, 0xdd, 0xf1, 0x84, + 0x5d, 0x11, 0xab, 0xbf, 0x3e, 0xc6, 0x13, 0xf6, 0xbf, 0xb0, 0x4d, 0xe5, 0x6f, 0xb0, 0xea, 0x60, + 0x37, 0xdc, 0x80, 0xcf, 0xe0, 0x46, 0xdd, 0x11, 0x13, 0x9c, 0x6e, 0x98, 0xd1, 0xfb, 0x53, 0x78, + 0xd9, 0xdb, 0x30, 0xd3, 0x48, 0x78, 0x99, 0x6b, 0x0a, 0xea, 0xb7, 0x38, 0x95, 0x76, 0xc0, 0x11, + 0xb3, 0x92, 0xfb, 0xf5, 0xf0, 0x08, 0x95, 0xf6, 0xd3, 0xe0, 0xc6, 0x8a, 0xd7, 0x83, 0x0a, 0xf2, + 0x34, 0x51, 0xcd, 0xd0, 0xa7, 0xe8, 0x84, 0xeb, 0x3e, 0x26, 0x89, 0xfb, 0x84, 0x4a, 0x75, 0xd4, + 0xc2, 0x49, 0x7c, 0xa3, 0x58, 0x1c, 0x0f, 0xd8, 0x83, 0xc9, 0x6c, 0xcc, 0x23, 0x76, 0xc7, 0x04, + 0xea, 0x70, 0xdc, 0x0f, 0x07, 0x63, 0x66, 0xfa, 0x46, 0xca, 0x6d, 0xf7, 0xe2, 0x82, 0x25, 0x3c, + 0xb0, 0x6e, 0x08, 0x79, 0x16, 0x0f, 0x75, 0x8f, 0x66, 0x2a, 0xff, 0xc2, 0xea, 0xb4, 0x43, 0x72, + 0xf9, 0x0f, 0x0d, 0xf5, 0x8f, 0x9b, 0x90, 0xe8, 0x71, 0x67, 0x5f, 0x6c, 0x3a, 0xd2, 0x0b, 0x13, + 0x85, 0x25, 0xf0, 0xe2, 0x72, 0x24, 0xee, 0xdf, 0x31, 0x78, 0xc1, 0x5f, 0x11, 0xb7, 0xff, 0x27, + 0x54, 0x33, 0x7b, 0x69, 0xdc, 0x01, 0x78, 0x31, 0x3a, 0x97, 0x4a, 0x26, 0x11, 0x1a, 0x33, 0x6b, + 0x49, 0xb1, 0x0c, 0x1e, 0x6f, 0x7d, 0xc8, 0xbc, 0x18, 0xcc, 0xc4, 0x6a, 0xb1, 0x13, 0xc8, 0x08, + 0xe1, 0x9a, 0x64, 0xe6, 0x5e, 0x87, 0x62, 0x55, 0x6b, 0xdc, 0x50, 0xad, 0x47, 0xc6, 0x9c, 0x7f, + 0x3b, 0xfc, 0xbe, 0x9e, 0x3c, 0x23, 0x7a, 0xcd, 0x20, 0xe4, 0xb9, 0x13, 0xf8, 0x31, 0x95, 0x0c, + 0x7c, 0x8a, 0x11, 0xd8, 0xbb, 0xc5, 0x32, 0x78, 0xd1, 0x98, 0x80, 0x99, 0x93, 0x19, 0xcc, 0xbb, + 0x3d, 0x6a, 0x64, 0xca, 0xa7, 0xe7, 0xe2, 0x47, 0x90, 0x8d, 0xf1, 0x57, 0x28, 0x46, 0x9a, 0x26, + 0x3d, 0x8b, 0x32, 0x9d, 0x6a, 0x66, 0x7f, 0x11, 0x4c, 0x03, 0x4e, 0xc0, 0x9b, 0xf1, 0x35, 0x72, + 0xf7, 0xd3, 0xb2, 0x62, 0x18, 0x51, 0xab, 0xe2, 0x2d, 0xc0, 0x6e, 0x98, 0xde, 0x0c, 0xc1, 0x1b, + 0xd2, 0xd5, 0x5a, 0xa1, 0xcc, 0x4b, 0xf0, 0x82, 0xb4, 0x3a, 0x7e, 0xc7, 0xcd, 0x68, 0xdc, 0x2d, + 0xdc, 0x20, 0xbc, 0x38, 0x8c, 0xa4, 0x7a, 0x13, 0x3e, 0x93, 0xf2, 0xbe, 0x8d, 0x6d, 0x9b, 0x57, + 0xb9, 0xf7, 0xc7, 0x0b, 0xe9, 0xad, 0xc0, 0x92, 0x98, 0x01, 0x7d, 0x04, 0x33, 0x09, 0x65, 0x36, + 0xb2, 0x31, 0x3e, 0xcf, 0x48, 0x8c, 0xc0, 0x73, 0x74, 0xc3, 0x50, 0xb7, 0xbc, 0x6d, 0xa8, 0xb0, + 0x39, 0xc1, 0x0a, 0xb8, 0x4d, 0x5f, 0xc7, 0x26, 0x89, 0x7f, 0x2c, 0x79, 0x4e, 0x2d, 0x14, 0x31, + 0xf4, 0x0b, 0x51, 0xce, 0x30, 0x5f, 0x8e, 0x17, 0xce, 0xc5, 0x29, 0x36, 0x69, 0x89, 0x78, 0x15, + 0x9b, 0x44, 0x6c, 0x8f, 0xe7, 0xdc, 0x3d, 0x21, 0x7e, 0x14, 0x9e, 0x3b, 0x7b, 0xe2, 0x85, 0xf5, + 0x9e, 0xc2, 0xdc, 0xc6, 0xb2, 0x98, 0x6e, 0xbe, 0x8f, 0x69, 0x53, 0x3d, 0x9c, 0x15, 0xf2, 0xbc, + 0x42, 0xf5, 0x9c, 0x8a, 0x38, 0x1e, 0xcf, 0x85, 0x5f, 0x50, 0xff, 0xfc, 0xc5, 0xa7, 0x78, 0xbe, + 0xf7, 0xac, 0x91, 0x66, 0x1f, 0xcc, 0xb0, 0xdd, 0x84, 0xfb, 0xe5, 0x30, 0xcc, 0xf4, 0x37, 0xd7, + 0x7c, 0x6c, 0x1a, 0x5e, 0x6f, 0xdf, 0xc3, 0xeb, 0xc3, 0x9f, 0x43, 0xfc, 0xc2, 0xa5, 0x39, 0x2a, + 0x31, 0x19, 0xd3, 0xbe, 0xad, 0xb1, 0x87, 0xa5, 0x14, 0xbf, 0xc2, 0xe3, 0x7c, 0x73, 0x2a, 0xcd, + 0x37, 0x8b, 0xd0, 0x0b, 0xd3, 0xdb, 0xa6, 0x10, 0xc6, 0xe1, 0xfe, 0x7e, 0xa3, 0x34, 0x47, 0x86, + 0x3b, 0xb0, 0x10, 0x28, 0x7a, 0x34, 0xeb, 0x87, 0xdb, 0xa4, 0xde, 0x39, 0x87, 0x68, 0xd6, 0x33, + 0x2f, 0x1e, 0xda, 0xd6, 0xc6, 0x6b, 0xe4, 0x5a, 0xcc, 0xdb, 0x26, 0xf5, 0xf3, 0xdc, 0x75, 0x1c, + 0x23, 0xf5, 0xec, 0xdc, 0xf3, 0xef, 0xb0, 0x05, 0xee, 0x93, 0x14, 0x91, 0xd1, 0xff, 0x41, 0x9d, + 0xb2, 0x26, 0xe1, 0xbe, 0xdc, 0x8c, 0xfa, 0xfd, 0x95, 0xe2, 0x26, 0x2a, 0x85, 0x8c, 0x67, 0x60, + 0x33, 0xd6, 0x57, 0xf1, 0xdc, 0x28, 0x32, 0xd3, 0x6b, 0x29, 0x2e, 0xc7, 0xef, 0x1c, 0x37, 0xea, + 0x7b, 0x52, 0x79, 0x7e, 0x6a, 0x24, 0x16, 0x60, 0xf5, 0xc4, 0x0c, 0xfc, 0x2c, 0xcc, 0x3b, 0xf6, + 0xc5, 0x63, 0x7a, 0x77, 0x8a, 0x85, 0xba, 0x87, 0x63, 0xb3, 0xa9, 0xdf, 0x53, 0x69, 0x8e, 0x15, + 0xf1, 0xb7, 0x90, 0x3f, 0x9a, 0xc6, 0xed, 0x49, 0x66, 0xc6, 0x18, 0x4d, 0xbb, 0x8e, 0xc1, 0x1b, + 0x93, 0xe8, 0x01, 0xaf, 0x5d, 0x08, 0xb5, 0x36, 0x6c, 0xb1, 0x9f, 0xdb, 0xe1, 0x8d, 0xd6, 0x14, + 0xcc, 0x9b, 0xed, 0x87, 0xcd, 0x91, 0xae, 0x01, 0x7e, 0xdd, 0x1e, 0x33, 0xe6, 0x65, 0xc4, 0xa5, + 0x09, 0x0f, 0xf6, 0x2d, 0xc2, 0xff, 0x07, 0xb0, 0xc4, 0xb3, 0xa9, 0x20, 0xed, 0xf3, 0x98, 0xb0, + 0xed, 0x8a, 0x17, 0x95, 0x3d, 0xc9, 0x18, 0xf7, 0x1e, 0x78, 0x17, 0x72, 0x7a, 0x08, 0xb3, 0xf0, + 0x0e, 0x63, 0x16, 0x19, 0x03, 0xbd, 0x1c, 0x96, 0xcc, 0x8e, 0x4d, 0xca, 0x1c, 0x4c, 0x66, 0x0f, + 0x78, 0x7c, 0xf8, 0x2d, 0x62, 0xc2, 0x3f, 0xa4, 0xd8, 0xf5, 0x5d, 0xe7, 0xe4, 0xfe, 0xfc, 0x40, + 0x2f, 0xaa, 0x19, 0xfa, 0x14, 0xdb, 0xe2, 0xf7, 0x49, 0x27, 0xe1, 0x14, 0xfc, 0xae, 0x11, 0xcb, + 0x27, 0xf1, 0x8d, 0xa0, 0x3d, 0x1e, 0x98, 0xc3, 0x28, 0xde, 0xa8, 0x44, 0x8c, 0xc5, 0x83, 0xf6, + 0x4c, 0xdc, 0xae, 0x7b, 0x51, 0x2d, 0xa9, 0x6c, 0x2a, 0xc9, 0xfb, 0x02, 0xde, 0xbd, 0xbd, 0x4b, + 0xf5, 0x81, 0xb7, 0xb7, 0xc8, 0x18, 0x51, 0xb0, 0x14, 0x66, 0x30, 0x66, 0xba, 0xe3, 0x80, 0x1c, + 0x89, 0x77, 0xdd, 0xe3, 0xf1, 0x6e, 0xfe, 0xa7, 0x78, 0x00, 0xc7, 0x03, 0x5e, 0x97, 0xe2, 0x71, + 0xd4, 0x13, 0x33, 0xc6, 0x2b, 0xe2, 0x89, 0x50, 0x0f, 0x37, 0x61, 0xc6, 0x7f, 0x3a, 0xb6, 0x2b, + 0x3b, 0x92, 0x6c, 0x61, 0xfa, 0x0b, 0xc5, 0x87, 0x54, 0x63, 0x88, 0x13, 0xa2, 0x63, 0xc8, 0xf7, + 0x34, 0x5e, 0xb8, 0xd7, 0x0f, 0xe5, 0x82, 0x17, 0xa9, 0x0f, 0x6a, 0x3c, 0x7f, 0x1d, 0x2a, 0x25, + 0x93, 0x29, 0x73, 0xde, 0x1b, 0x8f, 0xe5, 0xd4, 0x2e, 0xbc, 0x5f, 0x78, 0x76, 0x53, 0x08, 0xdf, + 0xc7, 0x63, 0xb2, 0x4f, 0xad, 0x97, 0xc4, 0xed, 0x78, 0x23, 0xb6, 0x69, 0x3c, 0x1b, 0xcf, 0xc1, + 0x1e, 0x25, 0x69, 0x3b, 0xd0, 0xd8, 0xe2, 0x1c, 0x5d, 0x98, 0x8d, 0xab, 0x91, 0x26, 0xba, 0xbb, + 0xfc, 0x7e, 0x8d, 0x34, 0x6b, 0x26, 0xff, 0x47, 0x53, 0x6d, 0xb7, 0xff, 0x26, 0xb6, 0xbf, 0x8c, + 0xcf, 0xb9, 0xa4, 0x81, 0xba, 0xb5, 0x36, 0x2e, 0xc1, 0xf3, 0xe9, 0x32, 0xcc, 0x3c, 0x9d, 0xd9, + 0x8c, 0xbc, 0x8b, 0x52, 0xbc, 0x99, 0xbf, 0x01, 0xd3, 0xca, 0x43, 0xb0, 0x7b, 0xb6, 0x22, 0x62, + 0x5f, 0x86, 0x0f, 0xf1, 0xc2, 0xd2, 0x8d, 0x6a, 0xc6, 0xef, 0x11, 0xb2, 0xc3, 0xd2, 0x79, 0x44, + 0xcd, 0x5e, 0x5e, 0x82, 0x35, 0x02, 0x6f, 0x14, 0xb6, 0xc7, 0x82, 0x8e, 0xc8, 0xcc, 0xbc, 0x84, + 0xb5, 0x4c, 0x45, 0x88, 0xf1, 0x65, 0x1b, 0xf4, 0xd7, 0xf1, 0x78, 0x1b, 0x4c, 0x25, 0x2d, 0x8d, + 0xff, 0x3f, 0xc4, 0x34, 0x67, 0x43, 0xbc, 0xa9, 0x3e, 0xb8, 0xa4, 0x9c, 0x32, 0xbc, 0x4f, 0xf1, + 0xe1, 0xd9, 0x15, 0x28, 0xb7, 0xeb, 0xbd, 0x12, 0x33, 0x20, 0xbb, 0x63, 0x26, 0xac, 0x96, 0x4b, + 0xcb, 0x3b, 0x30, 0xbd, 0xdd, 0x8b, 0x6c, 0x3e, 0xcf, 0x09, 0xff, 0xf7, 0xa0, 0xdc, 0xde, 0x3c, + 0xe2, 0x2c, 0x2c, 0x01, 0xfc, 0x2d, 0xde, 0xdc, 0xed, 0x50, 0x23, 0x2d, 0x64, 0xe7, 0x76, 0xca, + 0xce, 0x2c, 0xad, 0x8d, 0x25, 0x64, 0x7f, 0xa4, 0x9a, 0x81, 0x2d, 0xc3, 0x2d, 0x14, 0xbb, 0x54, + 0x8c, 0xb8, 0x9b, 0x4a, 0xed, 0xcd, 0x93, 0x98, 0xa6, 0xe6, 0x99, 0xbc, 0x7a, 0x88, 0x2e, 0x8c, + 0x47, 0x63, 0x06, 0xbd, 0x48, 0xf0, 0x54, 0x0b, 0xc2, 0xf4, 0xb4, 0x03, 0xc5, 0x9a, 0x58, 0x30, + 0x4d, 0xaa, 0xf7, 0x85, 0xc3, 0x85, 0xb0, 0x76, 0xa3, 0x57, 0x08, 0x3f, 0xc4, 0x73, 0xa4, 0x16, + 0xfd, 0x89, 0x98, 0x88, 0x05, 0x7d, 0xa7, 0xe0, 0x35, 0x66, 0x00, 0x99, 0x8b, 0xd0, 0xf9, 0x8d, + 0x0d, 0xb1, 0x90, 0xa8, 0x0b, 0xc5, 0x2e, 0xa2, 0x17, 0x34, 0xda, 0x51, 0xdd, 0xd6, 0xf1, 0xba, + 0xec, 0xac, 0x4b, 0x9a, 0x6e, 0x2e, 0x8d, 0xf5, 0x57, 0x8a, 0x3c, 0x1f, 0x76, 0x3a, 0xde, 0x90, + 0xdd, 0x85, 0x0f, 0x54, 0x3f, 0x45, 0xa5, 0x2b, 0xd8, 0x79, 0xc1, 0x7b, 0x78, 0x9c, 0x1c, 0x80, + 0x69, 0x73, 0x27, 0x2a, 0xb5, 0x23, 0x2f, 0xe3, 0x31, 0xb0, 0x27, 0xa6, 0xcd, 0xd7, 0x86, 0xd0, + 0x19, 0xd3, 0x8d, 0xed, 0xa9, 0x76, 0x3c, 0x02, 0xa6, 0x69, 0x53, 0xb0, 0x00, 0x69, 0xd5, 0x82, + 0xfb, 0x6f, 0x62, 0xba, 0xb2, 0x1f, 0x1e, 0xab, 0xab, 0x50, 0xb9, 0x09, 0x5a, 0x03, 0x6b, 0x24, + 0x8e, 0x27, 0x13, 0x6c, 0xbd, 0x8d, 0xf9, 0xad, 0x01, 0x35, 0xde, 0xe7, 0xf7, 0xe1, 0x7d, 0xae, + 0xa5, 0x52, 0x6b, 0x3c, 0x0d, 0xd3, 0xaf, 0xad, 0x80, 0x3b, 0xdb, 0x63, 0xe2, 0x51, 0xb6, 0xab, + 0xef, 0x85, 0x89, 0xf5, 0xd0, 0xf0, 0xff, 0x24, 0xdc, 0x09, 0xbd, 0xc2, 0xfd, 0x4e, 0xa1, 0xf2, + 0x3f, 0x4e, 0xf2, 0x4c, 0x0c, 0xbf, 0xf9, 0x5d, 0x78, 0x6f, 0xac, 0x2a, 0x89, 0x07, 0x0c, 0x66, + 0x62, 0xc2, 0x1b, 0x77, 0x7f, 0xef, 0x63, 0xe6, 0xa6, 0x5b, 0x92, 0x47, 0xa1, 0xf2, 0x53, 0x70, + 0x23, 0x8c, 0x2c, 0xa9, 0xe7, 0xf3, 0x14, 0x0f, 0x84, 0x95, 0x92, 0xfb, 0x0b, 0x02, 0x9d, 0xa9, + 0x94, 0x24, 0xe6, 0x4d, 0x5a, 0xc0, 0x4c, 0x5a, 0x7a, 0xc0, 0x6b, 0x03, 0xdc, 0xfe, 0x8d, 0x7a, + 0x36, 0xb8, 0x00, 0xab, 0xe6, 0xf2, 0x92, 0xab, 0xf3, 0xa8, 0x3e, 0x70, 0xf4, 0x39, 0x9e, 0x9c, + 0x6b, 0x61, 0x46, 0xb8, 0x17, 0x95, 0x92, 0xca, 0x5e, 0x98, 0xc0, 0x0f, 0xc9, 0xe5, 0x5b, 0x0d, + 0xab, 0x80, 0x1f, 0xa0, 0x9a, 0x29, 0xfc, 0x36, 0x95, 0x1b, 0x89, 0x81, 0x58, 0x7a, 0x37, 0x2c, + 0x89, 0x5b, 0x8b, 0xca, 0x05, 0xf7, 0xd9, 0xf0, 0x9b, 0x97, 0xb2, 0x82, 0x17, 0xb0, 0x27, 0x30, + 0x33, 0x9a, 0x6f, 0x3f, 0x70, 0xfb, 0xa4, 0xea, 0xd6, 0x59, 0x98, 0x20, 0x6f, 0x8d, 0x19, 0x94, + 0x89, 0xd4, 0x3f, 0x4c, 0x1b, 0xb1, 0x75, 0x48, 0xbf, 0x3d, 0x5e, 0x08, 0x4e, 0x26, 0xdb, 0x1c, + 0x82, 0x0f, 0x3b, 0xce, 0xce, 0xe5, 0x99, 0x4a, 0x26, 0xfd, 0x7d, 0x3b, 0xa9, 0x4b, 0x1f, 0xbc, + 0x81, 0x99, 0x8b, 0xd5, 0xe8, 0x27, 0xe1, 0x83, 0x2e, 0x51, 0x0b, 0xb5, 0x28, 0x96, 0x9a, 0x6d, + 0x42, 0xd6, 0xee, 0x9b, 0x62, 0xe6, 0xbf, 0x51, 0xaf, 0x2d, 0x9f, 0x62, 0x29, 0xfb, 0xd0, 0x90, + 0xb7, 0xc8, 0x47, 0xf0, 0xb9, 0x54, 0x9b, 0x36, 0xe5, 0xd1, 0x0e, 0xab, 0xdf, 0x6f, 0xa7, 0x5a, + 0xc2, 0x92, 0xc7, 0x52, 0x54, 0x1f, 0xac, 0x2e, 0xc3, 0x59, 0x78, 0x21, 0xdd, 0xb5, 0xc1, 0xf4, + 0x0b, 0x0a, 0x73, 0x93, 0xdf, 0xdf, 0xe0, 0xf6, 0xde, 0xb2, 0x3c, 0x79, 0x05, 0x4e, 0xa2, 0xd8, + 0x73, 0xd0, 0x6c, 0xbc, 0xa9, 0xec, 0x8f, 0x0f, 0x42, 0x35, 0xe2, 0xf9, 0x26, 0xc5, 0xa3, 0x78, + 0x21, 0x3f, 0x04, 0xcf, 0x97, 0x88, 0x8b, 0x43, 0xdd, 0xd6, 0x29, 0xc8, 0x73, 0x30, 0xd9, 0xb7, + 0x00, 0x1a, 0xc1, 0x1d, 0x78, 0x9e, 0x17, 0x49, 0xf3, 0xb6, 0xc5, 0xe3, 0x29, 0xef, 0xad, 0x24, + 0xc5, 0x68, 0xac, 0xdd, 0xea, 0x95, 0xc4, 0xcd, 0xa2, 0xd2, 0xdb, 0xcc, 0xe7, 0x64, 0x07, 0xa3, + 0x9a, 0x83, 0x47, 0xf1, 0x7c, 0x4d, 0xeb, 0xb6, 0x50, 0x88, 0x2b, 0xa3, 0x7d, 0xaf, 0x87, 0x3a, + 0x9d, 0x84, 0x17, 0xbf, 0x5a, 0x07, 0xae, 0x6e, 0x0f, 0xf5, 0xdc, 0x88, 0x4a, 0x09, 0xe0, 0x75, + 0x58, 0x2a, 0xd8, 0x0d, 0xd3, 0xb4, 0x22, 0xc4, 0x8d, 0xf5, 0x04, 0xdc, 0xc7, 0x8f, 0x61, 0xad, + 0x5a, 0x4b, 0x0f, 0x34, 0xb7, 0xc3, 0xc2, 0x82, 0xf8, 0xcd, 0x80, 0x14, 0x77, 0x54, 0xa5, 0xce, + 0x70, 0x1b, 0xb5, 0x37, 0xee, 0xd3, 0xa9, 0x96, 0x2a, 0x37, 0x47, 0xda, 0x19, 0x71, 0x00, 0x1e, + 0x8b, 0x3b, 0x61, 0xba, 0x9b, 0xa7, 0x79, 0xf5, 0x10, 0x85, 0x12, 0x4f, 0x52, 0xee, 0x87, 0x7d, + 0x22, 0x99, 0xe9, 0x49, 0x19, 0x9e, 0xa4, 0xf1, 0x79, 0x99, 0x47, 0x0f, 0xbc, 0xe9, 0xee, 0x49, + 0x26, 0xe8, 0xf9, 0x47, 0x0b, 0xcb, 0x6a, 0x2e, 0xae, 0xc5, 0xc2, 0x9d, 0xd3, 0x30, 0xad, 0x58, + 0xb3, 0x76, 0xf2, 0xf9, 0x8e, 0x47, 0xa9, 0xa6, 0x1f, 0xf1, 0xf0, 0xed, 0x78, 0x6a, 0x23, 0xf6, + 0x65, 0x23, 0xfd, 0x55, 0x0b, 0xfb, 0xe0, 0xf9, 0xb3, 0x3f, 0x3e, 0x40, 0xbe, 0x1c, 0x8d, 0xad, + 0x73, 0x73, 0xa9, 0xbf, 0x81, 0x00, 0x0b, 0x5c, 0x36, 0xc6, 0x6b, 0xec, 0x75, 0x05, 0xf7, 0xaf, + 0xc4, 0x9b, 0xf0, 0x3e, 0x98, 0x16, 0xcc, 0xc0, 0xbc, 0xd7, 0x11, 0x98, 0x6e, 0x14, 0xd1, 0x8e, + 0xb3, 0x71, 0xff, 0x3d, 0x84, 0xf9, 0x97, 0xa2, 0x03, 0xd1, 0x97, 0x62, 0xfa, 0xb0, 0x2f, 0x95, + 0x82, 0xb7, 0x76, 0x58, 0xeb, 0x3f, 0x9e, 0xcc, 0xe4, 0xf9, 0xfc, 0xf0, 0xfb, 0x01, 0xb5, 0xad, + 0x35, 0xba, 0x50, 0x5b, 0x08, 0x08, 0xb8, 0x51, 0x26, 0x51, 0xdb, 0xe6, 0x33, 0x75, 0x9d, 0xd8, + 0x8d, 0x4a, 0xd5, 0xf7, 0x6c, 0xcc, 0x88, 0xa5, 0x8b, 0xd9, 0xd6, 0x98, 0x80, 0xa7, 0x44, 0x68, + 0x49, 0x2c, 0xad, 0x4c, 0x3f, 0x38, 0x74, 0x2f, 0x1e, 0xd4, 0xab, 0x63, 0x26, 0x7c, 0x34, 0x66, + 0x34, 0xfa, 0x52, 0x79, 0xf2, 0x7e, 0xad, 0xf0, 0x9c, 0xe9, 0xb8, 0x31, 0x8a, 0x70, 0x1f, 0xc5, + 0x92, 0xc5, 0x1e, 0x21, 0x6f, 0x6b, 0xef, 0xa6, 0x9f, 0x20, 0xb3, 0x05, 0xcb, 0xc7, 0x4f, 0xc1, + 0x0c, 0x66, 0x3b, 0x2c, 0x7d, 0xc9, 0x13, 0xe3, 0x0b, 0xb1, 0xb4, 0x36, 0x4a, 0x07, 0x0e, 0xc2, + 0xa6, 0x24, 0xf5, 0xec, 0xfe, 0xc1, 0x4c, 0xd8, 0xb2, 0x98, 0x38, 0x74, 0xcf, 0x85, 0x15, 0x70, + 0xfb, 0xc6, 0x81, 0xde, 0x0d, 0x0f, 0xa8, 0x7a, 0xb6, 0xf2, 0x2f, 0x50, 0x29, 0x05, 0xdb, 0x0a, + 0x4b, 0xba, 0x7f, 0x87, 0x4d, 0x2b, 0xba, 0x93, 0x9d, 0x9c, 0x5e, 0x01, 0x7b, 0x6a, 0x88, 0x65, + 0x76, 0xc2, 0xbb, 0xc6, 0x2b, 0xa8, 0x34, 0x47, 0x19, 0x15, 0xd2, 0x45, 0x26, 0xa4, 0x1f, 0x5e, + 0xcc, 0x6f, 0x4a, 0xd2, 0x2c, 0x8c, 0x37, 0x7a, 0x5b, 0x92, 0xd9, 0x18, 0xa6, 0xed, 0x17, 0x31, + 0x16, 0x13, 0x8f, 0x3c, 0xd3, 0xfe, 0x32, 0xde, 0xfc, 0x1c, 0x4b, 0xe3, 0x3b, 0xfe, 0x2f, 0xb0, + 0xfa, 0x6a, 0x57, 0x8a, 0x25, 0x88, 0x4f, 0x93, 0x7d, 0x6c, 0x2b, 0xe2, 0x2e, 0x3c, 0x1e, 0x97, + 0xc1, 0x12, 0xa6, 0x55, 0xf1, 0x22, 0x30, 0x0b, 0xb7, 0xf7, 0xdd, 0x58, 0x2b, 0x74, 0x3c, 0x95, + 0xb6, 0xa7, 0x7d, 0xb0, 0x1a, 0x3e, 0xad, 0xdb, 0x2c, 0xac, 0xed, 0xa8, 0x65, 0xda, 0x12, 0xb1, + 0x2e, 0xde, 0xb1, 0xff, 0x19, 0x33, 0x2f, 0x27, 0xe0, 0x7e, 0x4f, 0x17, 0xb3, 0x8e, 0xd4, 0xf6, + 0xbe, 0x02, 0x66, 0xb6, 0x87, 0x61, 0x4d, 0x55, 0xfd, 0x0f, 0x1f, 0x54, 0x6e, 0x8e, 0xeb, 0xe1, + 0x49, 0xcc, 0x6c, 0x5e, 0x81, 0xc7, 0x50, 0x2a, 0x71, 0xad, 0xf7, 0x7e, 0xad, 0x81, 0x46, 0xfa, + 0xfd, 0x46, 0x4c, 0x7c, 0x1b, 0x35, 0xc3, 0xa8, 0xf5, 0xd1, 0x97, 0xbf, 0xe0, 0xf9, 0x37, 0x99, + 0x96, 0x9d, 0xcc, 0x3f, 0x1b, 0x8f, 0x97, 0x74, 0x31, 0xba, 0x0d, 0x2f, 0x3c, 0xd7, 0x60, 0x0d, + 0x12, 0x98, 0x76, 0x1c, 0x89, 0x19, 0x8e, 0x5a, 0x12, 0x98, 0x3c, 0xce, 0xc5, 0x1b, 0xdc, 0x7c, + 0x9e, 0xce, 0xd8, 0xdc, 0xe0, 0x42, 0xb2, 0xb3, 0x07, 0x45, 0x18, 0x83, 0xe7, 0x48, 0xde, 0x8e, + 0x39, 0x1d, 0x63, 0x2b, 0xe1, 0xf9, 0xdc, 0x5c, 0x8d, 0xc8, 0xe9, 0x78, 0xee, 0x8c, 0xc0, 0xcc, + 0xf2, 0x96, 0xf8, 0x9d, 0x97, 0xa7, 0xda, 0x0b, 0x47, 0x8a, 0xcb, 0xb1, 0x14, 0xba, 0x96, 0x57, + 0x18, 0xb0, 0xa6, 0xe6, 0x23, 0xaa, 0xe9, 0xed, 0xbd, 0x98, 0x36, 0x95, 0x6d, 0x00, 0x3a, 0x61, + 0xc1, 0x4f, 0xdc, 0xe0, 0x7e, 0x81, 0xdb, 0xbe, 0x3b, 0x56, 0x7b, 0xb7, 0x04, 0x03, 0xb1, 0xfd, + 0xf8, 0x40, 0x2a, 0x25, 0x8c, 0xed, 0xa9, 0x6d, 0x66, 0xf0, 0x0e, 0xd6, 0xcc, 0xad, 0x57, 0x23, + 0x4d, 0x6b, 0x20, 0xda, 0xd0, 0xc6, 0xcd, 0x47, 0xb4, 0x0f, 0x2e, 0x33, 0xf5, 0xd8, 0x8a, 0x8c, + 0xd9, 0xd8, 0x0a, 0x9b, 0xc4, 0x9c, 0x15, 0xc2, 0x76, 0x54, 0x32, 0x61, 0x3f, 0xc2, 0xed, 0x36, + 0x14, 0x8f, 0xa3, 0x48, 0xaf, 0x16, 0xa5, 0xda, 0x93, 0xd5, 0x69, 0xa1, 0xbc, 0x54, 0x1b, 0xb0, + 0x3a, 0xf5, 0x5d, 0x7e, 0x82, 0xdb, 0x71, 0x21, 0xca, 0x3f, 0x50, 0xb8, 0x20, 0x70, 0x0e, 0xe6, + 0x87, 0xca, 0xce, 0x1c, 0x2c, 0x28, 0x9c, 0x82, 0xfb, 0x24, 0xf2, 0x40, 0x1d, 0xb1, 0xe0, 0xe9, + 0x6e, 0x2a, 0x2d, 0x11, 0xc0, 0x9b, 0xd7, 0xd8, 0xcf, 0x3d, 0xc9, 0xfa, 0xf2, 0x3c, 0xdc, 0x5f, + 0xd1, 0xac, 0x6d, 0x09, 0x1a, 0x77, 0x51, 0x0c, 0xfe, 0xe0, 0x5a, 0x14, 0x86, 0x46, 0x33, 0xbc, + 0x74, 0x33, 0xfc, 0x31, 0x99, 0xc5, 0x40, 0xba, 0x96, 0xbf, 0x48, 0x26, 0xac, 0x6c, 0x87, 0x4d, + 0xb5, 0x8a, 0xe8, 0xfa, 0x83, 0x98, 0x57, 0xfd, 0x25, 0xc5, 0x9b, 0xb0, 0x6b, 0x31, 0x6d, 0x7e, + 0x9d, 0x4c, 0x70, 0xf0, 0x37, 0xfc, 0x0e, 0x37, 0x15, 0xa4, 0xdf, 0x1d, 0xcf, 0xcd, 0xd1, 0x78, + 0xfc, 0x6d, 0x4e, 0xf1, 0x17, 0x5d, 0x6f, 0xc3, 0xbc, 0xe7, 0x50, 0x2a, 0x2d, 0x15, 0x06, 0x62, + 0x3a, 0x36, 0x20, 0xd4, 0xb7, 0x23, 0xcd, 0xa3, 0xd5, 0xf5, 0x11, 0x4e, 0x9f, 0xa6, 0x5e, 0x08, + 0xf2, 0xe1, 0xb7, 0xc9, 0x89, 0xd6, 0xdf, 0xcb, 0x5e, 0x3f, 0xd2, 0xfb, 0x6b, 0xc8, 0xa7, 0x82, + 0x47, 0x85, 0x13, 0xba, 0x13, 0x94, 0x79, 0xfb, 0x88, 0xe1, 0x12, 0x65, 0x1f, 0x03, 0x8a, 0x61, + 0x65, 0x49, 0x8f, 0xc8, 0x1f, 0xcc, 0x38, 0x31, 0x89, 0x3f, 0x4c, 0xf6, 0x0c, 0x30, 0x41, 0xf6, + 0xfe, 0x71, 0xb9, 0x7c, 0x4a, 0x79, 0x4d, 0x65, 0x1f, 0xb9, 0x39, 0x23, 0x57, 0x56, 0x77, 0xf9, + 0xb4, 0xfe, 0x46, 0xb9, 0xf8, 0x5b, 0xe5, 0x0f, 0xc0, 0xb4, 0xe4, 0x44, 0x7b, 0xad, 0xf0, 0x5a, + 0x38, 0x9d, 0x9b, 0x8f, 0xbf, 0x37, 0x9c, 0xf0, 0xed, 0xac, 0xda, 0x1f, 0x96, 0xd8, 0x25, 0xbc, + 0xdf, 0x78, 0xd9, 0x5b, 0x48, 0x3c, 0x45, 0xbc, 0xb6, 0xec, 0x35, 0xe5, 0x8d, 0x70, 0xc2, 0xf7, + 0x53, 0xf9, 0x94, 0x76, 0x3c, 0x55, 0x5f, 0x0b, 0xf1, 0x63, 0x38, 0xa3, 0xe4, 0x8f, 0x4d, 0x3c, + 0x2e, 0x7f, 0xc8, 0x26, 0xfd, 0x30, 0x4c, 0x0c, 0x43, 0x42, 0x1e, 0xe4, 0x0f, 0x73, 0x5c, 0x15, + 0xda, 0xfa, 0xc1, 0x90, 0x37, 0xed, 0xbf, 0x3e, 0xa1, 0x0e, 0xf7, 0xcb, 0xde, 0x12, 0x8e, 0x4b, + 0xca, 0x3c, 0x34, 0x94, 0x93, 0xff, 0xb8, 0x54, 0xd7, 0xd0, 0xee, 0xcf, 0xcb, 0x27, 0xfd, 0xc7, + 0xc9, 0x1f, 0x4b, 0x21, 0xb4, 0xcd, 0x89, 0xf2, 0x49, 0xf8, 0x43, 0x55, 0x79, 0xd2, 0x3d, 0x6d, + 0xbf, 0x18, 0x17, 0x4f, 0xf8, 0xaf, 0xa6, 0xe2, 0xb6, 0x6c, 0xcd, 0x30, 0x41, 0xfe, 0x78, 0x4e, + 0x1a, 0xb7, 0xaa, 0x7c, 0xf2, 0x7a, 0x64, 0x49, 0x5b, 0x16, 0x85, 0x61, 0xb2, 0xe7, 0xa2, 0x09, + 0x92, 0x4e, 0x4a, 0xe2, 0xcf, 0x93, 0x34, 0x31, 0xbc, 0xcf, 0x58, 0xf9, 0x83, 0x42, 0x7b, 0x85, + 0x36, 0x97, 0xec, 0xc5, 0x63, 0x8c, 0xb2, 0xb1, 0x31, 0x28, 0xd7, 0x3e, 0xbd, 0xe4, 0x53, 0xf8, + 0x0f, 0x86, 0x74, 0x93, 0xe5, 0xb9, 0xb7, 0x71, 0x41, 0x39, 0x4d, 0x21, 0xdc, 0x2f, 0x7b, 0x24, + 0x48, 0x3f, 0xa6, 0xd1, 0x2f, 0x94, 0x2f, 0xd9, 0x3b, 0xc5, 0x93, 0x49, 0x78, 0x31, 0xc4, 0x0f, + 0x90, 0xbd, 0xc4, 0x48, 0xf6, 0x4c, 0x31, 0x59, 0x99, 0xe7, 0x9f, 0x7c, 0xd8, 0x58, 0x3e, 0xd5, + 0xfe, 0x8a, 0xdc, 0x7f, 0x4f, 0x87, 0xeb, 0xe8, 0x51, 0x27, 0xad, 0xdb, 0x34, 0x55, 0x7a, 0x7f, + 0xfa, 0x7b, 0xf2, 0x9c, 0x07, 0x42, 0xda, 0x7e, 0xca, 0x3c, 0x28, 0xbc, 0x2d, 0x8f, 0x8b, 0xfc, + 0x33, 0x25, 0xe9, 0xd8, 0xdc, 0x3b, 0xe5, 0xf3, 0x2c, 0x24, 0x7b, 0x02, 0x9a, 0x1a, 0xe2, 0x1f, + 0x93, 0xbd, 0x1f, 0xd4, 0x7a, 0xff, 0x4f, 0xe5, 0xf9, 0xb1, 0x83, 0x3c, 0x87, 0x3e, 0x0f, 0xe5, + 0xc6, 0x8f, 0x18, 0xdd, 0xa6, 0x8c, 0x96, 0x5d, 0x24, 0x7b, 0xa4, 0x92, 0xec, 0x3d, 0x60, 0x5f, + 0xd9, 0x03, 0xc2, 0x23, 0x21, 0xdf, 0xd3, 0x92, 0x8e, 0xca, 0xd5, 0xfb, 0x5b, 0xa1, 0x8d, 0xf2, + 0xef, 0x73, 0x50, 0x78, 0xff, 0xb1, 0x21, 0xff, 0x30, 0x55, 0x7e, 0x5c, 0xeb, 0xa7, 0xca, 0xbc, + 0x47, 0x4c, 0x0d, 0xf5, 0x58, 0xaa, 0xa0, 0x9c, 0x9d, 0x24, 0xbd, 0x2b, 0x7f, 0x8c, 0x68, 0xe5, + 0x50, 0x9f, 0x26, 0x99, 0x16, 0x2d, 0x12, 0xd2, 0xfc, 0x2c, 0xb4, 0x45, 0x6c, 0xab, 0x26, 0x65, + 0x1e, 0x1c, 0xce, 0x95, 0x3d, 0xf2, 0x8c, 0x91, 0x69, 0xca, 0x51, 0xf2, 0xfc, 0x1d, 0x23, 0x8f, + 0xa5, 0x09, 0xf2, 0x07, 0xe7, 0xd2, 0xb9, 0x70, 0x48, 0xae, 0xbc, 0xd1, 0xaa, 0xf4, 0x8c, 0x10, + 0xc3, 0x76, 0xe1, 0xfd, 0x3e, 0x96, 0xbd, 0x7c, 0x8c, 0x55, 0xa5, 0x47, 0x85, 0xa2, 0xb0, 0x58, + 0x28, 0xb3, 0xa8, 0xbc, 0x7c, 0xb8, 0x59, 0x52, 0xcf, 0x82, 0xf8, 0xe1, 0x72, 0x9f, 0xe7, 0xe3, + 0x2f, 0x91, 0x3d, 0x9f, 0xbc, 0xa7, 0xcc, 0x43, 0xc8, 0xa6, 0xa1, 0x1f, 0xe6, 0x84, 0x7a, 0x8e, + 0x96, 0x69, 0x40, 0x9a, 0xef, 0xd8, 0xdc, 0xfb, 0xde, 0x27, 0x7b, 0x70, 0x89, 0xf7, 0x67, 0x4a, + 0xfa, 0x4c, 0x95, 0xe3, 0xea, 0x49, 0x65, 0x9e, 0x2e, 0xa4, 0x72, 0xaf, 0x36, 0xe9, 0x07, 0xeb, + 0xd2, 0xb1, 0x5e, 0x96, 0xbe, 0x25, 0x61, 0x49, 0xd9, 0x73, 0xd7, 0x9b, 0xb2, 0x67, 0x9b, 0x01, + 0xe1, 0xfd, 0xff, 0xad, 0xcc, 0xb3, 0xd8, 0x9a, 0xca, 0xe6, 0xc8, 0xd9, 0xb2, 0x37, 0x89, 0xb1, + 0xb2, 0xe7, 0x8c, 0xfd, 0x92, 0xb2, 0xf6, 0x96, 0x69, 0xda, 0xe3, 0xb2, 0x27, 0xab, 0x33, 0xe5, + 0x8f, 0x32, 0x21, 0xd3, 0xaf, 0x97, 0xe4, 0xf1, 0xf3, 0xf7, 0x70, 0x4f, 0xb2, 0x67, 0xa1, 0xf8, + 0x71, 0xb5, 0x9f, 0xc8, 0xeb, 0xcb, 0x24, 0x79, 0x4c, 0x5f, 0x22, 0x8f, 0xbb, 0xf5, 0xe5, 0xf1, + 0x16, 0xdb, 0xf8, 0x9f, 0xb9, 0x77, 0x58, 0x2e, 0x94, 0xf3, 0x86, 0x3c, 0x7e, 0x47, 0x87, 0xfc, + 0xc7, 0xca, 0x34, 0x73, 0x8d, 0xf0, 0x5c, 0x85, 0xf7, 0x8c, 0xf3, 0x61, 0x6c, 0x12, 0x77, 0xb4, + 0xec, 0x79, 0x2b, 0xd2, 0x87, 0xcb, 0x73, 0xcf, 0x18, 0x12, 0xe2, 0x09, 0xf5, 0x6d, 0x0a, 0xd7, + 0xd3, 0x64, 0x5e, 0x08, 0xd9, 0xdb, 0x86, 0xe4, 0x31, 0xb0, 0xb2, 0x4c, 0x1b, 0xa2, 0x97, 0x93, + 0xd7, 0xe4, 0xb5, 0x3b, 0x7d, 0xee, 0xb4, 0xd0, 0x66, 0x07, 0x2a, 0xa3, 0x7b, 0xf7, 0xc9, 0x73, + 0x73, 0x74, 0xae, 0x6e, 0x45, 0xf5, 0x5d, 0x2d, 0xf7, 0x5e, 0x47, 0x87, 0x7a, 0xf4, 0x96, 0xe7, + 0xe8, 0x58, 0x79, 0x8e, 0xfe, 0x49, 0x95, 0xeb, 0x68, 0x1c, 0x47, 0xd7, 0xca, 0xf4, 0x77, 0x9c, + 0xdc, 0x97, 0xe9, 0x47, 0xd2, 0x8e, 0x92, 0x69, 0x78, 0x93, 0x3c, 0x1e, 0x2e, 0x4c, 0xde, 0x1f, + 0x99, 0xa7, 0x89, 0xeb, 0xf1, 0x6b, 0xf2, 0x07, 0xca, 0xe2, 0xbd, 0xe8, 0x5d, 0x6c, 0x9c, 0xec, + 0x15, 0x29, 0xff, 0x11, 0xae, 0xe3, 0x64, 0xba, 0x74, 0x8f, 0xa4, 0x81, 0x49, 0xfc, 0xae, 0x32, + 0x0d, 0x1e, 0x2f, 0xb7, 0x7f, 0x6f, 0x79, 0x6e, 0xdd, 0xa5, 0x8c, 0x67, 0x88, 0xe1, 0x08, 0x55, + 0xf7, 0x51, 0x1a, 0x6e, 0x51, 0xa5, 0xe7, 0xc1, 0x8e, 0xf2, 0x5a, 0x98, 0xf7, 0xf0, 0x74, 0x81, + 0xfc, 0x21, 0xc4, 0x07, 0x65, 0xde, 0x71, 0xa8, 0xbc, 0xc6, 0x7f, 0xac, 0x4a, 0xef, 0x2c, 0x31, + 0xfc, 0xaf, 0xb2, 0x8f, 0x28, 0xc6, 0xf0, 0xbe, 0x3c, 0x6e, 0x6e, 0x0a, 0xe1, 0xae, 0x5c, 0x5b, + 0xe5, 0xff, 0x0f, 0xa9, 0x71, 0x5d, 0x18, 0xda, 0x49, 0xcd, 0x31, 0x33, 0xaa, 0x8b, 0x29, 0x14, + 0xdb, 0xee, 0xac, 0xc5, 0xfc, 0x37, 0x2d, 0x89, 0x36, 0xcb, 0x07, 0x86, 0xdf, 0x35, 0xb1, 0xca, + 0x6f, 0x23, 0x5a, 0xf7, 0x70, 0x02, 0xa1, 0xcc, 0xeb, 0xa8, 0x3e, 0xec, 0x96, 0xe2, 0x34, 0x2c, + 0x0d, 0x3f, 0xbf, 0x46, 0x9a, 0x6f, 0x22, 0x3a, 0xe2, 0xf6, 0x8b, 0x9f, 0x4f, 0xaf, 0x87, 0xa5, + 0xf1, 0x8e, 0x79, 0x15, 0xbe, 0xbc, 0x8f, 0xda, 0x6c, 0x87, 0x25, 0x77, 0xe3, 0xb1, 0x84, 0x2d, + 0xda, 0x99, 0x2f, 0x82, 0xa5, 0x05, 0x65, 0xea, 0xf2, 0x36, 0xcc, 0x1f, 0x2c, 0x89, 0xcd, 0xe0, + 0x7a, 0x52, 0x2d, 0x19, 0x6a, 0x83, 0xb5, 0x9d, 0x83, 0xb0, 0x46, 0xf3, 0x19, 0x2c, 0xe1, 0x1b, + 0xce, 0x7f, 0xc6, 0x47, 0xa1, 0xda, 0x60, 0xba, 0x77, 0x2a, 0xc5, 0x1f, 0xb9, 0x5b, 0x07, 0xaf, + 0x65, 0x9b, 0x37, 0x98, 0x3e, 0xa2, 0xa9, 0xc6, 0xbd, 0x5e, 0xcd, 0xa9, 0xdc, 0x57, 0x04, 0xbb, + 0xe2, 0xc3, 0x78, 0xdb, 0x63, 0x4d, 0x7d, 0x3b, 0x2c, 0x0d, 0xbd, 0x11, 0x4b, 0x30, 0xeb, 0x7d, + 0xbc, 0xab, 0x11, 0x9c, 0x8a, 0xcd, 0xe2, 0xbe, 0x2e, 0x1f, 0x22, 0x6a, 0x64, 0x1c, 0xa5, 0x18, + 0x82, 0xa5, 0xf2, 0x65, 0xfe, 0xef, 0xbf, 0x29, 0xe8, 0x8b, 0xa5, 0xfe, 0x17, 0xd7, 0x4b, 0x98, + 0x60, 0x26, 0xd6, 0x02, 0x4d, 0xa7, 0xb2, 0xdd, 0x97, 0xc3, 0x1a, 0xb2, 0x23, 0xa9, 0xc3, 0x1b, + 0x2e, 0xa8, 0x8f, 0x84, 0x2c, 0x08, 0x9b, 0xef, 0xa3, 0xb1, 0xcd, 0xd3, 0xfa, 0xd8, 0x7e, 0xea, + 0x0c, 0x3c, 0xb1, 0x5a, 0x9b, 0x31, 0x07, 0xdb, 0x5d, 0x5f, 0x55, 0x27, 0xcd, 0xae, 0x64, 0x5f, + 0x98, 0x6c, 0x43, 0x86, 0xcf, 0x71, 0x3f, 0x35, 0x8a, 0xa3, 0xb1, 0x6d, 0xe1, 0x97, 0xc9, 0x58, + 0xdc, 0x8b, 0xd5, 0xdc, 0x87, 0xe1, 0x03, 0x7d, 0x8b, 0xe1, 0x83, 0x60, 0xaf, 0x52, 0x69, 0x6b, + 0xdf, 0x86, 0xf9, 0x87, 0x45, 0x31, 0x1d, 0x99, 0x81, 0xdd, 0x8a, 0xdd, 0x4c, 0x1b, 0x63, 0x5e, + 0x86, 0x57, 0xf0, 0x59, 0xa1, 0xfd, 0x70, 0x1b, 0xb5, 0x8d, 0xd1, 0xff, 0x3c, 0x0c, 0xc2, 0x26, + 0x20, 0x83, 0xc9, 0x36, 0xfb, 0xe0, 0xf3, 0x39, 0x4b, 0xe1, 0x73, 0x2c, 0xc7, 0x90, 0x7d, 0xc8, + 0xad, 0x1e, 0x7a, 0xb5, 0x66, 0xe5, 0xbe, 0x02, 0xb8, 0x0c, 0x9b, 0xb9, 0xc6, 0xc3, 0xb0, 0x22, + 0xf3, 0x8c, 0xd5, 0x5a, 0x26, 0x75, 0xdf, 0xa2, 0xdc, 0x83, 0x55, 0x1b, 0xbe, 0x39, 0xd8, 0x87, + 0x4c, 0xe8, 0xdb, 0x28, 0x8e, 0xc1, 0xde, 0xa1, 0x52, 0x07, 0x0c, 0x43, 0xb1, 0x49, 0xeb, 0x75, + 0x34, 0xb0, 0x79, 0x6c, 0x6d, 0xc9, 0xf9, 0x97, 0x8d, 0x75, 0xf0, 0xe1, 0xa1, 0x8b, 0xf0, 0xa9, + 0xd7, 0x5f, 0xd5, 0x4e, 0xde, 0x22, 0xfc, 0x00, 0xdb, 0x17, 0xef, 0x4d, 0xe5, 0x61, 0xc2, 0x36, + 0xb4, 0x2e, 0x16, 0xc1, 0x5f, 0x44, 0x9b, 0x45, 0xb5, 0x5f, 0xf5, 0x36, 0x7c, 0x33, 0x31, 0x08, + 0x6f, 0x92, 0x1e, 0xc1, 0x2e, 0xad, 0xda, 0x24, 0xc1, 0xb5, 0x71, 0x3a, 0x76, 0x7f, 0xb8, 0x09, + 0x95, 0x2e, 0x3e, 0xdb, 0xd0, 0x86, 0xaf, 0x3a, 0x9e, 0xc4, 0x0c, 0xf9, 0x8e, 0x58, 0x43, 0xbd, + 0x18, 0xb6, 0x9b, 0xee, 0x8d, 0xc7, 0x7b, 0xde, 0xfd, 0x68, 0xa3, 0x38, 0x04, 0x1f, 0x98, 0x3d, + 0x19, 0x9f, 0xa5, 0xb9, 0x98, 0xca, 0xb3, 0x72, 0x5f, 0x65, 0xb4, 0x49, 0xce, 0x1b, 0x43, 0x7b, + 0x7c, 0x10, 0xf4, 0x0b, 0x3c, 0xce, 0x16, 0xa3, 0x79, 0x1e, 0xbf, 0xf2, 0x68, 0x6e, 0xbb, 0x03, + 0x5f, 0xfe, 0xe7, 0xb5, 0x5b, 0x1b, 0xcf, 0x62, 0x37, 0x36, 0x8d, 0xf8, 0x3b, 0x6d, 0x09, 0xe2, + 0xc7, 0x93, 0xda, 0x18, 0xf3, 0xf9, 0x8f, 0xb9, 0x58, 0xbd, 0xfb, 0x44, 0xbd, 0x84, 0x6d, 0xf8, + 0xc6, 0xa0, 0xa5, 0x1f, 0x02, 0xfb, 0xa6, 0xe2, 0x14, 0x4c, 0xb3, 0x1e, 0xc4, 0x5a, 0x87, 0x67, + 0xa8, 0xfe, 0xb4, 0x79, 0x1b, 0xda, 0xf0, 0x55, 0xc4, 0x8f, 0xb1, 0x66, 0xfc, 0x9f, 0xf8, 0x5b, + 0x18, 0x71, 0xcd, 0xdf, 0x94, 0x96, 0x33, 0xe6, 0x60, 0x49, 0xfc, 0xba, 0xd8, 0x75, 0x7e, 0x25, + 0xe2, 0x26, 0x00, 0x00, 0x00, 0x32, 0x49, 0x44, 0x41, 0x54, 0xea, 0x65, 0x54, 0x3b, 0x08, 0xf8, + 0x2a, 0x62, 0x6f, 0xec, 0x38, 0x01, 0xec, 0xbd, 0x64, 0x43, 0xec, 0xb0, 0xa1, 0x16, 0xae, 0x26, + 0x73, 0xcc, 0xf1, 0x10, 0x16, 0x8c, 0x7c, 0x53, 0xd6, 0x62, 0x61, 0xcd, 0x55, 0x4f, 0xcc, 0xa0, + 0x1f, 0x5a, 0x3b, 0xf9, 0xfc, 0xc1, 0xff, 0x01, 0xf4, 0x4f, 0x9a, 0x26, 0x12, 0xca, 0xbf, 0xd8, + 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 +}; +#else +static const uint8_t source_serif_pro_regular_12_bmp[] = { + 0x42, 0x4d, 0xc2, 0x94, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x7c, 0x00, + 0x00, 0x00, 0xe7, 0x02, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x38, 0x94, 0x00, 0x00, 0xc3, 0x0e, 0x00, 0x00, 0xc3, 0x0e, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x42, 0x47, 0x52, 0x73, 0x80, 0xc2, 0xf5, 0x28, 0x60, 0xb8, + 0x1e, 0x15, 0x20, 0x85, 0xeb, 0x01, 0x40, 0x33, 0x33, 0x13, 0x80, 0x66, 0x66, 0x26, 0x40, 0x66, + 0x66, 0x06, 0xa0, 0x99, 0x99, 0x09, 0x3c, 0x0a, 0xd7, 0x03, 0x24, 0x5c, 0x8f, 0x32, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x00, 0x00 +}; +#endif + +static const uint8_t source_serif_pro_regular_12_xml[] = { + 0x3c, 0x3f, 0x78, 0x6d, 0x6c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x31, + 0x2e, 0x30, 0x22, 0x20, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x3d, 0x22, 0x75, 0x74, + 0x66, 0x2d, 0x38, 0x22, 0x3f, 0x3e, 0x0a, 0x3c, 0x46, 0x6f, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x7a, + 0x65, 0x3d, 0x22, 0x31, 0x32, 0x22, 0x20, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3d, 0x22, 0x53, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x53, 0x65, 0x72, 0x69, 0x66, 0x20, 0x50, 0x72, 0x6f, 0x22, + 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3d, 0x22, 0x32, 0x30, 0x22, 0x20, 0x73, 0x74, 0x79, + 0x6c, 0x65, 0x3d, 0x22, 0x52, 0x65, 0x67, 0x75, 0x6c, 0x61, 0x72, 0x22, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x31, 0x35, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x30, 0x20, 0x31, 0x33, 0x20, 0x30, 0x20, 0x30, 0x22, 0x20, 0x63, 0x6f, 0x64, + 0x65, 0x3d, 0x22, 0x20, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x32, 0x20, + 0x32, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x21, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x20, 0x31, 0x20, 0x35, 0x20, 0x35, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x26, 0x71, 0x75, 0x6f, 0x74, 0x3b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x37, 0x20, 0x32, 0x20, 0x38, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, + 0x65, 0x3d, 0x22, 0x23, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x35, 0x20, 0x31, + 0x20, 0x38, 0x20, 0x31, 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x24, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x31, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x33, 0x20, 0x32, 0x20, 0x31, 0x32, 0x20, 0x31, + 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x25, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x32, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x33, 0x35, 0x20, 0x32, 0x20, 0x31, 0x32, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x26, 0x61, 0x6d, 0x70, 0x3b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x33, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x34, 0x37, 0x20, 0x31, 0x20, 0x32, 0x20, 0x35, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, + 0x3d, 0x22, 0x27, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, + 0x31, 0x20, 0x32, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x39, 0x20, 0x30, 0x20, + 0x34, 0x20, 0x31, 0x37, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x28, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x32, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x33, 0x20, 0x30, 0x20, 0x35, 0x20, 0x31, 0x37, 0x22, 0x20, + 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x29, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, + 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, + 0x35, 0x38, 0x20, 0x31, 0x20, 0x38, 0x20, 0x36, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x2a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, + 0x36, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x36, 0x20, 0x34, 0x20, 0x39, 0x20, + 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x2b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x31, 0x33, 0x22, 0x20, 0x72, 0x65, + 0x63, 0x74, 0x3d, 0x22, 0x37, 0x35, 0x20, 0x31, 0x31, 0x20, 0x34, 0x20, 0x36, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x2c, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x31, 0x20, 0x31, 0x30, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, + 0x39, 0x20, 0x38, 0x20, 0x34, 0x20, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x2d, + 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, + 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x31, + 0x32, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x38, 0x33, 0x20, 0x31, 0x30, 0x20, 0x33, + 0x20, 0x33, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x2e, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x38, 0x36, 0x20, 0x31, 0x20, 0x36, 0x20, 0x31, 0x34, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x2f, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x39, 0x32, 0x20, + 0x32, 0x20, 0x37, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x30, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x39, 0x39, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, 0x31, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x31, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, + 0x22, 0x31, 0x30, 0x36, 0x20, 0x32, 0x20, 0x38, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, + 0x65, 0x3d, 0x22, 0x32, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x31, 0x34, 0x20, + 0x32, 0x20, 0x37, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x33, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x32, 0x31, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, + 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x34, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x31, 0x32, 0x38, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x35, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x33, 0x35, + 0x20, 0x31, 0x20, 0x37, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x36, + 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, + 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x35, + 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x34, 0x32, 0x20, 0x33, 0x20, 0x37, 0x20, + 0x31, 0x30, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x37, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x31, 0x34, 0x39, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x38, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x35, + 0x36, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x39, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, + 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x36, 0x33, 0x20, 0x35, 0x20, 0x33, + 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x3a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, + 0x63, 0x74, 0x3d, 0x22, 0x31, 0x36, 0x36, 0x20, 0x35, 0x20, 0x35, 0x20, 0x31, 0x32, 0x22, 0x20, + 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x3b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, + 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x35, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, + 0x37, 0x31, 0x20, 0x33, 0x20, 0x37, 0x20, 0x39, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x26, 0x6c, 0x74, 0x3b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x37, 0x38, 0x20, + 0x35, 0x20, 0x39, 0x20, 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x3d, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x35, 0x22, 0x20, + 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x31, 0x38, 0x37, 0x20, 0x33, 0x20, 0x37, 0x20, 0x39, 0x22, + 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x3e, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, + 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, + 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, + 0x31, 0x39, 0x34, 0x20, 0x31, 0x20, 0x36, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, + 0x3d, 0x22, 0x3f, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x30, 0x30, 0x20, + 0x32, 0x20, 0x31, 0x33, 0x20, 0x31, 0x33, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x40, + 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, + 0x3d, 0x22, 0x31, 0x31, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, + 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x31, 0x33, 0x20, 0x32, 0x20, 0x31, + 0x31, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x41, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, + 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, + 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x32, 0x34, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x42, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x32, 0x33, 0x33, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x43, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x31, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x34, + 0x32, 0x20, 0x32, 0x20, 0x31, 0x31, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, + 0x22, 0x44, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, + 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, + 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x35, 0x33, 0x20, 0x32, + 0x20, 0x39, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x45, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, + 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x36, 0x32, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x46, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x31, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x32, 0x37, 0x31, 0x20, 0x32, 0x20, 0x31, 0x30, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x47, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x32, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, + 0x38, 0x31, 0x20, 0x32, 0x20, 0x31, 0x32, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, + 0x3d, 0x22, 0x48, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, + 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x39, 0x33, 0x20, 0x32, + 0x20, 0x35, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x49, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x36, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x32, 0x20, 0x34, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x32, 0x39, 0x38, 0x20, 0x32, 0x20, 0x38, 0x20, 0x31, + 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x4a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x33, 0x30, 0x36, 0x20, 0x32, 0x20, 0x31, 0x31, 0x20, 0x31, 0x31, 0x22, 0x20, + 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x4b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, + 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, + 0x31, 0x37, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, + 0x22, 0x4c, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, + 0x74, 0x68, 0x3d, 0x22, 0x31, 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, + 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x32, 0x36, 0x20, 0x32, + 0x20, 0x31, 0x34, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x4d, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x31, 0x32, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, + 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x34, 0x30, 0x20, 0x32, 0x20, 0x31, 0x32, + 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x4e, 0x22, 0x2f, 0x3e, 0x0a, + 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x31, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x35, 0x32, 0x20, 0x32, 0x20, 0x31, 0x30, 0x20, 0x31, 0x31, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x4f, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x33, 0x36, 0x32, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x50, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x31, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x37, + 0x31, 0x20, 0x32, 0x20, 0x31, 0x30, 0x20, 0x31, 0x35, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, + 0x22, 0x51, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, + 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, + 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x38, 0x31, 0x20, 0x32, + 0x20, 0x31, 0x31, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x52, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x33, 0x39, 0x32, 0x20, 0x32, 0x20, 0x37, 0x20, 0x31, + 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x53, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x33, 0x39, 0x39, 0x20, 0x32, 0x20, 0x39, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x54, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x32, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, + 0x30, 0x38, 0x20, 0x32, 0x20, 0x31, 0x32, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, + 0x3d, 0x22, 0x55, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x31, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x32, 0x30, 0x20, + 0x32, 0x20, 0x31, 0x31, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x56, + 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, + 0x3d, 0x22, 0x31, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, + 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x33, 0x31, 0x20, 0x32, 0x20, 0x31, + 0x36, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x57, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, + 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x34, 0x22, 0x20, + 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x34, 0x37, 0x20, 0x32, 0x20, 0x31, 0x31, 0x20, 0x31, + 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x58, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, + 0x63, 0x74, 0x3d, 0x22, 0x34, 0x35, 0x38, 0x20, 0x32, 0x20, 0x31, 0x31, 0x20, 0x31, 0x31, 0x22, + 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x59, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, + 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x34, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, + 0x22, 0x34, 0x36, 0x39, 0x20, 0x32, 0x20, 0x38, 0x20, 0x31, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, + 0x65, 0x3d, 0x22, 0x5a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x32, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x37, 0x37, 0x20, + 0x31, 0x20, 0x34, 0x20, 0x31, 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x5b, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x38, 0x31, 0x20, 0x31, 0x20, 0x36, 0x20, 0x31, + 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x5c, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x34, 0x38, 0x37, 0x20, 0x31, 0x20, 0x34, 0x20, 0x31, 0x34, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x5d, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x39, 0x31, + 0x20, 0x35, 0x20, 0x37, 0x20, 0x35, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x5e, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x31, 0x35, + 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x34, 0x39, 0x38, 0x20, 0x31, 0x33, 0x20, 0x37, + 0x20, 0x31, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x5f, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x35, 0x30, 0x35, 0x20, 0x31, 0x20, 0x34, 0x20, 0x34, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x60, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x30, 0x39, + 0x20, 0x35, 0x20, 0x39, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x61, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, + 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x31, 0x38, 0x20, 0x31, 0x20, 0x39, 0x20, + 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x62, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x35, 0x32, 0x37, 0x20, 0x35, 0x20, 0x37, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x63, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x31, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x33, + 0x34, 0x20, 0x31, 0x20, 0x39, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x64, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, + 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x34, 0x33, 0x20, 0x35, 0x20, 0x37, + 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x65, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x36, 0x22, 0x20, + 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, + 0x74, 0x3d, 0x22, 0x35, 0x35, 0x30, 0x20, 0x31, 0x20, 0x38, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, + 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x66, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, + 0x74, 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x35, + 0x38, 0x20, 0x35, 0x20, 0x38, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x67, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, + 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x36, 0x36, 0x20, 0x31, 0x20, + 0x31, 0x30, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x68, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x34, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, + 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x37, 0x36, 0x20, 0x31, 0x20, 0x34, 0x20, 0x31, 0x32, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x69, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x34, 0x22, 0x20, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x32, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x35, 0x38, 0x30, 0x20, 0x31, 0x20, 0x36, 0x20, 0x31, 0x36, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x6a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x30, 0x20, 0x32, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x38, 0x36, + 0x20, 0x30, 0x20, 0x31, 0x30, 0x20, 0x31, 0x33, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x6b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, + 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x35, 0x39, 0x36, 0x20, 0x31, 0x20, 0x35, + 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x6c, 0x22, 0x2f, 0x3e, 0x0a, + 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x34, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x30, 0x31, 0x20, 0x35, 0x20, 0x31, 0x34, 0x20, 0x38, 0x22, + 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x6d, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, + 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, + 0x22, 0x36, 0x31, 0x35, 0x20, 0x35, 0x20, 0x31, 0x30, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, + 0x65, 0x3d, 0x22, 0x6e, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, + 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, + 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x32, 0x35, 0x20, + 0x35, 0x20, 0x38, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x6f, 0x22, 0x2f, + 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x31, 0x30, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x33, 0x33, 0x20, 0x35, 0x20, 0x39, 0x20, 0x31, + 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x70, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, + 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x36, 0x34, 0x32, 0x20, 0x35, 0x20, 0x39, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x71, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x37, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x35, 0x31, + 0x20, 0x35, 0x20, 0x37, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x72, 0x22, + 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x22, 0x37, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, + 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x35, 0x38, 0x20, 0x35, 0x20, 0x36, 0x20, 0x38, + 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x73, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, + 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, + 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x35, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x22, 0x36, 0x36, 0x34, 0x20, 0x33, 0x20, 0x36, 0x20, 0x31, 0x30, 0x22, 0x20, 0x63, 0x6f, + 0x64, 0x65, 0x3d, 0x22, 0x74, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, + 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x22, 0x2d, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x37, + 0x30, 0x20, 0x35, 0x20, 0x31, 0x30, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x75, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, + 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x36, 0x38, 0x30, 0x20, 0x35, 0x20, 0x38, + 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x76, 0x22, 0x2f, 0x3e, 0x0a, 0x20, + 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x31, 0x32, 0x22, + 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, + 0x63, 0x74, 0x3d, 0x22, 0x36, 0x38, 0x38, 0x20, 0x35, 0x20, 0x31, 0x33, 0x20, 0x38, 0x22, 0x20, + 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x77, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, + 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, + 0x30, 0x31, 0x20, 0x35, 0x20, 0x38, 0x20, 0x38, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, + 0x78, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x22, 0x38, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x2d, 0x31, + 0x20, 0x37, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, 0x30, 0x39, 0x20, 0x35, 0x20, + 0x39, 0x20, 0x31, 0x32, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x79, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x38, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x37, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, 0x31, 0x38, 0x20, 0x35, 0x20, 0x36, 0x20, 0x38, 0x22, 0x20, + 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x7a, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, + 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, + 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, + 0x32, 0x34, 0x20, 0x31, 0x20, 0x35, 0x20, 0x31, 0x34, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, + 0x22, 0x7b, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, + 0x74, 0x68, 0x3d, 0x22, 0x35, 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x32, + 0x20, 0x33, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, 0x32, 0x39, 0x20, 0x31, 0x20, + 0x32, 0x20, 0x31, 0x36, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x7c, 0x22, 0x2f, 0x3e, + 0x0a, 0x20, 0x3c, 0x43, 0x68, 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x35, + 0x22, 0x20, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x22, 0x30, 0x20, 0x33, 0x22, 0x20, 0x72, + 0x65, 0x63, 0x74, 0x3d, 0x22, 0x37, 0x33, 0x31, 0x20, 0x31, 0x20, 0x35, 0x20, 0x31, 0x34, 0x22, + 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x7d, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x3c, 0x43, 0x68, + 0x61, 0x72, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x39, 0x22, 0x20, 0x6f, 0x66, 0x66, + 0x73, 0x65, 0x74, 0x3d, 0x22, 0x31, 0x20, 0x38, 0x22, 0x20, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x22, + 0x37, 0x33, 0x36, 0x20, 0x36, 0x20, 0x37, 0x20, 0x33, 0x22, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x3d, + 0x22, 0x7e, 0x22, 0x2f, 0x3e, 0x0a, 0x3c, 0x2f, 0x46, 0x6f, 0x6e, 0x74, 0x3e, 0x0a +}; + +/** + * Bitmap fonts were generated using FontBuilder on Windows with the following settings: + * + * Line layout, no pixel separator, no "power of two image". + * The image is a png with alpha transparency. + * The .xml descriptor file is in the "Divo compatible" format. + */ + +/** + * These embedded resources were converted from binaries files to C arrays using "xxd -i" + */ + +SSIZE_T rdtk_get_embedded_resource_file(const char* filename, const uint8_t** pData) +{ +#if defined(WINPR_WITH_PNG) + if (strcmp(filename, "source_serif_pro_regular_12.png") == 0) + { + *pData = source_serif_pro_regular_12_png; + return ARRAYSIZE(source_serif_pro_regular_12_png); + } + else if (strcmp(filename, "btn_default_normal.9.png") == 0) + { + *pData = btn_default_normal_9_png; + return ARRAYSIZE(btn_default_normal_9_png); + } + else if (strcmp(filename, "textfield_default.9.png") == 0) + { + *pData = textfield_default_9_png; + return ARRAYSIZE(textfield_default_9_png); + } +#else + if (strcmp(filename, "source_serif_pro_regular_12.bmp") == 0) + { + *pData = source_serif_pro_regular_12_bmp; + return ARRAYSIZE(source_serif_pro_regular_12_bmp); + } + else if (strcmp(filename, "btn_default_normal.9.bmp") == 0) + { + *pData = btn_default_normal_9_bmp; + return ARRAYSIZE(btn_default_normal_9_bmp); + } + else if (strcmp(filename, "textfield_default.9.bmp") == 0) + { + *pData = textfield_default_9_bmp; + return ARRAYSIZE(textfield_default_9_bmp); + } +#endif + else if (strcmp(filename, "source_serif_pro_regular_12.xml") == 0) + { + *pData = source_serif_pro_regular_12_xml; + return ARRAYSIZE(source_serif_pro_regular_12_xml); + } + + return -1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.h new file mode 100644 index 0000000000000000000000000000000000000000..1716f00b16ce53567a13936a169fa6311e54cd5a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_resources.h @@ -0,0 +1,39 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_RESOURCES_PRIVATE_H +#define RDTK_RESOURCES_PRIVATE_H + +#include +#include +#include + +#include "rdtk_engine.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + SSIZE_T rdtk_get_embedded_resource_file(const char* filename, const uint8_t** pData); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_RESOURCES_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.c new file mode 100644 index 0000000000000000000000000000000000000000..c6eaef151328f1b17da0f0ff47fe6c334008c44e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.c @@ -0,0 +1,94 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include "rdtk_surface.h" + +#include + +int rdtk_surface_fill(rdtkSurface* surface, uint16_t x, uint16_t y, uint16_t width, uint16_t height, + uint32_t color) +{ + WINPR_ASSERT(surface); + + for (uint32_t i = y; i < y * 1ul + height; i++) + { + uint8_t* line = &surface->data[1ULL * i * surface->scanline]; + for (uint32_t j = x; j < x * 1ul + width; j++) + { + uint32_t* pixel = (uint32_t*)&line[j + 4ul]; + *pixel = color; + } + } + + return 1; +} + +rdtkSurface* rdtk_surface_new(rdtkEngine* engine, uint8_t* data, uint16_t width, uint16_t height, + uint32_t scanline) +{ + WINPR_ASSERT(engine); + + rdtkSurface* surface = (rdtkSurface*)calloc(1, sizeof(rdtkSurface)); + + if (!surface) + return NULL; + + surface->engine = engine; + + surface->width = width; + surface->height = height; + + if (scanline == 0) + scanline = width * 4ul; + + surface->scanline = scanline; + + surface->data = data; + surface->owner = false; + + if (!data) + { + surface->scanline = (surface->width + (surface->width % 4ul)) * 4ul; + + surface->data = (uint8_t*)calloc(surface->height, surface->scanline); + + if (!surface->data) + { + free(surface); + return NULL; + } + + surface->owner = true; + } + + return surface; +} + +void rdtk_surface_free(rdtkSurface* surface) +{ + if (!surface) + return; + + if (surface->owner) + free(surface->data); + + free(surface); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..8d69279d48882d610fc8f3d364620bff2c91d1ca --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_surface.h @@ -0,0 +1,38 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_SURFACE_PRIVATE_H +#define RDTK_SURFACE_PRIVATE_H + +#include +#include +#include + +#include "rdtk_engine.h" + +struct rdtk_surface +{ + rdtkEngine* engine; + + uint16_t width; + uint16_t height; + uint32_t scanline; + uint8_t* data; + bool owner; +}; +#endif /* RDTK_SURFACE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.c new file mode 100644 index 0000000000000000000000000000000000000000..73867ee9e9f9c9401dba9853cbac4df3270aadac --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.c @@ -0,0 +1,130 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include + +#include "rdtk_font.h" + +#include "rdtk_text_field.h" + +int rdtk_text_field_draw(rdtkSurface* surface, uint16_t nXDst, uint16_t nYDst, uint16_t nWidth, + uint16_t nHeight, rdtkTextField* textField, const char* text) +{ + uint16_t textWidth = 0; + uint16_t textHeight = 0; + + WINPR_ASSERT(surface); + WINPR_ASSERT(textField); + WINPR_ASSERT(text); + + rdtkEngine* engine = surface->engine; + rdtkFont* font = engine->font; + textField = surface->engine->textField; + rdtkNinePatch* ninePatch = textField->ninePatch; + + rdtk_font_text_draw_size(font, &textWidth, &textHeight, text); + + rdtk_nine_patch_draw(surface, nXDst, nYDst, nWidth, nHeight, ninePatch); + + if ((textWidth > 0) && (textHeight > 0)) + { + const int fwd = (ninePatch->width - ninePatch->fillWidth); + const int fhd = (ninePatch->height - ninePatch->fillHeight); + + uint16_t fillWidth = nWidth - WINPR_ASSERTING_INT_CAST(uint16_t, fwd); + uint16_t fillHeight = nHeight - WINPR_ASSERTING_INT_CAST(uint16_t, fhd); + uint16_t offsetX = WINPR_ASSERTING_INT_CAST(uint16_t, ninePatch->fillLeft); + uint16_t offsetY = WINPR_ASSERTING_INT_CAST(uint16_t, ninePatch->fillTop); + + if (textWidth < fillWidth) + { + const int wd = ((fillWidth - textWidth) / 2) + ninePatch->fillLeft; + offsetX = WINPR_ASSERTING_INT_CAST(uint16_t, wd); + } + else if (textWidth < ninePatch->width) + { + const int wd = ((ninePatch->width - textWidth) / 2); + offsetX = WINPR_ASSERTING_INT_CAST(uint16_t, wd); + } + + if (textHeight < fillHeight) + { + const int wd = ((fillHeight - textHeight) / 2) + ninePatch->fillTop; + offsetY = WINPR_ASSERTING_INT_CAST(uint16_t, wd); + } + else if (textHeight < ninePatch->height) + { + const int wd = ((ninePatch->height - textHeight) / 2); + offsetY = WINPR_ASSERTING_INT_CAST(uint16_t, wd); + } + + rdtk_font_draw_text(surface, nXDst + offsetX, nYDst + offsetY, font, text); + } + + return 1; +} + +rdtkTextField* rdtk_text_field_new(rdtkEngine* engine, rdtkNinePatch* ninePatch) +{ + WINPR_ASSERT(engine); + WINPR_ASSERT(ninePatch); + + rdtkTextField* textField = (rdtkTextField*)calloc(1, sizeof(rdtkTextField)); + + if (!textField) + return NULL; + + textField->engine = engine; + textField->ninePatch = ninePatch; + + return textField; +} + +void rdtk_text_field_free(rdtkTextField* textField) +{ + free(textField); +} + +int rdtk_text_field_engine_init(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + + if (!engine->textField) + { + engine->textField = rdtk_text_field_new(engine, engine->textField9patch); + if (!engine->textField) + return -1; + } + + return 1; +} + +int rdtk_text_field_engine_uninit(rdtkEngine* engine) +{ + WINPR_ASSERT(engine); + if (engine->textField) + { + rdtk_text_field_free(engine->textField); + engine->textField = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.h b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.h new file mode 100644 index 0000000000000000000000000000000000000000..571d80e259d52215c80bfcd05d6b46fed321bafb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/rdtk_text_field.h @@ -0,0 +1,50 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 RDTK_TEXT_FIELD_PRIVATE_H +#define RDTK_TEXT_FIELD_PRIVATE_H + +#include + +#include "rdtk_surface.h" +#include "rdtk_nine_patch.h" + +#include "rdtk_engine.h" + +struct rdtk_text_field +{ + rdtkEngine* engine; + rdtkNinePatch* ninePatch; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int rdtk_text_field_engine_init(rdtkEngine* engine); + int rdtk_text_field_engine_uninit(rdtkEngine* engine); + + rdtkTextField* rdtk_text_field_new(rdtkEngine* engine, rdtkNinePatch* ninePatch); + void rdtk_text_field_free(rdtkTextField* textField); + +#ifdef __cplusplus +} +#endif + +#endif /* RDTK_TEXT_FIELD_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a754a02046bb18d59050a46615adf771df2a859 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestRdTk") +set(MODULE_PREFIX "TEST_RDTK") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestRdTkNinePatch.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr rdtk) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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 "RdTk/Test") diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/TestRdTkNinePatch.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/TestRdTkNinePatch.c new file mode 100644 index 0000000000000000000000000000000000000000..2c7405f526616b07cb6ddc4ca00654c6a3350020 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/librdtk/test/TestRdTkNinePatch.c @@ -0,0 +1,62 @@ + +#include +#include +#include +#include + +int TestRdTkNinePatch(int argc, char* argv[]) +{ + rdtkEngine* engine = NULL; + rdtkSurface* surface = NULL; + uint32_t scanline = 0; + uint32_t width = 0; + uint32_t height = 0; + uint8_t* data = NULL; + int ret = -1; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!(engine = rdtk_engine_new())) + { + printf("%s: error creating rdtk engine (%" PRIu32 ")\n", __func__, GetLastError()); + goto out; + } + + width = 1024; + height = 768; + scanline = width * 4; + + /* let rdtk allocate the surface buffer */ + if (!(surface = rdtk_surface_new(engine, NULL, width, height, scanline))) + { + printf("%s: error creating auto-allocated surface (%" PRIu32 ")\n", __func__, + GetLastError()); + goto out; + } + rdtk_surface_free(surface); + surface = NULL; + + /* test self-allocated buffer */ + if (!(data = calloc(height, scanline))) + { + printf("%s: error allocating surface buffer (%" PRIu32 ")\n", __func__, GetLastError()); + goto out; + } + + if (!(surface = rdtk_surface_new(engine, data, width, height, scanline))) + { + printf("%s: error creating self-allocated surface (%" PRIu32 ")\n", __func__, + GetLastError()); + goto out; + } + + ret = 0; + +out: + rdtk_surface_free(surface); + rdtk_engine_free(engine); + free(data); + + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..de8b1d6c3f51d2675b6593b26d81f1583d82b54c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/CMakeLists.txt @@ -0,0 +1,35 @@ +# RdTk: Remote Desktop Toolkit +# rdtk cmake build script +# +# Copyright 2014 Marc-Andre Moreau +# +# 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 "rdtk-sample") +set(MODULE_PREFIX "RDTK_SAMPLE") + +find_package(X11 REQUIRED) + +include_directories(SYSTEM ${X11_INCLUDE_DIR}) + +set(SRCS rdtk_x11.c) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${RDTK_VERSION}" SRCS) + +set(LIBS rdtk) + +list(APPEND LIBS ${X11_LIBRARIES}) + +target_link_libraries(${MODULE_NAME} PRIVATE ${LIBS} winpr) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "RdTk") diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/rdtk_x11.c b/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/rdtk_x11.c new file mode 100644 index 0000000000000000000000000000000000000000..24a2d23490275329890139522e0c1ca2436346fe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/sample/rdtk_x11.c @@ -0,0 +1,142 @@ +/** + * RdTk: Remote Desktop Toolkit + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include +#include +#include +#include + +#include +#include + +#define TAG "rdtk.sample" + +int main(int argc, char** argv) +{ + int rc = 1; + int pf_count = 0; + XEvent event; + XImage* image = NULL; + Pixmap pixmap = 0; + Window window = 0; + rdtkSurface* surface = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + Display* display = XOpenDisplay(NULL); + + if (!display) + { + WLog_ERR(TAG, "Cannot open display"); + return 1; + } + + const INT32 x = 10; + const INT32 y = 10; + const UINT32 width = 640; + const UINT32 height = 480; + + const int screen_number = DefaultScreen(display); + const Screen* screen = ScreenOfDisplay(display, screen_number); + Visual* visual = DefaultVisual(display, screen_number); + const GC gc = DefaultGC(display, screen_number); + const int depth = DefaultDepthOfScreen(screen); + const Window root_window = RootWindow(display, screen_number); + const unsigned long border = BlackPixel(display, screen_number); + const unsigned long background = WhitePixel(display, screen_number); + + int scanline_pad = 0; + + XPixmapFormatValues* pfs = XListPixmapFormats(display, &pf_count); + + for (int index = 0; index < pf_count; index++) + { + XPixmapFormatValues* pf = &pfs[index]; + + if (pf->depth == depth) + { + scanline_pad = pf->scanline_pad; + break; + } + } + + XFree(pfs); + + rdtkEngine* engine = rdtk_engine_new(); + const size_t scanline = width * 4ULL; + uint8_t* buffer = (uint8_t*)calloc(height, scanline); + if (!engine || !buffer || (depth < 0)) + goto fail; + + surface = rdtk_surface_new(engine, buffer, width, height, scanline); + + rdtk_surface_fill(surface, 0, 0, width, height, 0x3BB9FF); + rdtk_label_draw(surface, 16, 16, 128, 32, NULL, "label", 0, 0); + rdtk_button_draw(surface, 16, 64, 128, 32, NULL, "button"); + rdtk_text_field_draw(surface, 16, 128, 128, 32, NULL, "text field"); + + window = XCreateSimpleWindow(display, root_window, x, y, width, height, 1, border, background); + + XSelectInput(display, window, ExposureMask | KeyPressMask); + XMapWindow(display, window); + + XSetFunction(display, gc, GXcopy); + XSetFillStyle(display, gc, FillSolid); + + pixmap = XCreatePixmap(display, window, width, height, (unsigned)depth); + + image = XCreateImage(display, visual, (unsigned)depth, ZPixmap, 0, (char*)buffer, width, height, + scanline_pad, 0); + + while (1) + { + XNextEvent(display, &event); + + if (event.type == Expose) + { + XPutImage(display, pixmap, gc, image, 0, 0, 0, 0, width, height); + XCopyArea(display, pixmap, window, gc, 0, 0, width, height, 0, 0); + } + + if (event.type == KeyPress) + break; + + if (event.type == ClientMessage) + break; + } + + XFlush(display); + + rc = 0; +fail: + if (image) + XDestroyImage(image); + XCloseDisplay(display); + + rdtk_surface_free(surface); + free(buffer); + + rdtk_engine_free(engine); + + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0fa9ab6c73d01aefed478041b97a4402f480896d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/CMakeLists.txt @@ -0,0 +1,48 @@ +if(NOT RDTK_FORCE_STATIC_BUILD) + include(SetFreeRDPCMakeInstallDir) + + # cmake package + export(PACKAGE rdtk) + + configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/rdtkConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/rdtkConfig.cmake + INSTALL_DESTINATION ${RDTK_CMAKE_INSTALL_DIR} PATH_VARS RDTK_INCLUDE_DIR + ) + + write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/rdtkConfigVersion.cmake VERSION ${RDTK_VERSION} COMPATIBILITY SameMajorVersion + ) +endif() + +set(RDTK_BUILD_CONFIG_LIST "") +get_cmake_property(res VARIABLES) +foreach(var ${res}) + if(var MATCHES "^WITH_*|^BUILD_TESTING*|^RDTK_HAVE_*") + list(APPEND RDTK_BUILD_CONFIG_LIST "${var}=${${var}}") + endif() +endforeach() + +include(pkg-config-install-prefix) + +string(REPLACE ";" " " RDTK_BUILD_CONFIG "${RDTK_BUILD_CONFIG_LIST}") +cleaning_configure_file(${CMAKE_CURRENT_SOURCE_DIR}/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/rdtk/version.h) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/buildflags.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/rdtk/buildflags.h +) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/build-config.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/rdtk/build-config.h +) +cleaning_configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/rdtk/config.h) + +if(NOT RDTK_FORCE_STATIC_BUILD) + cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/rdtk.pc.in ${CMAKE_CURRENT_BINARY_DIR}/rdtk${RDTK_VERSION_MAJOR}.pc @ONLY + ) + + set(RDTK_INSTALL_INCLUDE_DIR ${RDTK_INCLUDE_DIR}/rdtk) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/rdtk${RDTK_VERSION_MAJOR}.pc DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/rdtkConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/rdtkConfigVersion.cmake + DESTINATION ${RDTK_CMAKE_INSTALL_DIR} + ) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/build-config.h.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/build-config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..f1fe835b6564c8d8c43178d0b1757c8baa567be5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/build-config.h.in @@ -0,0 +1,20 @@ +#ifndef RDTK_BUILD_CONFIG_H +#define RDTK_BUILD_CONFIG_H + +#define RDTK_DATA_PATH "${WINPR_DATA_PATH}" +#define RDTK_KEYMAP_PATH "${WINPR_KEYMAP_PATH}" +#define RDTK_PLUGIN_PATH "${WINPR_PLUGIN_PATH}" + +#define RDTK_INSTALL_PREFIX "${WINPR_INSTALL_PREFIX}" + +#define RDTK_LIBRARY_PATH "${WINPR_LIBRARY_PATH}" + +#define RDTK_ADDIN_PATH "${WINPR_ADDIN_PATH}" + +#define RDTK_SHARED_LIBRARY_SUFFIX "${CMAKE_SHARED_LIBRARY_SUFFIX}" +#define RDTK_SHARED_LIBRARY_PREFIX "${CMAKE_SHARED_LIBRARY_PREFIX}" + +#define RDTK_VENDOR_STRING "${VENDOR}" +#define RDTK_PRODUCT_STRING "${PRODUCT}" + +#endif /* RDTK_BUILD_CONFIG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/buildflags.h.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/buildflags.h.in new file mode 100644 index 0000000000000000000000000000000000000000..affdadbec50f3e3faead59f66846cc93ee5fadfd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/buildflags.h.in @@ -0,0 +1,11 @@ +#ifndef RDTK_BUILD_FLAGS_H +#define RDTK_BUILD_FLAGS_H + +#define RDTK_CFLAGS "${CMAKE_CURRENT_C_FLAGS}" +#define RDTK_COMPILER_ID "${CMAKE_C_COMPILER_ID}" +#define RDTK_COMPILER_VERSION "${CMAKE_C_COMPILER_VERSION}" +#define RDTK_TARGET_ARCH "${TARGET_ARCH}" +#define RDTK_BUILD_CONFIG "${RDTK_BUILD_CONFIG}" +#define RDTK_BUILD_TYPE "${CURRENT_BUILD_CONFIG}" + +#endif /* RDTK_BUILD_FLAGS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/config.h.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..c6243d341c6e0b77501ffbb434957893fcff67ef --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/config.h.in @@ -0,0 +1,4 @@ +#ifndef RDTK_CONFIG_H +#define RDTK_CONFIG_H + +#endif /* RDTK_CONFIG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtk.pc.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtk.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..aed9f3b1b9afdd058a2a90dce4fdddc9e24d95a9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtk.pc.in @@ -0,0 +1,15 @@ +prefix=@PKG_CONFIG_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${prefix}/@RDTK_INCLUDE_DIR@ +libs=-lrdtk@RDTK_VERSION_MAJOR@ + +Name: rdtk@RDTK_API_VERSION@ +Description: rdtk: +URL: http://www.freerdp.com/ +Version: @RDTK_VERSION@ +Requires: +Requires.private: winpr@WINPR_VERSION_MAJOR@ +Libs: -L${libdir} ${libs} +Libs.private: +Cflags: -I${includedir} diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtkConfig.cmake.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtkConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..230e92c4449baaa3b0c4390fae4dbb177f78bafd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/rdtkConfig.cmake.in @@ -0,0 +1,9 @@ +@PACKAGE_INIT@ + +set(RDTK_VERSION_MAJOR "@RDTK_VERSION_MAJOR@") +set(RDTK_VERSION_MINOR "@RDTK_VERSION_MINOR@") +set(RDTK_VERSION_REVISION "@RDTK_VERSION_REVISION@") + +set_and_check(RDTK_INCLUDE_DIR "@PACKAGE_RDTK_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/rdtk.cmake") diff --git a/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/version.h.in b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/version.h.in new file mode 100644 index 0000000000000000000000000000000000000000..d1fd20067cd219ae3adab868c15589278cab21b1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/rdtk/templates/version.h.in @@ -0,0 +1,32 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Version includes + * + * Copyright 2021 Thincast Technologies GmbH + * Copyright 2021 Armin Novak + * + * 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 RDTK_VERSION_H +#define RDTK_VERSION_H + +#define RDTK_VERSION_MAJOR ${RDTK_VERSION_MAJOR} +#define RDTK_VERSION_MINOR ${RDTK_VERSION_MINOR} +#define RDTK_VERSION_REVISION ${RDTK_VERSION_REVISION} +#define RDTK_VERSION_SUFFIX "${RDTK_VERSION_SUFFIX}" +#define RDTK_API_VERSION "${RDTK_API_VERSION}" +#define RDTK_VERSION "${RDTK_VERSION}" +#define RDTK_VERSION_FULL "${RDTK_VERSION_FULL}" +#define RDTK_GIT_REVISION "${GIT_REVISION}" + +#endif /* RDTK_VERSION_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd5792d3667c2166a8575d5b38e3c1217e621294 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/CMakeLists.txt @@ -0,0 +1,77 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Mac OS X Server cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "mfreerdp-server") +set(MODULE_PREFIX "FREERDP_SERVER_MAC") + +find_library(AUDIO_TOOL AudioToolbox) +find_library(CORE_AUDIO CoreAudio) +find_library(CORE_VIDEO CoreVideo) +find_library(APP_SERVICES ApplicationServices) +find_library(IOKIT IOKit) +find_library(IOSURFACE IOSurface) +find_library(CARBON Carbon) + +set(${MODULE_PREFIX}_SRCS + mfreerdp.c + mfreerdp.h + mf_interface.c + mf_interface.h + mf_event.c + mf_event.h + mf_peer.c + mf_peer.h + mf_info.c + mf_info.h + mf_input.c + mf_input.h + mf_mountain_lion.c + mf_mountain_lion.h +) + +if(CHANNEL_AUDIN_SERVER) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS} mf_audin.c mf_audin.h) +endif() + +if(CHANNEL_RDPSND_SERVER) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS} mf_rdpsnd.c mf_rdpsnd.h) + +endif() + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) +if(WITH_BINARY_VERSIONING) + set_target_properties(${MODULE_NAME} PROPERTIES OUTPUT_NAME "${MODULE_NAME}${FREERDP_API_VERSION}") +endif() + +set(${MODULE_PREFIX}_LIBS + ${${MODULE_PREFIX}_LIBS} + freerdp-server + ${AUDIO_TOOL} + ${CORE_AUDIO} + ${CORE_VIDEO} + ${APP_SERVICES} + ${IOKIT} + ${IOSURFACE} + ${CARBON} +) + +set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} winpr freerdp) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS}) +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Mac") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..1699b443aab90acd63cbc8b7950029c50684d4ab --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_SERVER_NAME "mfreerdp-server") +set(FREERDP_SERVER_PLATFORM "X11") +set(FREERDP_SERVER_VENDOR "FreeRDP") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.c new file mode 100644 index 0000000000000000000000000000000000000000..aaabafa960885a6075df0f09ec757adc9668f7bc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.c @@ -0,0 +1,64 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Audio Input) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2023 Pascal Nowack + * + * 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 + +#include "mfreerdp.h" + +#include "mf_audin.h" +#include "mf_interface.h" + +#include +#include +#define TAG SERVER_TAG("mac") + +static UINT mf_peer_audin_data(audin_server_context* audin, const SNDIN_DATA* data) +{ + /* TODO: Implement */ + WINPR_ASSERT(audin); + WINPR_ASSERT(data); + + WLog_WARN(TAG, "not implemented"); + WLog_DBG(TAG, "receive %" PRIdz " bytes.", Stream_Length(data->Data)); + return CHANNEL_RC_OK; +} + +BOOL mf_peer_audin_init(mfPeerContext* context) +{ + WINPR_ASSERT(context); + + context->audin = audin_server_context_new(context->vcm); + context->audin->rdpcontext = &context->_p; + context->audin->userdata = context; + + context->audin->Data = mf_peer_audin_data; + + return audin_server_set_formats(context->audin, -1, NULL); +} + +void mf_peer_audin_uninit(mfPeerContext* context) +{ + WINPR_ASSERT(context); + + audin_server_context_free(context->audin); + context->audin = NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.h new file mode 100644 index 0000000000000000000000000000000000000000..31edffa73e110a0f7f2746fd4931f5b1df224cfb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_audin.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Audio Input) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_AUDIN_H +#define FREERDP_SERVER_MAC_AUDIN_H + +#include +#include + +#include "mf_types.h" +#include "mfreerdp.h" + +BOOL mf_peer_audin_init(mfPeerContext* context); +void mf_peer_audin_uninit(mfPeerContext* context); + +#endif /* FREERDP_SERVER_MAC_AUDIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.c new file mode 100644 index 0000000000000000000000000000000000000000..7ef315ea311bc11535ab3b5df0dfbdb2ef970531 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.c @@ -0,0 +1,219 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * OS X Server Event Handling + * + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include +#include +#include +#include + +#include "mf_event.h" + +#include +#define TAG SERVER_TAG("mac") + +static int mf_is_event_set(mfEventQueue* event_queue) +{ + fd_set rfds; + int num_set; + struct timeval time = { 0 }; + + FD_ZERO(&rfds); + FD_SET(event_queue->pipe_fd[0], &rfds); + num_set = select(event_queue->pipe_fd[0] + 1, &rfds, 0, 0, &time); + + return (num_set == 1); +} + +static void mf_signal_event(mfEventQueue* event_queue) +{ + int length; + + length = write(event_queue->pipe_fd[1], "sig", 4); + + if (length != 4) + WLog_ERR(TAG, "mf_signal_event: error"); +} + +static void mf_set_event(mfEventQueue* event_queue) +{ + int length; + + length = write(event_queue->pipe_fd[1], "sig", 4); + + if (length != 4) + WLog_ERR(TAG, "mf_set_event: error"); +} + +static void mf_clear_events(mfEventQueue* event_queue) +{ + int length; + + while (mf_is_event_set(event_queue)) + { + length = read(event_queue->pipe_fd[0], &length, 4); + + if (length != 4) + WLog_ERR(TAG, "mf_clear_event: error"); + } +} + +static void mf_clear_event(mfEventQueue* event_queue) +{ + int length; + + length = read(event_queue->pipe_fd[0], &length, 4); + + if (length != 4) + WLog_ERR(TAG, "mf_clear_event: error"); +} + +void mf_event_push(mfEventQueue* event_queue, mfEvent* event) +{ + pthread_mutex_lock(&(event_queue->mutex)); + + if (event_queue->count >= event_queue->size) + { + event_queue->size *= 2; + event_queue->events = + (mfEvent**)realloc((void*)event_queue->events, sizeof(mfEvent*) * event_queue->size); + } + + event_queue->events[(event_queue->count)++] = event; + + pthread_mutex_unlock(&(event_queue->mutex)); + + mf_set_event(event_queue); +} + +mfEvent* mf_event_peek(mfEventQueue* event_queue) +{ + mfEvent* event; + + pthread_mutex_lock(&(event_queue->mutex)); + + if (event_queue->count < 1) + event = NULL; + else + event = event_queue->events[0]; + + pthread_mutex_unlock(&(event_queue->mutex)); + + return event; +} + +mfEvent* mf_event_pop(mfEventQueue* event_queue) +{ + mfEvent* event; + + pthread_mutex_lock(&(event_queue->mutex)); + + if (event_queue->count < 1) + return NULL; + + /* remove event signal */ + mf_clear_event(event_queue); + + event = event_queue->events[0]; + (event_queue->count)--; + + memmove(&event_queue->events[0], &event_queue->events[1], event_queue->count * sizeof(void*)); + + pthread_mutex_unlock(&(event_queue->mutex)); + + return event; +} + +mfEventRegion* mf_event_region_new(int x, int y, int width, int height) +{ + mfEventRegion* event_region = malloc(sizeof(mfEventRegion)); + + if (event_region != NULL) + { + event_region->x = x; + event_region->y = y; + event_region->width = width; + event_region->height = height; + } + + return event_region; +} + +void mf_event_region_free(mfEventRegion* event_region) +{ + free(event_region); +} + +mfEvent* mf_event_new(int type) +{ + mfEvent* event = malloc(sizeof(mfEvent)); + if (!event) + return NULL; + event->type = type; + return event; +} + +void mf_event_free(mfEvent* event) +{ + free(event); +} + +mfEventQueue* mf_event_queue_new() +{ + mfEventQueue* event_queue = malloc(sizeof(mfEventQueue)); + + if (event_queue != NULL) + { + event_queue->pipe_fd[0] = -1; + event_queue->pipe_fd[1] = -1; + + event_queue->size = 16; + event_queue->count = 0; + event_queue->events = (mfEvent**)malloc(sizeof(mfEvent*) * event_queue->size); + + if (pipe(event_queue->pipe_fd) < 0) + { + free(event_queue); + return NULL; + } + + pthread_mutex_init(&(event_queue->mutex), NULL); + } + + return event_queue; +} + +void mf_event_queue_free(mfEventQueue* event_queue) +{ + if (event_queue->pipe_fd[0] != -1) + { + close(event_queue->pipe_fd[0]); + event_queue->pipe_fd[0] = -1; + } + + if (event_queue->pipe_fd[1] != -1) + { + close(event_queue->pipe_fd[1]); + event_queue->pipe_fd[1] = -1; + } + + pthread_mutex_destroy(&(event_queue->mutex)); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.h new file mode 100644 index 0000000000000000000000000000000000000000..197cfd7910e5fdfb6eccdcc64281ec10ca3234bb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_event.h @@ -0,0 +1,75 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * OS X Server Event Handling + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_EVENT_H +#define FREERDP_SERVER_MAC_EVENT_H + +typedef struct mf_event mfEvent; +typedef struct mf_event_queue mfEventQueue; +typedef struct mf_event_region mfEventRegion; + +#include +#include "mfreerdp.h" + +//#include "mf_peer.h" + +enum mf_event_type +{ + FREERDP_SERVER_MAC_EVENT_TYPE_REGION, + FREERDP_SERVER_MAC_EVENT_TYPE_FRAME_TICK +}; + +struct mf_event +{ + int type; +}; + +struct mf_event_queue +{ + int size; + int count; + int pipe_fd[2]; + mfEvent** events; + pthread_mutex_t mutex; +}; + +struct mf_event_region +{ + int type; + + int x; + int y; + int width; + int height; +}; + +void mf_event_push(mfEventQueue* event_queue, mfEvent* event); +mfEvent* mf_event_peek(mfEventQueue* event_queue); +mfEvent* mf_event_pop(mfEventQueue* event_queue); + +mfEventRegion* mf_event_region_new(int x, int y, int width, int height); +void mf_event_region_free(mfEventRegion* event_region); + +mfEvent* mf_event_new(int type); +void mf_event_free(mfEvent* event); + +mfEventQueue* mf_event_queue_new(void); +void mf_event_queue_free(mfEventQueue* event_queue); + +#endif /* FREERDP_SERVER_MAC_EVENT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.c new file mode 100644 index 0000000000000000000000000000000000000000..6da89cce921e9ff1791dd23e65f8f437f1a7a763 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.c @@ -0,0 +1,231 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Mac OS X Server + * + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include + +#include "mf_info.h" +#include "mf_mountain_lion.h" + +#define MF_INFO_DEFAULT_FPS 30 +#define MF_INFO_MAXPEERS 32 + +static mfInfo* mfInfoInstance = NULL; + +int mf_info_lock(mfInfo* mfi) +{ + int status = pthread_mutex_lock(&mfi->mutex); + + switch (status) + { + case 0: + return TRUE; + break; + + default: + return -1; + break; + } + + return 1; +} + +int mf_info_try_lock(mfInfo* mfi, UINT32 ms) +{ + int status = pthread_mutex_trylock(&mfi->mutex); + + switch (status) + { + case 0: + return TRUE; + break; + + case EBUSY: + return FALSE; + break; + + default: + return -1; + break; + } + + return 1; +} + +int mf_info_unlock(mfInfo* mfi) +{ + int status = pthread_mutex_unlock(&mfi->mutex); + + switch (status) + { + case 0: + return TRUE; + break; + + default: + return -1; + break; + } + + return 1; +} + +static mfInfo* mf_info_init(void) +{ + mfInfo* mfi; + + mfi = (mfInfo*)calloc(1, sizeof(mfInfo)); + + if (mfi != NULL) + { + pthread_mutex_init(&mfi->mutex, NULL); + + mfi->peers = (freerdp_peer**)calloc(MF_INFO_MAXPEERS, sizeof(freerdp_peer*)); + if (!mfi->peers) + { + free(mfi); + return NULL; + } + + mfi->framesPerSecond = MF_INFO_DEFAULT_FPS; + mfi->input_disabled = FALSE; + } + + return mfi; +} + +mfInfo* mf_info_get_instance(void) +{ + if (mfInfoInstance == NULL) + mfInfoInstance = mf_info_init(); + + return mfInfoInstance; +} + +void mf_info_peer_register(mfInfo* mfi, mfPeerContext* context) +{ + if (mf_info_lock(mfi) > 0) + { + int peerId; + + if (mfi->peerCount == MF_INFO_MAXPEERS) + { + mf_info_unlock(mfi); + return; + } + + context->info = mfi; + + if (mfi->peerCount == 0) + { + mf_mlion_display_info(&mfi->servscreen_width, &mfi->servscreen_height, &mfi->scale); + mf_mlion_screen_updates_init(); + mf_mlion_start_getting_screen_updates(); + } + + peerId = 0; + + for (int i = 0; i < MF_INFO_MAXPEERS; ++i) + { + // empty index will be our peer id + if (mfi->peers[i] == NULL) + { + peerId = i; + break; + } + } + + mfi->peers[peerId] = ((rdpContext*)context)->peer; + mfi->peers[peerId]->pId = peerId; + mfi->peerCount++; + + mf_info_unlock(mfi); + } +} + +void mf_info_peer_unregister(mfInfo* mfi, mfPeerContext* context) +{ + if (mf_info_lock(mfi) > 0) + { + int peerId; + + peerId = ((rdpContext*)context)->peer->pId; + mfi->peers[peerId] = NULL; + mfi->peerCount--; + + if (mfi->peerCount == 0) + mf_mlion_stop_getting_screen_updates(); + + mf_info_unlock(mfi); + } +} + +BOOL mf_info_have_updates(mfInfo* mfi) +{ + if (mfi->framesWaiting == 0) + return FALSE; + + return TRUE; +} + +void mf_info_update_changes(mfInfo* mfi) +{ +} + +void mf_info_find_invalid_region(mfInfo* mfi) +{ + mf_mlion_get_dirty_region(&mfi->invalid); +} + +void mf_info_clear_invalid_region(mfInfo* mfi) +{ + mf_mlion_clear_dirty_region(); + mfi->invalid.height = 0; + mfi->invalid.width = 0; +} + +void mf_info_invalidate_full_screen(mfInfo* mfi) +{ + mfi->invalid.x = 0; + mfi->invalid.y = 0; + mfi->invalid.height = mfi->servscreen_height; + mfi->invalid.width = mfi->servscreen_width; +} + +BOOL mf_info_have_invalid_region(mfInfo* mfi) +{ + if (mfi->invalid.width * mfi->invalid.height == 0) + return FALSE; + + return TRUE; +} + +void mf_info_getScreenData(mfInfo* mfi, long* width, long* height, BYTE** pBits, int* pitch) +{ + *width = mfi->invalid.width / mfi->scale; + *height = mfi->invalid.height / mfi->scale; + *pitch = mfi->servscreen_width * mfi->scale * 4; + + mf_mlion_get_pixelData(mfi->invalid.x / mfi->scale, mfi->invalid.y / mfi->scale, *width, + *height, pBits); + + *pBits = *pBits + (mfi->invalid.x * 4) + (*pitch * mfi->invalid.y); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.h new file mode 100644 index 0000000000000000000000000000000000000000..8f089824ef0a2295e4bf8c0dd59f5e09aadd7d77 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_info.h @@ -0,0 +1,49 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_INFO_H +#define FREERDP_SERVER_MAC_INFO_H + +#define FREERDP_SERVER_MAC_INFO_DEFAULT_FPS 1 +#define FREERDP_SERVER_MAC_INFO_MAXPEERS 1 + +#include +#include + +#include "mf_interface.h" + +int mf_info_lock(mfInfo* mfi); +int mf_info_try_lock(mfInfo* mfi, UINT32 ms); +int mf_info_unlock(mfInfo* mfi); + +mfInfo* mf_info_get_instance(void); +void mf_info_peer_register(mfInfo* mfi, mfPeerContext* context); +void mf_info_peer_unregister(mfInfo* mfi, mfPeerContext* context); + +BOOL mf_info_have_updates(mfInfo* mfi); +void mf_info_update_changes(mfInfo* mfi); +void mf_info_find_invalid_region(mfInfo* mfi); +void mf_info_clear_invalid_region(mfInfo* mfi); +void mf_info_invalidate_full_screen(mfInfo* mfi); +BOOL mf_info_have_invalid_region(mfInfo* mfi); +void mf_info_getScreenData(mfInfo* mfi, long* width, long* height, BYTE** pBits, int* pitch); +// BOOL CALLBACK mf_info_monEnumCB(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM +// dwData); + +#endif /* FREERDP_SERVER_MAC_INFO_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4af855d113ff1467f57689d92dd24c65e6be8a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.c @@ -0,0 +1,511 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Input) + * + * Copyright 2013 Corey Clayton + * + * 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 + +#include +#include + +#include + +#include "mf_input.h" +#include "mf_info.h" + +#include +#define TAG SERVER_TAG("mac") + +static const CGKeyCode keymap[256] = { + 0xFF, // 0x0 + kVK_Escape, // 0x1 + kVK_ANSI_1, // 0x2 + kVK_ANSI_2, // 0x3 + kVK_ANSI_3, // 0x4 + kVK_ANSI_4, // 0x5 + kVK_ANSI_5, // 0x6 + kVK_ANSI_6, // 0x7 + kVK_ANSI_7, // 0x8 + kVK_ANSI_8, // 0x9 + kVK_ANSI_9, // 0xa + kVK_ANSI_0, // 0xb + kVK_ANSI_Minus, // 0xc + kVK_ANSI_Equal, // 0xd + kVK_Delete, // 0xe + kVK_Tab, // 0xf + kVK_ANSI_Q, // 0x10 + kVK_ANSI_W, // 0x11 + kVK_ANSI_E, // 0x12 + kVK_ANSI_R, // 0x13 + kVK_ANSI_T, // 0x14 + kVK_ANSI_Y, // 0x15 + kVK_ANSI_U, // 0x16 + kVK_ANSI_I, // 0x17 + kVK_ANSI_O, // 0x18 + kVK_ANSI_P, // 0x19 + kVK_ANSI_LeftBracket, // 0x1a + kVK_ANSI_RightBracket, // 0x1b + kVK_Return, // 0x1c + kVK_Control, // 0x1d + kVK_ANSI_A, // 0x1e + kVK_ANSI_S, // 0x1f + kVK_ANSI_D, // 0x20 + kVK_ANSI_F, // 0x21 + kVK_ANSI_G, // 0x22 + kVK_ANSI_H, // 0x23 + kVK_ANSI_J, // 0x24 + kVK_ANSI_K, // 0x25 + kVK_ANSI_L, // 0x26 + kVK_ANSI_Semicolon, // 0x27 + kVK_ANSI_Quote, // 0x28 + kVK_ANSI_Grave, // 0x29 + kVK_Shift, // 0x2a + kVK_ANSI_Backslash, // 0x2b + kVK_ANSI_Z, // 0x2c + kVK_ANSI_X, // 0x2d + kVK_ANSI_C, // 0x2e + kVK_ANSI_V, // 0x2f + kVK_ANSI_B, // 0x30 + kVK_ANSI_N, // 0x31 + kVK_ANSI_M, // 0x32 + kVK_ANSI_Comma, // 0x33 + kVK_ANSI_Period, // 0x34 + kVK_ANSI_Slash, // 0x35 + kVK_Shift, // 0x36 + kVK_ANSI_KeypadMultiply, // 0x37 + kVK_Option, // 0x38 + kVK_Space, // 0x39 + kVK_CapsLock, // 0x3a + kVK_F1, // 0x3b + kVK_F2, // 0x3c + kVK_F3, // 0x3d + kVK_F4, // 0x3e + kVK_F5, // 0x3f + kVK_F6, // 0x40 + kVK_F7, // 0x41 + kVK_F8, // 0x42 + kVK_F9, // 0x43 + kVK_F10, // 0x44 + 0xFF, // 0x45 -- numlock + 0xFF, // 0x46 -- scroll lock + kVK_ANSI_Keypad7, // 0x47 + kVK_ANSI_Keypad8, // 0x48 + kVK_ANSI_Keypad9, // 0x49 + kVK_ANSI_KeypadMinus, // 0x4a + kVK_ANSI_Keypad4, // 0x4b + kVK_ANSI_Keypad5, // 0x4c + kVK_ANSI_Keypad6, // 0x4d + kVK_ANSI_KeypadPlus, // 0x4e + kVK_ANSI_Keypad1, // 0x4f + kVK_ANSI_Keypad2, // 0x50 + kVK_ANSI_Keypad3, // 0x51 + kVK_ANSI_Keypad0, // 0x52 + kVK_ANSI_KeypadDecimal, // 0x53 + 0xFF, // 0x54 + 0xFF, // 0x55 + 0xFF, // 0x56 + kVK_F11, // 0x57 + kVK_F12, // 0x58 + 0xFF, // 0x59 -- pause + 0xFF, // 0x5a + kVK_Control, // 0x5b + kVK_Control, // 0x5c + 0xFF, // 0x5d -- application + 0xFF, // 0x5e -- power + 0xFF, // 0x5f -- sleep + 0xFF, // 0x60 + 0xFF, // 0x61 + 0xFF, // 0x62 + 0xFF, // 0x63 -- wake + 0xFF, // 0x64 + 0xFF, // 0x65 + 0xFF, // 0x66 + 0xFF, // 0x67 + 0xFF, // 0x68 + 0xFF, // 0x69 + 0xFF, // 0x6a + 0xFF, // 0x6b + 0xFF, // 0x6c + 0xFF, // 0x6d + 0xFF, // 0x6e + 0xFF, // 0x6f + 0xFF, // 0x70 + 0xFF, // 0x71 + 0xFF, // 0x72 + 0xFF, // 0x73 + 0xFF, // 0x74 + 0xFF, // 0x75 + 0xFF, // 0x76 + 0xFF, // 0x77 + 0xFF, // 0x78 + 0xFF, // 0x79 + 0xFF, // 0x7a + 0xFF, // 0x7b + 0xFF, // 0x7c + 0xFF, // 0x7d + 0xFF, // 0x7e + 0xFF, // 0x7f + 0xFF, // 0x80 + 0xFF, // 0x81 + 0xFF, // 0x82 + 0xFF, // 0x83 + 0xFF, // 0x84 + 0xFF, // 0x85 + 0xFF, // 0x86 + 0xFF, // 0x87 + 0xFF, // 0x88 + 0xFF, // 0x89 + 0xFF, // 0x8a + 0xFF, // 0x8b + 0xFF, // 0x8c + 0xFF, // 0x8d + 0xFF, // 0x8e + 0xFF, // 0x8f + 0xFF, // 0x90 + 0xFF, // 0x91 + 0xFF, // 0x92 + 0xFF, // 0x93 + 0xFF, // 0x94 + 0xFF, // 0x95 + 0xFF, // 0x96 + 0xFF, // 0x97 + 0xFF, // 0x98 + 0xFF, // 0x99 + 0xFF, // 0x9a + 0xFF, // 0x9b + 0xFF, // 0x9c + 0xFF, // 0x9d + 0xFF, // 0x9e + 0xFF, // 0x9f + 0xFF, // 0xa0 + 0xFF, // 0xa1 + 0xFF, // 0xa2 + 0xFF, // 0xa3 + 0xFF, // 0xa4 + 0xFF, // 0xa5 + 0xFF, // 0xa6 + 0xFF, // 0xa7 + 0xFF, // 0xa8 + 0xFF, // 0xa9 + 0xFF, // 0xaa + 0xFF, // 0xab + 0xFF, // 0xac + 0xFF, // 0xad + 0xFF, // 0xae + 0xFF, // 0xaf + 0xFF, // 0xb0 + 0xFF, // 0xb1 + 0xFF, // 0xb2 + 0xFF, // 0xb3 + 0xFF, // 0xb4 + 0xFF, // 0xb5 + 0xFF, // 0xb6 + 0xFF, // 0xb7 + 0xFF, // 0xb8 + 0xFF, // 0xb9 + 0xFF, // 0xba + 0xFF, // 0xbb + 0xFF, // 0xbc + 0xFF, // 0xbd + 0xFF, // 0xbe + 0xFF, // 0xbf + 0xFF, // 0xc0 + 0xFF, // 0xc1 + 0xFF, // 0xc2 + 0xFF, // 0xc3 + 0xFF, // 0xc4 + 0xFF, // 0xc5 + 0xFF, // 0xc6 + 0xFF, // 0xc7 + 0xFF, // 0xc8 + 0xFF, // 0xc9 + 0xFF, // 0xca + 0xFF, // 0xcb + 0xFF, // 0xcc + 0xFF, // 0xcd + 0xFF, // 0xce + 0xFF, // 0xcf + 0xFF, // 0xd0 + 0xFF, // 0xd1 + 0xFF, // 0xd2 + 0xFF, // 0xd3 + 0xFF, // 0xd4 + 0xFF, // 0xd5 + 0xFF, // 0xd6 + 0xFF, // 0xd7 + 0xFF, // 0xd8 + 0xFF, // 0xd9 + 0xFF, // 0xda + 0xFF, // 0xdb + 0xFF, // 0xdc + 0xFF, // 0xdd + 0xFF, // 0xde + 0xFF, // 0xdf + 0xFF, // 0xe0 + 0xFF, // 0xe1 + 0xFF, // 0xe2 + 0xFF, // 0xe3 + 0xFF, // 0xe4 + 0xFF, // 0xe5 + 0xFF, // 0xe6 + 0xFF, // 0xe7 + 0xFF, // 0xe8 + 0xFF, // 0xe9 + 0xFF, // 0xea + 0xFF, // 0xeb + 0xFF, // 0xec + 0xFF, // 0xed + 0xFF, // 0xee + 0xFF, // 0xef + 0xFF, // 0xf0 + 0xFF, // 0xf1 + 0xFF, // 0xf2 + 0xFF, // 0xf3 + 0xFF, // 0xf4 + 0xFF, // 0xf5 + 0xFF, // 0xf6 + 0xFF, // 0xf7 + 0xFF, // 0xf8 + 0xFF, // 0xf9 + 0xFF, // 0xfa + 0xFF, // 0xfb + 0xFF, // 0xfc + 0xFF, // 0xfd + 0xFF, // 0xfe +}; + +BOOL mf_input_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + BOOL keyDown = TRUE; + CGEventRef kbEvent; + CGKeyCode kCode = 0xFF; + + if (flags & KBD_FLAGS_RELEASE) + { + keyDown = FALSE; + } + + if (flags & KBD_FLAGS_EXTENDED) + { + switch (code) + { + // case 0x52: //insert + case 0x53: + kCode = kVK_ForwardDelete; + break; + + case 0x4B: + kCode = kVK_LeftArrow; + break; + + case 0x47: + kCode = kVK_Home; + break; + + case 0x4F: + kCode = kVK_End; + break; + + case 0x48: + kCode = kVK_UpArrow; + break; + + case 0x50: + kCode = kVK_DownArrow; + break; + + case 0x49: + kCode = kVK_PageUp; + break; + + case 0x51: + kCode = kVK_PageDown; + break; + + case 0x4D: + kCode = kVK_RightArrow; + break; + + default: + break; + } + } + else + { + kCode = keymap[code]; + } + + kbEvent = CGEventCreateKeyboardEvent(source, kCode, keyDown); + CGEventPost(kCGHIDEventTap, kbEvent); + CFRelease(kbEvent); + CFRelease(source); + return TRUE; +} + +BOOL mf_input_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + return FALSE; +} + +BOOL mf_input_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + float width, height; + CGWheelCount wheelCount = 2; + INT32 scroll_x = 0; + INT32 scroll_y = 0; + + if (flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL)) + { + INT32 scroll = flags & WheelRotationMask; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + scroll = -(flags & WheelRotationMask) / 392; + else + scroll = (flags & WheelRotationMask) / 120; + + if (flags & PTR_FLAGS_WHEEL) + scroll_y = scroll; + else + scroll_x = scroll; + + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef scrollEvent = CGEventCreateScrollWheelEvent(source, kCGScrollEventUnitLine, + wheelCount, scroll_y, scroll_x); + CGEventPost(kCGHIDEventTap, scrollEvent); + CFRelease(scrollEvent); + CFRelease(source); + } + else + { + mfInfo* mfi; + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventType mouseType = kCGEventNull; + CGMouseButton mouseButton = kCGMouseButtonLeft; + mfi = mf_info_get_instance(); + // width and height of primary screen (even in multimon setups + width = (float)mfi->servscreen_width; + height = (float)mfi->servscreen_height; + x += mfi->servscreen_xoffset; + y += mfi->servscreen_yoffset; + + if (flags & PTR_FLAGS_MOVE) + { + if (mfi->mouse_down_left == TRUE) + { + mouseType = kCGEventLeftMouseDragged; + } + else if (mfi->mouse_down_right == TRUE) + { + mouseType = kCGEventRightMouseDragged; + } + else if (mfi->mouse_down_other == TRUE) + { + mouseType = kCGEventOtherMouseDragged; + } + else + { + mouseType = kCGEventMouseMoved; + } + + CGEventRef move = CGEventCreateMouseEvent(source, mouseType, CGPointMake(x, y), + mouseButton // ignored for just movement + ); + CGEventPost(kCGHIDEventTap, move); + CFRelease(move); + } + + if (flags & PTR_FLAGS_BUTTON1) + { + mouseButton = kCGMouseButtonLeft; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventLeftMouseDown; + mfi->mouse_down_left = TRUE; + } + else + { + mouseType = kCGEventLeftMouseUp; + mfi->mouse_down_right = FALSE; + } + } + else if (flags & PTR_FLAGS_BUTTON2) + { + mouseButton = kCGMouseButtonRight; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventRightMouseDown; + mfi->mouse_down_right = TRUE; + } + else + { + mouseType = kCGEventRightMouseUp; + mfi->mouse_down_right = FALSE; + } + } + else if (flags & PTR_FLAGS_BUTTON3) + { + mouseButton = kCGMouseButtonCenter; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventOtherMouseDown; + mfi->mouse_down_other = TRUE; + } + else + { + mouseType = kCGEventOtherMouseUp; + mfi->mouse_down_other = FALSE; + } + } + + CGEventRef mouseEvent = + CGEventCreateMouseEvent(source, mouseType, CGPointMake(x, y), mouseButton); + CGEventPost(kCGHIDEventTap, mouseEvent); + CFRelease(mouseEvent); + CFRelease(source); + } + + return TRUE; +} + +BOOL mf_input_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + return FALSE; +} + +BOOL mf_input_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code) +{ + return FALSE; +} + +BOOL mf_input_unicode_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code) +{ + return FALSE; +} + +BOOL mf_input_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + return FALSE; +} + +BOOL mf_input_extended_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.h new file mode 100644 index 0000000000000000000000000000000000000000..4c039f865a97edefa0e6c3afa71b5147ac994ea4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_input.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Input) + * + * Copyright 2013 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_INPUT_H +#define FREERDP_SERVER_MAC_INPUT_H + +#include "mf_interface.h" + +BOOL mf_input_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code); +BOOL mf_input_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code); +BOOL mf_input_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); +BOOL mf_input_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); + +// dummy versions +BOOL mf_input_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code); +BOOL mf_input_unicode_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code); +BOOL mf_input_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); +BOOL mf_input_extended_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); + +#endif /* FREERDP_SERVER_MAC_INPUT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_interface.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_interface.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..6ba86f33a592bfffaffcbebd59a1329722d7a09f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_interface.h @@ -0,0 +1,106 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Mac OS X Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_INTERFACE_H +#define FREERDP_SERVER_MAC_INTERFACE_H + +#include + +#include +#include +#include +#include +#include + +#include + +#ifdef WITH_SERVER_CHANNELS +#include +#endif + +#ifdef CHANNEL_RDPSND_SERVER +#include +#include "mf_rdpsnd.h" +#endif + +#ifdef CHANNEL_AUDIN_SERVER +#include +#include "mf_audin.h" +#endif + +#include "mf_types.h" + +struct mf_peer_context +{ + rdpContext _p; + + mfInfo* info; + wStream* s; + BOOL activated; + UINT32 frame_id; + BOOL audin_open; + RFX_CONTEXT* rfx_context; + NSC_CONTEXT* nsc_context; + +#ifdef WITH_SERVER_CHANNELS + HANDLE vcm; +#endif + +#ifdef CHANNEL_AUDIN_SERVER + audin_server_context* audin; +#endif + +#ifdef CHANNEL_RDPSND_SERVER + RdpsndServerContext* rdpsnd; +#endif +}; + +struct mf_info +{ + // STREAM* s; + + // screen and monitor info + UINT32 screenID; + UINT32 virtscreen_width; + UINT32 virtscreen_height; + UINT32 servscreen_width; + UINT32 servscreen_height; + UINT32 servscreen_xoffset; + UINT32 servscreen_yoffset; + + int bitsPerPixel; + int peerCount; + int activePeerCount; + int framesPerSecond; + freerdp_peer** peers; + unsigned int framesWaiting; + UINT32 scale; + + RFX_RECT invalid; + pthread_mutex_t mutex; + + BOOL mouse_down_left; + BOOL mouse_down_right; + BOOL mouse_down_other; + BOOL input_disabled; + BOOL force_all_disconnect; +}; + +#endif /* FREERDP_SERVER_MAC_INTERFACE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.c new file mode 100644 index 0000000000000000000000000000000000000000..9db86b899709e96cbe4625bee553cd3ab54445ed --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.c @@ -0,0 +1,269 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * OS X Server Event Handling + * + * Copyright 2012 Corey Clayton + * + * 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 +#include +#include +#include +#include + +#include "mf_mountain_lion.h" + +dispatch_semaphore_t region_sem; +dispatch_semaphore_t data_sem; +dispatch_queue_t screen_update_q; +CGDisplayStreamRef stream; + +CGDisplayStreamUpdateRef lastUpdate = NULL; + +BYTE* localBuf = NULL; + +BOOL ready = FALSE; + +void (^streamHandler)(CGDisplayStreamFrameStatus, uint64_t, IOSurfaceRef, + CGDisplayStreamUpdateRef) = ^(CGDisplayStreamFrameStatus status, + uint64_t displayTime, IOSurfaceRef frameSurface, + CGDisplayStreamUpdateRef updateRef) { + dispatch_semaphore_wait(region_sem, DISPATCH_TIME_FOREVER); + + // may need to move this down + if (ready == TRUE) + { + + RFX_RECT rect; + unsigned long offset_beg; + unsigned long stride; + + rect.x = 0; + rect.y = 0; + rect.width = 0; + rect.height = 0; + mf_mlion_peek_dirty_region(&rect); + + // lock surface + IOSurfaceLock(frameSurface, kIOSurfaceLockReadOnly, NULL); + // get pointer + void* baseAddress = IOSurfaceGetBaseAddress(frameSurface); + // copy region + + stride = IOSurfaceGetBytesPerRow(frameSurface); + // memcpy(localBuf, baseAddress + offset_beg, surflen); + for (int i = 0; i < rect.height; i++) + { + offset_beg = (stride * (rect.y + i) + (rect.x * 4)); + memcpy(localBuf + offset_beg, baseAddress + offset_beg, rect.width * 4); + } + + // unlock surface + IOSurfaceUnlock(frameSurface, kIOSurfaceLockReadOnly, NULL); + + ready = FALSE; + dispatch_semaphore_signal(data_sem); + } + + if (status != kCGDisplayStreamFrameStatusFrameComplete) + { + switch (status) + { + case kCGDisplayStreamFrameStatusFrameIdle: + break; + + case kCGDisplayStreamFrameStatusStopped: + break; + + case kCGDisplayStreamFrameStatusFrameBlank: + break; + + default: + break; + } + } + else if (lastUpdate == NULL) + { + CFRetain(updateRef); + lastUpdate = updateRef; + } + else + { + CGDisplayStreamUpdateRef tmpRef; + tmpRef = lastUpdate; + lastUpdate = CGDisplayStreamUpdateCreateMergedUpdate(tmpRef, updateRef); + CFRelease(tmpRef); + } + + dispatch_semaphore_signal(region_sem); +}; + +int mf_mlion_display_info(UINT32* disp_width, UINT32* disp_height, UINT32* scale) +{ + CGDirectDisplayID display_id; + + display_id = CGMainDisplayID(); + + CGDisplayModeRef mode = CGDisplayCopyDisplayMode(display_id); + + size_t pixelWidth = CGDisplayModeGetPixelWidth(mode); + // size_t pixelHeight = CGDisplayModeGetPixelHeight(mode); + + size_t wide = CGDisplayPixelsWide(display_id); + size_t high = CGDisplayPixelsHigh(display_id); + + CGDisplayModeRelease(mode); + + *disp_width = wide; // pixelWidth; + *disp_height = high; // pixelHeight; + *scale = pixelWidth / wide; + + return 0; +} + +int mf_mlion_screen_updates_init() +{ + CGDirectDisplayID display_id; + + display_id = CGMainDisplayID(); + + screen_update_q = dispatch_queue_create("mfreerdp.server.screenUpdate", NULL); + + region_sem = dispatch_semaphore_create(1); + data_sem = dispatch_semaphore_create(1); + + UINT32 pixelWidth; + UINT32 pixelHeight; + UINT32 scale; + + mf_mlion_display_info(&pixelWidth, &pixelHeight, &scale); + + localBuf = malloc(pixelWidth * pixelHeight * 4); + if (!localBuf) + return -1; + + CFDictionaryRef opts; + + void* keys[2]; + void* values[2]; + + keys[0] = (void*)kCGDisplayStreamShowCursor; + values[0] = (void*)kCFBooleanFalse; + + opts = CFDictionaryCreate(kCFAllocatorDefault, (const void**)keys, (const void**)values, 1, + NULL, NULL); + + stream = CGDisplayStreamCreateWithDispatchQueue(display_id, pixelWidth, pixelHeight, 'BGRA', + opts, screen_update_q, streamHandler); + + CFRelease(opts); + + return 0; +} + +int mf_mlion_start_getting_screen_updates() +{ + CGError err; + + err = CGDisplayStreamStart(stream); + + if (err != kCGErrorSuccess) + { + return 1; + } + + return 0; +} +int mf_mlion_stop_getting_screen_updates() +{ + CGError err; + + err = CGDisplayStreamStop(stream); + + if (err != kCGErrorSuccess) + { + return 1; + } + + return 0; +} + +int mf_mlion_get_dirty_region(RFX_RECT* invalid) +{ + dispatch_semaphore_wait(region_sem, DISPATCH_TIME_FOREVER); + + if (lastUpdate != NULL) + { + mf_mlion_peek_dirty_region(invalid); + } + + dispatch_semaphore_signal(region_sem); + + return 0; +} + +int mf_mlion_peek_dirty_region(RFX_RECT* invalid) +{ + size_t num_rects; + CGRect dirtyRegion; + + const CGRect* rects = + CGDisplayStreamUpdateGetRects(lastUpdate, kCGDisplayStreamUpdateDirtyRects, &num_rects); + + if (num_rects == 0) + { + return 0; + } + + dirtyRegion = *rects; + for (size_t i = 0; i < num_rects; i++) + { + dirtyRegion = CGRectUnion(dirtyRegion, *(rects + i)); + } + + invalid->x = dirtyRegion.origin.x; + invalid->y = dirtyRegion.origin.y; + invalid->height = dirtyRegion.size.height; + invalid->width = dirtyRegion.size.width; + + return 0; +} + +int mf_mlion_clear_dirty_region() +{ + dispatch_semaphore_wait(region_sem, DISPATCH_TIME_FOREVER); + + CFRelease(lastUpdate); + lastUpdate = NULL; + + dispatch_semaphore_signal(region_sem); + + return 0; +} + +int mf_mlion_get_pixelData(long x, long y, long width, long height, BYTE** pxData) +{ + dispatch_semaphore_wait(region_sem, DISPATCH_TIME_FOREVER); + ready = TRUE; + dispatch_semaphore_wait(data_sem, DISPATCH_TIME_FOREVER); + dispatch_semaphore_signal(region_sem); + + // this second wait allows us to block until data is copied... more on this later + dispatch_semaphore_wait(data_sem, DISPATCH_TIME_FOREVER); + *pxData = localBuf; + dispatch_semaphore_signal(data_sem); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.h new file mode 100644 index 0000000000000000000000000000000000000000..c1fbe9bb5ec5f869f5fd1378c808ce561b0e396a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_mountain_lion.h @@ -0,0 +1,38 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * OS X Server Event Handling + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_MLION_H +#define FREERDP_SERVER_MAC_MLION_H + +#include + +int mf_mlion_display_info(UINT32* disp_width, UINT32* dispHeight, UINT32* scale); + +int mf_mlion_screen_updates_init(void); + +int mf_mlion_start_getting_screen_updates(void); +int mf_mlion_stop_getting_screen_updates(void); + +int mf_mlion_get_dirty_region(RFX_RECT* invalid); +int mf_mlion_peek_dirty_region(RFX_RECT* invalid); +int mf_mlion_clear_dirty_region(void); + +int mf_mlion_get_pixelData(long x, long y, long width, long height, BYTE** pxData); + +#endif /* FREERDP_SERVER_MAC_MLION_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.c new file mode 100644 index 0000000000000000000000000000000000000000..066912714b61b279d6c186878205ca4acc3dbaa4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.c @@ -0,0 +1,485 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Mac OS X Server + * + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include +#include +#include +#include + +#include +#include + +#include "mf_peer.h" +#include "mf_info.h" +#include "mf_input.h" +#include "mf_event.h" +#include "mf_rdpsnd.h" +#include "mf_audin.h" + +#include +#include +#include + +#include "OpenGL/OpenGL.h" +#include "OpenGL/gl.h" + +#include "CoreVideo/CoreVideo.h" + +#include +#define TAG SERVER_TAG("mac") + +// refactor these +static int info_last_sec = 0; +static int info_last_nsec = 0; + +static dispatch_source_t info_timer; +static dispatch_queue_t info_queue; + +static mfEventQueue* info_event_queue; + +static CGLContextObj glContext; +static CGContextRef bmp; +static CGImageRef img; + +static void mf_peer_context_free(freerdp_peer* client, rdpContext* context); + +static BOOL mf_peer_get_fds(freerdp_peer* client, void** rfds, int* rcount) +{ + if (info_event_queue->pipe_fd[0] == -1) + return TRUE; + + rfds[*rcount] = (void*)(long)info_event_queue->pipe_fd[0]; + (*rcount)++; + return TRUE; +} + +static void mf_peer_rfx_update(freerdp_peer* client) +{ + // check + mfInfo* mfi = mf_info_get_instance(); + mf_info_find_invalid_region(mfi); + + if (mf_info_have_invalid_region(mfi) == false) + { + return; + } + + long width; + long height; + int pitch; + BYTE* dataBits = NULL; + mf_info_getScreenData(mfi, &width, &height, &dataBits, &pitch); + mf_info_clear_invalid_region(mfi); + // encode + wStream* s; + RFX_RECT rect; + rdpUpdate* update; + mfPeerContext* mfp; + SURFACE_BITS_COMMAND cmd = { 0 }; + + WINPR_ASSERT(client); + + mfp = (mfPeerContext*)client->context; + WINPR_ASSERT(mfp); + + update = client->context->update; + WINPR_ASSERT(update); + + s = mfp->s; + WINPR_ASSERT(s); + + Stream_Clear(s); + Stream_SetPosition(s, 0); + UINT32 x = mfi->invalid.x / mfi->scale; + UINT32 y = mfi->invalid.y / mfi->scale; + rect.x = 0; + rect.y = 0; + rect.width = width; + rect.height = height; + + rfx_context_reset(mfp->rfx_context, mfi->servscreen_width, mfi->servscreen_height); + + if (!(rfx_compose_message(mfp->rfx_context, s, &rect, 1, (BYTE*)dataBits, rect.width, + rect.height, pitch))) + { + return; + } + + cmd.destLeft = x; + cmd.destTop = y; + cmd.destRight = x + rect.width; + cmd.destBottom = y + rect.height; + cmd.bmp.bpp = 32; + cmd.bmp.codecID = 3; + cmd.bmp.width = rect.width; + cmd.bmp.height = rect.height; + cmd.bmp.bitmapDataLength = Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + // send + update->SurfaceBits(update->context, &cmd); + // clean up... maybe? +} + +static BOOL mf_peer_check_fds(freerdp_peer* client) +{ + mfPeerContext* context = (mfPeerContext*)client->context; + mfEvent* event; + + if (context->activated == FALSE) + return TRUE; + + event = mf_event_peek(info_event_queue); + + if (event != NULL) + { + if (event->type == FREERDP_SERVER_MAC_EVENT_TYPE_REGION) + { + } + else if (event->type == FREERDP_SERVER_MAC_EVENT_TYPE_FRAME_TICK) + { + event = mf_event_pop(info_event_queue); + mf_peer_rfx_update(client); + mf_event_free(event); + } + } + + return TRUE; +} + +/* Called when we have a new peer connecting */ +static BOOL mf_peer_context_new(freerdp_peer* client, rdpContext* context) +{ + rdpSettings* settings; + mfPeerContext* peer = (mfPeerContext*)context; + + WINPR_ASSERT(client); + WINPR_ASSERT(context); + + settings = context->settings; + WINPR_ASSERT(settings); + + if (!(peer->info = mf_info_get_instance())) + return FALSE; + + if (!(peer->rfx_context = rfx_context_new_ex( + TRUE, freerdp_settings_get_uint32(settings, FreeRDP_ThreadingFlags)))) + goto fail; + + rfx_context_reset(peer->rfx_context, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + rfx_context_set_mode(peer->rfx_context, RLGR3); + rfx_context_set_pixel_format(peer->rfx_context, PIXEL_FORMAT_BGRA32); + + if (!(peer->s = Stream_New(NULL, 0xFFFF))) + goto fail; + + peer->vcm = WTSOpenServerA((LPSTR)client->context); + + if (!peer->vcm || (peer->vcm == INVALID_HANDLE_VALUE)) + goto fail; + + mf_info_peer_register(peer->info, peer); + return TRUE; +fail: + mf_peer_context_free(client, context); + return FALSE; +} + +/* Called after a peer disconnects */ +static void mf_peer_context_free(freerdp_peer* client, rdpContext* context) +{ + mfPeerContext* peer = (mfPeerContext*)context; + if (context) + { + mf_info_peer_unregister(peer->info, peer); + dispatch_suspend(info_timer); + Stream_Free(peer->s, TRUE); + rfx_context_free(peer->rfx_context); + // nsc_context_free(peer->nsc_context); +#ifdef CHANNEL_AUDIN_SERVER + + mf_peer_audin_uninit(peer); + +#endif +#ifdef CHANNEL_RDPSND_SERVER + mf_peer_rdpsnd_stop(); + + if (peer->rdpsnd) + rdpsnd_server_context_free(peer->rdpsnd); + +#endif + WTSCloseServer(peer->vcm); + } +} + +/* Called when a new client connects */ +static BOOL mf_peer_init(freerdp_peer* client) +{ + client->ContextSize = sizeof(mfPeerContext); + client->ContextNew = mf_peer_context_new; + client->ContextFree = mf_peer_context_free; + + if (!freerdp_peer_context_new(client)) + return FALSE; + + info_event_queue = mf_event_queue_new(); + info_queue = dispatch_queue_create("FreeRDP.update.timer", DISPATCH_QUEUE_SERIAL); + info_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, info_queue); + + if (info_timer) + { + // DEBUG_WARN( "created timer\n"); + dispatch_source_set_timer(info_timer, DISPATCH_TIME_NOW, 42ull * NSEC_PER_MSEC, + 100ull * NSEC_PER_MSEC); + dispatch_source_set_event_handler(info_timer, ^{ + // DEBUG_WARN( "dispatch\n"); + mfEvent* event = mf_event_new(FREERDP_SERVER_MAC_EVENT_TYPE_FRAME_TICK); + mf_event_push(info_event_queue, (mfEvent*)event); + }); + dispatch_resume(info_timer); + } + + return TRUE; +} + +static BOOL mf_peer_post_connect(freerdp_peer* client) +{ + mfInfo* mfi = mf_info_get_instance(); + + WINPR_ASSERT(client); + + mfPeerContext* context = (mfPeerContext*)client->context; + WINPR_ASSERT(context); + + rdpSettings* settings = client->context->settings; + WINPR_ASSERT(settings); + + mfi->scale = 1; + // mfi->servscreen_width = 2880 / mfi->scale; + // mfi->servscreen_height = 1800 / mfi->scale; + UINT32 bitsPerPixel = 32; + + if ((freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) != mfi->servscreen_width) || + (freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) != mfi->servscreen_height)) + { + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, mfi->servscreen_width)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, mfi->servscreen_height)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, bitsPerPixel)) + return FALSE; + + WINPR_ASSERT(client->context->update); + WINPR_ASSERT(client->context->update->DesktopResize); + client->context->update->DesktopResize(client->context); + + mfi->mouse_down_left = FALSE; + mfi->mouse_down_right = FALSE; + mfi->mouse_down_other = FALSE; +#ifdef CHANNEL_RDPSND_SERVER + + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, "rdpsnd")) + { + mf_peer_rdpsnd_init(context); /* Audio Output */ + } + +#endif + /* Dynamic Virtual Channels */ +#ifdef CHANNEL_AUDIN_SERVER + mf_peer_audin_init(context); /* Audio Input */ +#endif + return TRUE; +} + +static BOOL mf_peer_activate(freerdp_peer* client) +{ + WINPR_ASSERT(client); + + mfPeerContext* context = (mfPeerContext*)client->context; + WINPR_ASSERT(context); + + rdpSettings* settings = client->context->settings; + WINPR_ASSERT(settings); + + rfx_context_reset(context->rfx_context, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + context->activated = TRUE; + return TRUE; +} + +static BOOL mf_peer_synchronize_event(rdpInput* input, UINT32 flags) +{ + return TRUE; +} + +static BOOL mf_peer_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + bool state_down = FALSE; + + if (flags == KBD_FLAGS_DOWN) + { + state_down = TRUE; + } + return TRUE; +} + +static BOOL mf_peer_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + return FALSE; +} + +static BOOL mf_peer_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) +{ + return FALSE; +} + +static void* mf_peer_main_loop(void* arg) +{ + mfPeerContext* context; + rdpSettings* settings; + rdpInput* input; + rdpUpdate* update; + freerdp_peer* client = (freerdp_peer*)arg; + + if (!mf_peer_init(client)) + goto fail; + + const mf_server_info* info = client->ContextExtra; + WINPR_ASSERT(info); + + WINPR_ASSERT(client->context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + /* Initialize the real server settings here */ + rdpPrivateKey* key = freerdp_key_new_from_file(info->key); + if (!key) + goto fail; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerRsaKey, key, 1)) + goto fail; + rdpCertificate* cert = freerdp_certificate_new_from_file(info->cert); + if (!cert) + goto fail; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerCertificate, cert, 1)) + goto fail; + + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + goto fail; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32)) + goto fail; + + if (!freerdp_settings_set_bool(settings, FreeRDP_SuppressOutput, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_RefreshRect, FALSE)) + goto fail; + + client->PostConnect = mf_peer_post_connect; + client->Activate = mf_peer_activate; + + input = client->context->input; + WINPR_ASSERT(input); + + input->SynchronizeEvent = mf_peer_synchronize_event; + input->KeyboardEvent = mf_input_keyboard_event; // mf_peer_keyboard_event; + input->UnicodeKeyboardEvent = mf_peer_unicode_keyboard_event; + input->MouseEvent = mf_input_mouse_event; + input->ExtendedMouseEvent = mf_input_extended_mouse_event; + + update = client->context->update; + WINPR_ASSERT(update); + + // update->RefreshRect = mf_peer_refresh_rect; + update->SuppressOutput = mf_peer_suppress_output; + + WINPR_ASSERT(client->Initialize); + const BOOL rc = client->Initialize(client); + if (!rc) + goto fail; + context = (mfPeerContext*)client->context; + + while (1) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = client->GetEventHandles(client, handles, ARRAYSIZE(handles)); + + if ((count == 0) || (count == MAXIMUM_WAIT_OBJECTS)) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + handles[count++] = WTSVirtualChannelManagerGetEventHandle(context->vcm); + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + if (client->CheckFileDescriptor(client) != TRUE) + { + break; + } + + if ((mf_peer_check_fds(client)) != TRUE) + { + break; + } + + if (WTSVirtualChannelManagerCheckFileDescriptor(context->vcm) != TRUE) + { + break; + } + } + + client->Disconnect(client); + freerdp_peer_context_free(client); +fail: + freerdp_peer_free(client); + return NULL; +} + +BOOL mf_peer_accepted(freerdp_listener* instance, freerdp_peer* client) +{ + pthread_t th; + + WINPR_ASSERT(instance); + WINPR_ASSERT(client); + + client->ContextExtra = instance->info; + if (pthread_create(&th, 0, mf_peer_main_loop, client) == 0) + { + pthread_detach(th); + return TRUE; + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.h new file mode 100644 index 0000000000000000000000000000000000000000..e4a966c3bf46ad8c27295234bb70f19d9ce97f17 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_peer.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_PEER_H +#define FREERDP_SERVER_MAC_PEER_H + +#include "mf_interface.h" + +typedef struct +{ + const char* cert; + const char* key; +} mf_server_info; + +BOOL mf_peer_accepted(freerdp_listener* instance, freerdp_peer* client); + +#endif /* FREERDP_SERVER_MAC_PEER_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.c new file mode 100644 index 0000000000000000000000000000000000000000..4962f0c68fa4ee94d5c49e8dc742c5fc11ca7279 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.c @@ -0,0 +1,200 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include + +#include "mf_info.h" +#include "mf_rdpsnd.h" +#include "mf_interface.h" + +#include +#include +#include +#define TAG SERVER_TAG("mac") + +AQRecorderState recorderState; + +static void mf_peer_rdpsnd_activated(RdpsndServerContext* context) +{ + OSStatus status; + BOOL formatAgreed = FALSE; + AUDIO_FORMAT* agreedFormat = NULL; + // we should actually loop through the list of client formats here + // and see if we can send the client something that it supports... + WLog_DBG(TAG, "Client supports the following %d formats: ", context->num_client_formats); + + int i = 0; + for (; i < context->num_client_formats; i++) + { + /* TODO: improve the way we agree on a format */ + for (int j = 0; j < context->num_server_formats; j++) + { + if ((context->client_formats[i].wFormatTag == context->server_formats[j].wFormatTag) && + (context->client_formats[i].nChannels == context->server_formats[j].nChannels) && + (context->client_formats[i].nSamplesPerSec == + context->server_formats[j].nSamplesPerSec)) + { + WLog_DBG(TAG, "agreed on format!"); + formatAgreed = TRUE; + agreedFormat = (AUDIO_FORMAT*)&context->server_formats[j]; + break; + } + } + + if (formatAgreed == TRUE) + break; + } + + if (formatAgreed == FALSE) + { + WLog_DBG(TAG, "Could not agree on a audio format with the server"); + return; + } + + context->SelectFormat(context, i); + context->SetVolume(context, 0x7FFF, 0x7FFF); + + switch (agreedFormat->wFormatTag) + { + case WAVE_FORMAT_ALAW: + recorderState.dataFormat.mFormatID = kAudioFormatDVIIntelIMA; + break; + + case WAVE_FORMAT_PCM: + recorderState.dataFormat.mFormatID = kAudioFormatLinearPCM; + break; + + default: + recorderState.dataFormat.mFormatID = kAudioFormatLinearPCM; + break; + } + + recorderState.dataFormat.mSampleRate = agreedFormat->nSamplesPerSec; + recorderState.dataFormat.mFormatFlags = + kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; + recorderState.dataFormat.mBytesPerPacket = 4; + recorderState.dataFormat.mFramesPerPacket = 1; + recorderState.dataFormat.mBytesPerFrame = 4; + recorderState.dataFormat.mChannelsPerFrame = agreedFormat->nChannels; + recorderState.dataFormat.mBitsPerChannel = agreedFormat->wBitsPerSample; + recorderState.snd_context = context; + status = + AudioQueueNewInput(&recorderState.dataFormat, mf_peer_rdpsnd_input_callback, &recorderState, + NULL, kCFRunLoopCommonModes, 0, &recorderState.queue); + + if (status != noErr) + { + WLog_DBG(TAG, "Failed to create a new Audio Queue. Status code: %" PRId32 "", status); + } + + UInt32 dataFormatSize = sizeof(recorderState.dataFormat); + AudioQueueGetProperty(recorderState.queue, kAudioConverterCurrentInputStreamDescription, + &recorderState.dataFormat, &dataFormatSize); + mf_rdpsnd_derive_buffer_size(recorderState.queue, &recorderState.dataFormat, 0.05, + &recorderState.bufferByteSize); + + for (size_t x = 0; x < SND_NUMBUFFERS; ++x) + { + AudioQueueAllocateBuffer(recorderState.queue, recorderState.bufferByteSize, + &recorderState.buffers[x]); + AudioQueueEnqueueBuffer(recorderState.queue, recorderState.buffers[x], 0, NULL); + } + + recorderState.currentPacket = 0; + recorderState.isRunning = true; + AudioQueueStart(recorderState.queue, NULL); +} + +BOOL mf_peer_rdpsnd_init(mfPeerContext* context) +{ + context->rdpsnd = rdpsnd_server_context_new(context->vcm); + context->rdpsnd->rdpcontext = &context->_p; + context->rdpsnd->data = context; + context->rdpsnd->num_server_formats = + server_rdpsnd_get_formats(&context->rdpsnd->server_formats); + + if (context->rdpsnd->num_server_formats > 0) + context->rdpsnd->src_format = &context->rdpsnd->server_formats[0]; + + context->rdpsnd->Activated = mf_peer_rdpsnd_activated; + context->rdpsnd->Initialize(context->rdpsnd, TRUE); + return TRUE; +} + +BOOL mf_peer_rdpsnd_stop(void) +{ + recorderState.isRunning = false; + AudioQueueStop(recorderState.queue, true); + return TRUE; +} + +void mf_peer_rdpsnd_input_callback(void* inUserData, AudioQueueRef inAQ, + AudioQueueBufferRef inBuffer, const AudioTimeStamp* inStartTime, + UInt32 inNumberPacketDescriptions, + const AudioStreamPacketDescription* inPacketDescs) +{ + OSStatus status; + AQRecorderState* rState; + rState = inUserData; + + if (inNumberPacketDescriptions == 0 && rState->dataFormat.mBytesPerPacket != 0) + { + inNumberPacketDescriptions = + inBuffer->mAudioDataByteSize / rState->dataFormat.mBytesPerPacket; + } + + if (rState->isRunning == 0) + { + return; + } + + rState->snd_context->SendSamples(rState->snd_context, inBuffer->mAudioData, + inBuffer->mAudioDataByteSize / 4, + (UINT16)(GetTickCount() & 0xffff)); + status = AudioQueueEnqueueBuffer(rState->queue, inBuffer, 0, NULL); + + if (status != noErr) + { + WLog_DBG(TAG, "AudioQueueEnqueueBuffer() returned status = %" PRId32 "", status); + } +} + +void mf_rdpsnd_derive_buffer_size(AudioQueueRef audioQueue, + AudioStreamBasicDescription* ASBDescription, Float64 seconds, + UInt32* outBufferSize) +{ + static const int maxBufferSize = 0x50000; + int maxPacketSize = ASBDescription->mBytesPerPacket; + + if (maxPacketSize == 0) + { + UInt32 maxVBRPacketSize = sizeof(maxPacketSize); + AudioQueueGetProperty(audioQueue, kAudioQueueProperty_MaximumOutputPacketSize, + // in Mac OS X v10.5, instead use + // kAudioConverterPropertyMaximumOutputPacketSize + &maxPacketSize, &maxVBRPacketSize); + } + + Float64 numBytesForTime = ASBDescription->mSampleRate * maxPacketSize * seconds; + *outBufferSize = (UInt32)(numBytesForTime < maxBufferSize ? numBytesForTime : maxBufferSize); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.h new file mode 100644 index 0000000000000000000000000000000000000000..28bcb0dc42e6e772dda75346ec5f530b5e43fe93 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_rdpsnd.h @@ -0,0 +1,58 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_MAC_RDPSND_H +#define FREERDP_SERVER_MAC_RDPSND_H + +#include +#include + +#include +#include +#include + +#include "mf_types.h" +#include "mfreerdp.h" + +void mf_rdpsnd_derive_buffer_size(AudioQueueRef audioQueue, + AudioStreamBasicDescription* ASBDescription, Float64 seconds, + UInt32* outBufferSize); + +void mf_peer_rdpsnd_input_callback(void* inUserData, AudioQueueRef inAQ, + AudioQueueBufferRef inBuffer, const AudioTimeStamp* inStartTime, + UInt32 inNumberPacketDescriptions, + const AudioStreamPacketDescription* inPacketDescs); + +#define SND_NUMBUFFERS 3 +typedef struct +{ + AudioStreamBasicDescription dataFormat; + AudioQueueRef queue; + AudioQueueBufferRef buffers[SND_NUMBUFFERS]; + AudioFileID audioFile; + UInt32 bufferByteSize; + SInt64 currentPacket; + bool isRunning; + RdpsndServerContext* snd_context; +} AQRecorderState; + +BOOL mf_peer_rdpsnd_init(mfPeerContext* context); +BOOL mf_peer_rdpsnd_stop(void); + +#endif /* FREERDP_SERVER_MAC_RDPSND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_types.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_types.h new file mode 100644 index 0000000000000000000000000000000000000000..e33be83b3ff39587d826f8327c69373b33f291c0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mf_types.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Mac OS X Server + * + * Copyright 2023 Armin Novak + * Copyright 2023 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 FREERDP_SERVER_MAC_TYPES_H +#define FREERDP_SERVER_MAC_TYPES_H + +#include + +#include + +#include + +typedef struct mf_info mfInfo; +typedef struct mf_peer_context mfPeerContext; + +#endif /* FREERDP_SERVER_MAC_TYPES_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.c b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..8a3fffdd6fddb2b73a5f3976c839f5eed2a6a338 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.c @@ -0,0 +1,108 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "mfreerdp.h" +#include "mf_peer.h" + +#include +#define TAG SERVER_TAG("mac") + +static void mf_server_main_loop(freerdp_listener* instance) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->GetEventHandles); + WINPR_ASSERT(instance->CheckFileDescriptor); + + while (1) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = instance->GetEventHandles(instance, handles, ARRAYSIZE(handles)); + + if (count == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + if (instance->CheckFileDescriptor(instance) != TRUE) + { + break; + } + } + + instance->Close(instance); +} + +int main(int argc, char* argv[]) +{ + freerdp_server_warn_unmaintained(argc, argv); + mf_server_info info = { .key = "server.key", .cert = "server.crt" }; + + freerdp_listener* instance; + + signal(SIGPIPE, SIG_IGN); + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + + if (!(instance = freerdp_listener_new())) + return 1; + + instance->info = &info; + instance->PeerAccepted = mf_peer_accepted; + + if (instance->Open(instance, NULL, 3389)) + { + mf_server_main_loop(instance); + } + + freerdp_listener_free(instance); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.h b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..38fa25bbd5a53e1b352af7c973c03fbae94cab1a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Mac/mfreerdp.h @@ -0,0 +1,28 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_MAC_FREERDP_H +#define FREERDP_SERVER_MAC_FREERDP_H + +#include +#include +#include + +#endif /* FREERDP_SERVER_MAC_FREERDP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..393e1a23f9ee0380d608422993b33efbdb2040cf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/CMakeLists.txt @@ -0,0 +1,63 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Sample Server cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "sfreerdp-server") +set(MODULE_PREFIX "FREERDP_SERVER_SAMPLE") + +set(SRCS + sfreerdp.c + sfreerdp.h + sf_audin.c + sf_audin.h + sf_rdpsnd.c + sf_rdpsnd.h + sf_encomsp.c + sf_encomsp.h +) + +if(CHANNEL_AINPUT_SERVER) + list(APPEND SRCS sf_ainput.c sf_ainput.h) +endif() + +option(SAMPLE_USE_VENDOR_PRODUCT_CONFIG_DIR "Use / path for resources" OFF) +set(SAMPLE_RESOURCE_ROOT ${CMAKE_INSTALL_FULL_DATAROOTDIR}) +if(SAMPLE_USE_VENDOR_PRODUCT_CONFIG_DIR) + string(APPEND SAMPLE_RESOURCE_ROOT "/${VENDOR}") +endif() +string(APPEND SAMPLE_RESOURCE_ROOT "/${PRODUCT}") + +if(WITH_RESOURCE_VERSIONING) + string(APPEND SAMPLE_RESOURCE_ROOT "${FREERDP_VERSION_MAJOR}") +endif() +string(APPEND SAMPLE_RESOURCE_ROOT "/images") + +set(SAMPLE_ICONS test_icon.bmp test_icon.png test_icon.jpg test_icon.webp) +install(FILES ${SAMPLE_ICONS} DESTINATION ${SAMPLE_RESOURCE_ROOT}) + +# We need this in runtime path for TestConnect +file(COPY test_icon.bmp DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${FREERDP_VERSION}" SRCS) + +target_compile_definitions(${MODULE_NAME} PRIVATE SAMPLE_RESOURCE_ROOT="${SAMPLE_RESOURCE_ROOT}") +list(APPEND LIBS freerdp-server) +list(APPEND LIBS winpr freerdp) + +target_link_libraries(${MODULE_NAME} ${LIBS}) +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT server) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Sample") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..a61be6c7ed66c154b79f0f8d5f7576572296b04b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_SERVER_NAME "sfreerdp-server") +set(FREERDP_SERVER_PLATFORM "Sample") +set(FREERDP_SERVER_VENDOR "FreeRDP") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.c b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.c new file mode 100644 index 0000000000000000000000000000000000000000..1c19e0704f7ab973a64c8bcbf7ac0555435511dd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.c @@ -0,0 +1,92 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Advanced Input) + * + * Copyright 2022 Armin Novak + * Copyright 2022 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 + +#include + +#include "sfreerdp.h" + +#include "sf_ainput.h" + +#include +#include + +#include +#define TAG SERVER_TAG("sample.ainput") + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT sf_peer_ainput_mouse_event(ainput_server_context* context, UINT64 timestamp, + UINT64 flags, INT32 x, INT32 y) +{ + /* TODO: Implement */ + WINPR_ASSERT(context); + + WLog_WARN(TAG, "not implemented: 0x%08" PRIx64 ", 0x%08" PRIx64 ", %" PRId32 "x%" PRId32, + timestamp, flags, x, y); + return CHANNEL_RC_OK; +} + +void sf_peer_ainput_init(testPeerContext* context) +{ + WINPR_ASSERT(context); + + context->ainput = ainput_server_context_new(context->vcm); + WINPR_ASSERT(context->ainput); + + context->ainput->rdpcontext = &context->_p; + context->ainput->data = context; + + context->ainput->MouseEvent = sf_peer_ainput_mouse_event; +} + +BOOL sf_peer_ainput_start(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->Open) + return FALSE; + + return context->ainput->Open(context->ainput) == CHANNEL_RC_OK; +} + +BOOL sf_peer_ainput_stop(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->Close) + return FALSE; + + return context->ainput->Close(context->ainput) == CHANNEL_RC_OK; +} + +BOOL sf_peer_ainput_running(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->IsOpen) + return FALSE; + + return context->ainput->IsOpen(context->ainput); +} + +void sf_peer_ainput_uninit(testPeerContext* context) +{ + ainput_server_context_free(context->ainput); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.h b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf78d53699db8fee3c5d97c5aec786e4a6b640b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_ainput.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Advanced Input) + * + * Copyright 2022 Armin Novak + * Copyright 2022 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 FREERDP_SERVER_SAMPLE_SF_AINPUT_H +#define FREERDP_SERVER_SAMPLE_SF_AINPUT_H + +#include +#include +#include + +#include "sfreerdp.h" + +void sf_peer_ainput_init(testPeerContext* context); +void sf_peer_ainput_uninit(testPeerContext* context); + +BOOL sf_peer_ainput_running(testPeerContext* context); +BOOL sf_peer_ainput_start(testPeerContext* context); +BOOL sf_peer_ainput_stop(testPeerContext* context); + +#endif /* FREERDP_SERVER_SAMPLE_SF_AINPUT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.c b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.c new file mode 100644 index 0000000000000000000000000000000000000000..5783fe60dca8b51298ed0db36443d5596fc65f95 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.c @@ -0,0 +1,112 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Audio Input) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2023 Pascal Nowack + * + * 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 + +#include + +#include "sfreerdp.h" + +#include "sf_audin.h" + +#include +#include +#define TAG SERVER_TAG("sample") + +#if defined(CHANNEL_AUDIN_SERVER) + +static UINT sf_peer_audin_data(audin_server_context* audin, const SNDIN_DATA* data) +{ + /* TODO: Implement */ + WINPR_ASSERT(audin); + WINPR_ASSERT(data); + + WLog_WARN(TAG, "not implemented"); + WLog_DBG(TAG, "receive %" PRIdz " bytes.", Stream_Length(data->Data)); + return CHANNEL_RC_OK; +} + +#endif + +BOOL sf_peer_audin_init(testPeerContext* context) +{ + WINPR_ASSERT(context); +#if defined(CHANNEL_AUDIN_SERVER) + context->audin = audin_server_context_new(context->vcm); + WINPR_ASSERT(context->audin); + + context->audin->rdpcontext = &context->_p; + context->audin->userdata = context; + + context->audin->Data = sf_peer_audin_data; + + return audin_server_set_formats(context->audin, -1, NULL); +#else + return TRUE; +#endif +} + +BOOL sf_peer_audin_start(testPeerContext* context) +{ +#if defined(CHANNEL_AUDIN_SERVER) + if (!context || !context->audin || !context->audin->Open) + return FALSE; + + return context->audin->Open(context->audin); +#else + return FALSE; +#endif +} + +BOOL sf_peer_audin_stop(testPeerContext* context) +{ +#if defined(CHANNEL_AUDIN_SERVER) + if (!context || !context->audin || !context->audin->Close) + return FALSE; + + return context->audin->Close(context->audin); +#else + return FALSE; +#endif +} + +BOOL sf_peer_audin_running(testPeerContext* context) +{ +#if defined(CHANNEL_AUDIN_SERVER) + if (!context || !context->audin || !context->audin->IsOpen) + return FALSE; + + return context->audin->IsOpen(context->audin); +#else + return FALSE; +#endif +} + +void sf_peer_audin_uninit(testPeerContext* context) +{ + WINPR_ASSERT(context); + +#if defined(CHANNEL_AUDIN_SERVER) + audin_server_context_free(context->audin); + context->audin = NULL; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.h b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.h new file mode 100644 index 0000000000000000000000000000000000000000..1769603cfe45ed3aa80eb0ff99c043a4b1b30849 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_audin.h @@ -0,0 +1,35 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Audio Input) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SAMPLE_SF_AUDIN_H +#define FREERDP_SERVER_SAMPLE_SF_AUDIN_H + +#include +#include + +#include "sfreerdp.h" + +BOOL sf_peer_audin_init(testPeerContext* context); +void sf_peer_audin_uninit(testPeerContext* context); + +BOOL sf_peer_audin_running(testPeerContext* context); +BOOL sf_peer_audin_start(testPeerContext* context); +BOOL sf_peer_audin_stop(testPeerContext* context); + +#endif /* FREERDP_SERVER_SAMPLE_SF_AUDIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.c b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.c new file mode 100644 index 0000000000000000000000000000000000000000..6d03f793a2ccee546bd5c7d7da83cdf74370456e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.c @@ -0,0 +1,43 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Lync Multiparty) + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include + +#include "sf_encomsp.h" + +BOOL sf_peer_encomsp_init(testPeerContext* context) +{ + WINPR_ASSERT(context); + + context->encomsp = encomsp_server_context_new(context->vcm); + if (!context->encomsp) + return FALSE; + + context->encomsp->rdpcontext = &context->_p; + + WINPR_ASSERT(context->encomsp->Start); + if (context->encomsp->Start(context->encomsp) != CHANNEL_RC_OK) + return FALSE; + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.h b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.h new file mode 100644 index 0000000000000000000000000000000000000000..7976abc1c198c5997edcc3d65f82ef43821b80e5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_encomsp.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Lync Multiparty) + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SAMPLE_SF_ENCOMSP_H +#define FREERDP_SERVER_SAMPLE_SF_ENCOMSP_H + +#include +#include +#include + +#include "sfreerdp.h" + +BOOL sf_peer_encomsp_init(testPeerContext* context); + +#endif /* FREERDP_SERVER_SAMPLE_SF_ENCOMSP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.c b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.c new file mode 100644 index 0000000000000000000000000000000000000000..6d4c1ecc3de89932318704798e1abeddb04cdd44 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.c @@ -0,0 +1,62 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include + +#include "sf_rdpsnd.h" + +#include +#include +#define TAG SERVER_TAG("sample") + +static void sf_peer_rdpsnd_activated(RdpsndServerContext* context) +{ + WINPR_UNUSED(context); + WINPR_ASSERT(context); + WLog_DBG(TAG, "RDPSND Activated"); +} + +BOOL sf_peer_rdpsnd_init(testPeerContext* context) +{ + WINPR_ASSERT(context); + + context->rdpsnd = rdpsnd_server_context_new(context->vcm); + WINPR_ASSERT(context->rdpsnd); + context->rdpsnd->rdpcontext = &context->_p; + context->rdpsnd->data = context; + context->rdpsnd->num_server_formats = + server_rdpsnd_get_formats(&context->rdpsnd->server_formats); + + if (context->rdpsnd->num_server_formats > 0) + context->rdpsnd->src_format = &context->rdpsnd->server_formats[0]; + + context->rdpsnd->Activated = sf_peer_rdpsnd_activated; + + WINPR_ASSERT(context->rdpsnd->Initialize); + if (context->rdpsnd->Initialize(context->rdpsnd, TRUE) != CHANNEL_RC_OK) + { + return FALSE; + } + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.h b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.h new file mode 100644 index 0000000000000000000000000000000000000000..f9b0ef4819980a473a56fc9c45b4449323b3c31e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sf_rdpsnd.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SAMPLE_SF_RDPSND_H +#define FREERDP_SERVER_SAMPLE_SF_RDPSND_H + +#include +#include +#include + +#include "sfreerdp.h" + +BOOL sf_peer_rdpsnd_init(testPeerContext* context); + +#endif /* FREERDP_SERVER_SAMPLE_SF_RDPSND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.c b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..582c7aee85997c73103697a0ea9074d647fa31f0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.c @@ -0,0 +1,1472 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Test Server + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2011 Vic Lee + * Copyright 2014 Norbert Federa + * + * 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 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include "sf_ainput.h" +#include "sf_audin.h" +#include "sf_rdpsnd.h" +#include "sf_encomsp.h" + +#include "sfreerdp.h" + +#include +#define TAG SERVER_TAG("sample") + +#define SAMPLE_SERVER_USE_CLIENT_RESOLUTION 1 +#define SAMPLE_SERVER_DEFAULT_WIDTH 1024 +#define SAMPLE_SERVER_DEFAULT_HEIGHT 768 + +struct server_info +{ + BOOL test_dump_rfx_realtime; + const char* test_pcap_file; + const char* replay_dump; + const char* cert; + const char* key; +}; + +static void test_peer_context_free(freerdp_peer* client, rdpContext* ctx) +{ + testPeerContext* context = (testPeerContext*)ctx; + + WINPR_UNUSED(client); + + if (context) + { + winpr_image_free(context->image, TRUE); + if (context->debug_channel_thread) + { + WINPR_ASSERT(context->stopEvent); + (void)SetEvent(context->stopEvent); + (void)WaitForSingleObject(context->debug_channel_thread, INFINITE); + (void)CloseHandle(context->debug_channel_thread); + } + + Stream_Free(context->s, TRUE); + free(context->bg_data); + rfx_context_free(context->rfx_context); + nsc_context_free(context->nsc_context); + + if (context->debug_channel) + (void)WTSVirtualChannelClose(context->debug_channel); + + sf_peer_audin_uninit(context); + +#if defined(CHANNEL_AINPUT_SERVER) + sf_peer_ainput_uninit(context); +#endif + + rdpsnd_server_context_free(context->rdpsnd); + encomsp_server_context_free(context->encomsp); + + WTSCloseServer(context->vcm); + } +} + +static BOOL test_peer_context_new(freerdp_peer* client, rdpContext* ctx) +{ + testPeerContext* context = (testPeerContext*)ctx; + + WINPR_ASSERT(client); + WINPR_ASSERT(context); + WINPR_ASSERT(ctx->settings); + + context->image = winpr_image_new(); + if (!context->image) + goto fail; + if (!(context->rfx_context = rfx_context_new_ex( + TRUE, freerdp_settings_get_uint32(ctx->settings, FreeRDP_ThreadingFlags)))) + goto fail; + + if (!rfx_context_reset(context->rfx_context, SAMPLE_SERVER_DEFAULT_WIDTH, + SAMPLE_SERVER_DEFAULT_HEIGHT)) + goto fail; + + const UINT32 rlgr = freerdp_settings_get_uint32(ctx->settings, FreeRDP_RemoteFxRlgrMode); + rfx_context_set_mode(context->rfx_context, rlgr); + + if (!(context->nsc_context = nsc_context_new())) + goto fail; + + if (!(context->s = Stream_New(NULL, 65536))) + goto fail; + + context->icon_x = UINT32_MAX; + context->icon_y = UINT32_MAX; + context->vcm = WTSOpenServerA((LPSTR)client->context); + + if (!context->vcm || context->vcm == INVALID_HANDLE_VALUE) + goto fail; + + return TRUE; +fail: + test_peer_context_free(client, ctx); + return FALSE; +} + +static BOOL test_peer_init(freerdp_peer* client) +{ + WINPR_ASSERT(client); + + client->ContextSize = sizeof(testPeerContext); + client->ContextNew = test_peer_context_new; + client->ContextFree = test_peer_context_free; + return freerdp_peer_context_new(client); +} + +static wStream* test_peer_stream_init(testPeerContext* context) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(context->s); + + Stream_Clear(context->s); + Stream_SetPosition(context->s, 0); + return context->s; +} + +static void test_peer_begin_frame(freerdp_peer* client) +{ + rdpUpdate* update = NULL; + SURFACE_FRAME_MARKER fm = { 0 }; + testPeerContext* context = NULL; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->context); + + update = client->context->update; + WINPR_ASSERT(update); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + fm.frameAction = SURFACECMD_FRAMEACTION_BEGIN; + fm.frameId = context->frame_id; + WINPR_ASSERT(update->SurfaceFrameMarker); + update->SurfaceFrameMarker(update->context, &fm); +} + +static void test_peer_end_frame(freerdp_peer* client) +{ + rdpUpdate* update = NULL; + SURFACE_FRAME_MARKER fm = { 0 }; + testPeerContext* context = NULL; + + WINPR_ASSERT(client); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + update = client->context->update; + WINPR_ASSERT(update); + + fm.frameAction = SURFACECMD_FRAMEACTION_END; + fm.frameId = context->frame_id; + WINPR_ASSERT(update->SurfaceFrameMarker); + update->SurfaceFrameMarker(update->context, &fm); + context->frame_id++; +} + +static BOOL stream_surface_bits_supported(const rdpSettings* settings) +{ + const UINT32 supported = + freerdp_settings_get_uint32(settings, FreeRDP_SurfaceCommandsSupported); + return ((supported & SURFCMDS_STREAM_SURFACE_BITS) != 0); +} + +static BOOL test_peer_draw_background(freerdp_peer* client) +{ + size_t size = 0; + wStream* s = NULL; + RFX_RECT rect; + BYTE* rgb_data = NULL; + const rdpSettings* settings = NULL; + rdpUpdate* update = NULL; + SURFACE_BITS_COMMAND cmd = { 0 }; + testPeerContext* context = NULL; + BOOL ret = FALSE; + const UINT32 colorFormat = PIXEL_FORMAT_RGB24; + const size_t bpp = FreeRDPGetBytesPerPixel(colorFormat); + + WINPR_ASSERT(client); + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + update = client->context->update; + WINPR_ASSERT(update); + + const BOOL RemoteFxCodec = freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec); + if (!RemoteFxCodec && !freerdp_settings_get_bool(settings, FreeRDP_NSCodec)) + return FALSE; + + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) <= UINT16_MAX); + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) <= UINT16_MAX); + + s = test_peer_stream_init(context); + rect.x = 0; + rect.y = 0; + rect.width = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + rect.height = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + size = bpp * rect.width * rect.height; + + if (!(rgb_data = malloc(size))) + { + WLog_ERR(TAG, "Problem allocating memory"); + return FALSE; + } + + memset(rgb_data, 0xA0, size); + + if (RemoteFxCodec && stream_surface_bits_supported(settings)) + { + WLog_DBG(TAG, "Using RemoteFX codec"); + rfx_context_set_pixel_format(context->rfx_context, colorFormat); + + WINPR_ASSERT(bpp <= UINT16_MAX); + if (!rfx_compose_message(context->rfx_context, s, &rect, 1, rgb_data, rect.width, + rect.height, (UINT32)(bpp * rect.width))) + { + goto out; + } + + const UINT32 RemoteFxCodecId = + freerdp_settings_get_uint32(settings, FreeRDP_RemoteFxCodecId); + WINPR_ASSERT(RemoteFxCodecId <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)RemoteFxCodecId; + cmd.cmdType = CMDTYPE_STREAM_SURFACE_BITS; + } + else + { + WLog_DBG(TAG, "Using NSCodec"); + nsc_context_set_parameters(context->nsc_context, NSC_COLOR_FORMAT, colorFormat); + + WINPR_ASSERT(bpp <= UINT16_MAX); + nsc_compose_message(context->nsc_context, s, rgb_data, rect.width, rect.height, + (UINT32)(bpp * rect.width)); + const UINT32 NSCodecId = freerdp_settings_get_uint32(settings, FreeRDP_NSCodecId); + WINPR_ASSERT(NSCodecId <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)NSCodecId; + cmd.cmdType = CMDTYPE_SET_SURFACE_BITS; + } + + cmd.destLeft = 0; + cmd.destTop = 0; + cmd.destRight = rect.width; + cmd.destBottom = rect.height; + cmd.bmp.bpp = 32; + cmd.bmp.flags = 0; + cmd.bmp.width = rect.width; + cmd.bmp.height = rect.height; + WINPR_ASSERT(Stream_GetPosition(s) <= UINT32_MAX); + cmd.bmp.bitmapDataLength = (UINT32)Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + test_peer_begin_frame(client); + update->SurfaceBits(update->context, &cmd); + test_peer_end_frame(client); + ret = TRUE; +out: + free(rgb_data); + return ret; +} + +static int open_icon(wImage* img) +{ + char* paths[] = { SAMPLE_RESOURCE_ROOT, "." }; + const char* names[] = { "test_icon.webp", "test_icon.png", "test_icon.jpg", "test_icon.bmp" }; + + for (size_t x = 0; x < ARRAYSIZE(paths); x++) + { + const char* path = paths[x]; + if (!winpr_PathFileExists(path)) + continue; + + for (size_t y = 0; y < ARRAYSIZE(names); y++) + { + const char* name = names[y]; + char* file = GetCombinedPath(path, name); + int rc = winpr_image_read(img, file); + free(file); + if (rc > 0) + return rc; + } + } + WLog_ERR(TAG, "Unable to open test icon"); + return -1; +} + +static BOOL test_peer_load_icon(freerdp_peer* client) +{ + testPeerContext* context = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec) && + !freerdp_settings_get_bool(settings, FreeRDP_NSCodec)) + { + WLog_ERR(TAG, "Client doesn't support RemoteFX or NSCodec"); + return FALSE; + } + + int rc = open_icon(context->image); + if (rc <= 0) + goto out_fail; + + /* background with same size, which will be used to erase the icon from old position */ + if (!(context->bg_data = calloc(context->image->height, 3ULL * context->image->width))) + goto out_fail; + + memset(context->bg_data, 0xA0, 3ULL * context->image->height * context->image->width); + return TRUE; +out_fail: + context->bg_data = NULL; + return FALSE; +} + +static void test_peer_draw_icon(freerdp_peer* client, UINT32 x, UINT32 y) +{ + wStream* s = NULL; + RFX_RECT rect; + rdpUpdate* update = NULL; + rdpSettings* settings = NULL; + SURFACE_BITS_COMMAND cmd = { 0 }; + testPeerContext* context = NULL; + + WINPR_ASSERT(client); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + update = client->context->update; + WINPR_ASSERT(update); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + if (freerdp_settings_get_bool(settings, FreeRDP_DumpRemoteFx)) + return; + + if (context->image->width < 1 || !context->activated) + return; + + rect.x = 0; + rect.y = 0; + + rect.width = WINPR_ASSERTING_INT_CAST(UINT16, context->image->width); + rect.height = WINPR_ASSERTING_INT_CAST(UINT16, context->image->height); + + const UINT32 w = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + const UINT32 h = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + if (context->icon_x + context->image->width > w) + return; + if (context->icon_y + context->image->height > h) + return; + if (x + context->image->width > w) + return; + if (y + context->image->height > h) + return; + + test_peer_begin_frame(client); + + const BOOL RemoteFxCodec = freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec); + if (RemoteFxCodec && stream_surface_bits_supported(settings)) + { + const UINT32 RemoteFxCodecId = + freerdp_settings_get_uint32(settings, FreeRDP_RemoteFxCodecId); + WINPR_ASSERT(RemoteFxCodecId <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)RemoteFxCodecId; + cmd.cmdType = CMDTYPE_STREAM_SURFACE_BITS; + } + else + { + const UINT32 NSCodecId = freerdp_settings_get_uint32(settings, FreeRDP_NSCodecId); + WINPR_ASSERT(NSCodecId <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)NSCodecId; + cmd.cmdType = CMDTYPE_SET_SURFACE_BITS; + } + + if (context->icon_x != UINT32_MAX) + { + const UINT32 colorFormat = PIXEL_FORMAT_RGB24; + const UINT32 bpp = FreeRDPGetBytesPerPixel(colorFormat); + s = test_peer_stream_init(context); + + if (RemoteFxCodec) + { + rfx_context_set_pixel_format(context->rfx_context, colorFormat); + rfx_compose_message(context->rfx_context, s, &rect, 1, context->bg_data, rect.width, + rect.height, rect.width * bpp); + } + else + { + nsc_context_set_parameters(context->nsc_context, NSC_COLOR_FORMAT, colorFormat); + nsc_compose_message(context->nsc_context, s, context->bg_data, rect.width, rect.height, + rect.width * bpp); + } + + cmd.destLeft = context->icon_x; + cmd.destTop = context->icon_y; + cmd.destRight = context->icon_x + rect.width; + cmd.destBottom = context->icon_y + rect.height; + cmd.bmp.bpp = 32; + cmd.bmp.flags = 0; + cmd.bmp.width = rect.width; + cmd.bmp.height = rect.height; + cmd.bmp.bitmapDataLength = (UINT32)Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + WINPR_ASSERT(update->SurfaceBits); + update->SurfaceBits(update->context, &cmd); + } + + s = test_peer_stream_init(context); + + { + const UINT32 colorFormat = + context->image->bitsPerPixel > 24 ? PIXEL_FORMAT_BGRA32 : PIXEL_FORMAT_BGR24; + + if (RemoteFxCodec) + { + rfx_context_set_pixel_format(context->rfx_context, colorFormat); + rfx_compose_message(context->rfx_context, s, &rect, 1, context->image->data, rect.width, + rect.height, context->image->scanline); + } + else + { + nsc_context_set_parameters(context->nsc_context, NSC_COLOR_FORMAT, colorFormat); + nsc_compose_message(context->nsc_context, s, context->image->data, rect.width, + rect.height, context->image->scanline); + } + } + + cmd.destLeft = x; + cmd.destTop = y; + cmd.destRight = x + rect.width; + cmd.destBottom = y + rect.height; + cmd.bmp.bpp = 32; + cmd.bmp.width = rect.width; + cmd.bmp.height = rect.height; + cmd.bmp.bitmapDataLength = (UINT32)Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + WINPR_ASSERT(update->SurfaceBits); + update->SurfaceBits(update->context, &cmd); + context->icon_x = x; + context->icon_y = y; + test_peer_end_frame(client); +} + +static BOOL test_sleep_tsdiff(UINT32* old_sec, UINT32* old_usec, UINT32 new_sec, UINT32 new_usec) +{ + INT64 sec = 0; + INT64 usec = 0; + + WINPR_ASSERT(old_sec); + WINPR_ASSERT(old_usec); + + if ((*old_sec == 0) && (*old_usec == 0)) + { + *old_sec = new_sec; + *old_usec = new_usec; + return TRUE; + } + + sec = new_sec - *old_sec; + usec = new_usec - *old_usec; + + if ((sec < 0) || ((sec == 0) && (usec < 0))) + { + WLog_ERR(TAG, "Invalid time stamp detected."); + return FALSE; + } + + *old_sec = new_sec; + *old_usec = new_usec; + + while (usec < 0) + { + usec += 1000000; + sec--; + } + + if (sec > 0) + Sleep((DWORD)sec * 1000); + + if (usec > 0) + USleep((DWORD)usec); + + return TRUE; +} + +static BOOL tf_peer_dump_rfx(freerdp_peer* client) +{ + BOOL rc = FALSE; + wStream* s = NULL; + UINT32 prev_seconds = 0; + UINT32 prev_useconds = 0; + rdpUpdate* update = NULL; + rdpPcap* pcap_rfx = NULL; + pcap_record record = { 0 }; + struct server_info* info = NULL; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->context); + + info = client->ContextExtra; + WINPR_ASSERT(info); + + s = Stream_New(NULL, 512); + + if (!s) + return FALSE; + + update = client->context->update; + WINPR_ASSERT(update); + + pcap_rfx = pcap_open(info->test_pcap_file, FALSE); + if (!pcap_rfx) + goto fail; + + prev_seconds = prev_useconds = 0; + + while (pcap_has_next_record(pcap_rfx)) + { + if (!pcap_get_next_record_header(pcap_rfx, &record)) + break; + + if (!Stream_EnsureCapacity(s, record.length)) + break; + + record.data = Stream_Buffer(s); + pcap_get_next_record_content(pcap_rfx, &record); + Stream_SetPosition(s, Stream_Capacity(s)); + + if (info->test_dump_rfx_realtime && + test_sleep_tsdiff(&prev_seconds, &prev_useconds, record.header.ts_sec, + record.header.ts_usec) == FALSE) + break; + + WINPR_ASSERT(update->SurfaceCommand); + update->SurfaceCommand(update->context, s); + + WINPR_ASSERT(client->CheckFileDescriptor); + if (client->CheckFileDescriptor(client) != TRUE) + break; + } + + rc = TRUE; +fail: + Stream_Free(s, TRUE); + pcap_close(pcap_rfx); + return rc; +} + +static DWORD WINAPI tf_debug_channel_thread_func(LPVOID arg) +{ + void* fd = NULL; + void* buffer = NULL; + DWORD BytesReturned = 0; + ULONG written = 0; + testPeerContext* context = (testPeerContext*)arg; + + WINPR_ASSERT(context); + if (WTSVirtualChannelQuery(context->debug_channel, WTSVirtualFileHandle, &buffer, + &BytesReturned) == TRUE) + { + fd = *((void**)buffer); + WTSFreeMemory(buffer); + + if (!(context->event = CreateWaitObjectEvent(NULL, TRUE, FALSE, fd))) + return 0; + } + + wStream* s = Stream_New(NULL, 4096); + if (!s) + goto fail; + + if (!WTSVirtualChannelWrite(context->debug_channel, (PCHAR) "test1", 5, &written)) + goto fail; + + while (1) + { + DWORD status = 0; + DWORD nCount = 0; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + + handles[nCount++] = context->event; + handles[nCount++] = freerdp_abort_event(&context->_p); + handles[nCount++] = context->stopEvent; + status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE); + switch (status) + { + case WAIT_OBJECT_0: + break; + default: + goto fail; + } + + Stream_SetPosition(s, 0); + + if (WTSVirtualChannelRead(context->debug_channel, 0, Stream_BufferAs(s, char), + (ULONG)Stream_Capacity(s), &BytesReturned) == FALSE) + { + if (BytesReturned == 0) + break; + + if (!Stream_EnsureRemainingCapacity(s, BytesReturned)) + break; + + if (WTSVirtualChannelRead(context->debug_channel, 0, Stream_BufferAs(s, char), + (ULONG)Stream_Capacity(s), &BytesReturned) == FALSE) + { + /* should not happen */ + break; + } + } + + Stream_SetPosition(s, BytesReturned); + WLog_DBG(TAG, "got %" PRIu32 " bytes", BytesReturned); + } +fail: + Stream_Free(s, TRUE); + return 0; +} + +static BOOL tf_peer_post_connect(freerdp_peer* client) +{ + testPeerContext* context = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + /** + * This callback is called when the entire connection sequence is done, i.e. we've received the + * Font List PDU from the client and sent out the Font Map PDU. + * The server may start sending graphics output and receiving keyboard/mouse input after this + * callback returns. + */ + WLog_DBG(TAG, "Client %s is activated (osMajorType %" PRIu32 " osMinorType %" PRIu32 ")", + client->local ? "(local)" : client->hostname, + freerdp_settings_get_uint32(settings, FreeRDP_OsMajorType), + freerdp_settings_get_uint32(settings, FreeRDP_OsMinorType)); + + if (freerdp_settings_get_bool(settings, FreeRDP_AutoLogonEnabled)) + { + const char* Username = freerdp_settings_get_string(settings, FreeRDP_Username); + const char* Domain = freerdp_settings_get_string(settings, FreeRDP_Domain); + WLog_DBG(TAG, " and wants to login automatically as %s\\%s", Domain ? Domain : "", + Username); + /* A real server may perform OS login here if NLA is not executed previously. */ + } + + WLog_DBG(TAG, ""); + WLog_DBG(TAG, "Client requested desktop: %" PRIu32 "x%" PRIu32 "x%" PRIu32 "", + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth)); +#if (SAMPLE_SERVER_USE_CLIENT_RESOLUTION == 1) + + if (!rfx_context_reset(context->rfx_context, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))) + return FALSE; + + WLog_DBG(TAG, "Using resolution requested by client."); +#else + client->freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) = + context->rfx_context->width; + client->freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) = + context->rfx_context->height; + WLog_DBG(TAG, "Resizing client to %" PRIu32 "x%" PRIu32 "", + client->freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + client->freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + client->update->DesktopResize(client->update->context); +#endif + + /* A real server should tag the peer as activated here and start sending updates in main loop. + */ + if (!test_peer_load_icon(client)) + { + WLog_DBG(TAG, "Unable to load icon"); + return FALSE; + } + + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, "rdpdbg")) + { + context->debug_channel = WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, "rdpdbg"); + + if (context->debug_channel != NULL) + { + WLog_DBG(TAG, "Open channel rdpdbg."); + + if (!(context->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + WLog_ERR(TAG, "Failed to create stop event"); + return FALSE; + } + + if (!(context->debug_channel_thread = + CreateThread(NULL, 0, tf_debug_channel_thread_func, (void*)context, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create debug channel thread"); + (void)CloseHandle(context->stopEvent); + context->stopEvent = NULL; + return FALSE; + } + } + } + + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, RDPSND_CHANNEL_NAME)) + { + sf_peer_rdpsnd_init(context); /* Audio Output */ + } + + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, ENCOMSP_SVC_CHANNEL_NAME)) + { + sf_peer_encomsp_init(context); /* Lync Multiparty */ + } + + /* Dynamic Virtual Channels */ + sf_peer_audin_init(context); /* Audio Input */ + +#if defined(CHANNEL_AINPUT_SERVER) + sf_peer_ainput_init(context); +#endif + + /* Return FALSE here would stop the execution of the peer main loop. */ + return TRUE; +} + +static BOOL tf_peer_activate(freerdp_peer* client) +{ + testPeerContext* context = NULL; + struct server_info* info = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + info = client->ContextExtra; + WINPR_ASSERT(info); + + context->activated = TRUE; + // PACKET_COMPR_TYPE_8K; + // PACKET_COMPR_TYPE_64K; + // PACKET_COMPR_TYPE_RDP6; + if (!freerdp_settings_set_uint32(settings, FreeRDP_CompressionLevel, PACKET_COMPR_TYPE_RDP8)) + return FALSE; + + if (info->test_pcap_file != NULL) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_DumpRemoteFx, TRUE)) + return FALSE; + + if (!tf_peer_dump_rfx(client)) + return FALSE; + } + else + test_peer_draw_background(client); + + return TRUE; +} + +static BOOL tf_peer_synchronize_event(rdpInput* input, UINT32 flags) +{ + WINPR_UNUSED(input); + WINPR_ASSERT(input); + WLog_DBG(TAG, "Client sent a synchronize event (flags:0x%" PRIX32 ")", flags); + return TRUE; +} + +static BOOL tf_peer_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + freerdp_peer* client = NULL; + rdpUpdate* update = NULL; + rdpContext* context = NULL; + testPeerContext* tcontext = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(input); + + context = input->context; + WINPR_ASSERT(context); + + client = context->peer; + WINPR_ASSERT(client); + + settings = context->settings; + WINPR_ASSERT(settings); + + update = context->update; + WINPR_ASSERT(update); + + tcontext = (testPeerContext*)context; + WINPR_ASSERT(tcontext); + + WLog_DBG(TAG, "Client sent a keyboard event (flags:0x%04" PRIX16 " code:0x%04" PRIX8 ")", flags, + code); + + if (((flags & KBD_FLAGS_RELEASE) == 0) && (code == RDP_SCANCODE_KEY_G)) /* 'g' key */ + { + if (freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) != 800) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, 800)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, 600)) + return FALSE; + } + else + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, + SAMPLE_SERVER_DEFAULT_WIDTH)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, + SAMPLE_SERVER_DEFAULT_HEIGHT)) + return FALSE; + } + + if (!rfx_context_reset(tcontext->rfx_context, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))) + return FALSE; + + WINPR_ASSERT(update->DesktopResize); + update->DesktopResize(update->context); + tcontext->activated = FALSE; + } + else if (((flags & KBD_FLAGS_RELEASE) == 0) && code == RDP_SCANCODE_KEY_C) /* 'c' key */ + { + if (tcontext->debug_channel) + { + ULONG written = 0; + if (!WTSVirtualChannelWrite(tcontext->debug_channel, (PCHAR) "test2", 5, &written)) + return FALSE; + } + } + else if (((flags & KBD_FLAGS_RELEASE) == 0) && code == RDP_SCANCODE_KEY_X) /* 'x' key */ + { + WINPR_ASSERT(client->Close); + client->Close(client); + } + else if (((flags & KBD_FLAGS_RELEASE) == 0) && code == RDP_SCANCODE_KEY_R) /* 'r' key */ + { + tcontext->audin_open = !tcontext->audin_open; + } +#if defined(CHANNEL_AINPUT_SERVER) + else if (((flags & KBD_FLAGS_RELEASE) == 0) && code == RDP_SCANCODE_KEY_I) /* 'i' key */ + { + tcontext->ainput_open = !tcontext->ainput_open; + } +#endif + else if (((flags & KBD_FLAGS_RELEASE) == 0) && code == RDP_SCANCODE_KEY_S) /* 's' key */ + { + } + + return TRUE; +} + +static BOOL tf_peer_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + WINPR_UNUSED(input); + WINPR_ASSERT(input); + + WLog_DBG(TAG, + "Client sent a unicode keyboard event (flags:0x%04" PRIX16 " code:0x%04" PRIX16 ")", + flags, code); + return TRUE; +} + +static BOOL tf_peer_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + WINPR_UNUSED(flags); + WINPR_ASSERT(input); + WINPR_ASSERT(input->context); + + // WLog_DBG(TAG, "Client sent a mouse event (flags:0x%04"PRIX16" pos:%"PRIu16",%"PRIu16")", + // flags, x, y); + test_peer_draw_icon(input->context->peer, x + 10, y); + return TRUE; +} + +static BOOL tf_peer_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + WINPR_UNUSED(flags); + WINPR_ASSERT(input); + WINPR_ASSERT(input->context); + + // WLog_DBG(TAG, "Client sent an extended mouse event (flags:0x%04"PRIX16" + // pos:%"PRIu16",%"PRIu16")", flags, x, y); + test_peer_draw_icon(input->context->peer, x + 10, y); + return TRUE; +} + +static BOOL tf_peer_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) +{ + WINPR_UNUSED(context); + WINPR_ASSERT(context); + WINPR_ASSERT(areas || (count == 0)); + + WLog_DBG(TAG, "Client requested to refresh:"); + + for (BYTE i = 0; i < count; i++) + { + WLog_DBG(TAG, " (%" PRIu16 ", %" PRIu16 ") (%" PRIu16 ", %" PRIu16 ")", areas[i].left, + areas[i].top, areas[i].right, areas[i].bottom); + } + + return TRUE; +} + +static BOOL tf_peer_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) +{ + WINPR_UNUSED(context); + + if (allow > 0) + { + WINPR_ASSERT(area); + WLog_DBG(TAG, + "Client restore output (%" PRIu16 ", %" PRIu16 ") (%" PRIu16 ", %" PRIu16 ").", + area->left, area->top, area->right, area->bottom); + } + else + { + WLog_DBG(TAG, "Client minimized and suppress output."); + } + + return TRUE; +} + +static int hook_peer_write_pdu(rdpTransport* transport, wStream* s) +{ + UINT64 ts = 0; + wStream* ls = NULL; + UINT64 last_ts = 0; + const struct server_info* info = NULL; + freerdp_peer* client = NULL; + testPeerContext* peerCtx = NULL; + size_t offset = 0; + UINT32 flags = 0; + rdpContext* context = transport_get_context(transport); + + WINPR_ASSERT(context); + WINPR_ASSERT(s); + + client = context->peer; + WINPR_ASSERT(client); + + peerCtx = (testPeerContext*)client->context; + WINPR_ASSERT(peerCtx); + WINPR_ASSERT(peerCtx->io.WritePdu); + + info = client->ContextExtra; + WINPR_ASSERT(info); + + /* Let the client authenticate. + * After that is done, we stop the normal operation and send + * a previously recorded session PDU by PDU to the client. + * + * This is fragile and the connecting client needs to use the same + * configuration as the one that recorded the session! + */ + WINPR_ASSERT(info); + CONNECTION_STATE state = freerdp_get_state(context); + if (state < CONNECTION_STATE_NEGO) + return peerCtx->io.WritePdu(transport, s); + + ls = Stream_New(NULL, 4096); + if (!ls) + goto fail; + + while (stream_dump_get(context, &flags, ls, &offset, &ts) > 0) + { + int rc = 0; + /* Skip messages from client. */ + if (flags & STREAM_MSG_SRV_TX) + { + if ((last_ts > 0) && (ts > last_ts)) + { + UINT64 diff = ts - last_ts; + while (diff > 0) + { + UINT32 d = diff > UINT32_MAX ? UINT32_MAX : (UINT32)diff; + diff -= d; + Sleep(d); + } + } + last_ts = ts; + rc = peerCtx->io.WritePdu(transport, ls); + if (rc < 0) + goto fail; + } + Stream_SetPosition(ls, 0); + } + +fail: + Stream_Free(ls, TRUE); + return -1; +} + +static DWORD WINAPI test_peer_mainloop(LPVOID arg) +{ + BOOL rc = 0; + DWORD error = CHANNEL_RC_OK; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = 0; + DWORD status = 0; + testPeerContext* context = NULL; + struct server_info* info = NULL; + rdpSettings* settings = NULL; + rdpInput* input = NULL; + rdpUpdate* update = NULL; + freerdp_peer* client = (freerdp_peer*)arg; + + WINPR_ASSERT(client); + + info = client->ContextExtra; + WINPR_ASSERT(info); + + if (!test_peer_init(client)) + { + freerdp_peer_free(client); + return 0; + } + + /* Initialize the real server settings here */ + WINPR_ASSERT(client->context); + settings = client->context->settings; + WINPR_ASSERT(settings); + if (info->replay_dump) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDumpReplay, TRUE) || + !freerdp_settings_set_string(settings, FreeRDP_TransportDumpFile, info->replay_dump)) + goto fail; + } + + rdpPrivateKey* key = freerdp_key_new_from_file(info->key); + if (!key) + goto fail; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerRsaKey, key, 1)) + goto fail; + rdpCertificate* cert = freerdp_certificate_new_from_file(info->cert); + if (!cert) + goto fail; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerCertificate, cert, 1)) + goto fail; + + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + goto fail; + if (!freerdp_settings_set_uint32(settings, FreeRDP_EncryptionLevel, + ENCRYPTION_LEVEL_CLIENT_COMPATIBLE)) + goto fail; + /* ENCRYPTION_LEVEL_HIGH; */ + /* ENCRYPTION_LEVEL_LOW; */ + /* ENCRYPTION_LEVEL_FIPS; */ + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, TRUE) || + !freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32)) + goto fail; + + if (!freerdp_settings_set_bool(settings, FreeRDP_SuppressOutput, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_RefreshRect, TRUE)) + goto fail; + + client->PostConnect = tf_peer_post_connect; + client->Activate = tf_peer_activate; + + WINPR_ASSERT(client->context); + input = client->context->input; + WINPR_ASSERT(input); + + input->SynchronizeEvent = tf_peer_synchronize_event; + input->KeyboardEvent = tf_peer_keyboard_event; + input->UnicodeKeyboardEvent = tf_peer_unicode_keyboard_event; + input->MouseEvent = tf_peer_mouse_event; + input->ExtendedMouseEvent = tf_peer_extended_mouse_event; + + update = client->context->update; + WINPR_ASSERT(update); + + update->RefreshRect = tf_peer_refresh_rect; + update->SuppressOutput = tf_peer_suppress_output; + if (!freerdp_settings_set_uint32(settings, FreeRDP_MultifragMaxRequestSize, + 0xFFFFFF /* FIXME */)) + goto fail; + + WINPR_ASSERT(client->Initialize); + rc = client->Initialize(client); + if (!rc) + goto fail; + + context = (testPeerContext*)client->context; + WINPR_ASSERT(context); + + if (info->replay_dump) + { + const rdpTransportIo* cb = freerdp_get_io_callbacks(client->context); + rdpTransportIo replay; + + WINPR_ASSERT(cb); + replay = *cb; + context->io = *cb; + replay.WritePdu = hook_peer_write_pdu; + freerdp_set_io_callbacks(client->context, &replay); + } + + WLog_INFO(TAG, "We've got a client %s", client->local ? "(local)" : client->hostname); + + while (error == CHANNEL_RC_OK) + { + count = 0; + { + WINPR_ASSERT(client->GetEventHandles); + DWORD tmp = client->GetEventHandles(client, &handles[count], 32 - count); + + if (tmp == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP transport event handles"); + break; + } + + count += tmp; + } + + HANDLE channelHandle = WTSVirtualChannelManagerGetEventHandle(context->vcm); + handles[count++] = channelHandle; + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed (errno: %d)", errno); + break; + } + + WINPR_ASSERT(client->CheckFileDescriptor); + if (client->CheckFileDescriptor(client) != TRUE) + break; + + if (WaitForSingleObject(channelHandle, 0) != WAIT_OBJECT_0) + continue; + + if (WTSVirtualChannelManagerCheckFileDescriptor(context->vcm) != TRUE) + break; + + /* Handle dynamic virtual channel initializations */ + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, DRDYNVC_SVC_CHANNEL_NAME)) + { + switch (WTSVirtualChannelManagerGetDrdynvcState(context->vcm)) + { + case DRDYNVC_STATE_NONE: + break; + + case DRDYNVC_STATE_INITIALIZED: + break; + + case DRDYNVC_STATE_READY: + + /* Here is the correct state to start dynamic virtual channels */ + if (sf_peer_audin_running(context) != context->audin_open) + { + if (!sf_peer_audin_running(context)) + sf_peer_audin_start(context); + else + sf_peer_audin_stop(context); + } + +#if defined(CHANNEL_AINPUT_SERVER) + if (sf_peer_ainput_running(context) != context->ainput_open) + { + if (!sf_peer_ainput_running(context)) + sf_peer_ainput_start(context); + else + sf_peer_ainput_stop(context); + } +#endif + + break; + + case DRDYNVC_STATE_FAILED: + default: + break; + } + } + } + + WLog_INFO(TAG, "Client %s disconnected.", client->local ? "(local)" : client->hostname); + + WINPR_ASSERT(client->Disconnect); + client->Disconnect(client); +fail: + freerdp_peer_context_free(client); + freerdp_peer_free(client); + return error; +} + +static BOOL test_peer_accepted(freerdp_listener* instance, freerdp_peer* client) +{ + HANDLE hThread = NULL; + struct server_info* info = NULL; + + WINPR_UNUSED(instance); + + WINPR_ASSERT(instance); + WINPR_ASSERT(client); + + info = instance->info; + client->ContextExtra = info; + + if (!(hThread = CreateThread(NULL, 0, test_peer_mainloop, (void*)client, 0, NULL))) + return FALSE; + + (void)CloseHandle(hThread); + return TRUE; +} + +static void test_server_mainloop(freerdp_listener* instance) +{ + HANDLE handles[32] = { 0 }; + DWORD count = 0; + DWORD status = 0; + + WINPR_ASSERT(instance); + while (1) + { + WINPR_ASSERT(instance->GetEventHandles); + count = instance->GetEventHandles(instance, handles, 32); + + if (0 == count) + { + WLog_ERR(TAG, "Failed to get FreeRDP event handles"); + break; + } + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + + if (WAIT_FAILED == status) + { + WLog_ERR(TAG, "select failed"); + break; + } + + WINPR_ASSERT(instance->CheckFileDescriptor); + if (instance->CheckFileDescriptor(instance) != TRUE) + { + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + break; + } + } + + WINPR_ASSERT(instance->Close); + instance->Close(instance); +} + +static const struct +{ + const char spcap[7]; + const char sfast[7]; + const char sport[7]; + const char slocal_only[13]; + const char scert[7]; + const char skey[6]; +} options = { "--pcap=", "--fast", "--port=", "--local-only", "--cert=", "--key=" }; + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL +WINPR_ATTR_FORMAT_ARG(2, 0) +static void print_entry(FILE* fp, WINPR_FORMAT_ARG const char* fmt, const char* what, size_t size) +{ + char buffer[32] = { 0 }; + strncpy(buffer, what, MIN(size, sizeof(buffer) - 1)); + (void)fprintf(fp, fmt, buffer); +} +WINPR_PRAGMA_DIAG_POP + +static int usage(const char* app, const char* invalid) +{ + FILE* fp = stdout; + + (void)fprintf(fp, "Invalid argument '%s'\n", invalid); + (void)fprintf(fp, "Usage: %s [ ...]\n", app); + (void)fprintf(fp, "Arguments:\n"); + print_entry(fp, "\t%s\n", options.spcap, sizeof(options.spcap)); + print_entry(fp, "\t%s\n", options.scert, sizeof(options.scert)); + print_entry(fp, "\t%s\n", options.skey, sizeof(options.skey)); + print_entry(fp, "\t%s\n", options.sfast, sizeof(options.sfast)); + print_entry(fp, "\t%s\n", options.sport, sizeof(options.sport)); + print_entry(fp, "\t%s\n", options.slocal_only, sizeof(options.slocal_only)); + return -1; +} + +int main(int argc, char* argv[]) +{ + int rc = -1; + BOOL started = FALSE; + WSADATA wsaData = { 0 }; + freerdp_listener* instance = NULL; + char* file = NULL; + char name[MAX_PATH] = { 0 }; + long port = 3389; + BOOL localOnly = FALSE; + struct server_info info = { 0 }; + const char* app = argv[0]; + + info.test_dump_rfx_realtime = TRUE; + + errno = 0; + + for (int i = 1; i < argc; i++) + { + char* arg = argv[i]; + + if (strncmp(arg, options.sfast, sizeof(options.sfast)) == 0) + info.test_dump_rfx_realtime = FALSE; + else if (strncmp(arg, options.sport, sizeof(options.sport)) == 0) + { + const char* sport = &arg[sizeof(options.sport)]; + port = strtol(sport, NULL, 10); + + if ((port < 1) || (port > UINT16_MAX) || (errno != 0)) + return usage(app, arg); + } + else if (strncmp(arg, options.slocal_only, sizeof(options.slocal_only)) == 0) + localOnly = TRUE; + else if (strncmp(arg, options.spcap, sizeof(options.spcap)) == 0) + { + info.test_pcap_file = &arg[sizeof(options.spcap)]; + if (!winpr_PathFileExists(info.test_pcap_file)) + return usage(app, arg); + } + else if (strncmp(arg, options.scert, sizeof(options.scert)) == 0) + { + info.cert = &arg[sizeof(options.scert)]; + if (!winpr_PathFileExists(info.cert)) + return usage(app, arg); + } + else if (strncmp(arg, options.skey, sizeof(options.skey)) == 0) + { + info.key = &arg[sizeof(options.skey)]; + if (!winpr_PathFileExists(info.key)) + return usage(app, arg); + } + else + return usage(app, arg); + } + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + instance = freerdp_listener_new(); + + if (!instance) + return -1; + + if (!info.cert) + info.cert = "server.crt"; + if (!info.key) + info.key = "server.key"; + + instance->info = (void*)&info; + instance->PeerAccepted = test_peer_accepted; + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) + goto fail; + + /* Open the server socket and start listening. */ + (void)sprintf_s(name, sizeof(name), "tfreerdp-server.%ld", port); + file = GetKnownSubPath(KNOWN_PATH_TEMP, name); + + if (!file) + goto fail; + + if (localOnly) + { + WINPR_ASSERT(instance->OpenLocal); + started = instance->OpenLocal(instance, file); + } + else + { + WINPR_ASSERT(instance->Open); + started = instance->Open(instance, NULL, (UINT16)port); + } + + if (started) + { + /* Entering the server main loop. In a real server the listener can be run in its own + * thread. */ + test_server_mainloop(instance); + } + + rc = 0; +fail: + free(file); + freerdp_listener_free(instance); + WSACleanup(); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.h b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..cba105240d68595a39861bde2ab709edc2906e09 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/sfreerdp.h @@ -0,0 +1,76 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SAMPLE_SFREERDP_SERVER_H +#define FREERDP_SERVER_SAMPLE_SFREERDP_SERVER_H + +#include +#include +#include +#include +#include +#if defined(CHANNEL_AINPUT_SERVER) +#include +#endif +#if defined(CHANNEL_AUDIN_SERVER) +#include +#endif +#include +#include +#include + +#include +#include +#include +#include + +struct test_peer_context +{ + rdpContext _p; + + RFX_CONTEXT* rfx_context; + NSC_CONTEXT* nsc_context; + wStream* s; + BYTE* bg_data; + UINT32 icon_x; + UINT32 icon_y; + BOOL activated; + HANDLE event; + HANDLE stopEvent; + HANDLE vcm; + void* debug_channel; + HANDLE debug_channel_thread; +#if defined(CHANNEL_AUDIN_SERVER) + audin_server_context* audin; +#endif + BOOL audin_open; +#if defined(CHANNEL_AINPUT_SERVER) + ainput_server_context* ainput; + BOOL ainput_open; +#endif + UINT32 frame_id; + RdpsndServerContext* rdpsnd; + EncomspServerContext* encomsp; + + rdpTransportIo io; + wImage* image; +}; +typedef struct test_peer_context testPeerContext; + +#endif /* FREERDP_SERVER_SAMPLE_SFREERDP_SERVER_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Sample/test_icon.ppm b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/test_icon.ppm new file mode 100644 index 0000000000000000000000000000000000000000..bcc4a0e58ac8017e89d844a54c66ab6144a0b378 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Sample/test_icon.ppm @@ -0,0 +1,5572 @@ +P3 +# CREATOR: GIMP PNM Filter Version 1.1 +29 64 +255 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +159 +159 +160 +135 +154 +160 +85 +141 +160 +82 +141 +160 +159 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +112 +148 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +155 +158 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +114 +148 +160 +74 +139 +160 +74 +139 +160 +75 +140 +161 +91 +143 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +136 +154 +160 +76 +140 +160 +74 +139 +160 +74 +139 +160 +75 +140 +161 +137 +154 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +152 +158 +160 +79 +141 +160 +75 +140 +161 +74 +139 +160 +74 +139 +160 +83 +141 +160 +159 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +90 +143 +160 +75 +140 +161 +74 +139 +160 +75 +140 +161 +75 +140 +161 +105 +147 +160 +159 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +125 +151 +160 +74 +139 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +74 +139 +160 +111 +154 +167 +158 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +154 +158 +160 +88 +143 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +138 +160 +99 +170 +189 +134 +171 +180 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +126 +151 +160 +74 +139 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +73 +137 +158 +63 +124 +147 +108 +181 +198 +152 +163 +165 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +80 +141 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +73 +138 +159 +21 +72 +99 +78 +143 +164 +126 +180 +192 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +129 +152 +160 +74 +139 +160 +75 +140 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +73 +138 +159 +25 +77 +104 +12 +60 +88 +105 +176 +194 +145 +167 +172 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +98 +145 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +27 +80 +106 +6 +53 +82 +57 +117 +140 +121 +182 +195 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +83 +141 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +76 +141 +162 +30 +83 +109 +6 +53 +82 +28 +81 +107 +108 +180 +197 +154 +162 +164 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +155 +158 +160 +80 +140 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +74 +139 +160 +74 +138 +159 +73 +138 +159 +75 +140 +161 +37 +92 +118 +2 +48 +78 +19 +69 +96 +100 +171 +189 +147 +165 +170 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +149 +157 +160 +79 +140 +160 +74 +139 +160 +74 +139 +160 +76 +142 +163 +82 +149 +169 +96 +165 +184 +106 +178 +196 +111 +185 +202 +114 +188 +205 +114 +188 +205 +97 +168 +186 +107 +179 +196 +150 +164 +168 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +146 +156 +160 +80 +141 +160 +74 +139 +160 +86 +154 +173 +102 +173 +191 +111 +184 +200 +111 +184 +201 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +111 +184 +201 +110 +183 +200 +113 +179 +195 +138 +170 +177 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +146 +156 +160 +77 +139 +159 +93 +162 +182 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +182 +199 +109 +182 +199 +110 +183 +200 +138 +169 +177 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +146 +156 +159 +99 +165 +182 +112 +185 +202 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +150 +165 +168 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +138 +168 +175 +110 +182 +199 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +182 +199 +107 +180 +197 +107 +168 +183 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +156 +161 +162 +117 +179 +194 +109 +182 +199 +109 +182 +199 +110 +183 +200 +109 +182 +199 +109 +182 +199 +109 +182 +199 +109 +182 +199 +109 +182 +199 +110 +183 +200 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +111 +185 +201 +83 +149 +168 +7 +52 +81 +101 +119 +130 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +144 +167 +172 +110 +183 +200 +110 +182 +199 +110 +183 +200 +109 +182 +199 +61 +125 +148 +47 +91 +116 +58 +95 +118 +43 +88 +112 +64 +128 +151 +108 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +112 +185 +202 +98 +168 +186 +125 +165 +175 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +126 +175 +187 +109 +182 +199 +110 +182 +199 +111 +184 +201 +55 +119 +143 +108 +136 +153 +230 +234 +237 +186 +198 +205 +234 +233 +221 +51 +89 +113 +68 +133 +155 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +109 +182 +199 +110 +183 +200 +123 +176 +188 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +114 +179 +195 +110 +183 +200 +110 +183 +200 +103 +175 +193 +66 +114 +136 +247 +248 +249 +240 +243 +244 +57 +95 +118 +22 +66 +93 +40 +80 +106 +64 +113 +135 +108 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +119 +177 +191 +156 +161 +162 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +110 +182 +199 +110 +183 +200 +110 +183 +200 +100 +172 +190 +106 +143 +161 +249 +250 +250 +251 +252 +252 +132 +155 +170 +51 +89 +113 +145 +165 +178 +79 +121 +142 +108 +181 +198 +110 +183 +200 +109 +182 +199 +110 +184 +200 +113 +187 +203 +103 +175 +193 +104 +177 +194 +117 +180 +195 +154 +162 +164 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +112 +180 +196 +110 +183 +200 +110 +183 +200 +107 +180 +197 +74 +124 +145 +250 +251 +251 +254 +254 +254 +250 +251 +251 +238 +241 +243 +220 +226 +230 +67 +122 +144 +109 +182 +199 +110 +183 +200 +110 +183 +200 +101 +171 +189 +38 +91 +116 +154 +176 +179 +94 +128 +141 +99 +165 +182 +153 +164 +166 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +120 +177 +190 +109 +182 +199 +110 +183 +200 +110 +184 +200 +81 +152 +172 +113 +144 +161 +242 +244 +245 +242 +244 +245 +235 +239 +241 +92 +129 +148 +87 +157 +177 +110 +183 +200 +110 +183 +200 +115 +189 +206 +37 +91 +116 +8 +55 +84 +0 +46 +77 +55 +117 +140 +118 +186 +201 +152 +163 +165 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +134 +171 +180 +109 +182 +199 +109 +181 +198 +109 +182 +199 +113 +187 +203 +88 +159 +179 +83 +140 +160 +105 +152 +169 +76 +134 +155 +88 +159 +179 +112 +185 +202 +109 +182 +199 +110 +183 +200 +110 +183 +200 +109 +182 +199 +81 +147 +167 +61 +122 +144 +113 +187 +204 +113 +179 +195 +153 +163 +165 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +152 +163 +166 +110 +183 +200 +109 +182 +199 +110 +183 +200 +109 +182 +199 +110 +183 +200 +109 +182 +199 +108 +180 +198 +109 +183 +200 +110 +183 +200 +109 +182 +199 +109 +182 +199 +110 +183 +200 +109 +182 +199 +110 +183 +200 +106 +178 +195 +74 +138 +159 +110 +183 +200 +117 +178 +192 +155 +162 +163 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +157 +161 +161 +121 +177 +190 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +95 +164 +183 +77 +142 +163 +110 +183 +200 +123 +175 +188 +158 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +139 +169 +176 +110 +182 +199 +110 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +70 +133 +154 +103 +173 +191 +109 +181 +198 +136 +171 +179 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +159 +160 +160 +115 +179 +194 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +108 +181 +198 +95 +164 +183 +110 +183 +200 +110 +182 +199 +156 +161 +162 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +149 +164 +168 +109 +182 +199 +109 +182 +199 +110 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +111 +183 +200 +109 +182 +199 +136 +170 +177 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +137 +169 +177 +110 +183 +200 +109 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +119 +178 +192 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +157 +161 +162 +120 +176 +189 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +181 +198 +148 +165 +169 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +143 +167 +172 +110 +181 +198 +109 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +181 +198 +109 +182 +199 +126 +175 +186 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +116 +180 +194 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +182 +199 +109 +182 +199 +153 +162 +164 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +132 +172 +181 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +124 +175 +187 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +138 +169 +176 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +115 +165 +178 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +134 +171 +180 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +184 +201 +96 +165 +184 +133 +152 +158 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +119 +177 +190 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +107 +179 +197 +90 +141 +158 +156 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +156 +161 +163 +111 +181 +197 +109 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +82 +149 +169 +127 +151 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +143 +167 +172 +111 +182 +199 +109 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +96 +166 +184 +77 +138 +160 +158 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +131 +172 +182 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +103 +174 +191 +77 +142 +163 +99 +145 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +157 +161 +162 +121 +176 +189 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +82 +149 +168 +74 +140 +160 +126 +152 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +154 +162 +164 +111 +180 +196 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +111 +184 +201 +91 +160 +178 +74 +139 +160 +82 +141 +160 +148 +157 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +145 +166 +171 +128 +173 +184 +122 +176 +189 +129 +174 +184 +160 +160 +160 +160 +160 +160 +160 +160 +160 +144 +166 +171 +109 +182 +199 +110 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +103 +174 +192 +74 +139 +160 +74 +140 +160 +94 +144 +160 +156 +159 +160 +160 +160 +160 +160 +160 +160 +152 +163 +165 +120 +177 +190 +109 +182 +199 +109 +182 +199 +109 +181 +198 +153 +163 +165 +160 +160 +160 +160 +160 +160 +160 +160 +160 +128 +173 +184 +110 +183 +200 +110 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +184 +201 +74 +139 +160 +75 +139 +160 +75 +140 +161 +95 +144 +160 +160 +160 +160 +158 +160 +161 +114 +180 +196 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +151 +164 +167 +160 +160 +160 +160 +160 +160 +160 +160 +160 +115 +179 +194 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +112 +185 +202 +77 +143 +163 +74 +139 +160 +75 +140 +160 +74 +139 +160 +104 +145 +159 +134 +169 +177 +110 +183 +200 +109 +181 +198 +110 +183 +200 +110 +182 +199 +109 +182 +199 +122 +176 +188 +160 +160 +160 +160 +160 +160 +160 +160 +160 +110 +183 +200 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +112 +185 +202 +79 +144 +165 +74 +139 +160 +75 +140 +161 +74 +139 +160 +74 +138 +160 +92 +155 +174 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +109 +181 +198 +110 +183 +200 +160 +160 +160 +160 +160 +160 +160 +160 +160 +110 +183 +200 +109 +181 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +112 +186 +202 +75 +141 +162 +74 +139 +160 +75 +140 +161 +75 +140 +160 +74 +139 +160 +74 +139 +160 +87 +154 +173 +111 +184 +201 +110 +183 +200 +110 +183 +200 +109 +181 +198 +110 +183 +200 +160 +160 +160 +160 +160 +160 +160 +160 +160 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +93 +162 +181 +110 +183 +200 +109 +182 +199 +109 +181 +198 +109 +182 +199 +160 +160 +160 +160 +160 +160 +160 +160 +160 +113 +181 +196 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +104 +176 +194 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +76 +141 +162 +103 +174 +192 +110 +182 +199 +110 +183 +200 +109 +182 +199 +160 +160 +160 +160 +160 +160 +160 +160 +160 +121 +176 +189 +109 +182 +199 +110 +183 +200 +109 +182 +199 +119 +187 +203 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +97 +167 +186 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +80 +145 +165 +111 +185 +202 +109 +182 +199 +143 +167 +173 +160 +160 +160 +160 +160 +160 +160 +160 +160 +133 +172 +181 +109 +182 +199 +110 +182 +199 +109 +182 +199 +140 +198 +211 +111 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +111 +184 +201 +87 +156 +175 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +138 +160 +117 +157 +169 +159 +161 +161 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +147 +165 +169 +110 +183 +200 +109 +182 +199 +110 +183 +200 +161 +208 +219 +113 +184 +201 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +105 +177 +194 +77 +142 +163 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +94 +144 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +154 +162 +164 +114 +181 +196 +109 +182 +199 +109 +182 +200 +181 +218 +227 +114 +185 +201 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +110 +183 +200 +95 +163 +183 +50 +106 +130 +75 +141 +162 +74 +139 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +81 +140 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +158 +160 +161 +125 +175 +187 +109 +182 +199 +108 +182 +199 +201 +228 +235 +116 +186 +202 +109 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +183 +200 +77 +141 +162 +36 +88 +115 +48 +104 +128 +69 +133 +154 +74 +139 +160 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +83 +141 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +139 +169 +176 +110 +182 +199 +107 +180 +197 +204 +230 +236 +137 +196 +210 +108 +182 +199 +110 +183 +200 +110 +183 +200 +110 +183 +200 +109 +182 +199 +110 +184 +200 +46 +101 +126 +38 +90 +116 +48 +103 +128 +61 +120 +143 +69 +133 +154 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +97 +145 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +158 +160 +161 +113 +181 +197 +107 +181 +198 +191 +223 +230 +176 +215 +225 +105 +180 +198 +110 +183 +200 +110 +183 +200 +110 +183 +200 +112 +185 +202 +81 +146 +166 +35 +87 +114 +57 +116 +139 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +127 +152 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +140 +169 +175 +107 +181 +199 +171 +212 +222 +218 +237 +241 +101 +178 +196 +110 +183 +200 +110 +183 +200 +110 +183 +200 +105 +177 +195 +42 +96 +122 +44 +98 +124 +71 +134 +156 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +75 +140 +161 +88 +143 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +120 +176 +189 +144 +200 +213 +251 +252 +252 +108 +182 +199 +109 +182 +199 +109 +182 +199 +109 +182 +199 +53 +110 +135 +37 +90 +116 +46 +101 +127 +72 +135 +157 +74 +139 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +161 +75 +140 +160 +74 +139 +160 +82 +141 +160 +146 +156 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +158 +159 +159 +146 +160 +164 +108 +179 +196 +248 +252 +253 +151 +203 +215 +107 +182 +199 +108 +181 +198 +69 +132 +153 +5 +52 +81 +5 +52 +81 +11 +59 +87 +45 +102 +126 +73 +138 +159 +75 +140 +160 +75 +140 +161 +75 +140 +161 +75 +140 +161 +74 +139 +160 +81 +140 +160 +142 +155 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +141 +147 +150 +70 +98 +115 +41 +77 +99 +41 +95 +119 +120 +157 +173 +157 +187 +198 +67 +131 +154 +46 +103 +127 +4 +50 +79 +6 +53 +82 +6 +54 +83 +6 +53 +82 +3 +50 +79 +28 +81 +108 +52 +111 +135 +61 +123 +145 +77 +132 +151 +94 +139 +154 +116 +146 +157 +154 +158 +159 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +155 +156 +157 +61 +91 +110 +19 +62 +89 +6 +53 +82 +6 +53 +82 +10 +55 +83 +19 +62 +89 +44 +81 +104 +47 +82 +103 +11 +56 +84 +6 +53 +82 +10 +56 +84 +28 +68 +93 +50 +83 +104 +71 +98 +115 +97 +116 +128 +126 +137 +144 +145 +152 +155 +150 +155 +157 +155 +157 +158 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 +160 diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e052beb0f47038f20c4f53257b6f9ec8e0e87029 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/CMakeLists.txt @@ -0,0 +1,82 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Windows Server cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "wfreerdp-server") +set(MODULE_PREFIX "FREERDP_SERVER_WINDOWS") + +include(WarnUnmaintained) +warn_unmaintained(${MODULE_NAME}) + +include_directories(.) + +set(${MODULE_PREFIX}_SRCS + wf_update.c + wf_update.h + wf_dxgi.c + wf_dxgi.h + wf_input.c + wf_input.h + wf_interface.c + wf_interface.h + wf_mirage.c + wf_mirage.h + wf_peer.c + wf_peer.h + wf_settings.c + wf_settings.h + wf_info.c + wf_info.h +) + +if(CHANNEL_RDPSND AND NOT WITH_RDPSND_DSOUND) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS} wf_rdpsnd.c wf_rdpsnd.h wf_wasapi.c wf_wasapi.h) +endif() + +if(CHANNEL_RDPSND AND WITH_RDPSND_DSOUND) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS} wf_rdpsnd.c wf_rdpsnd.h wf_directsound.c wf_directsound.h) +endif() + +if(WITH_SERVER_INTERFACE) + addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) + target_include_directories(${MODULE_NAME} INTERFACE $) +else() + list(APPEND ${MODULE_PREFIX}_SRCS cli/wfreerdp.c cli/wfreerdp.h) + addtargetwithresourcefile(${MODULE_NAME} TRUE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) +endif() + +if(NOT CMAKE_WINDOWS_VERSION STREQUAL "WINXP") + set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} d3d11 dxgi) +endif() + +set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} dsound) +set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} freerdp-server freerdp) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS}) + +if(WITH_SERVER_INTERFACE) + install(TARGETS ${MODULE_NAME} COMPONENT libraries ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) +else() + install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT server) +endif() + +if(WITH_SERVER_INTERFACE) + add_subdirectory(cli) +endif() + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Windows") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..b693f2e76ac83d1b3bc8871ab1ecc0ee5ad4cf4d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_SERVER_NAME "wfreerdp-server") +set(FREERDP_SERVER_PLATFORM "Windows") +set(FREERDP_SERVER_VENDOR "FreeRDP") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..52998c45ee64bd4652f53f0254d79ff21056ab99 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/CMakeLists.txt @@ -0,0 +1,34 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Windows Server (CLI) cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "wfreerdp-server-cli") +set(OUTPUT_NAME "wfreerdp-server") +set(MODULE_PREFIX "FREERDP_SERVER_WINDOWS_CLI") + +include_directories(..) + +set(${MODULE_PREFIX}_SRCS wfreerdp.c wfreerdp.h) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) + +set(${MODULE_PREFIX}_LIBS wfreerdp-server) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS}) + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT server) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Windows") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..110bce3a5939859fd1f5f03b37b4c6466ee4e4eb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.c @@ -0,0 +1,171 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include +#include + +#include "wf_interface.h" + +#include "wfreerdp.h" + +#include +#include +#define TAG SERVER_TAG("windows") + +int IDcount = 0; + +BOOL CALLBACK moncb(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) +{ + WLog_DBG(TAG, "%d\t(%ld, %ld), (%ld, %ld)", IDcount, lprcMonitor->left, lprcMonitor->top, + lprcMonitor->right, lprcMonitor->bottom); + IDcount++; + return TRUE; +} + +int main(int argc, char* argv[]) +{ + freerdp_server_warn_unmaintained(argc, argv); + + BOOL screen_selected = FALSE; + int index = 1; + wfServer* server; + server = wfreerdp_server_new(); + set_screen_id(0); + // handle args + errno = 0; + + while (index < argc) + { + // first the args that will cause the program to terminate + if (strcmp("--list-screens", argv[index]) == 0) + { + int width; + int height; + int bpp; + WLog_INFO(TAG, "Detecting screens..."); + WLog_INFO(TAG, "ID\tResolution\t\tName (Interface)"); + + for (int i = 0;; i++) + { + _TCHAR name[128] = { 0 }; + if (get_screen_info(i, name, ARRAYSIZE(name), &width, &height, &bpp) != 0) + { + if ((width * height * bpp) == 0) + continue; + + WLog_INFO(TAG, "%d\t%dx%dx%d\t", i, width, height, bpp); + WLog_INFO(TAG, "%s", name); + } + else + { + break; + } + } + + { + int vscreen_w; + int vscreen_h; + vscreen_w = GetSystemMetrics(SM_CXVIRTUALSCREEN); + vscreen_h = GetSystemMetrics(SM_CYVIRTUALSCREEN); + WLog_INFO(TAG, ""); + EnumDisplayMonitors(NULL, NULL, moncb, 0); + IDcount = 0; + WLog_INFO(TAG, "Virtual Screen = %dx%d", vscreen_w, vscreen_h); + } + + return 0; + } + + if (strcmp("--screen", argv[index]) == 0) + { + UINT32 val; + screen_selected = TRUE; + index++; + + if (index == argc) + { + WLog_INFO(TAG, "missing screen id parameter"); + return 0; + } + + val = strtoul(argv[index], NULL, 0); + + if ((errno != 0) || (val > UINT32_MAX)) + return -1; + + set_screen_id(val); + index++; + } + + if (index == argc - 1) + { + UINT32 val = strtoul(argv[index], NULL, 0); + + if ((errno != 0) || (val > UINT32_MAX)) + return -1; + + server->port = val; + break; + } + } + + if (screen_selected == FALSE) + { + int width; + int height; + int bpp; + WLog_INFO(TAG, "screen id not provided. attempting to detect..."); + WLog_INFO(TAG, "Detecting screens..."); + WLog_INFO(TAG, "ID\tResolution\t\tName (Interface)"); + + for (int i = 0;; i++) + { + _TCHAR name[128] = { 0 }; + if (get_screen_info(i, name, ARRAYSIZE(name), &width, &height, &bpp) != 0) + { + if ((width * height * bpp) == 0) + continue; + + WLog_INFO(TAG, "%d\t%dx%dx%d\t", i, width, height, bpp); + WLog_INFO(TAG, "%s", name); + set_screen_id(i); + break; + } + else + { + break; + } + } + } + + WLog_INFO(TAG, "Starting server"); + wfreerdp_server_start(server); + (void)WaitForSingleObject(server->thread, INFINITE); + WLog_INFO(TAG, "Stopping server"); + wfreerdp_server_stop(server); + wfreerdp_server_free(server); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..017106db46d450c6547a86cc34fbc2fbc0c2e417 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/cli/wfreerdp.h @@ -0,0 +1,25 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_FREERDP_H +#define FREERDP_SERVER_WIN_FREERDP_H + +#include + +#endif /* FREERDP_SERVER_WIN_FREERDP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.c new file mode 100644 index 0000000000000000000000000000000000000000..e116f40895f4ed097a1ffa201cff231a38c1a9c4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.c @@ -0,0 +1,219 @@ +#include "wf_directsound.h" +#include "wf_interface.h" +#include "wf_info.h" +#include "wf_rdpsnd.h" + +#include + +#define INITGUID +#include +#include + +#define CINTERFACE 1 +#include +#include + +#include +#define TAG SERVER_TAG("windows") + +IDirectSoundCapture8* cap; +IDirectSoundCaptureBuffer8* capBuf; +DSCBUFFERDESC dscbd; +DWORD lastPos; +wfPeerContext* latestPeer; + +int wf_rdpsnd_set_latest_peer(wfPeerContext* peer) +{ + latestPeer = peer; + return 0; +} + +int wf_directsound_activate(RdpsndServerContext* context) +{ + HRESULT hr; + wfInfo* wfi; + HANDLE hThread; + + LPDIRECTSOUNDCAPTUREBUFFER pDSCB; + + wfi = wf_info_get_instance(); + if (!wfi) + { + WLog_ERR(TAG, "Failed to wfi instance"); + return 1; + } + WLog_DBG(TAG, "RDPSND (direct sound) Activated"); + hr = DirectSoundCaptureCreate8(NULL, &cap, NULL); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to create sound capture device"); + return 1; + } + + WLog_INFO(TAG, "Created sound capture device"); + dscbd.dwSize = sizeof(DSCBUFFERDESC); + dscbd.dwFlags = 0; + dscbd.dwBufferBytes = wfi->agreed_format->nAvgBytesPerSec; + dscbd.dwReserved = 0; + dscbd.lpwfxFormat = wfi->agreed_format; + dscbd.dwFXCount = 0; + dscbd.lpDSCFXDesc = NULL; + + hr = cap->lpVtbl->CreateCaptureBuffer(cap, &dscbd, &pDSCB, NULL); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to create capture buffer"); + } + + WLog_INFO(TAG, "Created capture buffer"); + hr = pDSCB->lpVtbl->QueryInterface(pDSCB, &IID_IDirectSoundCaptureBuffer8, (LPVOID*)&capBuf); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to QI capture buffer"); + } + WLog_INFO(TAG, "Created IDirectSoundCaptureBuffer8"); + pDSCB->lpVtbl->Release(pDSCB); + lastPos = 0; + + if (!(hThread = CreateThread(NULL, 0, wf_rdpsnd_directsound_thread, latestPeer, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create direct sound thread"); + return 1; + } + (void)CloseHandle(hThread); + + return 0; +} + +static DWORD WINAPI wf_rdpsnd_directsound_thread(LPVOID lpParam) +{ + HRESULT hr; + DWORD beg = 0; + DWORD end = 0; + DWORD diff, rate; + wfPeerContext* context; + wfInfo* wfi; + + VOID* pbCaptureData = NULL; + DWORD dwCaptureLength = 0; + VOID* pbCaptureData2 = NULL; + DWORD dwCaptureLength2 = 0; + VOID* pbPlayData = NULL; + DWORD dwReadPos = 0; + LONG lLockSize = 0; + + wfi = wf_info_get_instance(); + if (!wfi) + { + WLog_ERR(TAG, "Failed get instance"); + return 1; + } + + context = (wfPeerContext*)lpParam; + rate = 1000 / 24; + WLog_INFO(TAG, "Trying to start capture"); + hr = capBuf->lpVtbl->Start(capBuf, DSCBSTART_LOOPING); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to start capture"); + } + WLog_INFO(TAG, "Capture started"); + + while (1) + { + + end = GetTickCount(); + diff = end - beg; + + if (diff < rate) + { + Sleep(rate - diff); + } + + beg = GetTickCount(); + + if (wf_rdpsnd_lock() > 0) + { + // check for main exit condition + if (wfi->snd_stop == TRUE) + { + wf_rdpsnd_unlock(); + break; + } + + hr = capBuf->lpVtbl->GetCurrentPosition(capBuf, NULL, &dwReadPos); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get read pos"); + wf_rdpsnd_unlock(); + break; + } + + lLockSize = dwReadPos - lastPos; // dscbd.dwBufferBytes; + if (lLockSize < 0) + lLockSize += dscbd.dwBufferBytes; + + // WLog_DBG(TAG, "Last, read, lock = [%"PRIu32", %"PRIu32", %"PRId32"]\n", lastPos, + // dwReadPos, lLockSize); + + if (lLockSize == 0) + { + wf_rdpsnd_unlock(); + continue; + } + + hr = capBuf->lpVtbl->Lock(capBuf, lastPos, lLockSize, &pbCaptureData, &dwCaptureLength, + &pbCaptureData2, &dwCaptureLength2, 0L); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to lock sound capture buffer"); + wf_rdpsnd_unlock(); + break; + } + + // fwrite(pbCaptureData, 1, dwCaptureLength, pFile); + // fwrite(pbCaptureData2, 1, dwCaptureLength2, pFile); + + // FIXME: frames = bytes/(bytespersample * channels) + + context->rdpsnd->SendSamples(context->rdpsnd, pbCaptureData, dwCaptureLength / 4, + (UINT16)(beg & 0xffff)); + context->rdpsnd->SendSamples(context->rdpsnd, pbCaptureData2, dwCaptureLength2 / 4, + (UINT16)(beg & 0xffff)); + + hr = capBuf->lpVtbl->Unlock(capBuf, pbCaptureData, dwCaptureLength, pbCaptureData2, + dwCaptureLength2); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to unlock sound capture buffer"); + wf_rdpsnd_unlock(); + return 0; + } + + // TODO keep track of location in buffer + lastPos += dwCaptureLength; + lastPos %= dscbd.dwBufferBytes; + lastPos += dwCaptureLength2; + lastPos %= dscbd.dwBufferBytes; + + wf_rdpsnd_unlock(); + } + } + + WLog_INFO(TAG, "Trying to stop sound capture"); + hr = capBuf->lpVtbl->Stop(capBuf); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to stop capture"); + } + + WLog_INFO(TAG, "Capture stopped"); + capBuf->lpVtbl->Release(capBuf); + cap->lpVtbl->Release(cap); + + lastPos = 0; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.h new file mode 100644 index 0000000000000000000000000000000000000000..01c1bdd2049274948ac162c46554574451d38b5e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_directsound.h @@ -0,0 +1,13 @@ +#ifndef FREERDP_SERVER_WIN_DSOUND_H +#define FREERDP_SERVER_WIN_DSOUND_H + +#include +#include "wf_interface.h" + +int wf_rdpsnd_set_latest_peer(wfPeerContext* peer); + +int wf_directsound_activate(RdpsndServerContext* context); + +DWORD WINAPI wf_rdpsnd_directsound_thread(LPVOID lpParam); + +#endif /* FREERDP_SERVER_WIN_DSOUND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.c new file mode 100644 index 0000000000000000000000000000000000000000..899cb55e4717a583b3e6b54bf7a47937edcad32b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.c @@ -0,0 +1,486 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Corey Clayton + * + * 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 + +#include "wf_interface.h" + +#ifdef WITH_DXGI_1_2 + +#define CINTERFACE + +#include +#include + +#include +#include "wf_dxgi.h" + +#include +#define TAG SERVER_TAG("windows") + +/* Driver types supported */ +D3D_DRIVER_TYPE DriverTypes[] = { + D3D_DRIVER_TYPE_HARDWARE, + D3D_DRIVER_TYPE_WARP, + D3D_DRIVER_TYPE_REFERENCE, +}; +UINT NumDriverTypes = ARRAYSIZE(DriverTypes); + +/* Feature levels supported */ +D3D_FEATURE_LEVEL FeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_1 }; + +UINT NumFeatureLevels = ARRAYSIZE(FeatureLevels); + +D3D_FEATURE_LEVEL FeatureLevel; + +ID3D11Device* gDevice = NULL; +ID3D11DeviceContext* gContext = NULL; +IDXGIOutputDuplication* gOutputDuplication = NULL; +ID3D11Texture2D* gAcquiredDesktopImage = NULL; + +IDXGISurface* surf; +ID3D11Texture2D* sStage; + +DXGI_OUTDUPL_FRAME_INFO FrameInfo; + +int wf_dxgi_init(wfInfo* wfi) +{ + gAcquiredDesktopImage = NULL; + + if (wf_dxgi_createDevice(wfi) != 0) + { + return 1; + } + + if (wf_dxgi_getDuplication(wfi) != 0) + { + return 1; + } + + return 0; +} + +int wf_dxgi_createDevice(wfInfo* wfi) +{ + HRESULT status; + UINT DriverTypeIndex; + + for (DriverTypeIndex = 0; DriverTypeIndex < NumDriverTypes; ++DriverTypeIndex) + { + status = D3D11CreateDevice(NULL, DriverTypes[DriverTypeIndex], NULL, 0, FeatureLevels, + NumFeatureLevels, D3D11_SDK_VERSION, &gDevice, &FeatureLevel, + &gContext); + if (SUCCEEDED(status)) + break; + + WLog_INFO(TAG, "D3D11CreateDevice returned [%ld] for Driver Type %d", status, + DriverTypes[DriverTypeIndex]); + } + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to create device in InitializeDx"); + return 1; + } + + return 0; +} + +int wf_dxgi_getDuplication(wfInfo* wfi) +{ + HRESULT status; + UINT dTop, i = 0; + DXGI_OUTPUT_DESC desc = { 0 }; + IDXGIOutput* pOutput; + IDXGIDevice* DxgiDevice = NULL; + IDXGIAdapter* DxgiAdapter = NULL; + IDXGIOutput* DxgiOutput = NULL; + IDXGIOutput1* DxgiOutput1 = NULL; + + status = gDevice->lpVtbl->QueryInterface(gDevice, &IID_IDXGIDevice, (void**)&DxgiDevice); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get QI for DXGI Device"); + return 1; + } + + status = DxgiDevice->lpVtbl->GetParent(DxgiDevice, &IID_IDXGIAdapter, (void**)&DxgiAdapter); + DxgiDevice->lpVtbl->Release(DxgiDevice); + DxgiDevice = NULL; + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get parent DXGI Adapter"); + return 1; + } + + pOutput = NULL; + + while (DxgiAdapter->lpVtbl->EnumOutputs(DxgiAdapter, i, &pOutput) != DXGI_ERROR_NOT_FOUND) + { + DXGI_OUTPUT_DESC* pDesc = &desc; + + status = pOutput->lpVtbl->GetDesc(pOutput, pDesc); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get description"); + return 1; + } + + WLog_INFO(TAG, "Output %u: [%s] [%d]", i, pDesc->DeviceName, pDesc->AttachedToDesktop); + + if (pDesc->AttachedToDesktop) + dTop = i; + + pOutput->lpVtbl->Release(pOutput); + ++i; + } + + dTop = wfi->screenID; + + status = DxgiAdapter->lpVtbl->EnumOutputs(DxgiAdapter, dTop, &DxgiOutput); + DxgiAdapter->lpVtbl->Release(DxgiAdapter); + DxgiAdapter = NULL; + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get output"); + return 1; + } + + status = + DxgiOutput->lpVtbl->QueryInterface(DxgiOutput, &IID_IDXGIOutput1, (void**)&DxgiOutput1); + DxgiOutput->lpVtbl->Release(DxgiOutput); + DxgiOutput = NULL; + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get IDXGIOutput1"); + return 1; + } + + status = + DxgiOutput1->lpVtbl->DuplicateOutput(DxgiOutput1, (IUnknown*)gDevice, &gOutputDuplication); + DxgiOutput1->lpVtbl->Release(DxgiOutput1); + DxgiOutput1 = NULL; + + if (FAILED(status)) + { + if (status == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) + { + WLog_ERR( + TAG, + "There is already the maximum number of applications using the Desktop Duplication " + "API running, please close one of those applications and then try again."); + return 1; + } + + WLog_ERR(TAG, "Failed to get duplicate output. Status = %ld", status); + return 1; + } + + return 0; +} + +int wf_dxgi_cleanup(wfInfo* wfi) +{ + if (wfi->framesWaiting > 0) + { + wf_dxgi_releasePixelData(wfi); + } + + if (gAcquiredDesktopImage) + { + gAcquiredDesktopImage->lpVtbl->Release(gAcquiredDesktopImage); + gAcquiredDesktopImage = NULL; + } + + if (gOutputDuplication) + { + gOutputDuplication->lpVtbl->Release(gOutputDuplication); + gOutputDuplication = NULL; + } + + if (gContext) + { + gContext->lpVtbl->Release(gContext); + gContext = NULL; + } + + if (gDevice) + { + gDevice->lpVtbl->Release(gDevice); + gDevice = NULL; + } + + return 0; +} + +int wf_dxgi_nextFrame(wfInfo* wfi, UINT timeout) +{ + HRESULT status = 0; + UINT i = 0; + UINT DataBufferSize = 0; + BYTE* DataBuffer = NULL; + IDXGIResource* DesktopResource = NULL; + + if (wfi->framesWaiting > 0) + { + wf_dxgi_releasePixelData(wfi); + } + + if (gAcquiredDesktopImage) + { + gAcquiredDesktopImage->lpVtbl->Release(gAcquiredDesktopImage); + gAcquiredDesktopImage = NULL; + } + + status = gOutputDuplication->lpVtbl->AcquireNextFrame(gOutputDuplication, timeout, &FrameInfo, + &DesktopResource); + + if (status == DXGI_ERROR_WAIT_TIMEOUT) + { + return 1; + } + + if (FAILED(status)) + { + if (status == DXGI_ERROR_ACCESS_LOST) + { + WLog_ERR(TAG, "Failed to acquire next frame with status=%ld", status); + WLog_ERR(TAG, "Trying to reinitialize due to ACCESS LOST..."); + + if (gAcquiredDesktopImage) + { + gAcquiredDesktopImage->lpVtbl->Release(gAcquiredDesktopImage); + gAcquiredDesktopImage = NULL; + } + + if (gOutputDuplication) + { + gOutputDuplication->lpVtbl->Release(gOutputDuplication); + gOutputDuplication = NULL; + } + + wf_dxgi_getDuplication(wfi); + + return 1; + } + else + { + WLog_ERR(TAG, "Failed to acquire next frame with status=%ld", status); + status = gOutputDuplication->lpVtbl->ReleaseFrame(gOutputDuplication); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to release frame with status=%ld", status); + } + + return 1; + } + } + + status = DesktopResource->lpVtbl->QueryInterface(DesktopResource, &IID_ID3D11Texture2D, + (void**)&gAcquiredDesktopImage); + DesktopResource->lpVtbl->Release(DesktopResource); + DesktopResource = NULL; + + if (FAILED(status)) + { + return 1; + } + + wfi->framesWaiting = FrameInfo.AccumulatedFrames; + + if (FrameInfo.AccumulatedFrames == 0) + { + status = gOutputDuplication->lpVtbl->ReleaseFrame(gOutputDuplication); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to release frame with status=%ld", status); + } + } + + return 0; +} + +int wf_dxgi_getPixelData(wfInfo* wfi, BYTE** data, int* pitch, RECT* invalid) +{ + HRESULT status; + D3D11_BOX Box; + DXGI_MAPPED_RECT mappedRect; + D3D11_TEXTURE2D_DESC tDesc; + + tDesc.Width = (invalid->right - invalid->left); + tDesc.Height = (invalid->bottom - invalid->top); + tDesc.MipLevels = 1; + tDesc.ArraySize = 1; + tDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + tDesc.SampleDesc.Count = 1; + tDesc.SampleDesc.Quality = 0; + tDesc.Usage = D3D11_USAGE_STAGING; + tDesc.BindFlags = 0; + tDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + tDesc.MiscFlags = 0; + + Box.top = invalid->top; + Box.left = invalid->left; + Box.right = invalid->right; + Box.bottom = invalid->bottom; + Box.front = 0; + Box.back = 1; + + status = gDevice->lpVtbl->CreateTexture2D(gDevice, &tDesc, NULL, &sStage); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to create staging surface"); + exit(1); + return 1; + } + + gContext->lpVtbl->CopySubresourceRegion(gContext, (ID3D11Resource*)sStage, 0, 0, 0, 0, + (ID3D11Resource*)gAcquiredDesktopImage, 0, &Box); + + status = sStage->lpVtbl->QueryInterface(sStage, &IID_IDXGISurface, (void**)&surf); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to QI staging surface"); + exit(1); + return 1; + } + + surf->lpVtbl->Map(surf, &mappedRect, DXGI_MAP_READ); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to map staging surface"); + exit(1); + return 1; + } + + *data = mappedRect.pBits; + *pitch = mappedRect.Pitch; + + return 0; +} + +int wf_dxgi_releasePixelData(wfInfo* wfi) +{ + HRESULT status; + + surf->lpVtbl->Unmap(surf); + surf->lpVtbl->Release(surf); + surf = NULL; + sStage->lpVtbl->Release(sStage); + sStage = NULL; + + status = gOutputDuplication->lpVtbl->ReleaseFrame(gOutputDuplication); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to release frame"); + return 1; + } + + wfi->framesWaiting = 0; + + return 0; +} + +int wf_dxgi_getInvalidRegion(RECT* invalid) +{ + HRESULT status; + UINT dirty; + UINT BufSize; + RECT* pRect; + BYTE* DirtyRects; + UINT DataBufferSize = 0; + BYTE* DataBuffer = NULL; + + if (FrameInfo.AccumulatedFrames == 0) + { + return 1; + } + + if (FrameInfo.TotalMetadataBufferSize) + { + + if (FrameInfo.TotalMetadataBufferSize > DataBufferSize) + { + if (DataBuffer) + { + free(DataBuffer); + DataBuffer = NULL; + } + + DataBuffer = (BYTE*)malloc(FrameInfo.TotalMetadataBufferSize); + + if (!DataBuffer) + { + DataBufferSize = 0; + WLog_ERR(TAG, "Failed to allocate memory for metadata"); + exit(1); + } + + DataBufferSize = FrameInfo.TotalMetadataBufferSize; + } + + BufSize = FrameInfo.TotalMetadataBufferSize; + + status = gOutputDuplication->lpVtbl->GetFrameMoveRects( + gOutputDuplication, BufSize, (DXGI_OUTDUPL_MOVE_RECT*)DataBuffer, &BufSize); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get frame move rects"); + return 1; + } + + DirtyRects = DataBuffer + BufSize; + BufSize = FrameInfo.TotalMetadataBufferSize - BufSize; + + status = gOutputDuplication->lpVtbl->GetFrameDirtyRects(gOutputDuplication, BufSize, + (RECT*)DirtyRects, &BufSize); + + if (FAILED(status)) + { + WLog_ERR(TAG, "Failed to get frame dirty rects"); + return 1; + } + dirty = BufSize / sizeof(RECT); + + pRect = (RECT*)DirtyRects; + + for (UINT i = 0; i < dirty; ++i) + { + UnionRect(invalid, invalid, pRect); + ++pRect; + } + } + + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.h new file mode 100644 index 0000000000000000000000000000000000000000..560aec021aba846df00f163eaffd7e1794a7ffc8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_dxgi.h @@ -0,0 +1,41 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_WIN_DXGI_H +#define FREERDP_SERVER_WIN_DXGI_H + +#include "wf_interface.h" + +int wf_dxgi_init(wfInfo* context); + +int wf_dxgi_createDevice(wfInfo* context); + +int wf_dxgi_getDuplication(wfInfo* context); + +int wf_dxgi_cleanup(wfInfo* context); + +int wf_dxgi_nextFrame(wfInfo* context, UINT timeout); + +int wf_dxgi_getPixelData(wfInfo* context, BYTE** data, int* pitch, RECT* invalid); + +int wf_dxgi_releasePixelData(wfInfo* context); + +int wf_dxgi_getInvalidRegion(RECT* invalid); + +#endif /* FREERDP_SERVER_WIN_DXGI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.c new file mode 100644 index 0000000000000000000000000000000000000000..f0d053b04e427df26ac863a13804974f4dea0e9c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.c @@ -0,0 +1,402 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Windows Server + * + * Copyright 2012 Corey Clayton + * + * 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 + +#include + +#include + +#include +#include + +#include "wf_info.h" +#include "wf_update.h" +#include "wf_mirage.h" +#include "wf_dxgi.h" + +#include +#define TAG SERVER_TAG("windows") + +#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" FREERDP_PRODUCT_STRING "\\Server" + +static wfInfo* wfInfoInstance = NULL; +static int _IDcount = 0; + +BOOL wf_info_lock(wfInfo* wfi) +{ + DWORD dRes; + dRes = WaitForSingleObject(wfi->mutex, INFINITE); + + switch (dRes) + { + case WAIT_ABANDONED: + case WAIT_OBJECT_0: + return TRUE; + + case WAIT_TIMEOUT: + return FALSE; + + case WAIT_FAILED: + WLog_ERR(TAG, "wf_info_lock failed with 0x%08lX", GetLastError()); + return FALSE; + } + + return FALSE; +} + +BOOL wf_info_try_lock(wfInfo* wfi, DWORD dwMilliseconds) +{ + DWORD dRes; + dRes = WaitForSingleObject(wfi->mutex, dwMilliseconds); + + switch (dRes) + { + case WAIT_ABANDONED: + case WAIT_OBJECT_0: + return TRUE; + + case WAIT_TIMEOUT: + return FALSE; + + case WAIT_FAILED: + WLog_ERR(TAG, "wf_info_try_lock failed with 0x%08lX", GetLastError()); + return FALSE; + } + + return FALSE; +} + +BOOL wf_info_unlock(wfInfo* wfi) +{ + if (!ReleaseMutex(wfi->mutex)) + { + WLog_ERR(TAG, "wf_info_unlock failed with 0x%08lX", GetLastError()); + return FALSE; + } + + return TRUE; +} + +wfInfo* wf_info_init() +{ + wfInfo* wfi; + wfi = (wfInfo*)calloc(1, sizeof(wfInfo)); + + if (wfi != NULL) + { + HKEY hKey; + LONG status; + DWORD dwType; + DWORD dwSize; + DWORD dwValue; + wfi->mutex = CreateMutex(NULL, FALSE, NULL); + + if (wfi->mutex == NULL) + { + WLog_ERR(TAG, "CreateMutex error: %lu", GetLastError()); + free(wfi); + return NULL; + } + + wfi->updateSemaphore = CreateSemaphore(NULL, 0, 32, NULL); + + if (!wfi->updateSemaphore) + { + WLog_ERR(TAG, "CreateSemaphore error: %lu", GetLastError()); + (void)CloseHandle(wfi->mutex); + free(wfi); + return NULL; + } + + wfi->updateThread = CreateThread(NULL, 0, wf_update_thread, wfi, CREATE_SUSPENDED, NULL); + + if (!wfi->updateThread) + { + WLog_ERR(TAG, "Failed to create update thread"); + (void)CloseHandle(wfi->mutex); + (void)CloseHandle(wfi->updateSemaphore); + free(wfi); + return NULL; + } + + wfi->peers = + (freerdp_peer**)calloc(FREERDP_SERVER_WIN_INFO_MAXPEERS, sizeof(freerdp_peer*)); + + if (!wfi->peers) + { + WLog_ERR(TAG, "Failed to allocate memory for peer"); + (void)CloseHandle(wfi->mutex); + (void)CloseHandle(wfi->updateSemaphore); + (void)CloseHandle(wfi->updateThread); + free(wfi); + return NULL; + } + + // Set FPS + wfi->framesPerSecond = FREERDP_SERVER_WIN_INFO_DEFAULT_FPS; + status = + RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status == ERROR_SUCCESS) + { + if (RegQueryValueEx(hKey, _T("FramesPerSecond"), NULL, &dwType, (BYTE*)&dwValue, + &dwSize) == ERROR_SUCCESS) + wfi->framesPerSecond = dwValue; + } + + RegCloseKey(hKey); + // Set input toggle + wfi->input_disabled = FALSE; + status = + RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status == ERROR_SUCCESS) + { + if (RegQueryValueEx(hKey, _T("DisableInput"), NULL, &dwType, (BYTE*)&dwValue, + &dwSize) == ERROR_SUCCESS) + { + if (dwValue != 0) + wfi->input_disabled = TRUE; + } + } + + RegCloseKey(hKey); + } + + return wfi; +} + +wfInfo* wf_info_get_instance() +{ + if (wfInfoInstance == NULL) + wfInfoInstance = wf_info_init(); + + return wfInfoInstance; +} + +BOOL wf_info_peer_register(wfInfo* wfi, wfPeerContext* context) +{ + int peerId = 0; + + if (!wfi || !context) + return FALSE; + + if (!wf_info_lock(wfi)) + return FALSE; + + if (wfi->peerCount == FREERDP_SERVER_WIN_INFO_MAXPEERS) + goto fail_peer_count; + + context->info = wfi; + + if (!(context->updateEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail_update_event; + + // get the offset of the top left corner of selected screen + EnumDisplayMonitors(NULL, NULL, wf_info_monEnumCB, 0); + _IDcount = 0; +#ifdef WITH_DXGI_1_2 + + if (wfi->peerCount == 0) + if (wf_dxgi_init(wfi) != 0) + goto fail_driver_init; + +#else + + if (!wf_mirror_driver_activate(wfi)) + goto fail_driver_init; + +#endif + + // look through the array of peers until an empty slot + for (int i = 0; i < FREERDP_SERVER_WIN_INFO_MAXPEERS; ++i) + { + // empty index will be our peer id + if (wfi->peers[i] == NULL) + { + peerId = i; + break; + } + } + + wfi->peers[peerId] = ((rdpContext*)context)->peer; + wfi->peers[peerId]->pId = peerId; + wfi->peerCount++; + WLog_INFO(TAG, "Registering Peer: id=%d #=%d", peerId, wfi->peerCount); + wf_info_unlock(wfi); + wfreerdp_server_peer_callback_event(peerId, FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_CONNECT); + return TRUE; +fail_driver_init: + (void)CloseHandle(context->updateEvent); + context->updateEvent = NULL; +fail_update_event: +fail_peer_count: + context->socketClose = TRUE; + wf_info_unlock(wfi); + return FALSE; +} + +void wf_info_peer_unregister(wfInfo* wfi, wfPeerContext* context) +{ + if (wf_info_lock(wfi)) + { + int peerId; + peerId = ((rdpContext*)context)->peer->pId; + wfi->peers[peerId] = NULL; + wfi->peerCount--; + (void)CloseHandle(context->updateEvent); + WLog_INFO(TAG, "Unregistering Peer: id=%d, #=%d", peerId, wfi->peerCount); +#ifdef WITH_DXGI_1_2 + + if (wfi->peerCount == 0) + wf_dxgi_cleanup(wfi); + +#endif + wf_info_unlock(wfi); + wfreerdp_server_peer_callback_event(peerId, + FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_DISCONNECT); + } +} + +BOOL wf_info_have_updates(wfInfo* wfi) +{ +#ifdef WITH_DXGI_1_2 + + if (wfi->framesWaiting == 0) + return FALSE; + +#else + + if (wfi->nextUpdate == wfi->lastUpdate) + return FALSE; + +#endif + return TRUE; +} + +void wf_info_update_changes(wfInfo* wfi) +{ +#ifdef WITH_DXGI_1_2 + wf_dxgi_nextFrame(wfi, wfi->framesPerSecond * 1000); +#else + GETCHANGESBUF* buf; + buf = (GETCHANGESBUF*)wfi->changeBuffer; + wfi->nextUpdate = buf->buffer->counter; +#endif +} + +void wf_info_find_invalid_region(wfInfo* wfi) +{ +#ifdef WITH_DXGI_1_2 + wf_dxgi_getInvalidRegion(&wfi->invalid); +#else + GETCHANGESBUF* buf; + buf = (GETCHANGESBUF*)wfi->changeBuffer; + + for (ULONG i = wfi->lastUpdate; i != wfi->nextUpdate; i = (i + 1) % MAXCHANGES_BUF) + { + LPRECT lpR = &buf->buffer->pointrect[i].rect; + + // need to make sure we only get updates from the selected screen + if ((lpR->left >= wfi->servscreen_xoffset) && + (lpR->right <= (wfi->servscreen_xoffset + wfi->servscreen_width)) && + (lpR->top >= wfi->servscreen_yoffset) && + (lpR->bottom <= (wfi->servscreen_yoffset + wfi->servscreen_height))) + { + UnionRect(&wfi->invalid, &wfi->invalid, lpR); + } + else + { + continue; + } + } + +#endif + + if (wfi->invalid.left < 0) + wfi->invalid.left = 0; + + if (wfi->invalid.top < 0) + wfi->invalid.top = 0; + + if (wfi->invalid.right >= wfi->servscreen_width) + wfi->invalid.right = wfi->servscreen_width - 1; + + if (wfi->invalid.bottom >= wfi->servscreen_height) + wfi->invalid.bottom = wfi->servscreen_height - 1; + + // WLog_DBG(TAG, "invalid region: (%"PRId32", %"PRId32"), (%"PRId32", %"PRId32")", + // wfi->invalid.left, wfi->invalid.top, wfi->invalid.right, wfi->invalid.bottom); +} + +void wf_info_clear_invalid_region(wfInfo* wfi) +{ + wfi->lastUpdate = wfi->nextUpdate; + SetRectEmpty(&wfi->invalid); +} + +void wf_info_invalidate_full_screen(wfInfo* wfi) +{ + SetRect(&wfi->invalid, 0, 0, wfi->servscreen_width, wfi->servscreen_height); +} + +BOOL wf_info_have_invalid_region(wfInfo* wfi) +{ + return IsRectEmpty(&wfi->invalid); +} + +void wf_info_getScreenData(wfInfo* wfi, long* width, long* height, BYTE** pBits, int* pitch) +{ + *width = (wfi->invalid.right - wfi->invalid.left); + *height = (wfi->invalid.bottom - wfi->invalid.top); +#ifdef WITH_DXGI_1_2 + wf_dxgi_getPixelData(wfi, pBits, pitch, &wfi->invalid); +#else + { + long offset; + GETCHANGESBUF* changes; + changes = (GETCHANGESBUF*)wfi->changeBuffer; + *width += 1; + *height += 1; + offset = (4 * wfi->invalid.left) + (wfi->invalid.top * wfi->virtscreen_width * 4); + *pBits = ((BYTE*)(changes->Userbuffer)) + offset; + *pitch = wfi->virtscreen_width * 4; + } +#endif +} + +BOOL CALLBACK wf_info_monEnumCB(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, + LPARAM dwData) +{ + wfInfo* wfi; + wfi = wf_info_get_instance(); + + if (!wfi) + return FALSE; + + if (_IDcount == wfi->screenID) + { + wfi->servscreen_xoffset = lprcMonitor->left; + wfi->servscreen_yoffset = lprcMonitor->top; + } + + _IDcount++; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.h new file mode 100644 index 0000000000000000000000000000000000000000..82b1781b58404101462ec9c7f7d288f870412e17 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_info.h @@ -0,0 +1,46 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_WIN_INFO_H +#define FREERDP_SERVER_WIN_INFO_H + +#include "wf_interface.h" + +#define FREERDP_SERVER_WIN_INFO_DEFAULT_FPS 24 +#define FREERDP_SERVER_WIN_INFO_MAXPEERS 32 + +BOOL wf_info_lock(wfInfo* wfi); +BOOL wf_info_try_lock(wfInfo* wfi, DWORD dwMilliseconds); +BOOL wf_info_unlock(wfInfo* wfi); + +wfInfo* wf_info_get_instance(void); +BOOL wf_info_peer_register(wfInfo* wfi, wfPeerContext* context); +void wf_info_peer_unregister(wfInfo* wfi, wfPeerContext* context); + +BOOL wf_info_have_updates(wfInfo* wfi); +void wf_info_update_changes(wfInfo* wfi); +void wf_info_find_invalid_region(wfInfo* wfi); +void wf_info_clear_invalid_region(wfInfo* wfi); +void wf_info_invalidate_full_screen(wfInfo* wfi); +BOOL wf_info_have_invalid_region(wfInfo* wfi); +void wf_info_getScreenData(wfInfo* wfi, long* width, long* height, BYTE** pBits, int* pitch); +BOOL CALLBACK wf_info_monEnumCB(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, + LPARAM dwData); + +#endif /* FREERDP_SERVER_WIN_INFO_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.c new file mode 100644 index 0000000000000000000000000000000000000000..ece39ee2ac4512e615e172f114a5de8283d6eb87 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.c @@ -0,0 +1,223 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include "wf_input.h" +#include "wf_info.h" + +BOOL wf_peer_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + INPUT keyboard_event; + WINPR_UNUSED(input); + keyboard_event.type = INPUT_KEYBOARD; + keyboard_event.u.ki.wVk = 0; + keyboard_event.u.ki.wScan = code; + keyboard_event.u.ki.dwFlags = KEYEVENTF_SCANCODE; + keyboard_event.u.ki.dwExtraInfo = 0; + keyboard_event.u.ki.time = 0; + + if (flags & KBD_FLAGS_RELEASE) + keyboard_event.u.ki.dwFlags |= KEYEVENTF_KEYUP; + + if (flags & KBD_FLAGS_EXTENDED) + keyboard_event.u.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; + + SendInput(1, &keyboard_event, sizeof(INPUT)); + return TRUE; +} + +BOOL wf_peer_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + INPUT keyboard_event; + WINPR_UNUSED(input); + keyboard_event.type = INPUT_KEYBOARD; + keyboard_event.u.ki.wVk = 0; + keyboard_event.u.ki.wScan = code; + keyboard_event.u.ki.dwFlags = KEYEVENTF_UNICODE; + keyboard_event.u.ki.dwExtraInfo = 0; + keyboard_event.u.ki.time = 0; + + if (flags & KBD_FLAGS_RELEASE) + keyboard_event.u.ki.dwFlags |= KEYEVENTF_KEYUP; + + SendInput(1, &keyboard_event, sizeof(INPUT)); + return TRUE; +} + +BOOL wf_peer_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + INPUT mouse_event = { 0 }; + float width, height; + WINPR_UNUSED(input); + + WINPR_ASSERT(input); + mouse_event.type = INPUT_MOUSE; + + if (flags & PTR_FLAGS_WHEEL) + { + mouse_event.u.mi.dwFlags = MOUSEEVENTF_WHEEL; + mouse_event.u.mi.mouseData = flags & WheelRotationMask; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + mouse_event.u.mi.mouseData *= -1; + + SendInput(1, &mouse_event, sizeof(INPUT)); + } + else + { + wfInfo* wfi; + wfi = wf_info_get_instance(); + + if (!wfi) + return FALSE; + + // width and height of primary screen (even in multimon setups + width = (float)GetSystemMetrics(SM_CXSCREEN); + height = (float)GetSystemMetrics(SM_CYSCREEN); + x += wfi->servscreen_xoffset; + y += wfi->servscreen_yoffset; + mouse_event.u.mi.dx = (LONG)((float)x * (65535.0f / width)); + mouse_event.u.mi.dy = (LONG)((float)y * (65535.0f / height)); + mouse_event.u.mi.dwFlags = MOUSEEVENTF_ABSOLUTE; + + if (flags & PTR_FLAGS_MOVE) + { + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_MOVE; + SendInput(1, &mouse_event, sizeof(INPUT)); + } + + mouse_event.u.mi.dwFlags = MOUSEEVENTF_ABSOLUTE; + + if (flags & PTR_FLAGS_BUTTON1) + { + if (flags & PTR_FLAGS_DOWN) + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_LEFTDOWN; + else + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_LEFTUP; + + SendInput(1, &mouse_event, sizeof(INPUT)); + } + else if (flags & PTR_FLAGS_BUTTON2) + { + if (flags & PTR_FLAGS_DOWN) + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_RIGHTDOWN; + else + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_RIGHTUP; + + SendInput(1, &mouse_event, sizeof(INPUT)); + } + else if (flags & PTR_FLAGS_BUTTON3) + { + if (flags & PTR_FLAGS_DOWN) + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_MIDDLEDOWN; + else + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_MIDDLEUP; + + SendInput(1, &mouse_event, sizeof(INPUT)); + } + } + + return TRUE; +} + +BOOL wf_peer_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + if ((flags & PTR_XFLAGS_BUTTON1) || (flags & PTR_XFLAGS_BUTTON2)) + { + INPUT mouse_event = { 0 }; + mouse_event.type = INPUT_MOUSE; + + if (flags & PTR_FLAGS_MOVE) + { + float width, height; + wfInfo* wfi; + wfi = wf_info_get_instance(); + + if (!wfi) + return FALSE; + + // width and height of primary screen (even in multimon setups + width = (float)GetSystemMetrics(SM_CXSCREEN); + height = (float)GetSystemMetrics(SM_CYSCREEN); + x += wfi->servscreen_xoffset; + y += wfi->servscreen_yoffset; + mouse_event.u.mi.dx = (LONG)((float)x * (65535.0f / width)); + mouse_event.u.mi.dy = (LONG)((float)y * (65535.0f / height)); + mouse_event.u.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; + SendInput(1, &mouse_event, sizeof(INPUT)); + } + + mouse_event.u.mi.dx = mouse_event.u.mi.dy = mouse_event.u.mi.dwFlags = 0; + + if (flags & PTR_XFLAGS_DOWN) + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_XDOWN; + else + mouse_event.u.mi.dwFlags |= MOUSEEVENTF_XUP; + + if (flags & PTR_XFLAGS_BUTTON1) + mouse_event.u.mi.mouseData = XBUTTON1; + else if (flags & PTR_XFLAGS_BUTTON2) + mouse_event.u.mi.mouseData = XBUTTON2; + + SendInput(1, &mouse_event, sizeof(INPUT)); + } + else + { + wf_peer_mouse_event(input, flags, x, y); + } + + return TRUE; +} + +BOOL wf_peer_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT8 code) +{ + WINPR_UNUSED(input); + WINPR_UNUSED(flags); + WINPR_UNUSED(code); + return TRUE; +} + +BOOL wf_peer_unicode_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code) +{ + WINPR_UNUSED(input); + WINPR_UNUSED(flags); + WINPR_UNUSED(code); + return TRUE; +} + +BOOL wf_peer_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + WINPR_UNUSED(input); + WINPR_UNUSED(flags); + WINPR_UNUSED(x); + WINPR_UNUSED(y); + return TRUE; +} + +BOOL wf_peer_extended_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + WINPR_UNUSED(input); + WINPR_UNUSED(flags); + WINPR_UNUSED(x); + WINPR_UNUSED(y); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.h new file mode 100644 index 0000000000000000000000000000000000000000..8123652de0825415dd9bb8fcb51a53d563583b26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_input.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_INPUT_H +#define FREERDP_SERVER_WIN_INPUT_H + +#include "wf_interface.h" + +BOOL wf_peer_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code); +BOOL wf_peer_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code); +BOOL wf_peer_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); +BOOL wf_peer_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); + +// dummy versions +BOOL wf_peer_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT8 code); +BOOL wf_peer_unicode_keyboard_event_dummy(rdpInput* input, UINT16 flags, UINT16 code); +BOOL wf_peer_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); +BOOL wf_peer_extended_mouse_event_dummy(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y); + +#endif /* FREERDP_SERVER_WIN_INPUT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..37923bf007717aa780ab6b61e9bf47586fa2cc8c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.c @@ -0,0 +1,341 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "wf_peer.h" +#include "wf_settings.h" +#include "wf_info.h" + +#include "wf_interface.h" + +#include +#define TAG SERVER_TAG("windows") + +#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" FREERDP_PRODUCT_STRING "\\Server" + +static cbCallback cbEvent = NULL; + +int get_screen_info(int id, _TCHAR* name, size_t length, int* width, int* height, int* bpp) +{ + DISPLAY_DEVICE dd = { 0 }; + + dd.cb = sizeof(DISPLAY_DEVICE); + + if (EnumDisplayDevices(NULL, id, &dd, 0) != 0) + { + HDC dc; + + if (name != NULL) + _stprintf_s(name, length, _T("%s (%s)"), dd.DeviceName, dd.DeviceString); + + dc = CreateDC(dd.DeviceName, NULL, NULL, NULL); + *width = GetDeviceCaps(dc, HORZRES); + *height = GetDeviceCaps(dc, VERTRES); + *bpp = GetDeviceCaps(dc, BITSPIXEL); + // ReleaseDC(NULL, dc); + DeleteDC(dc); + } + else + { + return 0; + } + + return 1; +} + +void set_screen_id(int id) +{ + wfInfo* wfi; + + wfi = wf_info_get_instance(); + if (!wfi) + return; + wfi->screenID = id; + + return; +} + +static DWORD WINAPI wf_server_main_loop(LPVOID lpParam) +{ + freerdp_listener* instance; + wfInfo* wfi; + + wfi = wf_info_get_instance(); + if (!wfi) + { + WLog_ERR(TAG, "Failed to get instance"); + return -1; + } + + wfi->force_all_disconnect = FALSE; + + instance = (freerdp_listener*)lpParam; + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->GetEventHandles); + WINPR_ASSERT(instance->CheckFileDescriptor); + + while (wfi->force_all_disconnect == FALSE) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = instance->GetEventHandles(instance, handles, ARRAYSIZE(handles)); + + if (count == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + if (instance->CheckFileDescriptor(instance) != TRUE) + { + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + break; + } + } + + WLog_INFO(TAG, "wf_server_main_loop terminating"); + instance->Close(instance); + + return 0; +} + +BOOL wfreerdp_server_start(wfServer* server) +{ + freerdp_listener* instance; + + server->instance = freerdp_listener_new(); + server->instance->PeerAccepted = wf_peer_accepted; + instance = server->instance; + + wf_settings_read_dword(HKEY_LOCAL_MACHINE, SERVER_KEY, _T("DefaultPort"), &server->port); + + if (!instance->Open(instance, NULL, (UINT16)server->port)) + return FALSE; + + if (!(server->thread = CreateThread(NULL, 0, wf_server_main_loop, (void*)instance, 0, NULL))) + return FALSE; + + return TRUE; +} + +BOOL wfreerdp_server_stop(wfServer* server) +{ + wfInfo* wfi; + + wfi = wf_info_get_instance(); + if (!wfi) + return FALSE; + WLog_INFO(TAG, "Stopping server"); + wfi->force_all_disconnect = TRUE; + server->instance->Close(server->instance); + return TRUE; +} + +wfServer* wfreerdp_server_new() +{ + WSADATA wsaData; + wfServer* server; + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) + return NULL; + + server = (wfServer*)calloc(1, sizeof(wfServer)); + + if (server) + { + server->port = 3389; + } + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + + cbEvent = NULL; + + return server; +} + +void wfreerdp_server_free(wfServer* server) +{ + free(server); + + WSACleanup(); +} + +BOOL wfreerdp_server_is_running(wfServer* server) +{ + DWORD tStatus; + BOOL bRet; + + bRet = GetExitCodeThread(server->thread, &tStatus); + if (bRet == 0) + { + WLog_ERR(TAG, "Error in call to GetExitCodeThread"); + return FALSE; + } + + if (tStatus == STILL_ACTIVE) + return TRUE; + return FALSE; +} + +UINT32 wfreerdp_server_num_peers() +{ + wfInfo* wfi; + + wfi = wf_info_get_instance(); + if (!wfi) + return -1; + return wfi->peerCount; +} + +UINT32 wfreerdp_server_get_peer_hostname(int pId, wchar_t* dstStr) +{ + wfInfo* wfi; + freerdp_peer* peer; + + wfi = wf_info_get_instance(); + if (!wfi) + return 0; + peer = wfi->peers[pId]; + + if (peer) + { + UINT32 sLen; + + sLen = strnlen_s(peer->hostname, 50); + swprintf(dstStr, 50, L"%hs", peer->hostname); + return sLen; + } + else + { + WLog_WARN(TAG, "nonexistent peer id=%d", pId); + return 0; + } +} + +BOOL wfreerdp_server_peer_is_local(int pId) +{ + wfInfo* wfi; + freerdp_peer* peer; + + wfi = wf_info_get_instance(); + if (!wfi) + return FALSE; + peer = wfi->peers[pId]; + + if (peer) + { + return peer->local; + } + else + { + return FALSE; + } +} + +BOOL wfreerdp_server_peer_is_connected(int pId) +{ + wfInfo* wfi; + freerdp_peer* peer; + + wfi = wf_info_get_instance(); + if (!wfi) + return FALSE; + peer = wfi->peers[pId]; + + if (peer) + { + return peer->connected; + } + else + { + return FALSE; + } +} + +BOOL wfreerdp_server_peer_is_activated(int pId) +{ + wfInfo* wfi; + freerdp_peer* peer; + + wfi = wf_info_get_instance(); + if (!wfi) + return FALSE; + peer = wfi->peers[pId]; + + if (peer) + { + return peer->activated; + } + else + { + return FALSE; + } +} + +BOOL wfreerdp_server_peer_is_authenticated(int pId) +{ + wfInfo* wfi; + freerdp_peer* peer; + + wfi = wf_info_get_instance(); + if (!wfi) + return FALSE; + peer = wfi->peers[pId]; + + if (peer) + { + return peer->authenticated; + } + else + { + return FALSE; + } +} + +void wfreerdp_server_register_callback_event(cbCallback cb) +{ + cbEvent = cb; +} + +void wfreerdp_server_peer_callback_event(int pId, UINT32 eType) +{ + if (cbEvent) + cbEvent(pId, eType); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..5fcbad4ee98289cc37dd626696e0e21ddf55768f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_interface.h @@ -0,0 +1,140 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 FREERDP_SERVER_WIN_INTERFACE_H +#define FREERDP_SERVER_WIN_INTERFACE_H + +#include + +#include +#include +#include + +#include +#include + +#include + +#if _WIN32_WINNT >= 0x0602 +#define WITH_DXGI_1_2 1 +#endif + +#define FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_CONNECT 1 +#define FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_DISCONNECT 2 +#define FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_ACTIVATE 4 +#define FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_AUTH 8 + +typedef struct wf_info wfInfo; +typedef struct wf_peer_context wfPeerContext; + +struct wf_info +{ + wStream* s; + + // screen and monitor info + int screenID; + int virtscreen_width; + int virtscreen_height; + int servscreen_width; + int servscreen_height; + int servscreen_xoffset; + int servscreen_yoffset; + + int frame_idx; + int bitsPerPixel; + HDC driverDC; + int peerCount; + int activePeerCount; + void* changeBuffer; + int framesPerSecond; + LPTSTR deviceKey; + TCHAR deviceName[32]; + freerdp_peer** peers; + BOOL mirrorDriverActive; + UINT framesWaiting; + + HANDLE snd_mutex; + BOOL snd_stop; + AUDIO_FORMAT* agreed_format; + + RECT invalid; + HANDLE mutex; + BOOL updatePending; + HANDLE updateEvent; + HANDLE updateThread; + HANDLE updateSemaphore; + RFX_CONTEXT* rfx_context; + unsigned long lastUpdate; + unsigned long nextUpdate; + SURFACE_BITS_COMMAND cmd; + + BOOL input_disabled; + BOOL force_all_disconnect; +}; + +struct wf_peer_context +{ + rdpContext _p; + + wfInfo* info; + int frame_idx; + HANDLE updateEvent; + BOOL socketClose; + HANDLE socketEvent; + HANDLE socketThread; + HANDLE socketSemaphore; + + HANDLE vcm; + RdpsndServerContext* rdpsnd; +}; + +struct wf_server +{ + DWORD port; + HANDLE thread; + freerdp_listener* instance; +}; +typedef struct wf_server wfServer; + +typedef void(__stdcall* cbCallback)(int, UINT32); + +FREERDP_API int get_screen_info(int id, _TCHAR* name, size_t length, int* w, int* h, int* b); +FREERDP_API void set_screen_id(int id); + +FREERDP_API BOOL wfreerdp_server_start(wfServer* server); +FREERDP_API BOOL wfreerdp_server_stop(wfServer* server); + +FREERDP_API wfServer* wfreerdp_server_new(void); +FREERDP_API void wfreerdp_server_free(wfServer* server); + +FREERDP_API BOOL wfreerdp_server_is_running(wfServer* server); + +FREERDP_API UINT32 wfreerdp_server_num_peers(void); +FREERDP_API UINT32 wfreerdp_server_get_peer_hostname(int pId, wchar_t* dstStr); +FREERDP_API BOOL wfreerdp_server_peer_is_local(int pId); +FREERDP_API BOOL wfreerdp_server_peer_is_connected(int pId); +FREERDP_API BOOL wfreerdp_server_peer_is_activated(int pId); +FREERDP_API BOOL wfreerdp_server_peer_is_authenticated(int pId); + +FREERDP_API void wfreerdp_server_register_callback_event(cbCallback cb); + +void wfreerdp_server_peer_callback_event(int pId, UINT32 eType); + +#endif /* FREERDP_SERVER_WIN_INTERFACE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.c new file mode 100644 index 0000000000000000000000000000000000000000..8ce6f00967d9520b894e0336091d1d9531932490 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.c @@ -0,0 +1,361 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012-2013 Corey Clayton + * + * 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 +#include + +#include "wf_mirage.h" + +#include +#define TAG SERVER_TAG("Windows.mirror") + +#define DEVICE_KEY_PREFIX _T("\\Registry\\Machine\\") +/* +This function will iterate over the loaded display devices until it finds +the mirror device we want to load. If found, it will then copy the registry +key corresponding to the device to the wfi and returns TRUE. Otherwise +the function returns FALSE. +*/ +BOOL wf_mirror_driver_find_display_device(wfInfo* wfi) +{ + BOOL result; + BOOL devFound; + DWORD deviceNumber; + DISPLAY_DEVICE deviceInfo; + devFound = FALSE; + deviceNumber = 0; + deviceInfo.cb = sizeof(deviceInfo); + + while (result = EnumDisplayDevices(NULL, deviceNumber, &deviceInfo, 0)) + { + if (_tcscmp(deviceInfo.DeviceString, _T("Mirage Driver")) == 0) + { + int deviceKeyLength; + int deviceKeyPrefixLength; + deviceKeyPrefixLength = _tcslen(DEVICE_KEY_PREFIX); + + if (_tcsnicmp(deviceInfo.DeviceKey, DEVICE_KEY_PREFIX, deviceKeyPrefixLength) == 0) + { + deviceKeyLength = _tcslen(deviceInfo.DeviceKey) - deviceKeyPrefixLength; + wfi->deviceKey = (LPTSTR)malloc((deviceKeyLength + 1) * sizeof(TCHAR)); + + if (!wfi->deviceKey) + return FALSE; + + _tcsncpy_s(wfi->deviceKey, deviceKeyLength + 1, + &deviceInfo.DeviceKey[deviceKeyPrefixLength], deviceKeyLength); + } + + _tcsncpy_s(wfi->deviceName, 32, deviceInfo.DeviceName, _tcslen(deviceInfo.DeviceName)); + return TRUE; + } + + deviceNumber++; + } + + return FALSE; +} + +/** + * This function will attempt to access the the windows registry using the device + * key stored in the current wfi. It will attempt to read the value of the + * "Attach.ToDesktop" subkey and will return TRUE if the value is already set to + * val. If unable to read the subkey, this function will return FALSE. If the + * subkey is not set to val it will then attempt to set it to val and return TRUE. If + * unsuccessful or an unexpected value is encountered, the function returns + * FALSE. + */ + +BOOL wf_mirror_driver_display_device_attach(wfInfo* wfi, DWORD mode) +{ + HKEY hKey; + LONG status; + DWORD dwType; + DWORD dwSize; + DWORD dwValue; + status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, wfi->deviceKey, 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, + &hKey); + + if (status != ERROR_SUCCESS) + { + WLog_DBG(TAG, "Error opening RegKey: status=0x%08lX", status); + + if (status == ERROR_ACCESS_DENIED) + WLog_DBG(TAG, "access denied. Do you have admin privileges?"); + + return FALSE; + } + + dwSize = sizeof(DWORD); + status = RegQueryValueEx(hKey, _T("Attach.ToDesktop"), NULL, &dwType, (BYTE*)&dwValue, &dwSize); + + if (status != ERROR_SUCCESS) + { + WLog_DBG(TAG, "Error querying RegKey: status=0x%08lX", status); + + if (status == ERROR_ACCESS_DENIED) + WLog_DBG(TAG, "access denied. Do you have admin privileges?"); + + return FALSE; + } + + if (dwValue ^ mode) // only if we want to change modes + { + dwValue = mode; + dwSize = sizeof(DWORD); + status = RegSetValueEx(hKey, _T("Attach.ToDesktop"), 0, REG_DWORD, (BYTE*)&dwValue, dwSize); + + if (status != ERROR_SUCCESS) + { + WLog_DBG(TAG, "Error writing registry key: %ld", status); + + if (status == ERROR_ACCESS_DENIED) + WLog_DBG(TAG, "access denied. Do you have admin privileges?"); + + WLog_DBG(TAG, ""); + return FALSE; + } + } + + return TRUE; +} + +void wf_mirror_driver_print_display_change_status(LONG status) +{ + TCHAR disp_change[64]; + + switch (status) + { + case DISP_CHANGE_SUCCESSFUL: + _tcscpy(disp_change, _T("DISP_CHANGE_SUCCESSFUL")); + break; + + case DISP_CHANGE_BADDUALVIEW: + _tcscpy(disp_change, _T("DISP_CHANGE_BADDUALVIEW")); + break; + + case DISP_CHANGE_BADFLAGS: + _tcscpy(disp_change, _T("DISP_CHANGE_BADFLAGS")); + break; + + case DISP_CHANGE_BADMODE: + _tcscpy(disp_change, _T("DISP_CHANGE_BADMODE")); + break; + + case DISP_CHANGE_BADPARAM: + _tcscpy(disp_change, _T("DISP_CHANGE_BADPARAM")); + break; + + case DISP_CHANGE_FAILED: + _tcscpy(disp_change, _T("DISP_CHANGE_FAILED")); + break; + + case DISP_CHANGE_NOTUPDATED: + _tcscpy(disp_change, _T("DISP_CHANGE_NOTUPDATED")); + break; + + case DISP_CHANGE_RESTART: + _tcscpy(disp_change, _T("DISP_CHANGE_RESTART")); + break; + + default: + _tcscpy(disp_change, _T("DISP_CHANGE_UNKNOWN")); + break; + } + + if (status != DISP_CHANGE_SUCCESSFUL) + WLog_ERR(TAG, "ChangeDisplaySettingsEx() failed with %s (%ld)", disp_change, status); + else + WLog_INFO(TAG, "ChangeDisplaySettingsEx() succeeded with %s (%ld)", disp_change, status); +} + +/** + * This function will attempt to apply the currently configured display settings + * in the registry to the display driver. It will return TRUE if successful + * otherwise it returns FALSE. + * If mode is MIRROR_UNLOAD then the the driver will be asked to remove itself. + */ + +BOOL wf_mirror_driver_update(wfInfo* wfi, int mode) +{ + BOOL status; + DWORD* extHdr; + WORD drvExtraSaved; + DEVMODE* deviceMode; + LONG disp_change_status; + DWORD dmf_devmodewext_magic_sig = 0xDF20C0DE; + + if ((mode != MIRROR_LOAD) && (mode != MIRROR_UNLOAD)) + { + WLog_DBG(TAG, "Invalid mirror mode!"); + return FALSE; + } + + deviceMode = (DEVMODE*)malloc(sizeof(DEVMODE) + EXT_DEVMODE_SIZE_MAX); + + if (!deviceMode) + return FALSE; + + deviceMode->dmDriverExtra = 2 * sizeof(DWORD); + extHdr = (DWORD*)((BYTE*)&deviceMode + sizeof(DEVMODE)); + extHdr[0] = dmf_devmodewext_magic_sig; + extHdr[1] = 0; + drvExtraSaved = deviceMode->dmDriverExtra; + memset(deviceMode, 0, sizeof(DEVMODE) + EXT_DEVMODE_SIZE_MAX); + deviceMode->dmSize = sizeof(DEVMODE); + deviceMode->dmDriverExtra = drvExtraSaved; + + if (mode == MIRROR_LOAD) + { + wfi->virtscreen_width = GetSystemMetrics(SM_CXVIRTUALSCREEN); + wfi->virtscreen_height = GetSystemMetrics(SM_CYVIRTUALSCREEN); + deviceMode->dmPelsWidth = wfi->virtscreen_width; + deviceMode->dmPelsHeight = wfi->virtscreen_height; + deviceMode->dmBitsPerPel = wfi->bitsPerPixel; + deviceMode->u.s2.dmPosition.x = wfi->servscreen_xoffset; + deviceMode->u.s2.dmPosition.y = wfi->servscreen_yoffset; + } + + deviceMode->dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_POSITION; + _tcsncpy_s(deviceMode->dmDeviceName, 32, wfi->deviceName, _tcslen(wfi->deviceName)); + disp_change_status = + ChangeDisplaySettingsEx(wfi->deviceName, deviceMode, NULL, CDS_UPDATEREGISTRY, NULL); + status = (disp_change_status == DISP_CHANGE_SUCCESSFUL) ? TRUE : FALSE; + + if (!status) + wf_mirror_driver_print_display_change_status(disp_change_status); + + return status; +} + +BOOL wf_mirror_driver_map_memory(wfInfo* wfi) +{ + int status; + wfi->driverDC = CreateDC(wfi->deviceName, NULL, NULL, NULL); + + if (wfi->driverDC == NULL) + { + WLog_ERR(TAG, "Could not create device driver context!"); + { + LPVOID lpMsgBuf; + DWORD dw = GetLastError(); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, + NULL); + // Display the error message and exit the process + WLog_ERR(TAG, "CreateDC failed on device [%s] with error %lu: %s", wfi->deviceName, dw, + lpMsgBuf); + LocalFree(lpMsgBuf); + } + return FALSE; + } + + wfi->changeBuffer = calloc(1, sizeof(GETCHANGESBUF)); + + if (!wfi->changeBuffer) + return FALSE; + + status = ExtEscape(wfi->driverDC, dmf_esc_usm_pipe_map, 0, 0, sizeof(GETCHANGESBUF), + (LPSTR)wfi->changeBuffer); + + if (status <= 0) + { + WLog_ERR(TAG, "Failed to map shared memory from the driver! code %d", status); + return FALSE; + } + + return TRUE; +} + +/* Unmap the shared memory and release the DC */ + +BOOL wf_mirror_driver_cleanup(wfInfo* wfi) +{ + int status; + status = ExtEscape(wfi->driverDC, dmf_esc_usm_pipe_unmap, sizeof(GETCHANGESBUF), + (LPSTR)wfi->changeBuffer, 0, 0); + + if (status <= 0) + { + WLog_ERR(TAG, "Failed to unmap shared memory from the driver! code %d", status); + } + + if (wfi->driverDC != NULL) + { + status = DeleteDC(wfi->driverDC); + + if (status == 0) + { + WLog_ERR(TAG, "Failed to release DC!"); + } + } + + free(wfi->changeBuffer); + return TRUE; +} + +BOOL wf_mirror_driver_activate(wfInfo* wfi) +{ + if (!wfi->mirrorDriverActive) + { + WLog_DBG(TAG, "Activating Mirror Driver"); + + if (wf_mirror_driver_find_display_device(wfi) == FALSE) + { + WLog_DBG(TAG, "Could not find dfmirage mirror driver! Is it installed?"); + return FALSE; + } + + if (wf_mirror_driver_display_device_attach(wfi, 1) == FALSE) + { + WLog_DBG(TAG, "Could not attach display device!"); + return FALSE; + } + + if (wf_mirror_driver_update(wfi, MIRROR_LOAD) == FALSE) + { + WLog_DBG(TAG, "could not update system with new display settings!"); + return FALSE; + } + + if (wf_mirror_driver_map_memory(wfi) == FALSE) + { + WLog_DBG(TAG, "Unable to map memory for mirror driver!"); + return FALSE; + } + + wfi->mirrorDriverActive = TRUE; + } + + return TRUE; +} + +void wf_mirror_driver_deactivate(wfInfo* wfi) +{ + if (wfi->mirrorDriverActive) + { + WLog_DBG(TAG, "Deactivating Mirror Driver"); + wf_mirror_driver_cleanup(wfi); + wf_mirror_driver_display_device_attach(wfi, 0); + wf_mirror_driver_update(wfi, MIRROR_UNLOAD); + wfi->mirrorDriverActive = FALSE; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.h new file mode 100644 index 0000000000000000000000000000000000000000..a03f0b95f06d42dd5510817d7625bd1c4d953bc3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_mirage.h @@ -0,0 +1,219 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012-2013 Corey Clayton + * + * 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 FREERDP_SERVER_WIN_MIRAGE_H +#define FREERDP_SERVER_WIN_MIRAGE_H + +#include "wf_interface.h" + +enum +{ + MIRROR_LOAD = 0, + MIRROR_UNLOAD = 1 +}; + +enum +{ + DMF_ESCAPE_BASE_1_VB = 1030, + DMF_ESCAPE_BASE_2_VB = 1026, + DMF_ESCAPE_BASE_3_VB = 24 +}; + +#ifdef _WIN64 + +#define CLIENT_64BIT 0x8000 + +enum +{ + DMF_ESCAPE_BASE_1 = CLIENT_64BIT | DMF_ESCAPE_BASE_1_VB, + DMF_ESCAPE_BASE_2 = CLIENT_64BIT | DMF_ESCAPE_BASE_2_VB, + DMF_ESCAPE_BASE_3 = CLIENT_64BIT | DMF_ESCAPE_BASE_3_VB, +}; + +#else + +enum +{ + DMF_ESCAPE_BASE_1 = DMF_ESCAPE_BASE_1_VB, + DMF_ESCAPE_BASE_2 = DMF_ESCAPE_BASE_2_VB, + DMF_ESCAPE_BASE_3 = DMF_ESCAPE_BASE_3_VB, +}; + +#endif + +typedef enum +{ + dmf_esc_qry_ver_info = DMF_ESCAPE_BASE_2 + 0, + dmf_esc_usm_pipe_map = DMF_ESCAPE_BASE_1 + 0, + dmf_esc_usm_pipe_unmap = DMF_ESCAPE_BASE_1 + 1, + dmf_esc_test = DMF_ESCAPE_BASE_1 + 20, + dmf_esc_usm_pipe_mapping_test = DMF_ESCAPE_BASE_1 + 21, + dmf_esc_pointer_shape_get = DMF_ESCAPE_BASE_3, + +} dmf_escape; + +#define CLIP_LIMIT 50 +#define MAXCHANGES_BUF 20000 + +typedef enum +{ + dmf_dfo_IGNORE = 0, + dmf_dfo_FROM_SCREEN = 1, + dmf_dfo_FROM_DIB = 2, + dmf_dfo_TO_SCREEN = 3, + dmf_dfo_SCREEN_SCREEN = 11, + dmf_dfo_BLIT = 12, + dmf_dfo_SOLIDFILL = 13, + dmf_dfo_BLEND = 14, + dmf_dfo_TRANS = 15, + dmf_dfo_PLG = 17, + dmf_dfo_TEXTOUT = 18, + dmf_dfo_Ptr_Shape = 19, + dmf_dfo_Ptr_Engage = 48, + dmf_dfo_Ptr_Avert = 49, + dmf_dfn_assert_on = 64, + dmf_dfn_assert_off = 65, +} dmf_UpdEvent; + +#define NOCACHE 1 +#define OLDCACHE 2 +#define NEWCACHE 3 + +typedef struct +{ + ULONG type; + RECT rect; +#ifndef DFMIRAGE_LEAN + RECT origrect; + POINT point; + ULONG color; + ULONG refcolor; +#endif +} CHANGES_RECORD; + +typedef CHANGES_RECORD* PCHANGES_RECORD; + +typedef struct +{ + ULONG counter; + CHANGES_RECORD pointrect[MAXCHANGES_BUF]; +} CHANGES_BUF; + +#define EXT_DEVMODE_SIZE_MAX 3072 +#define DMF_PIPE_SEC_SIZE_DEFAULT ALIGN64K(sizeof(CHANGES_BUF)) + +typedef struct +{ + CHANGES_BUF* buffer; + PVOID Userbuffer; +} GETCHANGESBUF; + +#define dmf_sprb_ERRORMASK 0x07FF +#define dmf_sprb_STRICTSESSION_AFF 0x1FFF + +typedef enum +{ + dmf_sprb_internal_error = 0x0001, + dmf_sprb_miniport_gen_error = 0x0004, + dmf_sprb_memory_alloc_failed = 0x0008, + dmf_sprb_pipe_buff_overflow = 0x0010, + dmf_sprb_pipe_buff_insufficient = 0x0020, + dmf_sprb_pipe_not_ready = 0x0040, + dmf_sprb_gdi_err = 0x0100, + dmf_sprb_owner_died = 0x0400, + dmf_sprb_tgtwnd_gone = 0x0800, + dmf_sprb_pdev_detached = 0x2000, +} dmf_session_prob_status; + +#define DMF_ESC_RET_FAILF 0x80000000 +#define DMF_ESC_RET_SSTMASK 0x0000FFFF +#define DMF_ESC_RET_IMMMASK 0x7FFF0000 + +typedef enum +{ + dmf_escret_generic_ok = 0x00010000, + dmf_escret_bad_state = 0x00100000, + dmf_escret_access_denied = 0x00200000, + dmf_escret_bad_buffer_size = 0x00400000, + dmf_escret_internal_err = 0x00800000, + dmf_escret_out_of_memory = 0x02000000, + dmf_escret_already_connected = 0x04000000, + dmf_escret_oh_boy_too_late = 0x08000000, + dmf_escret_bad_window = 0x10000000, + dmf_escret_drv_ver_higher = 0x20000000, + dmf_escret_drv_ver_lower = 0x40000000, +} dmf_esc_retcode; + +typedef struct +{ + ULONG cbSize; + ULONG app_actual_version; + ULONG display_minreq_version; + ULONG connect_options; +} Esc_dmf_Qvi_IN; + +enum +{ + esc_qvi_prod_name_max = 16, +}; + +#define ESC_QVI_PROD_MIRAGE "MIRAGE" +#define ESC_QVI_PROD_QUASAR "QUASAR" + +typedef struct +{ + ULONG cbSize; + ULONG display_actual_version; + ULONG miniport_actual_version; + ULONG app_minreq_version; + ULONG display_buildno; + ULONG miniport_buildno; + char prod_name[esc_qvi_prod_name_max]; +} Esc_dmf_Qvi_OUT; + +typedef struct +{ + ULONG cbSize; + char* pDstBmBuf; + ULONG nDstBmBufSize; +} Esc_dmf_pointer_shape_get_IN; + +typedef struct +{ + ULONG cbSize; + POINTL BmSize; + char* pMaskBm; + ULONG nMaskBmSize; + char* pColorBm; + ULONG nColorBmSize; + char* pColorBmPal; + ULONG nColorBmPalEntries; +} Esc_dmf_pointer_shape_get_OUT; + +BOOL wf_mirror_driver_find_display_device(wfInfo* wfi); +BOOL wf_mirror_driver_display_device_attach(wfInfo* wfi, DWORD mode); +BOOL wf_mirror_driver_update(wfInfo* wfi, int mode); +BOOL wf_mirror_driver_map_memory(wfInfo* wfi); +BOOL wf_mirror_driver_cleanup(wfInfo* wfi); + +BOOL wf_mirror_driver_activate(wfInfo* wfi); +void wf_mirror_driver_deactivate(wfInfo* wfi); + +#endif /* FREERDP_SERVER_WIN_MIRAGE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.c new file mode 100644 index 0000000000000000000000000000000000000000..1fb60ffb78771c7125121dd1ecbf85aed707aa88 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.c @@ -0,0 +1,414 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "wf_info.h" +#include "wf_input.h" +#include "wf_mirage.h" +#include "wf_update.h" +#include "wf_settings.h" +#include "wf_rdpsnd.h" + +#include "wf_peer.h" +#include + +#include +#define TAG SERVER_TAG("windows") + +#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" FREERDP_PRODUCT_STRING + +static DWORD WINAPI wf_peer_main_loop(LPVOID lpParam); + +static BOOL wf_peer_context_new(freerdp_peer* client, rdpContext* ctx) +{ + wfPeerContext* context = (wfPeerContext*)ctx; + WINPR_ASSERT(context); + + if (!(context->info = wf_info_get_instance())) + return FALSE; + + context->vcm = WTSOpenServerA((LPSTR)client->context); + + if (!context->vcm || context->vcm == INVALID_HANDLE_VALUE) + return FALSE; + + if (!wf_info_peer_register(context->info, context)) + { + WTSCloseServer(context->vcm); + context->vcm = NULL; + return FALSE; + } + + return TRUE; +} + +static void wf_peer_context_free(freerdp_peer* client, rdpContext* ctx) +{ + wfPeerContext* context = (wfPeerContext*)ctx; + WINPR_ASSERT(context); + + wf_info_peer_unregister(context->info, context); + + if (context->rdpsnd) + { + wf_rdpsnd_lock(); + context->info->snd_stop = TRUE; + rdpsnd_server_context_free(context->rdpsnd); + wf_rdpsnd_unlock(); + } + + WTSCloseServer(context->vcm); +} + +static BOOL wf_peer_init(freerdp_peer* client) +{ + client->ContextSize = sizeof(wfPeerContext); + client->ContextNew = wf_peer_context_new; + client->ContextFree = wf_peer_context_free; + return freerdp_peer_context_new(client); +} + +static BOOL wf_peer_post_connect(freerdp_peer* client) +{ + wfInfo* wfi; + rdpSettings* settings; + wfPeerContext* context; + + WINPR_ASSERT(client); + + context = (wfPeerContext*)client->context; + WINPR_ASSERT(context); + + wfi = context->info; + WINPR_ASSERT(wfi); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + if ((get_screen_info(wfi->screenID, NULL, 0, &wfi->servscreen_width, &wfi->servscreen_height, + &wfi->bitsPerPixel) == 0) || + (wfi->servscreen_width == 0) || (wfi->servscreen_height == 0) || (wfi->bitsPerPixel == 0)) + { + WLog_ERR(TAG, "postconnect: error getting screen info for screen %d", wfi->screenID); + WLog_ERR(TAG, "\t%dx%dx%d", wfi->servscreen_height, wfi->servscreen_width, + wfi->bitsPerPixel); + return FALSE; + } + + if ((freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) != wfi->servscreen_width) || + (freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) != wfi->servscreen_height)) + { + /* + WLog_DBG(TAG, "Client requested resolution %"PRIu32"x%"PRIu32", but will resize to %dx%d", + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), wfi->servscreen_width, + wfi->servscreen_height); + */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, wfi->servscreen_width) || + !freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, wfi->servscreen_height) || + !freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, wfi->bitsPerPixel)) + return FALSE; + + WINPR_ASSERT(client->context->update); + WINPR_ASSERT(client->context->update->DesktopResize); + client->context->update->DesktopResize(client->context); + } + + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, "rdpsnd")) + { + wf_peer_rdpsnd_init(context); /* Audio Output */ + } + + return TRUE; +} + +static BOOL wf_peer_activate(freerdp_peer* client) +{ + wfInfo* wfi; + wfPeerContext* context = (wfPeerContext*)client->context; + wfi = context->info; + client->activated = TRUE; + wf_update_peer_activate(wfi, context); + wfreerdp_server_peer_callback_event(((rdpContext*)context)->peer->pId, + FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_ACTIVATE); + return TRUE; +} + +static BOOL wf_peer_logon(freerdp_peer* client, const SEC_WINNT_AUTH_IDENTITY* identity, + BOOL automatic) +{ + wfreerdp_server_peer_callback_event(((rdpContext*)client->context)->peer->pId, + FREERDP_SERVER_WIN_SRV_CALLBACK_EVENT_AUTH); + return TRUE; +} + +static BOOL wf_peer_synchronize_event(rdpInput* input, UINT32 flags) +{ + return TRUE; +} + +BOOL wf_peer_accepted(freerdp_listener* instance, freerdp_peer* client) +{ + HANDLE hThread; + + if (!(hThread = CreateThread(NULL, 0, wf_peer_main_loop, client, 0, NULL))) + return FALSE; + + (void)CloseHandle(hThread); + return TRUE; +} + +static DWORD WINAPI wf_peer_socket_listener(LPVOID lpParam) +{ + wfPeerContext* context; + freerdp_peer* client = (freerdp_peer*)lpParam; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->GetEventHandles); + WINPR_ASSERT(client->CheckFileDescriptor); + + context = (wfPeerContext*)client->context; + WINPR_ASSERT(context); + + while (1) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = client->GetEventHandles(client, handles, ARRAYSIZE(handles)); + + if (count == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + (void)SetEvent(context->socketEvent); + (void)WaitForSingleObject(context->socketSemaphore, INFINITE); + + if (context->socketClose) + break; + } + + return 0; +} + +static BOOL wf_peer_read_settings(freerdp_peer* client) +{ + rdpSettings* settings; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + char* CertificateFile = NULL; + if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, SERVER_KEY, _T("CertificateFile"), + &(CertificateFile))) + CertificateFile = _strdup("server.crt"); + + rdpCertificate* cert = freerdp_certificate_new_from_file(CertificateFile); + free(CertificateFile); + if (!cert) + return FALSE; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerCertificate, cert, 1)) + return FALSE; + + char* PrivateKeyFile = NULL; + if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, SERVER_KEY, _T("PrivateKeyFile"), + &(PrivateKeyFile))) + PrivateKeyFile = _strdup("server.key"); + + rdpPrivateKey* key = freerdp_key_new_from_file(PrivateKeyFile); + free(PrivateKeyFile); + + if (!key) + return FALSE; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerRsaKey, key, 1)) + return FALSE; + + return TRUE; +} + +DWORD WINAPI wf_peer_main_loop(LPVOID lpParam) +{ + wfInfo* wfi; + DWORD nCount; + DWORD status; + HANDLE handles[32]; + rdpSettings* settings; + wfPeerContext* context; + freerdp_peer* client = (freerdp_peer*)lpParam; + + if (!wf_peer_init(client)) + goto fail_peer_init; + + WINPR_ASSERT(client->context); + + settings = client->context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + goto fail_peer_init; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32)) + goto fail_peer_init; + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, FALSE)) + goto fail_peer_init; + if (!freerdp_settings_set_bool(settings, FreeRDP_JpegCodec, FALSE)) + goto fail_peer_init; + + if (!wf_peer_read_settings(client)) + goto fail_peer_init; + + client->PostConnect = wf_peer_post_connect; + client->Activate = wf_peer_activate; + client->Logon = wf_peer_logon; + + WINPR_ASSERT(client->context->input); + client->context->input->SynchronizeEvent = wf_peer_synchronize_event; + client->context->input->KeyboardEvent = wf_peer_keyboard_event; + client->context->input->UnicodeKeyboardEvent = wf_peer_unicode_keyboard_event; + client->context->input->MouseEvent = wf_peer_mouse_event; + client->context->input->ExtendedMouseEvent = wf_peer_extended_mouse_event; + + WINPR_ASSERT(client->Initialize); + if (!client->Initialize(client)) + goto fail_client_initialize; + + context = (wfPeerContext*)client->context; + + if (context->socketClose) + goto fail_socked_closed; + + wfi = context->info; + + if (wfi->input_disabled) + { + WLog_INFO(TAG, "client input is disabled"); + client->context->input->KeyboardEvent = wf_peer_keyboard_event_dummy; + client->context->input->UnicodeKeyboardEvent = wf_peer_unicode_keyboard_event_dummy; + client->context->input->MouseEvent = wf_peer_mouse_event_dummy; + client->context->input->ExtendedMouseEvent = wf_peer_extended_mouse_event_dummy; + } + + if (!(context->socketEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail_socket_event; + + if (!(context->socketSemaphore = CreateSemaphore(NULL, 0, 1, NULL))) + goto fail_socket_semaphore; + + if (!(context->socketThread = CreateThread(NULL, 0, wf_peer_socket_listener, client, 0, NULL))) + goto fail_socket_thread; + + WLog_INFO(TAG, "We've got a client %s", client->local ? "(local)" : client->hostname); + nCount = 0; + handles[nCount++] = context->updateEvent; + handles[nCount++] = context->socketEvent; + + while (1) + { + status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE); + + if ((status == WAIT_FAILED) || (status == WAIT_TIMEOUT)) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + if (WaitForSingleObject(context->updateEvent, 0) == 0) + { + if (client->activated) + wf_update_peer_send(wfi, context); + + (void)ResetEvent(context->updateEvent); + ReleaseSemaphore(wfi->updateSemaphore, 1, NULL); + } + + if (WaitForSingleObject(context->socketEvent, 0) == 0) + { + if (client->CheckFileDescriptor(client) != TRUE) + { + WLog_ERR(TAG, "Failed to check peer file descriptor"); + context->socketClose = TRUE; + } + + (void)ResetEvent(context->socketEvent); + ReleaseSemaphore(context->socketSemaphore, 1, NULL); + + if (context->socketClose) + break; + } + + // force disconnect + if (wfi->force_all_disconnect == TRUE) + { + WLog_INFO(TAG, "Forcing Disconnect -> "); + break; + } + + /* FIXME: we should wait on this, instead of calling it every time */ + if (WTSVirtualChannelManagerCheckFileDescriptor(context->vcm) != TRUE) + break; + } + + WLog_INFO(TAG, "Client %s disconnected.", client->local ? "(local)" : client->hostname); + + if (WaitForSingleObject(context->updateEvent, 0) == 0) + { + (void)ResetEvent(context->updateEvent); + ReleaseSemaphore(wfi->updateSemaphore, 1, NULL); + } + + wf_update_peer_deactivate(wfi, context); + client->Disconnect(client); +fail_socket_thread: + (void)CloseHandle(context->socketSemaphore); + context->socketSemaphore = NULL; +fail_socket_semaphore: + (void)CloseHandle(context->socketEvent); + context->socketEvent = NULL; +fail_socket_event: +fail_socked_closed: +fail_client_initialize: + freerdp_peer_context_free(client); +fail_peer_init: + freerdp_peer_free(client); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.h new file mode 100644 index 0000000000000000000000000000000000000000..19d823c2016997f75df1161d554dc0c5374d2dbe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_peer.h @@ -0,0 +1,29 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_PEER_H +#define FREERDP_SERVER_WIN_PEER_H + +#include "wf_interface.h" + +#include + +BOOL wf_peer_accepted(freerdp_listener* instance, freerdp_peer* client); + +#endif /* FREERDP_SERVER_WIN_PEER_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.c new file mode 100644 index 0000000000000000000000000000000000000000..cb961e550591bbb2ed7d68c2f2a50c51e00eaf6e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.c @@ -0,0 +1,153 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Corey Clayton + * + * 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 + +#include +#include + +#include +#include + +#include "wf_rdpsnd.h" +#include "wf_info.h" + +#ifdef WITH_RDPSND_DSOUND + +#include "wf_directsound.h" + +#else + +#include "wf_wasapi.h" + +#endif + +#include +#define TAG SERVER_TAG("windows") + +static void wf_peer_rdpsnd_activated(RdpsndServerContext* context) +{ + wfInfo* wfi; + wfi = wf_info_get_instance(); + wfi->agreed_format = NULL; + WLog_DBG(TAG, "Client supports the following %d formats:", context->num_client_formats); + + size_t i = 0; + for (; i < context->num_client_formats; i++) + { + // TODO: improve the way we agree on a format + for (size_t j = 0; j < context->num_server_formats; j++) + { + if ((context->client_formats[i].wFormatTag == context->server_formats[j].wFormatTag) && + (context->client_formats[i].nChannels == context->server_formats[j].nChannels) && + (context->client_formats[i].nSamplesPerSec == + context->server_formats[j].nSamplesPerSec)) + { + WLog_DBG(TAG, "agreed on format!"); + wfi->agreed_format = (AUDIO_FORMAT*)&context->server_formats[j]; + break; + } + } + + if (wfi->agreed_format != NULL) + break; + } + + if (wfi->agreed_format == NULL) + { + WLog_ERR(TAG, "Could not agree on a audio format with the server"); + return; + } + + context->SelectFormat(context, i); + context->SetVolume(context, 0x7FFF, 0x7FFF); +#ifdef WITH_RDPSND_DSOUND + wf_directsound_activate(context); +#else + wf_wasapi_activate(context); +#endif +} + +int wf_rdpsnd_lock() +{ + DWORD dRes; + wfInfo* wfi; + wfi = wf_info_get_instance(); + dRes = WaitForSingleObject(wfi->snd_mutex, INFINITE); + + switch (dRes) + { + case WAIT_ABANDONED: + case WAIT_OBJECT_0: + return TRUE; + break; + + case WAIT_TIMEOUT: + return FALSE; + break; + + case WAIT_FAILED: + WLog_ERR(TAG, "wf_rdpsnd_lock failed with 0x%08lX", GetLastError()); + return -1; + break; + } + + return -1; +} + +int wf_rdpsnd_unlock() +{ + wfInfo* wfi; + wfi = wf_info_get_instance(); + + if (ReleaseMutex(wfi->snd_mutex) == 0) + { + WLog_DBG(TAG, "wf_rdpsnd_unlock failed with 0x%08lX", GetLastError()); + return -1; + } + + return TRUE; +} + +BOOL wf_peer_rdpsnd_init(wfPeerContext* context) +{ + wfInfo* wfi = wf_info_get_instance(); + + if (!wfi) + return FALSE; + + if (!(wfi->snd_mutex = CreateMutex(NULL, FALSE, NULL))) + return FALSE; + + context->rdpsnd = rdpsnd_server_context_new(context->vcm); + context->rdpsnd->rdpcontext = &context->_p; + context->rdpsnd->data = context; + context->rdpsnd->num_server_formats = + server_rdpsnd_get_formats(&context->rdpsnd->server_formats); + + if (context->rdpsnd->num_server_formats > 0) + context->rdpsnd->src_format = &context->rdpsnd->server_formats[0]; + + context->rdpsnd->Activated = wf_peer_rdpsnd_activated; + context->rdpsnd->Initialize(context->rdpsnd, TRUE); + wf_rdpsnd_set_latest_peer(context); + wfi->snd_stop = FALSE; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.h new file mode 100644 index 0000000000000000000000000000000000000000..88e631d9766f704c45bcaec57b50dd450df0a625 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_rdpsnd.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server (Audio Output) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_RDPSND_H +#define FREERDP_SERVER_WIN_RDPSND_H + +#include +#include +#include + +#include "wf_interface.h" + +int wf_rdpsnd_lock(void); +int wf_rdpsnd_unlock(void); +BOOL wf_peer_rdpsnd_init(wfPeerContext* context); + +#endif /* FREERDP_SERVER_WIN_RDPSND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.c new file mode 100644 index 0000000000000000000000000000000000000000..63d232770d43b14154b9e5020bd0d6807847c2f8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.c @@ -0,0 +1,102 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include "wf_settings.h" + +BOOL wf_settings_read_dword(HKEY key, LPCSTR subkey, LPTSTR name, DWORD* value) +{ + HKEY hKey; + LONG status; + DWORD dwType; + DWORD dwSize; + DWORD dwValue; + + status = RegOpenKeyExA(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status == ERROR_SUCCESS) + { + dwSize = sizeof(DWORD); + + status = RegQueryValueEx(hKey, name, NULL, &dwType, (BYTE*)&dwValue, &dwSize); + + if (status == ERROR_SUCCESS) + *value = dwValue; + + RegCloseKey(hKey); + + return (status == ERROR_SUCCESS) ? TRUE : FALSE; + } + + return FALSE; +} + +BOOL wf_settings_read_string_ascii(HKEY key, LPCSTR subkey, LPTSTR name, char** value) +{ + HKEY hKey; + int length; + LONG status; + DWORD dwType; + DWORD dwSize; + char* strA; + TCHAR* strX = NULL; + + status = RegOpenKeyExA(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status != ERROR_SUCCESS) + return FALSE; + + status = RegQueryValueEx(hKey, name, NULL, &dwType, NULL, &dwSize); + + if (status == ERROR_SUCCESS) + { + strX = (LPTSTR)malloc(dwSize + sizeof(TCHAR)); + if (!strX) + return FALSE; + status = RegQueryValueEx(hKey, name, NULL, &dwType, (BYTE*)strX, &dwSize); + + if (status != ERROR_SUCCESS) + { + free(strX); + RegCloseKey(hKey); + return FALSE; + } + } + + if (strX) + { +#ifdef UNICODE + length = WideCharToMultiByte(CP_UTF8, 0, strX, lstrlenW(strX), NULL, 0, NULL, NULL); + strA = (char*)malloc(length + 1); + WideCharToMultiByte(CP_UTF8, 0, strX, lstrlenW(strX), strA, length, NULL, NULL); + strA[length] = '\0'; + free(strX); +#else + strA = (char*)strX; +#endif + *value = strA; + return TRUE; + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.h new file mode 100644 index 0000000000000000000000000000000000000000..40e25aa2bed4b843f932a5236b0b7b0fbf3e6181 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_settings.h @@ -0,0 +1,28 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_SETTINGS_H +#define FREERDP_SERVER_WIN_SETTINGS_H + +#include "wf_interface.h" + +BOOL wf_settings_read_dword(HKEY key, LPCSTR subkey, LPTSTR name, DWORD* value); +BOOL wf_settings_read_string_ascii(HKEY key, LPCSTR subkey, LPTSTR name, char** value); + +#endif /* FREERDP_SERVER_WIN_SETTINGS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.c new file mode 100644 index 0000000000000000000000000000000000000000..8867efb848589589b2d4387345c625167926916e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.c @@ -0,0 +1,252 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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 + +#include + +#include + +#include +#include + +#include "wf_peer.h" +#include "wf_info.h" +#include "wf_mirage.h" + +#include "wf_update.h" + +#include +#define TAG SERVER_TAG("windows") + +DWORD WINAPI wf_update_thread(LPVOID lpParam) +{ + DWORD fps; + wfInfo* wfi; + DWORD beg, end; + DWORD diff, rate; + wfi = (wfInfo*)lpParam; + fps = wfi->framesPerSecond; + rate = 1000 / fps; + + while (1) + { + beg = GetTickCount(); + + if (wf_info_lock(wfi) > 0) + { + if (wfi->activePeerCount > 0) + { + wf_info_update_changes(wfi); + + if (wf_info_have_updates(wfi)) + { + wf_update_encode(wfi); + // WLog_DBG(TAG, "Start of parallel sending"); + int index = 0; + + for (int peerindex = 0; peerindex < wfi->peerCount; peerindex++) + { + for (; index < FREERDP_SERVER_WIN_INFO_MAXPEERS; index++) + { + if (wfi->peers[index] && wfi->peers[index]->activated) + { + // WLog_DBG(TAG, "Setting event for %d of %d", index + 1, + // wfi->activePeerCount); + (void)SetEvent( + ((wfPeerContext*)wfi->peers[index]->context)->updateEvent); + } + } + } + + for (int index = 0; index < wfi->activePeerCount; index++) + { + // WLog_DBG(TAG, "Waiting for %d of %d", index + 1, wfi->activePeerCount); + // WaitForSingleObject(wfi->updateSemaphore, INFINITE); + (void)WaitForSingleObject(wfi->updateSemaphore, 1000); + } + + // WLog_DBG(TAG, "End of parallel sending"); + wf_info_clear_invalid_region(wfi); + } + } + + wf_info_unlock(wfi); + } + + end = GetTickCount(); + diff = end - beg; + + if (diff < rate) + { + Sleep(rate - diff); + } + } + + // WLog_DBG(TAG, "Exiting Update Thread"); + return 0; +} + +void wf_update_encode(wfInfo* wfi) +{ + RFX_RECT rect; + long height, width; + BYTE* pDataBits = NULL; + int stride; + SURFACE_BITS_COMMAND* cmd; + wf_info_find_invalid_region(wfi); + cmd = &wfi->cmd; + Stream_SetPosition(wfi->s, 0); + wf_info_getScreenData(wfi, &width, &height, &pDataBits, &stride); + rect.x = 0; + rect.y = 0; + rect.width = (UINT16)width; + rect.height = (UINT16)height; + // WLog_DBG(TAG, "x:%"PRId32" y:%"PRId32" w:%ld h:%ld", wfi->invalid.left, wfi->invalid.top, + // width, height); + Stream_Clear(wfi->s); + + if (!(rfx_compose_message(wfi->rfx_context, wfi->s, &rect, 1, pDataBits, width, height, + stride))) + { + return; + } + + wfi->frame_idx = rfx_context_get_frame_idx(wfi->rfx_context); + cmd->destLeft = wfi->invalid.left; + cmd->destTop = wfi->invalid.top; + cmd->destRight = wfi->invalid.left + width; + cmd->destBottom = wfi->invalid.top + height; + cmd->bmp.bpp = 32; + cmd->bmp.codecID = 3; + cmd->bmp.width = width; + cmd->bmp.height = height; + cmd->bmp.bitmapDataLength = Stream_GetPosition(wfi->s); + cmd->bmp.bitmapData = Stream_Buffer(wfi->s); +} + +void wf_update_peer_send(wfInfo* wfi, wfPeerContext* context) +{ + freerdp_peer* client; + + WINPR_ASSERT(wfi); + WINPR_ASSERT(context); + + client = ((rdpContext*)context)->peer; + WINPR_ASSERT(client); + + /* This happens when the RemoteFX encoder state is reset */ + + if (wfi->frame_idx == 1) + context->frame_idx = 0; + + /* + * When a new client connects, it is possible that old frames from + * from a previous encoding state remain. Those frames should be discarded + * as they will cause an error condition in mstsc. + */ + + if ((context->frame_idx + 1) != wfi->frame_idx) + { + /* This frame is meant to be discarded */ + if (context->frame_idx == 0) + return; + + /* This is an unexpected error condition */ + WLog_DBG(TAG, "Unexpected Frame Index: Actual: %d Expected: %d", wfi->frame_idx, + context->frame_idx + 1); + } + + WINPR_ASSERT(client->context); + WINPR_ASSERT(client->context->settings); + WINPR_ASSERT(client->context->update); + WINPR_ASSERT(client->context->update->SurfaceBits); + + wfi->cmd.bmp.codecID = + freerdp_settings_get_uint32(client->context->settings, FreeRDP_RemoteFxCodecId); + client->context->update->SurfaceBits(client->context, &wfi->cmd); + context->frame_idx++; +} + +void wf_update_encoder_reset(wfInfo* wfi) +{ + if (wf_info_lock(wfi) > 0) + { + WLog_DBG(TAG, "Resetting encoder"); + + if (wfi->rfx_context) + { + rfx_context_reset(wfi->rfx_context, wfi->servscreen_width, wfi->servscreen_height); + } + else + { + /* TODO: pass ThreadingFlags somehow */ + wfi->rfx_context = rfx_context_new(TRUE); + rfx_context_set_mode(wfi->rfx_context, RLGR3); + rfx_context_reset(wfi->rfx_context, wfi->servscreen_width, wfi->servscreen_height); + rfx_context_set_pixel_format(wfi->rfx_context, PIXEL_FORMAT_BGRA32); + wfi->s = Stream_New(NULL, 0xFFFF); + } + + wf_info_invalidate_full_screen(wfi); + wf_info_unlock(wfi); + } +} + +void wf_update_peer_activate(wfInfo* wfi, wfPeerContext* context) +{ + if (wf_info_lock(wfi) > 0) + { + if (wfi->activePeerCount < 1) + { +#ifndef WITH_DXGI_1_2 + wf_mirror_driver_activate(wfi); +#endif + ResumeThread(wfi->updateThread); + } + + wf_update_encoder_reset(wfi); + wfi->activePeerCount++; + WLog_DBG(TAG, "Activating Peer Updates: %d", wfi->activePeerCount); + wf_info_unlock(wfi); + } +} + +void wf_update_peer_deactivate(wfInfo* wfi, wfPeerContext* context) +{ + if (wf_info_lock(wfi) > 0) + { + freerdp_peer* client = ((rdpContext*)context)->peer; + + if (client->activated) + { + if (wfi->activePeerCount <= 1) + { + wf_mirror_driver_deactivate(wfi); + } + + client->activated = FALSE; + wfi->activePeerCount--; + WLog_DBG(TAG, "Deactivating Peer Updates: %d", wfi->activePeerCount); + } + + wf_info_unlock(wfi); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.h new file mode 100644 index 0000000000000000000000000000000000000000..47553aff0e7047d26f34e0471190b2dfe92bef9e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_update.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Windows Server + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_WIN_UPDATE_H +#define FREERDP_SERVER_WIN_UPDATE_H + +#include "wf_interface.h" + +void wf_update_encode(wfInfo* wfi); +void wf_update_send(wfInfo* wfi); + +DWORD WINAPI wf_update_thread(LPVOID lpParam); + +void wf_update_begin(wfInfo* wfi); +void wf_update_peer_send(wfInfo* wfi, wfPeerContext* context); +void wf_update_end(wfInfo* wfi); + +void wf_update_peer_activate(wfInfo* wfi, wfPeerContext* context); +void wf_update_peer_deactivate(wfInfo* wfi, wfPeerContext* context); + +#endif /* FREERDP_SERVER_WIN_UPDATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.c b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.c new file mode 100644 index 0000000000000000000000000000000000000000..a3490b1c901fb811455d7325b4a3bb9b49117570 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.c @@ -0,0 +1,333 @@ + +#include "wf_wasapi.h" +#include "wf_info.h" + +#include +#include +#include +#include + +#include +#define TAG SERVER_TAG("windows") + +//#define REFTIMES_PER_SEC 10000000 +//#define REFTIMES_PER_MILLISEC 10000 + +#define REFTIMES_PER_SEC 100000 +#define REFTIMES_PER_MILLISEC 100 + +//#define REFTIMES_PER_SEC 50000 +//#define REFTIMES_PER_MILLISEC 50 + +#ifndef __MINGW32__ +DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, 0x8E, 0x3D, 0xC4, 0x57, 0x92, + 0x91, 0x69, 0x2E); +DEFINE_GUID(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, + 0x17, 0xE6); +DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, + 0xb2); +DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, + 0xd3, 0x17); +#endif + +LPWSTR devStr = NULL; +wfPeerContext* latestPeer = NULL; + +int wf_rdpsnd_set_latest_peer(wfPeerContext* peer) +{ + latestPeer = peer; + return 0; +} + +int wf_wasapi_activate(RdpsndServerContext* context) +{ + wchar_t* pattern = L"Stereo Mix"; + HANDLE hThread; + + wf_wasapi_get_device_string(pattern, &devStr); + + if (devStr == NULL) + { + WLog_ERR(TAG, "Failed to match for output device! Disabling rdpsnd."); + return 1; + } + + WLog_DBG(TAG, "RDPSND (WASAPI) Activated"); + if (!(hThread = CreateThread(NULL, 0, wf_rdpsnd_wasapi_thread, latestPeer, 0, NULL))) + { + WLog_ERR(TAG, "CreateThread failed"); + return 1; + } + (void)CloseHandle(hThread); + + return 0; +} + +int wf_wasapi_get_device_string(LPWSTR pattern, LPWSTR* deviceStr) +{ + HRESULT hr; + IMMDeviceEnumerator* pEnumerator = NULL; + IMMDeviceCollection* pCollection = NULL; + IMMDevice* pEndpoint = NULL; + IPropertyStore* pProps = NULL; + LPWSTR pwszID = NULL; + unsigned int count; + + CoInitialize(NULL); + hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, + (void**)&pEnumerator); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to cocreate device enumerator"); + exit(1); + } + + hr = pEnumerator->lpVtbl->EnumAudioEndpoints(pEnumerator, eCapture, DEVICE_STATE_ACTIVE, + &pCollection); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to create endpoint collection"); + exit(1); + } + + pCollection->lpVtbl->GetCount(pCollection, &count); + WLog_INFO(TAG, "Num endpoints: %u", count); + + if (count == 0) + { + WLog_ERR(TAG, "No endpoints!"); + exit(1); + } + + for (unsigned int i = 0; i < count; ++i) + { + PROPVARIANT nameVar; + PropVariantInit(&nameVar); + + hr = pCollection->lpVtbl->Item(pCollection, i, &pEndpoint); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get endpoint %u", i); + exit(1); + } + + hr = pEndpoint->lpVtbl->GetId(pEndpoint, &pwszID); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get endpoint ID"); + exit(1); + } + + hr = pEndpoint->lpVtbl->OpenPropertyStore(pEndpoint, STGM_READ, &pProps); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to open property store"); + exit(1); + } + + hr = pProps->lpVtbl->GetValue(pProps, &PKEY_Device_FriendlyName, &nameVar); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get device friendly name"); + exit(1); + } + + // do this a more reliable way + if (wcscmp(pattern, nameVar.pwszVal) < 0) + { + unsigned int devStrLen; + WLog_INFO(TAG, "Using sound output endpoint: [%s] (%s)", nameVar.pwszVal, pwszID); + // WLog_INFO(TAG, "matched %d characters", wcscmp(pattern, nameVar.pwszVal); + devStrLen = wcslen(pwszID); + *deviceStr = (LPWSTR)calloc(devStrLen + 1, 2); + if (!deviceStr) + return -1; + wcscpy_s(*deviceStr, devStrLen + 1, pwszID); + } + CoTaskMemFree(pwszID); + pwszID = NULL; + PropVariantClear(&nameVar); + + pProps->lpVtbl->Release(pProps); + pProps = NULL; + + pEndpoint->lpVtbl->Release(pEndpoint); + pEndpoint = NULL; + } + + pCollection->lpVtbl->Release(pCollection); + pCollection = NULL; + + pEnumerator->lpVtbl->Release(pEnumerator); + pEnumerator = NULL; + CoUninitialize(); + + return 0; +} + +DWORD WINAPI wf_rdpsnd_wasapi_thread(LPVOID lpParam) +{ + IMMDeviceEnumerator* pEnumerator = NULL; + IMMDevice* pDevice = NULL; + IAudioClient* pAudioClient = NULL; + IAudioCaptureClient* pCaptureClient = NULL; + WAVEFORMATEX* pwfx = NULL; + HRESULT hr; + REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC; + REFERENCE_TIME hnsActualDuration; + UINT32 bufferFrameCount; + UINT32 numFramesAvailable; + UINT32 packetLength = 0; + UINT32 dCount = 0; + BYTE* pData; + + wfPeerContext* context; + wfInfo* wfi; + + wfi = wf_info_get_instance(); + context = (wfPeerContext*)lpParam; + + CoInitialize(NULL); + hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, + (void**)&pEnumerator); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to cocreate device enumerator"); + exit(1); + } + + hr = pEnumerator->lpVtbl->GetDevice(pEnumerator, devStr, &pDevice); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to cocreate get device"); + exit(1); + } + + hr = pDevice->lpVtbl->Activate(pDevice, &IID_IAudioClient, CLSCTX_ALL, NULL, + (void**)&pAudioClient); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to activate audio client"); + exit(1); + } + + hr = pAudioClient->lpVtbl->GetMixFormat(pAudioClient, &pwfx); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get mix format"); + exit(1); + } + + pwfx->wFormatTag = wfi->agreed_format->wFormatTag; + pwfx->nChannels = wfi->agreed_format->nChannels; + pwfx->nSamplesPerSec = wfi->agreed_format->nSamplesPerSec; + pwfx->nAvgBytesPerSec = wfi->agreed_format->nAvgBytesPerSec; + pwfx->nBlockAlign = wfi->agreed_format->nBlockAlign; + pwfx->wBitsPerSample = wfi->agreed_format->wBitsPerSample; + pwfx->cbSize = wfi->agreed_format->cbSize; + + hr = pAudioClient->lpVtbl->Initialize(pAudioClient, AUDCLNT_SHAREMODE_SHARED, 0, + hnsRequestedDuration, 0, pwfx, NULL); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to initialize the audio client"); + exit(1); + } + + hr = pAudioClient->lpVtbl->GetBufferSize(pAudioClient, &bufferFrameCount); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get buffer size"); + exit(1); + } + + hr = pAudioClient->lpVtbl->GetService(pAudioClient, &IID_IAudioCaptureClient, + (void**)&pCaptureClient); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get the capture client"); + exit(1); + } + + hnsActualDuration = (UINT32)REFTIMES_PER_SEC * bufferFrameCount / pwfx->nSamplesPerSec; + + hr = pAudioClient->lpVtbl->Start(pAudioClient); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to start capture"); + exit(1); + } + + dCount = 0; + + while (wfi->snd_stop == FALSE) + { + DWORD flags; + + Sleep(hnsActualDuration / REFTIMES_PER_MILLISEC / 2); + + hr = pCaptureClient->lpVtbl->GetNextPacketSize(pCaptureClient, &packetLength); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get packet length"); + exit(1); + } + + while (packetLength != 0) + { + hr = pCaptureClient->lpVtbl->GetBuffer(pCaptureClient, &pData, &numFramesAvailable, + &flags, NULL, NULL); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get buffer"); + exit(1); + } + + // Here we are writing the audio data + // not sure if this flag is ever set by the system; msdn is not clear about it + if (!(flags & AUDCLNT_BUFFERFLAGS_SILENT)) + context->rdpsnd->SendSamples(context->rdpsnd, pData, packetLength, + (UINT16)(GetTickCount() & 0xffff)); + + hr = pCaptureClient->lpVtbl->ReleaseBuffer(pCaptureClient, numFramesAvailable); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to release buffer"); + exit(1); + } + + hr = pCaptureClient->lpVtbl->GetNextPacketSize(pCaptureClient, &packetLength); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to get packet length"); + exit(1); + } + } + } + + pAudioClient->lpVtbl->Stop(pAudioClient); + if (FAILED(hr)) + { + WLog_ERR(TAG, "Failed to stop audio client"); + exit(1); + } + + CoTaskMemFree(pwfx); + + if (pEnumerator != NULL) + pEnumerator->lpVtbl->Release(pEnumerator); + + if (pDevice != NULL) + pDevice->lpVtbl->Release(pDevice); + + if (pAudioClient != NULL) + pAudioClient->lpVtbl->Release(pAudioClient); + + if (pCaptureClient != NULL) + pCaptureClient->lpVtbl->Release(pCaptureClient); + + CoUninitialize(); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.h b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.h new file mode 100644 index 0000000000000000000000000000000000000000..da9c7dc2172ddc988134a1c3d35532ad379828c6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/Windows/wf_wasapi.h @@ -0,0 +1,15 @@ +#ifndef FREERDP_SERVER_WIN_WASAPI_H +#define FREERDP_SERVER_WIN_WASAPI_H + +#include +#include "wf_interface.h" + +int wf_rdpsnd_set_latest_peer(wfPeerContext* peer); + +int wf_wasapi_activate(RdpsndServerContext* context); + +int wf_wasapi_get_device_string(LPWSTR pattern, LPWSTR* deviceStr); + +DWORD WINAPI wf_rdpsnd_wasapi_thread(LPVOID lpParam); + +#endif /* FREERDP_SERVER_WIN_WASAPI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/common/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/common/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5690f81f8c4c0d7c85cf2ac9e24466e161c6a15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/common/CMakeLists.txt @@ -0,0 +1,49 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Server Common +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "freerdp-server") +set(MODULE_PREFIX "FREERDP_SERVER") + +# Policy CMP0022: INTERFACE_LINK_LIBRARIES defines the link +# interface. Run "cmake --help-policy CMP0022" for policy details. Use the +# cmake_policy command to set the policy and suppress this warning. +if(POLICY CMP0022) + cmake_policy(SET CMP0022 NEW) +endif() + +set(${MODULE_PREFIX}_SRCS server.c) + +foreach(FREERDP_CHANNELS_SERVER_SRC ${FREERDP_CHANNELS_SERVER_SRCS}) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS} "${FREERDP_CHANNELS_SERVER_SRC}") +endforeach() + +if(MSVC) + set(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_SRCS}) +endif() + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${FREERDP_CHANNELS_SERVER_LIBS}) +target_link_libraries(${MODULE_NAME} PUBLIC winpr freerdp) + +install(TARGETS ${MODULE_NAME} COMPONENT libraries EXPORT FreeRDP-ServerTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Common") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/common/server.c b/local-test-freerdp-delta-01/afc-freerdp/server/common/server.c new file mode 100644 index 0000000000000000000000000000000000000000..62f126f7c96b4b6c2eb7e4da31f229d27a244056 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/common/server.c @@ -0,0 +1,236 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Server Common + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include +#include + +#define TAG FREERDP_TAG("server.common") + +size_t server_audin_get_formats(AUDIO_FORMAT** dst_formats) +{ + /* Default supported audio formats */ + BYTE adpcm_data_7[] = { 0xf4, 0x07, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, + 0xff, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x40, 0x00, 0xf0, 0x00, + 0x00, 0x00, 0xcc, 0x01, 0x30, 0xff, 0x88, 0x01, 0x18, 0xff }; + BYTE adpcm_data_3[] = { 0xf4, 0x03, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, + 0xff, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x40, 0x00, 0xf0, 0x00, + 0x00, 0x00, 0xcc, 0x01, 0x30, 0xff, 0x88, 0x01, 0x18, 0xff }; + BYTE adpcm_data_1[] = { 0xf4, 0x01, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, + 0xff, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x40, 0x00, 0xf0, 0x00, + 0x00, 0x00, 0xcc, 0x01, 0x30, 0xff, 0x88, 0x01, 0x18, 0xff }; + BYTE adpcm_dvi_data_7[] = { 0xf9, 0x07 }; + BYTE adpcm_dvi_data_3[] = { 0xf9, 0x03 }; + BYTE adpcm_dvi_data_1[] = { 0xf9, 0x01 }; + BYTE gsm610_data[] = { 0x40, 0x01 }; + const AUDIO_FORMAT default_supported_audio_formats[] = { + /* Formats sent by windows 10 server */ + { WAVE_FORMAT_AAC_MS, 2, 44100, 24000, 4, 16, 0, NULL }, + { WAVE_FORMAT_AAC_MS, 2, 44100, 20000, 4, 16, 0, NULL }, + { WAVE_FORMAT_AAC_MS, 2, 44100, 16000, 4, 16, 0, NULL }, + { WAVE_FORMAT_AAC_MS, 2, 44100, 12000, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_ADPCM, 2, 44100, 44359, 2048, 4, 32, adpcm_data_7 }, + { WAVE_FORMAT_DVI_ADPCM, 2, 44100, 44251, 2048, 4, 2, adpcm_dvi_data_7 }, + { WAVE_FORMAT_ALAW, 2, 22050, 44100, 2, 8, 0, NULL }, + { WAVE_FORMAT_ADPCM, 2, 22050, 22311, 1024, 4, 32, adpcm_data_3 }, + { WAVE_FORMAT_DVI_ADPCM, 2, 22050, 22201, 1024, 4, 2, adpcm_dvi_data_3 }, + { WAVE_FORMAT_ADPCM, 1, 44100, 22179, 1024, 4, 32, adpcm_data_7 }, + { WAVE_FORMAT_DVI_ADPCM, 1, 44100, 22125, 1024, 4, 2, adpcm_dvi_data_7 }, + { WAVE_FORMAT_ADPCM, 2, 11025, 11289, 512, 4, 32, adpcm_data_1 }, + { WAVE_FORMAT_DVI_ADPCM, 2, 11025, 11177, 512, 4, 2, adpcm_dvi_data_1 }, + { WAVE_FORMAT_ADPCM, 1, 22050, 11155, 512, 4, 32, adpcm_data_3 }, + { WAVE_FORMAT_DVI_ADPCM, 1, 22050, 11100, 512, 4, 2, adpcm_dvi_data_3 }, + { WAVE_FORMAT_GSM610, 1, 44100, 8957, 65, 0, 2, gsm610_data }, + { WAVE_FORMAT_ADPCM, 2, 8000, 8192, 512, 4, 32, adpcm_data_1 }, + { WAVE_FORMAT_DVI_ADPCM, 2, 8000, 8110, 512, 4, 2, adpcm_dvi_data_1 }, + { WAVE_FORMAT_ADPCM, 1, 11025, 5644, 256, 4, 32, adpcm_data_1 }, + { WAVE_FORMAT_DVI_ADPCM, 1, 11025, 5588, 256, 4, 2, adpcm_dvi_data_1 }, + { WAVE_FORMAT_GSM610, 1, 22050, 4478, 65, 0, 2, gsm610_data }, + { WAVE_FORMAT_ADPCM, 1, 8000, 4096, 256, 4, 32, adpcm_data_1 }, + { WAVE_FORMAT_DVI_ADPCM, 1, 8000, 4055, 256, 4, 2, adpcm_dvi_data_1 }, + { WAVE_FORMAT_GSM610, 1, 11025, 2239, 65, 0, 2, gsm610_data }, + { WAVE_FORMAT_GSM610, 1, 8000, 1625, 65, 0, 2, gsm610_data }, + /* Formats added for others */ + + { WAVE_FORMAT_MSG723, 2, 44100, 0, 4, 16, 0, NULL }, + { WAVE_FORMAT_MSG723, 2, 22050, 0, 4, 16, 0, NULL }, + { WAVE_FORMAT_MSG723, 1, 44100, 0, 4, 16, 0, NULL }, + { WAVE_FORMAT_MSG723, 1, 22050, 0, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 2, 22050, 88200, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 1, 44100, 88200, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 1, 22050, 44100, 4, 16, 0, NULL }, + { WAVE_FORMAT_MULAW, 2, 44100, 88200, 4, 16, 0, NULL }, + { WAVE_FORMAT_MULAW, 2, 22050, 44100, 4, 16, 0, NULL }, + { WAVE_FORMAT_MULAW, 1, 44100, 44100, 4, 16, 0, NULL }, + { WAVE_FORMAT_MULAW, 1, 22050, 22050, 4, 16, 0, NULL }, + { WAVE_FORMAT_ALAW, 2, 44100, 88200, 2, 8, 0, NULL }, + { WAVE_FORMAT_ALAW, 2, 22050, 44100, 2, 8, 0, NULL }, + { WAVE_FORMAT_ALAW, 1, 44100, 44100, 2, 8, 0, NULL }, + { WAVE_FORMAT_ALAW, 1, 22050, 22050, 2, 8, 0, NULL } + }; + const size_t nrDefaultFormatsMax = ARRAYSIZE(default_supported_audio_formats); + size_t nr_formats = 0; + AUDIO_FORMAT* formats = audio_formats_new(nrDefaultFormatsMax); + + if (!dst_formats) + goto fail; + + *dst_formats = NULL; + + if (!formats) + goto fail; + + for (size_t x = 0; x < nrDefaultFormatsMax; x++) + { + const AUDIO_FORMAT* format = &default_supported_audio_formats[x]; + + if (freerdp_dsp_supports_format(format, FALSE)) + { + AUDIO_FORMAT* dst = &formats[nr_formats++]; + + if (!audio_format_copy(format, dst)) + goto fail; + } + } + + *dst_formats = formats; + return nr_formats; +fail: + audio_formats_free(formats, nrDefaultFormatsMax); + return 0; +} + +size_t server_rdpsnd_get_formats(AUDIO_FORMAT** dst_formats) +{ + /* Default supported audio formats */ + static const AUDIO_FORMAT default_supported_audio_formats[] = { + { WAVE_FORMAT_AAC_MS, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_MPEGLAYER3, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_MSG723, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_GSM610, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_ADPCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_ALAW, 2, 22050, 44100, 2, 8, 0, NULL }, + { WAVE_FORMAT_MULAW, 2, 22050, 44100, 2, 8, 0, NULL }, + }; + AUDIO_FORMAT* supported_audio_formats = + audio_formats_new(ARRAYSIZE(default_supported_audio_formats)); + + if (!supported_audio_formats) + goto fail; + + size_t y = 0; + for (size_t x = 0; x < ARRAYSIZE(default_supported_audio_formats); x++) + { + const AUDIO_FORMAT* format = &default_supported_audio_formats[x]; + + if (freerdp_dsp_supports_format(format, TRUE)) + supported_audio_formats[y++] = *format; + } + + /* Set default audio formats. */ + *dst_formats = supported_audio_formats; + return y; +fail: + audio_formats_free(supported_audio_formats, ARRAYSIZE(default_supported_audio_formats)); + + if (dst_formats) + *dst_formats = NULL; + + return 0; +} + +void freerdp_server_warn_unmaintained(int argc, char* argv[]) +{ + const char* app = (argc > 0) ? argv[0] : "INVALID_ARGV"; + const DWORD log_level = WLOG_WARN; + wLog* log = WLog_Get(TAG); + WINPR_ASSERT(log); + + if (!WLog_IsLevelActive(log, log_level)) + return; + + WLog_Print_unchecked(log, log_level, "[unmaintained] %s server is currently unmaintained!", + app); + WLog_Print_unchecked( + log, log_level, + " If problems occur please check https://github.com/FreeRDP/FreeRDP/issues for " + "known issues!"); + WLog_Print_unchecked( + log, log_level, + "Be prepared to fix issues yourself though as nobody is actively working on this."); + WLog_Print_unchecked( + log, log_level, + " Developers hang out in https://matrix.to/#/#FreeRDP:matrix.org?via=matrix.org " + "- dont hesitate to ask some questions. (replies might take some time depending " + "on your timezone) - if you intend using this component write us a message"); +} + +void freerdp_server_warn_experimental(int argc, char* argv[]) +{ + const char* app = (argc > 0) ? argv[0] : "INVALID_ARGV"; + const DWORD log_level = WLOG_WARN; + wLog* log = WLog_Get(TAG); + WINPR_ASSERT(log); + + if (!WLog_IsLevelActive(log, log_level)) + return; + + WLog_Print_unchecked(log, log_level, "[experimental] %s server is currently experimental!", + app); + WLog_Print_unchecked( + log, log_level, + " If problems occur please check https://github.com/FreeRDP/FreeRDP/issues for " + "known issues or create a new one!"); + WLog_Print_unchecked( + log, log_level, + " Developers hang out in https://matrix.to/#/#FreeRDP:matrix.org?via=matrix.org " + "- dont hesitate to ask some questions. (replies might take some time depending " + "on your timezone)"); +} + +void freerdp_server_warn_deprecated(int argc, char* argv[]) +{ + const char* app = (argc > 0) ? argv[0] : "INVALID_ARGV"; + const DWORD log_level = WLOG_WARN; + wLog* log = WLog_Get(TAG); + WINPR_ASSERT(log); + + if (!WLog_IsLevelActive(log, log_level)) + return; + + WLog_Print_unchecked(log, log_level, "[deprecated] %s server has been deprecated", app); + WLog_Print_unchecked(log, log_level, "As replacement there is a SDL based client available."); + WLog_Print_unchecked( + log, log_level, + "If you are interested in keeping %s alive get in touch with the developers", app); + WLog_Print_unchecked( + log, log_level, + "The project is hosted at https://github.com/freerdp/freerdp and " + " developers hang out in https://matrix.to/#/#FreeRDP:matrix.org?via=matrix.org " + "- dont hesitate to ask some questions. (replies might take some time depending " + "on your timezone)"); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c55db471305d91c62412f2d27119a17f3a89434 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/CMakeLists.txt @@ -0,0 +1,106 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Proxy Server +# +# Copyright 2019 Mati Shabtay +# Copyright 2019 Kobi Mizrachi +# Copyright 2019 Idan Freiberg +# Copyright 2021 Armin Novak +# 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. + +include(CMakeDependentOption) +set(MODULE_NAME "freerdp-server-proxy") +set(MODULE_PREFIX "FREERDP_SERVER_PROXY") + +set(${MODULE_PREFIX}_SRCS + pf_context.c + pf_channel.c + pf_channel.h + pf_client.c + pf_client.h + pf_input.c + pf_input.h + pf_update.c + pf_update.h + pf_server.c + pf_server.h + pf_config.c + pf_modules.c + pf_utils.h + pf_utils.c + $ +) + +set(PROXY_APP_SRCS freerdp_proxy.c) + +option(WITH_PROXY_EMULATE_SMARTCARD "Compile proxy smartcard emulation" OFF) +add_subdirectory("channels") + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) + +set(PRIVATE_LIBS freerdp-client freerdp-server) + +set(PUBLIC_LIBS winpr freerdp) + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${PRIVATE_LIBS} PUBLIC ${PUBLIC_LIBS}) + +install(TARGETS ${MODULE_NAME} COMPONENT server EXPORT FreeRDP-ProxyTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/Proxy") + +# pkg-config +include(pkg-config-install-prefix) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/freerdp-proxy.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${MODULE_NAME}${FREERDP_VERSION_MAJOR}.pc + @ONLY +) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${MODULE_NAME}${FREERDP_VERSION_MAJOR}.pc + DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR} +) + +export(PACKAGE freerdp-proxy) + +setfreerdpcmakeinstalldir(FREERDP_PROXY_CMAKE_INSTALL_DIR "FreeRDP-Proxy${FREERDP_VERSION_MAJOR}") + +configure_package_config_file( + FreeRDP-ProxyConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ProxyConfig.cmake + INSTALL_DESTINATION ${FREERDP_PROXY_CMAKE_INSTALL_DIR} PATH_VARS FREERDP_INCLUDE_DIR +) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ProxyConfigVersion.cmake VERSION ${FREERDP_VERSION} + COMPATIBILITY SameMajorVersion +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ProxyConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ProxyConfigVersion.cmake + DESTINATION ${FREERDP_PROXY_CMAKE_INSTALL_DIR} +) +install(EXPORT FreeRDP-ProxyTargets DESTINATION ${FREERDP_PROXY_CMAKE_INSTALL_DIR}) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/proxy") + +option(WITH_PROXY_APP "Compile proxy application" ON) + +if(WITH_PROXY_APP) + add_subdirectory("cli") +endif() + +option(WITH_PROXY_MODULES "Compile proxy modules" ON) +if(WITH_PROXY_MODULES) + add_subdirectory("modules") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/FreeRDP-ProxyConfig.cmake.in b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/FreeRDP-ProxyConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..406da3ad382e046611c78ee3e9f92e00fc671bbf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/FreeRDP-ProxyConfig.cmake.in @@ -0,0 +1,10 @@ + +@PACKAGE_INIT@ + +set(FreeRDP-Proxy_VERSION_MAJOR "@FREERDP_VERSION_MAJOR@") +set(FreeRDP-Proxy_VERSION_MINOR "@FREERDP_VERSION_MINOR@") +set(FreeRDP-Proxy_VERSION_REVISION "@FREERDP_VERSION_REVISION@") + +set_and_check(FreeRDP-Proxy_INCLUDE_DIR "@PACKAGE_FREERDP_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/FreeRDP-ProxyTargets.cmake") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..927be79f90a0584af431bd0013aa33bd7aff7296 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/CMakeLists.txt @@ -0,0 +1,8 @@ +set(MODULE_NAME pf_channels) +set(SOURCES pf_channel_rdpdr.c pf_channel_rdpdr.h pf_channel_drdynvc.c pf_channel_drdynvc.h) + +if(WITH_PROXY_EMULATE_SMARTCARD) + list(APPEND SOURCES pf_channel_smartcard.c pf_channel_smartcard.h) +endif() + +add_library(${MODULE_NAME} OBJECT ${SOURCES}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.c new file mode 100644 index 0000000000000000000000000000000000000000..2a1a3d0a652d94736e600dd7fc1c5d5921a0394a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.c @@ -0,0 +1,713 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * pf_channel_drdynvc + * + * Copyright 2022 David Fort + * + * 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 + +#include +#include +#include + +#include "pf_channel_drdynvc.h" +#include "../pf_channel.h" +#include "../proxy_modules.h" +#include "../pf_utils.h" + +#define DTAG PROXY_TAG("drdynvc") + +/** @brief channel opened status */ +typedef enum +{ + CHANNEL_OPENSTATE_WAITING_OPEN_STATUS, /*!< dynamic channel waiting for create response */ + CHANNEL_OPENSTATE_OPENED, /*!< opened */ + CHANNEL_OPENSTATE_CLOSED /*!< dynamic channel has been opened then closed */ +} PfDynChannelOpenStatus; + +typedef struct p_server_dynamic_channel_context pServerDynamicChannelContext; +typedef struct DynChannelTrackerState DynChannelTrackerState; + +typedef PfChannelResult (*dynamic_channel_on_data_fn)(pServerContext* ps, + pServerDynamicChannelContext* channel, + BOOL isBackData, ChannelStateTracker* tracker, + BOOL firstPacket, BOOL lastPacket); + +/** @brief tracker state for a drdynvc stream */ +struct DynChannelTrackerState +{ + UINT32 currentDataLength; + UINT32 CurrentDataReceived; + UINT32 CurrentDataFragments; + wStream* currentPacket; + dynamic_channel_on_data_fn dataCallback; +}; + +typedef void (*channel_data_dtor_fn)(void** user_data); + +struct p_server_dynamic_channel_context +{ + char* channelName; + UINT32 channelId; + PfDynChannelOpenStatus openStatus; + pf_utils_channel_mode channelMode; + BOOL packetReassembly; + DynChannelTrackerState backTracker; + DynChannelTrackerState frontTracker; + + void* channelData; + channel_data_dtor_fn channelDataDtor; +}; + +/** @brief context for the dynamic channel */ +typedef struct +{ + wHashTable* channels; + ChannelStateTracker* backTracker; + ChannelStateTracker* frontTracker; + wLog* log; +} DynChannelContext; + +/** @brief result of dynamic channel packet treatment */ +typedef enum +{ + DYNCVC_READ_OK, /*!< read was OK */ + DYNCVC_READ_ERROR, /*!< an error happened during read */ + DYNCVC_READ_INCOMPLETE /*!< missing bytes to read the complete packet */ +} DynvcReadResult; + +static const char* openstatus2str(PfDynChannelOpenStatus status) +{ + switch (status) + { + case CHANNEL_OPENSTATE_WAITING_OPEN_STATUS: + return "CHANNEL_OPENSTATE_WAITING_OPEN_STATUS"; + case CHANNEL_OPENSTATE_CLOSED: + return "CHANNEL_OPENSTATE_CLOSED"; + case CHANNEL_OPENSTATE_OPENED: + return "CHANNEL_OPENSTATE_OPENED"; + default: + return "CHANNEL_OPENSTATE_UNKNOWN"; + } +} + +static PfChannelResult data_cb(pServerContext* ps, pServerDynamicChannelContext* channel, + BOOL isBackData, ChannelStateTracker* tracker, BOOL firstPacket, + BOOL lastPacket) +{ + WINPR_ASSERT(ps); + WINPR_ASSERT(channel); + WINPR_ASSERT(tracker); + WINPR_ASSERT(ps->pdata); + + wStream* currentPacket = channelTracker_getCurrentPacket(tracker); + proxyDynChannelInterceptData dyn = { .name = channel->channelName, + .channelId = channel->channelId, + .data = currentPacket, + .isBackData = isBackData, + .first = firstPacket, + .last = lastPacket, + .rewritten = FALSE, + .packetSize = channelTracker_getCurrentPacketSize(tracker), + .result = PF_CHANNEL_RESULT_ERROR }; + Stream_SealLength(dyn.data); + if (!pf_modules_run_filter(ps->pdata->module, FILTER_TYPE_INTERCEPT_CHANNEL, ps->pdata, &dyn)) + return PF_CHANNEL_RESULT_ERROR; + + channelTracker_setCurrentPacketSize(tracker, dyn.packetSize); + if (dyn.rewritten) + return channelTracker_flushCurrent(tracker, firstPacket, lastPacket, !isBackData); + return dyn.result; +} + +static pServerDynamicChannelContext* DynamicChannelContext_new(wLog* log, pServerContext* ps, + const char* name, UINT32 id) +{ + WINPR_ASSERT(log); + + pServerDynamicChannelContext* ret = calloc(1, sizeof(*ret)); + if (!ret) + { + WLog_Print(log, WLOG_ERROR, "error allocating dynamic channel context '%s'", name); + return NULL; + } + + ret->channelId = id; + ret->channelName = _strdup(name); + if (!ret->channelName) + { + WLog_Print(log, WLOG_ERROR, "error allocating name in dynamic channel context '%s'", name); + free(ret); + return NULL; + } + + ret->frontTracker.dataCallback = data_cb; + ret->backTracker.dataCallback = data_cb; + + proxyChannelToInterceptData dyn = { .name = name, .channelId = id, .intercept = FALSE }; + if (pf_modules_run_filter(ps->pdata->module, FILTER_TYPE_DYN_INTERCEPT_LIST, ps->pdata, &dyn) && + dyn.intercept) + ret->channelMode = PF_UTILS_CHANNEL_INTERCEPT; + else + ret->channelMode = pf_utils_get_channel_mode(ps->pdata->config, name); + ret->openStatus = CHANNEL_OPENSTATE_OPENED; + ret->packetReassembly = (ret->channelMode == PF_UTILS_CHANNEL_INTERCEPT); + + return ret; +} + +static void DynamicChannelContext_free(void* ptr) +{ + pServerDynamicChannelContext* c = (pServerDynamicChannelContext*)ptr; + if (!c) + return; + + if (c->backTracker.currentPacket) + Stream_Free(c->backTracker.currentPacket, TRUE); + + if (c->frontTracker.currentPacket) + Stream_Free(c->frontTracker.currentPacket, TRUE); + + if (c->channelDataDtor) + c->channelDataDtor(&c->channelData); + + free(c->channelName); + free(c); +} + +static UINT32 ChannelId_Hash(const void* key) +{ + const UINT32* v = (const UINT32*)key; + return *v; +} + +static BOOL ChannelId_Compare(const void* objA, const void* objB) +{ + const UINT32* v1 = objA; + const UINT32* v2 = objB; + return (*v1 == *v2); +} + +static DynvcReadResult dynvc_read_varInt(wLog* log, wStream* s, size_t len, UINT64* varInt, + BOOL last) +{ + WINPR_ASSERT(varInt); + switch (len) + { + case 0x00: + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 1)) + return last ? DYNCVC_READ_ERROR : DYNCVC_READ_INCOMPLETE; + Stream_Read_UINT8(s, *varInt); + break; + case 0x01: + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 2)) + return last ? DYNCVC_READ_ERROR : DYNCVC_READ_INCOMPLETE; + Stream_Read_UINT16(s, *varInt); + break; + case 0x02: + if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 4)) + return last ? DYNCVC_READ_ERROR : DYNCVC_READ_INCOMPLETE; + Stream_Read_UINT32(s, *varInt); + break; + case 0x03: + default: + WLog_Print(log, WLOG_ERROR, "Unknown int len %" PRIuz, len); + return DYNCVC_READ_ERROR; + } + return DYNCVC_READ_OK; +} + +static PfChannelResult DynvcTrackerPeekFn(ChannelStateTracker* tracker, BOOL firstPacket, + BOOL lastPacket) +{ + BYTE cmd = 0; + BYTE byte0 = 0; + wStream* s = NULL; + wStream sbuffer; + BOOL haveChannelId = 0; + BOOL haveLength = 0; + UINT64 dynChannelId = 0; + UINT64 Length = 0; + pServerDynamicChannelContext* dynChannel = NULL; + + WINPR_ASSERT(tracker); + + DynChannelContext* dynChannelContext = + (DynChannelContext*)channelTracker_getCustomData(tracker); + WINPR_ASSERT(dynChannelContext); + + BOOL isBackData = (tracker == dynChannelContext->backTracker); + DynChannelTrackerState* trackerState = NULL; + + UINT32 flags = lastPacket ? CHANNEL_FLAG_LAST : 0; + proxyData* pdata = channelTracker_getPData(tracker); + WINPR_ASSERT(pdata); + + const char* direction = isBackData ? "B->F" : "F->B"; + + { + wStream* currentPacket = channelTracker_getCurrentPacket(tracker); + s = Stream_StaticConstInit(&sbuffer, Stream_Buffer(currentPacket), + Stream_GetPosition(currentPacket)); + } + + if (!Stream_CheckAndLogRequiredLengthWLog(dynChannelContext->log, s, 1)) + return PF_CHANNEL_RESULT_ERROR; + + Stream_Read_UINT8(s, byte0); + cmd = byte0 >> 4; + + switch (cmd) + { + case CREATE_REQUEST_PDU: + case CLOSE_REQUEST_PDU: + case DATA_PDU: + case DATA_COMPRESSED_PDU: + haveChannelId = TRUE; + haveLength = FALSE; + break; + case DATA_FIRST_PDU: + case DATA_FIRST_COMPRESSED_PDU: + haveLength = TRUE; + haveChannelId = TRUE; + break; + default: + haveChannelId = FALSE; + haveLength = FALSE; + break; + } + + if (haveChannelId) + { + BYTE cbId = byte0 & 0x03; + + switch (dynvc_read_varInt(dynChannelContext->log, s, cbId, &dynChannelId, lastPacket)) + { + case DYNCVC_READ_OK: + break; + case DYNCVC_READ_INCOMPLETE: + return PF_CHANNEL_RESULT_DROP; + case DYNCVC_READ_ERROR: + default: + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "DynvcTrackerPeekFn: invalid channelId field"); + return PF_CHANNEL_RESULT_ERROR; + } + + /* we always try to retrieve the dynamic channel in case it would have been opened + * and closed + */ + dynChannel = (pServerDynamicChannelContext*)HashTable_GetItemValue( + dynChannelContext->channels, &dynChannelId); + if ((cmd != CREATE_REQUEST_PDU) || !isBackData) + { + if (!dynChannel || (dynChannel->openStatus == CHANNEL_OPENSTATE_CLOSED)) + { + /* we've not found the target channel, so we drop this chunk, plus all the rest of + * the packet */ + channelTracker_setMode(tracker, CHANNEL_TRACKER_DROP); + return PF_CHANNEL_RESULT_DROP; + } + } + } + + if (haveLength) + { + BYTE lenLen = (byte0 >> 2) & 0x03; + switch (dynvc_read_varInt(dynChannelContext->log, s, lenLen, &Length, lastPacket)) + { + case DYNCVC_READ_OK: + break; + case DYNCVC_READ_INCOMPLETE: + return PF_CHANNEL_RESULT_DROP; + case DYNCVC_READ_ERROR: + default: + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "DynvcTrackerPeekFn: invalid length field"); + return PF_CHANNEL_RESULT_ERROR; + } + } + + switch (cmd) + { + case CAPABILITY_REQUEST_PDU: + WLog_Print(dynChannelContext->log, WLOG_DEBUG, "DynvcTracker: %s CAPABILITY_%s", + direction, isBackData ? "REQUEST" : "RESPONSE"); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PASS); + return PF_CHANNEL_RESULT_PASS; + + case CREATE_REQUEST_PDU: + { + UINT32 creationStatus = 0; + + /* we only want the full packet */ + if (!lastPacket) + return PF_CHANNEL_RESULT_DROP; + + if (isBackData) + { + proxyChannelDataEventInfo dev = { 0 }; + const char* name = Stream_ConstPointer(s); + const size_t nameLen = Stream_GetRemainingLength(s); + + const size_t len = strnlen(name, nameLen); + if ((len == 0) || (len == nameLen) || (dynChannelId > UINT16_MAX)) + return PF_CHANNEL_RESULT_ERROR; + + wStream* currentPacket = channelTracker_getCurrentPacket(tracker); + dev.channel_id = (UINT16)dynChannelId; + dev.channel_name = name; + dev.data = Stream_Buffer(s); + dev.data_len = Stream_GetPosition(currentPacket); + dev.flags = flags; + dev.total_size = Stream_GetPosition(currentPacket); + + if (dynChannel) + { + WLog_Print( + dynChannelContext->log, WLOG_WARN, + "Reusing channel id %" PRIu32 ", previously %s [state %s, mode %s], now %s", + dynChannel->channelId, dynChannel->channelName, + openstatus2str(dynChannel->openStatus), + pf_utils_channel_mode_string(dynChannel->channelMode), dev.channel_name); + + HashTable_Remove(dynChannelContext->channels, &dynChannel->channelId); + } + + if (!pf_modules_run_filter(pdata->module, + FILTER_TYPE_CLIENT_PASSTHROUGH_DYN_CHANNEL_CREATE, pdata, + &dev)) + return PF_CHANNEL_RESULT_DROP; /* Silently drop */ + + dynChannel = DynamicChannelContext_new(dynChannelContext->log, pdata->ps, name, + (UINT32)dynChannelId); + if (!dynChannel) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "unable to create dynamic channel context data"); + return PF_CHANNEL_RESULT_ERROR; + } + + WLog_Print(dynChannelContext->log, WLOG_DEBUG, "Adding channel '%s'[%d]", + dynChannel->channelName, dynChannel->channelId); + if (!HashTable_Insert(dynChannelContext->channels, &dynChannel->channelId, + dynChannel)) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "unable register dynamic channel context data"); + DynamicChannelContext_free(dynChannel); + return PF_CHANNEL_RESULT_ERROR; + } + + dynChannel->openStatus = CHANNEL_OPENSTATE_WAITING_OPEN_STATUS; + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert owns dynChannel + return channelTracker_flushCurrent(tracker, firstPacket, lastPacket, FALSE); + } + + /* CREATE_REQUEST_PDU response */ + if (!Stream_CheckAndLogRequiredLengthWLog(dynChannelContext->log, s, 4)) + return PF_CHANNEL_RESULT_ERROR; + + Stream_Read_UINT32(s, creationStatus); + WLog_Print(dynChannelContext->log, WLOG_DEBUG, + "DynvcTracker(%" PRIu64 ",%s): %s CREATE_RESPONSE openStatus=%" PRIu32, + dynChannelId, dynChannel->channelName, direction, creationStatus); + + if (creationStatus == 0) + dynChannel->openStatus = CHANNEL_OPENSTATE_OPENED; + + return channelTracker_flushCurrent(tracker, firstPacket, lastPacket, TRUE); + } + + case CLOSE_REQUEST_PDU: + if (!lastPacket) + return PF_CHANNEL_RESULT_DROP; + + WLog_Print(dynChannelContext->log, WLOG_DEBUG, + "DynvcTracker(%s): %s Close request on channel", dynChannel->channelName, + direction); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PASS); + if (dynChannel->openStatus != CHANNEL_OPENSTATE_OPENED) + { + WLog_Print(dynChannelContext->log, WLOG_WARN, + "DynvcTracker(%s): is in state %s, expected %s", dynChannel->channelName, + openstatus2str(dynChannel->openStatus), + openstatus2str(CHANNEL_OPENSTATE_OPENED)); + } + dynChannel->openStatus = CHANNEL_OPENSTATE_CLOSED; + return channelTracker_flushCurrent(tracker, firstPacket, lastPacket, !isBackData); + + case SOFT_SYNC_REQUEST_PDU: + /* just pass then as is for now */ + WLog_Print(dynChannelContext->log, WLOG_DEBUG, "SOFT_SYNC_REQUEST_PDU"); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PASS); + /*TODO: return pf_treat_softsync_req(pdata, s);*/ + return PF_CHANNEL_RESULT_PASS; + + case SOFT_SYNC_RESPONSE_PDU: + /* just pass then as is for now */ + WLog_Print(dynChannelContext->log, WLOG_DEBUG, "SOFT_SYNC_RESPONSE_PDU"); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PASS); + return PF_CHANNEL_RESULT_PASS; + + case DATA_FIRST_PDU: + case DATA_PDU: + /* treat these below */ + trackerState = isBackData ? &dynChannel->backTracker : &dynChannel->frontTracker; + break; + + case DATA_FIRST_COMPRESSED_PDU: + case DATA_COMPRESSED_PDU: + WLog_Print(dynChannelContext->log, WLOG_DEBUG, + "TODO: compressed data packets, pass them as is for now"); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PASS); + return channelTracker_flushCurrent(tracker, firstPacket, lastPacket, !isBackData); + + default: + return PF_CHANNEL_RESULT_ERROR; + } + + if (dynChannel->openStatus != CHANNEL_OPENSTATE_OPENED) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "DynvcTracker(%s [%s]): channel is not opened", dynChannel->channelName, + drdynvc_get_packet_type(cmd)); + return PF_CHANNEL_RESULT_ERROR; + } + + if ((cmd == DATA_FIRST_PDU) || (cmd == DATA_FIRST_COMPRESSED_PDU)) + { + WLog_Print(dynChannelContext->log, WLOG_DEBUG, + "DynvcTracker(%s [%s]): %s DATA_FIRST currentPacketLength=%" PRIu64 "", + dynChannel->channelName, drdynvc_get_packet_type(cmd), direction, Length); + if (Length > UINT32_MAX) + return PF_CHANNEL_RESULT_ERROR; + trackerState->currentDataLength = (UINT32)Length; + trackerState->CurrentDataReceived = 0; + trackerState->CurrentDataFragments = 0; + + if (dynChannel->packetReassembly) + { + if (trackerState->currentPacket) + Stream_SetPosition(trackerState->currentPacket, 0); + } + } + + if (cmd == DATA_PDU || cmd == DATA_FIRST_PDU) + { + size_t extraSize = Stream_GetRemainingLength(s); + + trackerState->CurrentDataFragments++; + trackerState->CurrentDataReceived += extraSize; + + if (dynChannel->packetReassembly) + { + if (!trackerState->currentPacket) + { + trackerState->currentPacket = Stream_New(NULL, 1024); + if (!trackerState->currentPacket) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "unable to create current packet"); + return PF_CHANNEL_RESULT_ERROR; + } + } + + if (!Stream_EnsureRemainingCapacity(trackerState->currentPacket, extraSize)) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, "unable to grow current packet"); + return PF_CHANNEL_RESULT_ERROR; + } + + Stream_Write(trackerState->currentPacket, Stream_ConstPointer(s), extraSize); + } + WLog_Print(dynChannelContext->log, WLOG_DEBUG, + "DynvcTracker(%s [%s]): %s frags=%" PRIu32 " received=%" PRIu32 "(%" PRIu32 ")", + dynChannel->channelName, drdynvc_get_packet_type(cmd), direction, + trackerState->CurrentDataFragments, trackerState->CurrentDataReceived, + trackerState->currentDataLength); + } + + if (cmd == DATA_PDU) + { + if (trackerState->currentDataLength) + { + if (trackerState->CurrentDataReceived > trackerState->currentDataLength) + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "DynvcTracker (%s [%s]): reassembled packet (%" PRIu32 + ") is bigger than announced length (%" PRIu32 ")", + dynChannel->channelName, drdynvc_get_packet_type(cmd), + trackerState->CurrentDataReceived, trackerState->currentDataLength); + return PF_CHANNEL_RESULT_ERROR; + } + } + else + { + trackerState->CurrentDataFragments = 0; + trackerState->CurrentDataReceived = 0; + } + } + + PfChannelResult result = PF_CHANNEL_RESULT_ERROR; + switch (dynChannel->channelMode) + { + case PF_UTILS_CHANNEL_PASSTHROUGH: + result = channelTracker_flushCurrent(tracker, firstPacket, lastPacket, !isBackData); + break; + case PF_UTILS_CHANNEL_BLOCK: + channelTracker_setMode(tracker, CHANNEL_TRACKER_DROP); + result = PF_CHANNEL_RESULT_DROP; + break; + case PF_UTILS_CHANNEL_INTERCEPT: + if (trackerState->dataCallback) + { + result = trackerState->dataCallback(pdata->ps, dynChannel, isBackData, tracker, + firstPacket, lastPacket); + } + else + { + WLog_Print(dynChannelContext->log, WLOG_ERROR, + "no intercept callback for channel %s(fromBack=%d), dropping packet", + dynChannel->channelName, isBackData); + result = PF_CHANNEL_RESULT_DROP; + } + break; + default: + WLog_Print(dynChannelContext->log, WLOG_ERROR, "unknown channel mode %d", + dynChannel->channelMode); + result = PF_CHANNEL_RESULT_ERROR; + break; + } + + if (!trackerState->currentDataLength || + (trackerState->CurrentDataReceived == trackerState->currentDataLength)) + { + trackerState->currentDataLength = 0; + trackerState->CurrentDataFragments = 0; + trackerState->CurrentDataReceived = 0; + + if (dynChannel->packetReassembly && trackerState->currentPacket) + Stream_SetPosition(trackerState->currentPacket, 0); + } + + return result; +} + +static void DynChannelContext_free(void* context) +{ + DynChannelContext* c = context; + if (!c) + return; + channelTracker_free(c->backTracker); + channelTracker_free(c->frontTracker); + HashTable_Free(c->channels); + free(c); +} + +static const char* dynamic_context(void* arg) +{ + proxyData* pdata = arg; + if (!pdata) + return "pdata=null"; + return pdata->session_id; +} + +static DynChannelContext* DynChannelContext_new(proxyData* pdata, + pServerStaticChannelContext* channel) +{ + DynChannelContext* dyn = calloc(1, sizeof(DynChannelContext)); + if (!dyn) + return FALSE; + + dyn->log = WLog_Get(DTAG); + WINPR_ASSERT(dyn->log); + WLog_SetContext(dyn->log, dynamic_context, pdata); + + dyn->backTracker = channelTracker_new(channel, DynvcTrackerPeekFn, dyn); + if (!dyn->backTracker) + goto fail; + if (!channelTracker_setPData(dyn->backTracker, pdata)) + goto fail; + + dyn->frontTracker = channelTracker_new(channel, DynvcTrackerPeekFn, dyn); + if (!dyn->frontTracker) + goto fail; + if (!channelTracker_setPData(dyn->frontTracker, pdata)) + goto fail; + + dyn->channels = HashTable_New(FALSE); + if (!dyn->channels) + goto fail; + + if (!HashTable_SetHashFunction(dyn->channels, ChannelId_Hash)) + goto fail; + + wObject* kobj = HashTable_KeyObject(dyn->channels); + WINPR_ASSERT(kobj); + kobj->fnObjectEquals = ChannelId_Compare; + + wObject* vobj = HashTable_ValueObject(dyn->channels); + WINPR_ASSERT(vobj); + vobj->fnObjectFree = DynamicChannelContext_free; + + return dyn; + +fail: + DynChannelContext_free(dyn); + return NULL; +} + +static PfChannelResult pf_dynvc_back_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + WINPR_ASSERT(channel); + + DynChannelContext* dyn = (DynChannelContext*)channel->context; + WINPR_UNUSED(pdata); + WINPR_ASSERT(dyn); + + return channelTracker_update(dyn->backTracker, xdata, xsize, flags, totalSize); +} + +static PfChannelResult pf_dynvc_front_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + WINPR_ASSERT(channel); + + DynChannelContext* dyn = (DynChannelContext*)channel->context; + WINPR_UNUSED(pdata); + WINPR_ASSERT(dyn); + + return channelTracker_update(dyn->frontTracker, xdata, xsize, flags, totalSize); +} + +BOOL pf_channel_setup_drdynvc(proxyData* pdata, pServerStaticChannelContext* channel) +{ + DynChannelContext* ret = DynChannelContext_new(pdata, channel); + if (!ret) + return FALSE; + + channel->onBackData = pf_dynvc_back_data; + channel->onFrontData = pf_dynvc_front_data; + channel->contextDtor = DynChannelContext_free; + channel->context = ret; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.h new file mode 100644 index 0000000000000000000000000000000000000000..b0841439a3704d5b19d7256c4285a085dc6c662c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_drdynvc.h @@ -0,0 +1,26 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * pf_channel_drdynvc + * + * Copyright 2022 David Fort + * + * 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 SERVER_PROXY_CHANNELS_PF_CHANNEL_DRDYNVC_H_ +#define SERVER_PROXY_CHANNELS_PF_CHANNEL_DRDYNVC_H_ + +#include + +BOOL pf_channel_setup_drdynvc(proxyData* pdata, pServerStaticChannelContext* channel); + +#endif /* SERVER_PROXY_CHANNELS_PF_CHANNEL_DRDYNVC_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.c new file mode 100644 index 0000000000000000000000000000000000000000..c533102a3b902d1750d1533aff56179c534fd0f7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.c @@ -0,0 +1,2020 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * 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. + */ + +#include + +#include +#include +#include +#include + +#include "pf_channel_rdpdr.h" +#include "pf_channel_smartcard.h" + +#include +#include +#include +#include + +#define RTAG PROXY_TAG("channel.rdpdr") + +#define SCARD_DEVICE_ID UINT32_MAX + +typedef struct +{ + InterceptContextMapEntry base; + wStream* s; + wStream* buffer; + UINT16 versionMajor; + UINT16 versionMinor; + UINT32 clientID; + UINT32 computerNameLen; + BOOL computerNameUnicode; + union + { + WCHAR* wc; + char* c; + void* v; + } computerName; + UINT32 SpecialDeviceCount; + UINT32 capabilityVersions[6]; +} pf_channel_common_context; + +typedef enum +{ + STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST = 0x01, + STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST = 0x02, + STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM = 0x04, + STATE_CLIENT_CHANNEL_RUNNING = 0x10 +} pf_channel_client_state; + +typedef struct +{ + pf_channel_common_context common; + pf_channel_client_state state; + UINT32 flags; + UINT16 maxMajorVersion; + UINT16 maxMinorVersion; + wQueue* queue; + wLog* log; +} pf_channel_client_context; + +typedef enum +{ + STATE_SERVER_INITIAL, + STATE_SERVER_EXPECT_CLIENT_ANNOUNCE_REPLY, + STATE_SERVER_EXPECT_CLIENT_NAME_REQUEST, + STATE_SERVER_EXPECT_EXPECT_CLIENT_CAPABILITY_RESPONE, + STATE_SERVER_CHANNEL_RUNNING +} pf_channel_server_state; + +typedef struct +{ + pf_channel_common_context common; + pf_channel_server_state state; + DWORD SessionId; + HANDLE handle; + wArrayList* blockedDevices; + wLog* log; +} pf_channel_server_context; + +#define proxy_client "[proxy<-->client]" +#define proxy_server "[proxy<-->server]" + +#define proxy_client_rx proxy_client " receive" +#define proxy_client_tx proxy_client " send" +#define proxy_server_rx proxy_server " receive" +#define proxy_server_tx proxy_server " send" + +#define SERVER_RX_LOG(log, lvl, fmt, ...) WLog_Print(log, lvl, proxy_client_rx fmt, ##__VA_ARGS__) +#define CLIENT_RX_LOG(log, lvl, fmt, ...) WLog_Print(log, lvl, proxy_server_rx fmt, ##__VA_ARGS__) +#define SERVER_TX_LOG(log, lvl, fmt, ...) WLog_Print(log, lvl, proxy_client_tx fmt, ##__VA_ARGS__) +#define CLIENT_TX_LOG(log, lvl, fmt, ...) WLog_Print(log, lvl, proxy_server_tx fmt, ##__VA_ARGS__) +#define RX_LOG(srv, lvl, fmt, ...) \ + do \ + { \ + if (srv) \ + { \ + SERVER_RX_LOG(lvl, fmt, ##__VA_ARGS__); \ + } \ + else \ + { \ + CLIENT_RX_LOG(lvl, fmt, ##__VA_ARGS__); \ + } \ + } while (0) + +#define SERVER_RXTX_LOG(send, log, lvl, fmt, ...) \ + do \ + { \ + if (send) \ + { \ + SERVER_TX_LOG(log, lvl, fmt, ##__VA_ARGS__); \ + } \ + else \ + { \ + SERVER_RX_LOG(log, lvl, fmt, ##__VA_ARGS__); \ + } \ + } while (0) + +#define Stream_CheckAndLogRequiredLengthSrv(log, s, len) \ + Stream_CheckAndLogRequiredLengthWLogEx(log, WLOG_WARN, s, len, 1, \ + proxy_client_rx " %s(%s:%" PRIuz ")", __func__, \ + __FILE__, (size_t)__LINE__) +#define Stream_CheckAndLogRequiredLengthClient(log, s, len) \ + Stream_CheckAndLogRequiredLengthWLogEx(log, WLOG_WARN, s, len, 1, \ + proxy_server_rx " %s(%s:%" PRIuz ")", __func__, \ + __FILE__, (size_t)__LINE__) +#define Stream_CheckAndLogRequiredLengthRx(srv, log, s, len) \ + Stream_CheckAndLogRequiredLengthRx_(srv, log, s, len, 1, __func__, __FILE__, __LINE__) +static BOOL Stream_CheckAndLogRequiredLengthRx_(BOOL srv, wLog* log, wStream* s, size_t nmemb, + size_t size, const char* fkt, const char* file, + size_t line) +{ + const char* fmt = + srv ? proxy_server_rx " %s(%s:%" PRIuz ")" : proxy_client_rx " %s(%s:%" PRIuz ")"; + + return Stream_CheckAndLogRequiredLengthWLogEx(log, WLOG_WARN, s, nmemb, size, fmt, fkt, file, + line); +} + +static const char* rdpdr_server_state_to_string(pf_channel_server_state state) +{ + switch (state) + { + case STATE_SERVER_INITIAL: + return "STATE_SERVER_INITIAL"; + case STATE_SERVER_EXPECT_CLIENT_ANNOUNCE_REPLY: + return "STATE_SERVER_EXPECT_CLIENT_ANNOUNCE_REPLY"; + case STATE_SERVER_EXPECT_CLIENT_NAME_REQUEST: + return "STATE_SERVER_EXPECT_CLIENT_NAME_REQUEST"; + case STATE_SERVER_EXPECT_EXPECT_CLIENT_CAPABILITY_RESPONE: + return "STATE_SERVER_EXPECT_EXPECT_CLIENT_CAPABILITY_RESPONE"; + case STATE_SERVER_CHANNEL_RUNNING: + return "STATE_SERVER_CHANNEL_RUNNING"; + default: + return "STATE_SERVER_UNKNOWN"; + } +} + +static const char* rdpdr_client_state_to_string(pf_channel_client_state state) +{ + switch (state) + { + case STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST: + return "STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST"; + case STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST: + return "STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST"; + case STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM: + return "STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM"; + case STATE_CLIENT_CHANNEL_RUNNING: + return "STATE_CLIENT_CHANNEL_RUNNING"; + default: + return "STATE_CLIENT_UNKNOWN"; + } +} + +static wStream* rdpdr_get_send_buffer(pf_channel_common_context* rdpdr, UINT16 component, + UINT16 PacketID, size_t capacity) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(rdpdr->s); + if (!Stream_SetPosition(rdpdr->s, 0)) + return NULL; + if (!Stream_EnsureCapacity(rdpdr->s, capacity + 4)) + return NULL; + Stream_Write_UINT16(rdpdr->s, component); + Stream_Write_UINT16(rdpdr->s, PacketID); + return rdpdr->s; +} + +static wStream* rdpdr_client_get_send_buffer(pf_channel_client_context* rdpdr, UINT16 component, + UINT16 PacketID, size_t capacity) +{ + WINPR_ASSERT(rdpdr); + return rdpdr_get_send_buffer(&rdpdr->common, component, PacketID, capacity); +} + +static wStream* rdpdr_server_get_send_buffer(pf_channel_server_context* rdpdr, UINT16 component, + UINT16 PacketID, size_t capacity) +{ + WINPR_ASSERT(rdpdr); + return rdpdr_get_send_buffer(&rdpdr->common, component, PacketID, capacity); +} + +static UINT rdpdr_client_send(wLog* log, pClientContext* pc, wStream* s) +{ + UINT16 channelId = 0; + + WINPR_ASSERT(log); + WINPR_ASSERT(pc); + WINPR_ASSERT(s); + WINPR_ASSERT(pc->context.instance); + + if (!pc->connected) + { + CLIENT_TX_LOG(log, WLOG_WARN, "Ignoring channel %s message, not connected!", + RDPDR_SVC_CHANNEL_NAME); + return CHANNEL_RC_OK; + } + + channelId = freerdp_channels_get_id_by_name(pc->context.instance, RDPDR_SVC_CHANNEL_NAME); + /* Ignore unmappable channels. Might happen when the channel was already down and + * some delayed message is tried to be sent. */ + if ((channelId == 0) || (channelId == UINT16_MAX)) + return ERROR_INTERNAL_ERROR; + + Stream_SealLength(s); + rdpdr_dump_send_packet(log, WLOG_TRACE, s, proxy_server_tx); + WINPR_ASSERT(pc->context.instance->SendChannelData); + if (!pc->context.instance->SendChannelData(pc->context.instance, channelId, Stream_Buffer(s), + Stream_Length(s))) + return ERROR_EVT_CHANNEL_NOT_FOUND; + return CHANNEL_RC_OK; +} + +static UINT rdpdr_seal_send_free_request(pf_channel_server_context* context, wStream* s) +{ + BOOL status = 0; + size_t len = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->handle); + WINPR_ASSERT(s); + + Stream_SealLength(s); + len = Stream_Length(s); + WINPR_ASSERT(len <= UINT32_MAX); + + rdpdr_dump_send_packet(context->log, WLOG_TRACE, s, proxy_client_tx); + status = WTSVirtualChannelWrite(context->handle, Stream_BufferAs(s, char), (ULONG)len, NULL); + return (status) ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; +} + +static BOOL rdpdr_process_server_header(BOOL server, wLog* log, wStream* s, UINT16 component, + UINT16 PacketId, size_t expect) +{ + UINT16 rpacketid = 0; + UINT16 rcomponent = 0; + + WINPR_ASSERT(s); + if (!Stream_CheckAndLogRequiredLengthRx(server, log, s, 4)) + { + RX_LOG(server, log, WLOG_WARN, "RDPDR_HEADER[%s | %s]: expected length 4, got %" PRIuz, + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), + Stream_GetRemainingLength(s)); + return FALSE; + } + + Stream_Read_UINT16(s, rcomponent); + Stream_Read_UINT16(s, rpacketid); + + if (rcomponent != component) + { + RX_LOG(server, log, WLOG_WARN, "RDPDR_HEADER[%s | %s]: got component %s", + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), + rdpdr_component_string(rcomponent)); + return FALSE; + } + + if (rpacketid != PacketId) + { + RX_LOG(server, log, WLOG_WARN, "RDPDR_HEADER[%s | %s]: got PacketID %s", + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), + rdpdr_packetid_string(rpacketid)); + return FALSE; + } + + if (!Stream_CheckAndLogRequiredLengthRx(server, log, s, expect)) + { + RX_LOG(server, log, WLOG_WARN, + "RDPDR_HEADER[%s | %s] not enough data, expected %" PRIuz ", " + "got %" PRIuz, + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), expect, + Stream_GetRemainingLength(s)); + return ERROR_INVALID_DATA; + } + + return TRUE; +} + +static BOOL rdpdr_check_version(BOOL server, wLog* log, UINT16 versionMajor, UINT16 versionMinor, + UINT16 component, UINT16 PacketId) +{ + if (versionMajor != RDPDR_VERSION_MAJOR) + { + RX_LOG(server, log, WLOG_WARN, "[%s | %s] expected MajorVersion %" PRIu16 ", got %" PRIu16, + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), + RDPDR_VERSION_MAJOR, versionMajor); + return FALSE; + } + switch (versionMinor) + { + case RDPDR_VERSION_MINOR_RDP50: + case RDPDR_VERSION_MINOR_RDP51: + case RDPDR_VERSION_MINOR_RDP52: + case RDPDR_VERSION_MINOR_RDP6X: + case RDPDR_VERSION_MINOR_RDP10X: + break; + default: + { + RX_LOG(server, log, WLOG_WARN, "[%s | %s] unsupported MinorVersion %" PRIu16, + rdpdr_component_string(component), rdpdr_packetid_string(PacketId), + versionMinor); + return FALSE; + } + } + return TRUE; +} + +static UINT rdpdr_process_server_announce_request(pf_channel_client_context* rdpdr, wStream* s) +{ + const UINT16 component = RDPDR_CTYP_CORE; + const UINT16 packetid = PAKID_CORE_SERVER_ANNOUNCE; + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!rdpdr_process_server_header(FALSE, rdpdr->log, s, component, packetid, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, rdpdr->common.versionMajor); + Stream_Read_UINT16(s, rdpdr->common.versionMinor); + + if (!rdpdr_check_version(FALSE, rdpdr->log, rdpdr->common.versionMajor, + rdpdr->common.versionMinor, component, packetid)) + return ERROR_INVALID_DATA; + + /* Limit maximum channel protocol version to the one set by proxy server */ + if (rdpdr->common.versionMajor > rdpdr->maxMajorVersion) + { + rdpdr->common.versionMajor = rdpdr->maxMajorVersion; + rdpdr->common.versionMinor = rdpdr->maxMinorVersion; + } + else if (rdpdr->common.versionMinor > rdpdr->maxMinorVersion) + rdpdr->common.versionMinor = rdpdr->maxMinorVersion; + + Stream_Read_UINT32(s, rdpdr->common.clientID); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_server_send_announce_request(pf_channel_server_context* context) +{ + wStream* s = + rdpdr_server_get_send_buffer(context, RDPDR_CTYP_CORE, PAKID_CORE_SERVER_ANNOUNCE, 8); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT16(s, context->common.versionMajor); /* VersionMajor (2 bytes) */ + Stream_Write_UINT16(s, context->common.versionMinor); /* VersionMinor (2 bytes) */ + Stream_Write_UINT32(s, context->common.clientID); /* ClientId (4 bytes) */ + return rdpdr_seal_send_free_request(context, s); +} + +static UINT rdpdr_process_client_announce_reply(pf_channel_server_context* rdpdr, wStream* s) +{ + const UINT16 component = RDPDR_CTYP_CORE; + const UINT16 packetid = PAKID_CORE_CLIENTID_CONFIRM; + UINT16 versionMajor = 0; + UINT16 versionMinor = 0; + UINT32 clientID = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!rdpdr_process_server_header(TRUE, rdpdr->log, s, component, packetid, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, versionMajor); + Stream_Read_UINT16(s, versionMinor); + + if (!rdpdr_check_version(TRUE, rdpdr->log, versionMajor, versionMinor, component, packetid)) + return ERROR_INVALID_DATA; + + if ((rdpdr->common.versionMajor != versionMajor) || + (rdpdr->common.versionMinor != versionMinor)) + { + SERVER_RX_LOG( + rdpdr->log, WLOG_WARN, + "[%s | %s] downgrading version from %" PRIu16 ".%" PRIu16 " to %" PRIu16 ".%" PRIu16, + rdpdr_component_string(component), rdpdr_packetid_string(packetid), + rdpdr->common.versionMajor, rdpdr->common.versionMinor, versionMajor, versionMinor); + rdpdr->common.versionMajor = versionMajor; + rdpdr->common.versionMinor = versionMinor; + } + Stream_Read_UINT32(s, clientID); + if (rdpdr->common.clientID != clientID) + { + SERVER_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] changing clientID 0x%08" PRIu32 " to 0x%08" PRIu32, + rdpdr_component_string(component), rdpdr_packetid_string(packetid), + rdpdr->common.clientID, clientID); + rdpdr->common.clientID = clientID; + } + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_send_client_announce_reply(pClientContext* pc, pf_channel_client_context* rdpdr) +{ + wStream* s = + rdpdr_client_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_CLIENTID_CONFIRM, 8); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT16(s, rdpdr->common.versionMajor); + Stream_Write_UINT16(s, rdpdr->common.versionMinor); + Stream_Write_UINT32(s, rdpdr->common.clientID); + return rdpdr_client_send(rdpdr->log, pc, s); +} + +static UINT rdpdr_process_client_name_request(pf_channel_server_context* rdpdr, wStream* s, + pClientContext* pc) +{ + UINT32 unicodeFlag = 0; + UINT32 codePage = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + WINPR_ASSERT(pc); + + if (!rdpdr_process_server_header(TRUE, rdpdr->log, s, RDPDR_CTYP_CORE, PAKID_CORE_CLIENT_NAME, + 12)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, unicodeFlag); + rdpdr->common.computerNameUnicode = ((unicodeFlag & 1) != 0) ? TRUE : FALSE; + + Stream_Read_UINT32(s, codePage); + WINPR_UNUSED(codePage); /* Field is ignored */ + Stream_Read_UINT32(s, rdpdr->common.computerNameLen); + if (!Stream_CheckAndLogRequiredLengthSrv(rdpdr->log, s, rdpdr->common.computerNameLen)) + { + SERVER_RX_LOG( + rdpdr->log, WLOG_WARN, "[%s | %s]: missing data, got %" PRIu32 ", expected %" PRIu32, + rdpdr_component_string(RDPDR_CTYP_CORE), rdpdr_packetid_string(PAKID_CORE_CLIENT_NAME), + Stream_GetRemainingLength(s), rdpdr->common.computerNameLen); + return ERROR_INVALID_DATA; + } + void* tmp = realloc(rdpdr->common.computerName.v, rdpdr->common.computerNameLen); + if (!tmp) + return CHANNEL_RC_NO_MEMORY; + rdpdr->common.computerName.v = tmp; + + Stream_Read(s, rdpdr->common.computerName.v, rdpdr->common.computerNameLen); + + pc->computerNameLen = rdpdr->common.computerNameLen; + pc->computerNameUnicode = rdpdr->common.computerNameUnicode; + tmp = realloc(pc->computerName.v, pc->computerNameLen); + if (!tmp) + return CHANNEL_RC_NO_MEMORY; + pc->computerName.v = tmp; + memcpy(pc->computerName.v, rdpdr->common.computerName.v, pc->computerNameLen); + + return CHANNEL_RC_OK; +} + +static UINT rdpdr_send_client_name_request(pClientContext* pc, pf_channel_client_context* rdpdr) +{ + wStream* s = NULL; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(pc); + + { + void* tmp = realloc(rdpdr->common.computerName.v, pc->computerNameLen); + if (!tmp) + return CHANNEL_RC_NO_MEMORY; + rdpdr->common.computerName.v = tmp; + rdpdr->common.computerNameLen = pc->computerNameLen; + rdpdr->common.computerNameUnicode = pc->computerNameUnicode; + memcpy(rdpdr->common.computerName.v, pc->computerName.v, pc->computerNameLen); + } + s = rdpdr_client_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_CLIENT_NAME, + 12U + rdpdr->common.computerNameLen); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT32(s, rdpdr->common.computerNameUnicode + ? 1 + : 0); /* unicodeFlag, 0 for ASCII and 1 for Unicode */ + Stream_Write_UINT32(s, 0); /* codePage, must be set to zero */ + Stream_Write_UINT32(s, rdpdr->common.computerNameLen); + Stream_Write(s, rdpdr->common.computerName.v, rdpdr->common.computerNameLen); + return rdpdr_client_send(rdpdr->log, pc, s); +} + +#define rdpdr_ignore_capset(srv, log, s, header) \ + rdpdr_ignore_capset_((srv), (log), (s), header, __func__) +static UINT rdpdr_ignore_capset_(BOOL srv, wLog* log, wStream* s, + const RDPDR_CAPABILITY_HEADER* header, const char* fkt) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + Stream_Seek(s, header->CapabilityLength); + return CHANNEL_RC_OK; +} + +static UINT rdpdr_client_process_general_capset(pf_channel_client_context* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(rdpdr); + return rdpdr_ignore_capset(FALSE, rdpdr->log, s, header); +} + +static UINT rdpdr_process_printer_capset(pf_channel_client_context* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(rdpdr); + return rdpdr_ignore_capset(FALSE, rdpdr->log, s, header); +} + +static UINT rdpdr_process_port_capset(pf_channel_client_context* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(rdpdr); + return rdpdr_ignore_capset(FALSE, rdpdr->log, s, header); +} + +static UINT rdpdr_process_drive_capset(pf_channel_client_context* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(rdpdr); + return rdpdr_ignore_capset(FALSE, rdpdr->log, s, header); +} + +static UINT rdpdr_process_smartcard_capset(pf_channel_client_context* rdpdr, wStream* s, + const RDPDR_CAPABILITY_HEADER* header) +{ + WINPR_UNUSED(rdpdr); + return rdpdr_ignore_capset(FALSE, rdpdr->log, s, header); +} + +static UINT rdpdr_process_server_core_capability_request(pf_channel_client_context* rdpdr, + wStream* s) +{ + UINT status = CHANNEL_RC_OK; + UINT16 numCapabilities = 0; + + WINPR_ASSERT(rdpdr); + + if (!rdpdr_process_server_header(FALSE, rdpdr->log, s, RDPDR_CTYP_CORE, + PAKID_CORE_SERVER_CAPABILITY, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, numCapabilities); + Stream_Seek(s, 2); /* pad (2 bytes) */ + + for (UINT16 i = 0; i < numCapabilities; i++) + { + RDPDR_CAPABILITY_HEADER header = { 0 }; + UINT error = rdpdr_read_capset_header(rdpdr->log, s, &header); + if (error != CHANNEL_RC_OK) + return error; + + if (header.CapabilityType < ARRAYSIZE(rdpdr->common.capabilityVersions)) + { + if (rdpdr->common.capabilityVersions[header.CapabilityType] > header.Version) + rdpdr->common.capabilityVersions[header.CapabilityType] = header.Version; + + WLog_Print(rdpdr->log, WLOG_TRACE, + "capability %s got version %" PRIu32 ", will use version %" PRIu32, + rdpdr_cap_type_string(header.CapabilityType), header.Version, + rdpdr->common.capabilityVersions[header.CapabilityType]); + } + + switch (header.CapabilityType) + { + case CAP_GENERAL_TYPE: + status = rdpdr_client_process_general_capset(rdpdr, s, &header); + break; + + case CAP_PRINTER_TYPE: + status = rdpdr_process_printer_capset(rdpdr, s, &header); + break; + + case CAP_PORT_TYPE: + status = rdpdr_process_port_capset(rdpdr, s, &header); + break; + + case CAP_DRIVE_TYPE: + status = rdpdr_process_drive_capset(rdpdr, s, &header); + break; + + case CAP_SMARTCARD_TYPE: + status = rdpdr_process_smartcard_capset(rdpdr, s, &header); + break; + + default: + WLog_Print(rdpdr->log, WLOG_WARN, + "unknown capability 0x%04" PRIx16 ", length %" PRIu16 + ", version %" PRIu32, + header.CapabilityType, header.CapabilityLength, header.Version); + Stream_Seek(s, header.CapabilityLength); + break; + } + + if (status != CHANNEL_RC_OK) + return status; + } + + return CHANNEL_RC_OK; +} + +static BOOL rdpdr_write_general_capset(wLog* log, pf_channel_common_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + const RDPDR_CAPABILITY_HEADER header = { CAP_GENERAL_TYPE, 44, + rdpdr->capabilityVersions[CAP_GENERAL_TYPE] }; + if (rdpdr_write_capset_header(log, s, &header) != CHANNEL_RC_OK) + return FALSE; + Stream_Write_UINT32(s, 0); /* osType, ignored on receipt */ + Stream_Write_UINT32(s, 0); /* osVersion, should be ignored */ + Stream_Write_UINT16(s, rdpdr->versionMajor); /* protocolMajorVersion, must be set to 1 */ + Stream_Write_UINT16(s, rdpdr->versionMinor); /* protocolMinorVersion */ + Stream_Write_UINT32(s, 0x0000FFFF); /* ioCode1 */ + Stream_Write_UINT32(s, 0); /* ioCode2, must be set to zero, reserved for future use */ + Stream_Write_UINT32(s, RDPDR_DEVICE_REMOVE_PDUS | RDPDR_CLIENT_DISPLAY_NAME_PDU | + RDPDR_USER_LOGGEDON_PDU); /* extendedPDU */ + Stream_Write_UINT32(s, ENABLE_ASYNCIO); /* extraFlags1 */ + Stream_Write_UINT32(s, 0); /* extraFlags2, must be set to zero, reserved for future use */ + Stream_Write_UINT32(s, rdpdr->SpecialDeviceCount); /* SpecialTypeDeviceCap, number of special + devices to be redirected before logon */ + return TRUE; +} + +static BOOL rdpdr_write_printer_capset(wLog* log, pf_channel_common_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + const RDPDR_CAPABILITY_HEADER header = { CAP_PRINTER_TYPE, 8, + rdpdr->capabilityVersions[CAP_PRINTER_TYPE] }; + if (rdpdr_write_capset_header(log, s, &header) != CHANNEL_RC_OK) + return FALSE; + return TRUE; +} + +static BOOL rdpdr_write_port_capset(wLog* log, pf_channel_common_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + const RDPDR_CAPABILITY_HEADER header = { CAP_PORT_TYPE, 8, + rdpdr->capabilityVersions[CAP_PORT_TYPE] }; + if (rdpdr_write_capset_header(log, s, &header) != CHANNEL_RC_OK) + return FALSE; + return TRUE; +} + +static BOOL rdpdr_write_drive_capset(wLog* log, pf_channel_common_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + const RDPDR_CAPABILITY_HEADER header = { CAP_DRIVE_TYPE, 8, + rdpdr->capabilityVersions[CAP_DRIVE_TYPE] }; + if (rdpdr_write_capset_header(log, s, &header) != CHANNEL_RC_OK) + return FALSE; + return TRUE; +} + +static BOOL rdpdr_write_smartcard_capset(wLog* log, pf_channel_common_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + const RDPDR_CAPABILITY_HEADER header = { CAP_SMARTCARD_TYPE, 8, + rdpdr->capabilityVersions[CAP_SMARTCARD_TYPE] }; + if (rdpdr_write_capset_header(log, s, &header) != CHANNEL_RC_OK) + return FALSE; + return TRUE; +} + +static UINT rdpdr_send_server_capability_request(pf_channel_server_context* rdpdr) +{ + wStream* s = + rdpdr_server_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_SERVER_CAPABILITY, 8); + if (!s) + return CHANNEL_RC_NO_MEMORY; + Stream_Write_UINT16(s, 5); /* numCapabilities */ + Stream_Write_UINT16(s, 0); /* pad */ + if (!rdpdr_write_general_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_printer_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_port_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_drive_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_smartcard_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + return rdpdr_seal_send_free_request(rdpdr, s); +} + +static UINT rdpdr_process_client_capability_response(pf_channel_server_context* rdpdr, wStream* s) +{ + const UINT16 component = RDPDR_CTYP_CORE; + const UINT16 packetid = PAKID_CORE_CLIENT_CAPABILITY; + UINT status = CHANNEL_RC_OK; + UINT16 numCapabilities = 0; + WINPR_ASSERT(rdpdr); + + if (!rdpdr_process_server_header(TRUE, rdpdr->log, s, component, packetid, 4)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, numCapabilities); + Stream_Seek_UINT16(s); /* padding */ + + for (UINT16 x = 0; x < numCapabilities; x++) + { + RDPDR_CAPABILITY_HEADER header = { 0 }; + UINT error = rdpdr_read_capset_header(rdpdr->log, s, &header); + if (error != CHANNEL_RC_OK) + return error; + if (header.CapabilityType < ARRAYSIZE(rdpdr->common.capabilityVersions)) + { + if (rdpdr->common.capabilityVersions[header.CapabilityType] > header.Version) + rdpdr->common.capabilityVersions[header.CapabilityType] = header.Version; + + WLog_Print(rdpdr->log, WLOG_TRACE, + "capability %s got version %" PRIu32 ", will use version %" PRIu32, + rdpdr_cap_type_string(header.CapabilityType), header.Version, + rdpdr->common.capabilityVersions[header.CapabilityType]); + } + + switch (header.CapabilityType) + { + case CAP_GENERAL_TYPE: + status = rdpdr_ignore_capset(TRUE, rdpdr->log, s, &header); + break; + + case CAP_PRINTER_TYPE: + status = rdpdr_ignore_capset(TRUE, rdpdr->log, s, &header); + break; + + case CAP_PORT_TYPE: + status = rdpdr_ignore_capset(TRUE, rdpdr->log, s, &header); + break; + + case CAP_DRIVE_TYPE: + status = rdpdr_ignore_capset(TRUE, rdpdr->log, s, &header); + break; + + case CAP_SMARTCARD_TYPE: + status = rdpdr_ignore_capset(TRUE, rdpdr->log, s, &header); + break; + + default: + SERVER_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] invalid capability type 0x%04" PRIx16, + rdpdr_component_string(component), rdpdr_packetid_string(packetid), + header.CapabilityType); + status = ERROR_INVALID_DATA; + break; + } + + if (status != CHANNEL_RC_OK) + break; + } + + return status; +} + +static UINT rdpdr_send_client_capability_response(pClientContext* pc, + pf_channel_client_context* rdpdr) +{ + wStream* s = NULL; + + WINPR_ASSERT(rdpdr); + s = rdpdr_client_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_CLIENT_CAPABILITY, 4); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT16(s, 5); /* numCapabilities */ + Stream_Write_UINT16(s, 0); /* pad */ + if (!rdpdr_write_general_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_printer_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_port_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_drive_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + if (!rdpdr_write_smartcard_capset(rdpdr->log, &rdpdr->common, s)) + return CHANNEL_RC_NO_MEMORY; + return rdpdr_client_send(rdpdr->log, pc, s); +} + +static UINT rdpdr_send_server_clientid_confirm(pf_channel_server_context* rdpdr) +{ + wStream* s = NULL; + + s = rdpdr_server_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_CLIENTID_CONFIRM, 8); + if (!s) + return CHANNEL_RC_NO_MEMORY; + Stream_Write_UINT16(s, rdpdr->common.versionMajor); + Stream_Write_UINT16(s, rdpdr->common.versionMinor); + Stream_Write_UINT32(s, rdpdr->common.clientID); + return rdpdr_seal_send_free_request(rdpdr, s); +} + +static UINT rdpdr_process_server_clientid_confirm(pf_channel_client_context* rdpdr, wStream* s) +{ + UINT16 versionMajor = 0; + UINT16 versionMinor = 0; + UINT32 clientID = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!rdpdr_process_server_header(FALSE, rdpdr->log, s, RDPDR_CTYP_CORE, + PAKID_CORE_CLIENTID_CONFIRM, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT16(s, versionMajor); + Stream_Read_UINT16(s, versionMinor); + if (!rdpdr_check_version(FALSE, rdpdr->log, versionMajor, versionMinor, RDPDR_CTYP_CORE, + PAKID_CORE_CLIENTID_CONFIRM)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, clientID); + + if ((versionMajor != rdpdr->common.versionMajor) || + (versionMinor != rdpdr->common.versionMinor)) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] Version mismatch, sent %" PRIu16 ".%" PRIu16 + ", downgraded to %" PRIu16 ".%" PRIu16, + rdpdr_component_string(RDPDR_CTYP_CORE), + rdpdr_packetid_string(PAKID_CORE_CLIENTID_CONFIRM), + rdpdr->common.versionMajor, rdpdr->common.versionMinor, versionMajor, + versionMinor); + rdpdr->common.versionMajor = versionMajor; + rdpdr->common.versionMinor = versionMinor; + } + + if (clientID != rdpdr->common.clientID) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] clientID mismatch, sent 0x%08" PRIx32 ", changed to 0x%08" PRIx32, + rdpdr_component_string(RDPDR_CTYP_CORE), + rdpdr_packetid_string(PAKID_CORE_CLIENTID_CONFIRM), rdpdr->common.clientID, + clientID); + rdpdr->common.clientID = clientID; + } + + return CHANNEL_RC_OK; +} + +static BOOL +rdpdr_process_server_capability_request_or_clientid_confirm(pf_channel_client_context* rdpdr, + wStream* s) +{ + const UINT32 mask = STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM | + STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST; + const UINT16 rcomponent = RDPDR_CTYP_CORE; + UINT16 component = 0; + UINT16 packetid = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if ((rdpdr->flags & mask) == mask) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, "already past this state, abort!"); + return FALSE; + } + + if (!Stream_CheckAndLogRequiredLengthClient(rdpdr->log, s, 4)) + return FALSE; + + Stream_Read_UINT16(s, component); + if (rcomponent != component) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, "got component %s, expected %s", + rdpdr_component_string(component), rdpdr_component_string(rcomponent)); + return FALSE; + } + Stream_Read_UINT16(s, packetid); + Stream_Rewind(s, 4); + + switch (packetid) + { + case PAKID_CORE_SERVER_CAPABILITY: + if (rdpdr->flags & STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, "got duplicate packetid %s", + rdpdr_packetid_string(packetid)); + return FALSE; + } + rdpdr->flags |= STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST; + return rdpdr_process_server_core_capability_request(rdpdr, s) == CHANNEL_RC_OK; + case PAKID_CORE_CLIENTID_CONFIRM: + default: + if (rdpdr->flags & STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, "got duplicate packetid %s", + rdpdr_packetid_string(packetid)); + return FALSE; + } + rdpdr->flags |= STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM; + return rdpdr_process_server_clientid_confirm(rdpdr, s) == CHANNEL_RC_OK; + } +} + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) +static UINT rdpdr_send_emulated_scard_device_list_announce_request(pClientContext* pc, + pf_channel_client_context* rdpdr) +{ + wStream* s = NULL; + + s = rdpdr_client_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_DEVICELIST_ANNOUNCE, 24); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT32(s, 1); /* deviceCount -> our emulated smartcard only */ + Stream_Write_UINT32(s, RDPDR_DTYP_SMARTCARD); /* deviceType */ + Stream_Write_UINT32( + s, SCARD_DEVICE_ID); /* deviceID -> reserve highest value for the emulated smartcard */ + Stream_Write(s, "SCARD\0\0\0", 8); + Stream_Write_UINT32(s, 6); + Stream_Write(s, "SCARD\0", 6); + + return rdpdr_client_send(rdpdr->log, pc, s); +} + +static UINT rdpdr_send_emulated_scard_device_remove(pClientContext* pc, + pf_channel_client_context* rdpdr) +{ + wStream* s = NULL; + + s = rdpdr_client_get_send_buffer(rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_DEVICELIST_REMOVE, 24); + if (!s) + return CHANNEL_RC_NO_MEMORY; + + Stream_Write_UINT32(s, 1); /* deviceCount -> our emulated smartcard only */ + Stream_Write_UINT32( + s, SCARD_DEVICE_ID); /* deviceID -> reserve highest value for the emulated smartcard */ + + return rdpdr_client_send(rdpdr->log, pc, s); +} + +static UINT rdpdr_process_server_device_announce_response(pf_channel_client_context* rdpdr, + wStream* s) +{ + const UINT16 component = RDPDR_CTYP_CORE; + const UINT16 packetid = PAKID_CORE_DEVICE_REPLY; + UINT32 deviceID = 0; + UINT32 resultCode = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (!rdpdr_process_server_header(TRUE, rdpdr->log, s, component, packetid, 8)) + return ERROR_INVALID_DATA; + + Stream_Read_UINT32(s, deviceID); + Stream_Read_UINT32(s, resultCode); + + if (deviceID != SCARD_DEVICE_ID) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] deviceID mismatch, sent 0x%08" PRIx32 ", changed to 0x%08" PRIx32, + rdpdr_component_string(component), rdpdr_packetid_string(packetid), + SCARD_DEVICE_ID, deviceID); + } + else if (resultCode != 0) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, + "[%s | %s] deviceID 0x%08" PRIx32 " resultCode=0x%08" PRIx32, + rdpdr_component_string(component), rdpdr_packetid_string(packetid), deviceID, + resultCode); + } + else + CLIENT_RX_LOG(rdpdr->log, WLOG_DEBUG, + "[%s | %s] deviceID 0x%08" PRIx32 " resultCode=0x%08" PRIx32 + " -> emulated smartcard redirected!", + rdpdr_component_string(component), rdpdr_packetid_string(packetid), deviceID, + resultCode); + + return CHANNEL_RC_OK; +} +#endif + +static BOOL pf_channel_rdpdr_rewrite_device_list_to(wStream* s, UINT32 fromVersion, + UINT32 toVersion) +{ + BOOL rc = FALSE; + if (fromVersion == toVersion) + return TRUE; + + const size_t cap = Stream_GetRemainingLength(s); + wStream* clone = Stream_New(NULL, cap); + if (!clone) + goto fail; + const size_t pos = Stream_GetPosition(s); + Stream_Copy(s, clone, cap); + Stream_SealLength(clone); + + Stream_SetPosition(clone, 0); + Stream_SetPosition(s, pos); + + /* Skip device count */ + if (!Stream_SafeSeek(s, 4)) + goto fail; + + UINT32 count = 0; + if (Stream_GetRemainingLength(clone) < 4) + goto fail; + Stream_Read_UINT32(clone, count); + + for (UINT32 x = 0; x < count; x++) + { + RdpdrDevice device = { 0 }; + const size_t charCount = ARRAYSIZE(device.PreferredDosName); + if (Stream_GetRemainingLength(clone) < 20) + goto fail; + + Stream_Read_UINT32(clone, device.DeviceType); /* DeviceType (4 bytes) */ + Stream_Read_UINT32(clone, device.DeviceId); /* DeviceId (4 bytes) */ + Stream_Read(clone, device.PreferredDosName, charCount); /* PreferredDosName (8 bytes) */ + Stream_Read_UINT32(clone, device.DeviceDataLength); /* DeviceDataLength (4 bytes) */ + device.DeviceData = Stream_Pointer(clone); + if (!Stream_SafeSeek(clone, device.DeviceDataLength)) + goto fail; + + if (!Stream_EnsureRemainingCapacity(s, 20)) + goto fail; + Stream_Write_UINT32(s, device.DeviceType); + Stream_Write_UINT32(s, device.DeviceId); + Stream_Write(s, device.PreferredDosName, charCount); + + if (device.DeviceType == RDPDR_DTYP_FILESYSTEM) + { + if (toVersion == DRIVE_CAPABILITY_VERSION_01) + Stream_Write_UINT32(s, 0); /* No unicode name */ + else + { + const size_t datalen = charCount * sizeof(WCHAR); + if (!Stream_EnsureRemainingCapacity(s, datalen + sizeof(UINT32))) + goto fail; + Stream_Write_UINT32(s, datalen); + + const SSIZE_T rcw = Stream_Write_UTF16_String_From_UTF8( + s, charCount, device.PreferredDosName, charCount - 1, TRUE); + if (rcw < 0) + goto fail; + } + } + else + { + Stream_Write_UINT32(s, device.DeviceDataLength); + if (!Stream_EnsureRemainingCapacity(s, device.DeviceDataLength)) + goto fail; + Stream_Write(s, device.DeviceData, device.DeviceDataLength); + } + } + + Stream_SealLength(s); + rc = TRUE; + +fail: + Stream_Free(clone, TRUE); + return rc; +} + +static BOOL pf_channel_rdpdr_rewrite_device_list(pf_channel_client_context* rdpdr, + pServerContext* ps, wStream* s, BOOL toServer) +{ + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(ps); + + const size_t pos = Stream_GetPosition(s); + UINT16 component = 0; + UINT16 packetid = 0; + Stream_SetPosition(s, 0); + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 4)) + return FALSE; + + Stream_Read_UINT16(s, component); + Stream_Read_UINT16(s, packetid); + if ((component != RDPDR_CTYP_CORE) || (packetid != PAKID_CORE_DEVICELIST_ANNOUNCE)) + { + Stream_SetPosition(s, pos); + return TRUE; + } + + const pf_channel_server_context* srv = + HashTable_GetItemValue(ps->interceptContextMap, RDPDR_SVC_CHANNEL_NAME); + if (!srv) + { + WLog_Print(rdpdr->log, WLOG_ERROR, "No channel %s in intercep map", RDPDR_SVC_CHANNEL_NAME); + return FALSE; + } + + UINT32 from = srv->common.capabilityVersions[CAP_DRIVE_TYPE]; + UINT32 to = rdpdr->common.capabilityVersions[CAP_DRIVE_TYPE]; + if (toServer) + { + from = rdpdr->common.capabilityVersions[CAP_DRIVE_TYPE]; + to = srv->common.capabilityVersions[CAP_DRIVE_TYPE]; + } + if (!pf_channel_rdpdr_rewrite_device_list_to(s, from, to)) + return FALSE; + + Stream_SetPosition(s, pos); + return TRUE; +} + +static BOOL pf_channel_rdpdr_client_send_to_server(pf_channel_client_context* rdpdr, + pServerContext* ps, wStream* s) +{ + WINPR_ASSERT(rdpdr); + if (ps) + { + UINT16 server_channel_id = WTSChannelGetId(ps->context.peer, RDPDR_SVC_CHANNEL_NAME); + + /* Ignore messages for channels that can not be mapped. + * The client might not have enabled support for this specific channel, + * so just drop the message. */ + if (server_channel_id == 0) + return TRUE; + + if (!pf_channel_rdpdr_rewrite_device_list(rdpdr, ps, s, TRUE)) + return FALSE; + size_t len = Stream_Length(s); + Stream_SetPosition(s, len); + rdpdr_dump_send_packet(rdpdr->log, WLOG_TRACE, s, proxy_client_tx); + WINPR_ASSERT(ps->context.peer); + WINPR_ASSERT(ps->context.peer->SendChannelData); + return ps->context.peer->SendChannelData(ps->context.peer, server_channel_id, + Stream_Buffer(s), len); + } + return TRUE; +} + +static BOOL pf_channel_send_client_queue(pClientContext* pc, pf_channel_client_context* rdpdr); + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) +static BOOL rdpdr_process_server_loggedon_request(pServerContext* ps, pClientContext* pc, + pf_channel_client_context* rdpdr, wStream* s, + UINT16 component, UINT16 packetid) +{ + WINPR_ASSERT(rdpdr); + WLog_Print(rdpdr->log, WLOG_DEBUG, "[%s | %s]", rdpdr_component_string(component), + rdpdr_packetid_string(packetid)); + if (rdpdr_send_emulated_scard_device_remove(pc, rdpdr) != CHANNEL_RC_OK) + return FALSE; + if (rdpdr_send_emulated_scard_device_list_announce_request(pc, rdpdr) != CHANNEL_RC_OK) + return FALSE; + return pf_channel_rdpdr_client_send_to_server(rdpdr, ps, s); +} + +static BOOL filter_smartcard_io_requests(pf_channel_client_context* rdpdr, wStream* s, + UINT16* pPacketid) +{ + BOOL rc = FALSE; + UINT16 component = 0; + UINT16 packetid = 0; + UINT32 deviceID = 0; + size_t pos = 0; + + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(pPacketid); + + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 4)) + return FALSE; + + pos = Stream_GetPosition(s); + Stream_Read_UINT16(s, component); + Stream_Read_UINT16(s, packetid); + + if (Stream_GetRemainingLength(s) >= 4) + Stream_Read_UINT32(s, deviceID); + + WLog_Print(rdpdr->log, WLOG_DEBUG, "got: [%s | %s]: [0x%08" PRIx32 "]", + rdpdr_component_string(component), rdpdr_packetid_string(packetid), deviceID); + + if (component != RDPDR_CTYP_CORE) + goto fail; + + switch (packetid) + { + case PAKID_CORE_SERVER_ANNOUNCE: + case PAKID_CORE_CLIENTID_CONFIRM: + case PAKID_CORE_CLIENT_NAME: + case PAKID_CORE_DEVICELIST_ANNOUNCE: + case PAKID_CORE_DEVICELIST_REMOVE: + case PAKID_CORE_SERVER_CAPABILITY: + case PAKID_CORE_CLIENT_CAPABILITY: + WLog_Print(rdpdr->log, WLOG_WARN, "Filtering client -> server message [%s | %s]", + rdpdr_component_string(component), rdpdr_packetid_string(packetid)); + *pPacketid = packetid; + break; + case PAKID_CORE_USER_LOGGEDON: + *pPacketid = packetid; + break; + case PAKID_CORE_DEVICE_REPLY: + case PAKID_CORE_DEVICE_IOREQUEST: + if (deviceID != SCARD_DEVICE_ID) + goto fail; + *pPacketid = packetid; + break; + default: + if (deviceID != SCARD_DEVICE_ID) + goto fail; + WLog_Print(rdpdr->log, WLOG_WARN, + "Got [%s | %s] for deviceID 0x%08" PRIx32 ", TODO: Not handled!", + rdpdr_component_string(component), rdpdr_packetid_string(packetid), + deviceID); + goto fail; + } + + rc = TRUE; + +fail: + Stream_SetPosition(s, pos); + return rc; +} +#endif + +BOOL pf_channel_send_client_queue(pClientContext* pc, pf_channel_client_context* rdpdr) +{ + UINT16 channelId = 0; + + WINPR_ASSERT(pc); + WINPR_ASSERT(rdpdr); + + if (rdpdr->state != STATE_CLIENT_CHANNEL_RUNNING) + return FALSE; + channelId = freerdp_channels_get_id_by_name(pc->context.instance, RDPDR_SVC_CHANNEL_NAME); + if ((channelId == 0) || (channelId == UINT16_MAX)) + return TRUE; + + Queue_Lock(rdpdr->queue); + while (Queue_Count(rdpdr->queue) > 0) + { + wStream* s = Queue_Dequeue(rdpdr->queue); + if (!s) + continue; + + size_t len = Stream_Length(s); + Stream_SetPosition(s, len); + + rdpdr_dump_send_packet(rdpdr->log, WLOG_TRACE, s, proxy_server_tx " (queue) "); + WINPR_ASSERT(pc->context.instance->SendChannelData); + if (!pc->context.instance->SendChannelData(pc->context.instance, channelId, + Stream_Buffer(s), len)) + { + CLIENT_TX_LOG(rdpdr->log, WLOG_ERROR, "xxxxxx TODO: Failed to send data!"); + } + Stream_Free(s, TRUE); + } + Queue_Unlock(rdpdr->queue); + return TRUE; +} + +static BOOL rdpdr_handle_server_announce_request(pClientContext* pc, + pf_channel_client_context* rdpdr, wStream* s) +{ + WINPR_ASSERT(pc); + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + + if (rdpdr_process_server_announce_request(rdpdr, s) != CHANNEL_RC_OK) + return FALSE; + if (rdpdr_send_client_announce_reply(pc, rdpdr) != CHANNEL_RC_OK) + return FALSE; + if (rdpdr_send_client_name_request(pc, rdpdr) != CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST; + return TRUE; +} + +BOOL pf_channel_rdpdr_client_handle(pClientContext* pc, UINT16 channelId, const char* channel_name, + const BYTE* xdata, size_t xsize, UINT32 flags, size_t totalSize) +{ + pf_channel_client_context* rdpdr = NULL; + pServerContext* ps = NULL; + wStream* s = NULL; +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + UINT16 packetid = 0; +#endif + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + WINPR_ASSERT(pc->interceptContextMap); + WINPR_ASSERT(channel_name); + WINPR_ASSERT(xdata); + + ps = pc->pdata->ps; + + rdpdr = HashTable_GetItemValue(pc->interceptContextMap, channel_name); + if (!rdpdr) + { + CLIENT_RX_LOG(WLog_Get(RTAG), WLOG_ERROR, + "Channel %s [0x%04" PRIx16 "] missing context in interceptContextMap", + channel_name, channelId); + return FALSE; + } + s = rdpdr->common.buffer; + if (flags & CHANNEL_FLAG_FIRST) + Stream_SetPosition(s, 0); + if (!Stream_EnsureRemainingCapacity(s, xsize)) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_ERROR, + "Channel %s [0x%04" PRIx16 "] not enough memory [need %" PRIuz "]", + channel_name, channelId, xsize); + return FALSE; + } + Stream_Write(s, xdata, xsize); + if ((flags & CHANNEL_FLAG_LAST) == 0) + return TRUE; + + Stream_SealLength(s); + Stream_SetPosition(s, 0); + if (Stream_Length(s) != totalSize) + { + CLIENT_RX_LOG(rdpdr->log, WLOG_WARN, + "Received invalid %s channel data (server -> proxy), expected %" PRIuz + "bytes, got %" PRIuz, + channel_name, totalSize, Stream_Length(s)); + return FALSE; + } + + rdpdr_dump_received_packet(rdpdr->log, WLOG_TRACE, s, proxy_server_rx); + switch (rdpdr->state) + { + case STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST: + if (!rdpdr_handle_server_announce_request(pc, rdpdr, s)) + return FALSE; + break; + case STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST: + if (!rdpdr_process_server_capability_request_or_clientid_confirm(rdpdr, s)) + return FALSE; + rdpdr->state = STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM; + break; + case STATE_CLIENT_EXPECT_SERVER_CLIENT_ID_CONFIRM: + if (!rdpdr_process_server_capability_request_or_clientid_confirm(rdpdr, s)) + return FALSE; + if (rdpdr_send_client_capability_response(pc, rdpdr) != CHANNEL_RC_OK) + return FALSE; +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (pf_channel_smartcard_client_emulate(pc)) + { + if (rdpdr_send_emulated_scard_device_list_announce_request(pc, rdpdr) != + CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_CLIENT_CHANNEL_RUNNING; + } + else +#endif + { + rdpdr->state = STATE_CLIENT_CHANNEL_RUNNING; + pf_channel_send_client_queue(pc, rdpdr); + } + + break; + case STATE_CLIENT_CHANNEL_RUNNING: +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (!pf_channel_smartcard_client_emulate(pc) || + !filter_smartcard_io_requests(rdpdr, s, &packetid)) + return pf_channel_rdpdr_client_send_to_server(rdpdr, ps, s); + else + { + switch (packetid) + { + case PAKID_CORE_USER_LOGGEDON: + return rdpdr_process_server_loggedon_request(ps, pc, rdpdr, s, + RDPDR_CTYP_CORE, packetid); + case PAKID_CORE_DEVICE_IOREQUEST: + { + wStream* out = rdpdr_client_get_send_buffer( + rdpdr, RDPDR_CTYP_CORE, PAKID_CORE_DEVICE_IOCOMPLETION, 0); + WINPR_ASSERT(out); + + if (!rdpdr_process_server_header(FALSE, rdpdr->log, s, RDPDR_CTYP_CORE, + PAKID_CORE_DEVICE_IOREQUEST, 20)) + return FALSE; + + if (!pf_channel_smartcard_client_handle(rdpdr->log, pc, s, out, + rdpdr_client_send)) + return FALSE; + } + break; + case PAKID_CORE_SERVER_ANNOUNCE: + pf_channel_rdpdr_client_reset(pc); + if (!rdpdr_handle_server_announce_request(pc, rdpdr, s)) + return FALSE; + break; + case PAKID_CORE_SERVER_CAPABILITY: + rdpdr->state = STATE_CLIENT_EXPECT_SERVER_CORE_CAPABILITY_REQUEST; + rdpdr->flags = 0; + return pf_channel_rdpdr_client_handle(pc, channelId, channel_name, xdata, + xsize, flags, totalSize); + case PAKID_CORE_DEVICE_REPLY: + break; + default: + CLIENT_RX_LOG( + rdpdr->log, WLOG_ERROR, + "Channel %s [0x%04" PRIx16 + "] we´ve reached an impossible state %s! [%s] aliens invaded!", + channel_name, channelId, rdpdr_client_state_to_string(rdpdr->state), + rdpdr_packetid_string(packetid)); + return FALSE; + } + } + break; +#else + return pf_channel_rdpdr_client_send_to_server(rdpdr, ps, s); +#endif + default: + CLIENT_RX_LOG(rdpdr->log, WLOG_ERROR, + "Channel %s [0x%04" PRIx16 + "] we´ve reached an impossible state %s! aliens invaded!", + channel_name, channelId, rdpdr_client_state_to_string(rdpdr->state)); + return FALSE; + } + + return TRUE; +} + +static void pf_channel_rdpdr_common_context_free(pf_channel_common_context* common) +{ + if (!common) + return; + free(common->computerName.v); + Stream_Free(common->s, TRUE); + Stream_Free(common->buffer, TRUE); +} + +static void pf_channel_rdpdr_client_context_free(InterceptContextMapEntry* base) +{ + pf_channel_client_context* entry = (pf_channel_client_context*)base; + if (!entry) + return; + + pf_channel_rdpdr_common_context_free(&entry->common); + Queue_Free(entry->queue); + free(entry); +} + +static BOOL pf_channel_rdpdr_common_context_new(pf_channel_common_context* common, + void (*fkt)(InterceptContextMapEntry*)) +{ + if (!common) + return FALSE; + common->base.free = fkt; + common->s = Stream_New(NULL, 1024); + if (!common->s) + return FALSE; + common->buffer = Stream_New(NULL, 1024); + if (!common->buffer) + return FALSE; + common->computerNameUnicode = 1; + common->computerName.v = NULL; + common->versionMajor = RDPDR_VERSION_MAJOR; + common->versionMinor = RDPDR_VERSION_MINOR_RDP10X; + common->clientID = SCARD_DEVICE_ID; + + const UINT32 versions[] = { 0, + GENERAL_CAPABILITY_VERSION_02, + PRINT_CAPABILITY_VERSION_01, + PORT_CAPABILITY_VERSION_01, + DRIVE_CAPABILITY_VERSION_02, + SMARTCARD_CAPABILITY_VERSION_01 }; + + memcpy(common->capabilityVersions, versions, sizeof(common->capabilityVersions)); + return TRUE; +} + +static BOOL pf_channel_rdpdr_client_pass_message(pServerContext* ps, pClientContext* pc, + UINT16 channelId, const char* channel_name, + wStream* s) +{ + pf_channel_client_context* rdpdr = NULL; + + WINPR_ASSERT(ps); + WINPR_ASSERT(pc); + + rdpdr = HashTable_GetItemValue(pc->interceptContextMap, channel_name); + if (!rdpdr) + return TRUE; /* Ignore data for channels not available on proxy -> server connection */ + WINPR_ASSERT(rdpdr->queue); + + if (!pf_channel_rdpdr_rewrite_device_list(rdpdr, ps, s, FALSE)) + return FALSE; + if (!Queue_Enqueue(rdpdr->queue, s)) + return FALSE; + pf_channel_send_client_queue(pc, rdpdr); + return TRUE; +} + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) +static BOOL filter_smartcard_device_list_remove(pf_channel_server_context* rdpdr, wStream* s) +{ + size_t pos = 0; + UINT32 count = 0; + + WINPR_ASSERT(rdpdr); + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, sizeof(UINT32))) + return TRUE; + pos = Stream_GetPosition(s); + Stream_Read_UINT32(s, count); + + if (count == 0) + return TRUE; + + if (!Stream_CheckAndLogRequiredLengthOfSizeWLog(rdpdr->log, s, count, sizeof(UINT32))) + return TRUE; + + for (UINT32 x = 0; x < count; x++) + { + UINT32 deviceID = 0; + BYTE* dst = Stream_Pointer(s); + Stream_Read_UINT32(s, deviceID); + if (deviceID == SCARD_DEVICE_ID) + { + ArrayList_Remove(rdpdr->blockedDevices, (void*)(size_t)deviceID); + + /* This is the only device, filter it! */ + if (count == 1) + return TRUE; + + /* Remove this device from the list */ + memmove(dst, Stream_ConstPointer(s), (count - x - 1) * sizeof(UINT32)); + + count--; + Stream_SetPosition(s, pos); + Stream_Write_UINT32(s, count); + return FALSE; + } + } + + return FALSE; +} + +static BOOL filter_smartcard_device_io_request(pf_channel_server_context* rdpdr, wStream* s) +{ + UINT32 DeviceID = 0; + WINPR_ASSERT(rdpdr); + WINPR_ASSERT(s); + Stream_Read_UINT32(s, DeviceID); + return ArrayList_Contains(rdpdr->blockedDevices, (void*)(size_t)DeviceID); +} + +static BOOL filter_smartcard_device_list_announce(pf_channel_server_context* rdpdr, wStream* s) +{ + UINT32 count = 0; + + WINPR_ASSERT(rdpdr); + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, sizeof(UINT32))) + return TRUE; + const size_t pos = Stream_GetPosition(s); + Stream_Read_UINT32(s, count); + + if (count == 0) + return TRUE; + + for (UINT32 x = 0; x < count; x++) + { + UINT32 DeviceType = 0; + UINT32 DeviceId = 0; + char PreferredDosName[8]; + UINT32 DeviceDataLength = 0; + BYTE* dst = Stream_Pointer(s); + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 20)) + return TRUE; + Stream_Read_UINT32(s, DeviceType); + Stream_Read_UINT32(s, DeviceId); + Stream_Read(s, PreferredDosName, ARRAYSIZE(PreferredDosName)); + Stream_Read_UINT32(s, DeviceDataLength); + if (!Stream_SafeSeek(s, DeviceDataLength)) + return TRUE; + if (DeviceType == RDPDR_DTYP_SMARTCARD) + { + ArrayList_Append(rdpdr->blockedDevices, (void*)(size_t)DeviceId); + if (count == 1) + return TRUE; + + WLog_Print(rdpdr->log, WLOG_INFO, "Filtering smartcard device 0x%08" PRIx32 "", + DeviceId); + + memmove(dst, Stream_ConstPointer(s), Stream_GetRemainingLength(s)); + Stream_SetPosition(s, pos); + Stream_Write_UINT32(s, count - 1); + return FALSE; + } + } + + return FALSE; +} + +static BOOL filter_smartcard_device_list_announce_request(pf_channel_server_context* rdpdr, + wStream* s) +{ + BOOL rc = TRUE; + size_t pos = 0; + UINT16 component = 0; + UINT16 packetid = 0; + + WINPR_ASSERT(rdpdr); + if (!Stream_CheckAndLogRequiredLengthWLog(rdpdr->log, s, 8)) + return FALSE; + + pos = Stream_GetPosition(s); + + Stream_Read_UINT16(s, component); + Stream_Read_UINT16(s, packetid); + + if (component != RDPDR_CTYP_CORE) + goto fail; + + switch (packetid) + { + case PAKID_CORE_DEVICELIST_ANNOUNCE: + if (filter_smartcard_device_list_announce(rdpdr, s)) + goto fail; + break; + case PAKID_CORE_DEVICELIST_REMOVE: + if (filter_smartcard_device_list_remove(rdpdr, s)) + goto fail; + break; + case PAKID_CORE_DEVICE_IOREQUEST: + if (filter_smartcard_device_io_request(rdpdr, s)) + goto fail; + break; + + case PAKID_CORE_SERVER_ANNOUNCE: + case PAKID_CORE_CLIENTID_CONFIRM: + case PAKID_CORE_CLIENT_NAME: + case PAKID_CORE_DEVICE_REPLY: + case PAKID_CORE_SERVER_CAPABILITY: + case PAKID_CORE_CLIENT_CAPABILITY: + case PAKID_CORE_USER_LOGGEDON: + WLog_Print(rdpdr->log, WLOG_WARN, "Filtering client -> server message [%s | %s]", + rdpdr_component_string(component), rdpdr_packetid_string(packetid)); + goto fail; + default: + break; + } + + rc = FALSE; +fail: + Stream_SetPosition(s, pos); + return rc; +} +#endif + +static void* stream_copy(const void* obj) +{ + const wStream* src = obj; + wStream* dst = Stream_New(NULL, Stream_Capacity(src)); + if (!dst) + return NULL; + memcpy(Stream_Buffer(dst), Stream_ConstBuffer(src), Stream_Capacity(dst)); + Stream_SetLength(dst, Stream_Length(src)); + Stream_SetPosition(dst, Stream_GetPosition(src)); + return dst; +} + +static void stream_free(void* obj) +{ + wStream* s = obj; + Stream_Free(s, TRUE); +} + +static const char* pf_channel_rdpdr_client_context(void* arg) +{ + pClientContext* pc = arg; + if (!pc) + return "pc=null"; + if (!pc->pdata) + return "pc->pdata=null"; + return pc->pdata->session_id; +} + +BOOL pf_channel_rdpdr_client_new(pClientContext* pc) +{ + wObject* obj = NULL; + pf_channel_client_context* rdpdr = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->interceptContextMap); + + rdpdr = calloc(1, sizeof(pf_channel_client_context)); + if (!rdpdr) + return FALSE; + rdpdr->log = WLog_Get(RTAG); + WINPR_ASSERT(rdpdr->log); + + WLog_SetContext(rdpdr->log, pf_channel_rdpdr_client_context, pc); + if (!pf_channel_rdpdr_common_context_new(&rdpdr->common, pf_channel_rdpdr_client_context_free)) + goto fail; + + rdpdr->maxMajorVersion = RDPDR_VERSION_MAJOR; + rdpdr->maxMinorVersion = RDPDR_VERSION_MINOR_RDP10X; + rdpdr->state = STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST; + + rdpdr->queue = Queue_New(TRUE, 0, 0); + if (!rdpdr->queue) + goto fail; + obj = Queue_Object(rdpdr->queue); + WINPR_ASSERT(obj); + obj->fnObjectNew = stream_copy; + obj->fnObjectFree = stream_free; + if (!HashTable_Insert(pc->interceptContextMap, RDPDR_SVC_CHANNEL_NAME, rdpdr)) + goto fail; + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership of rdpdr + return TRUE; +fail: + pf_channel_rdpdr_client_context_free(&rdpdr->common.base); + return FALSE; +} + +void pf_channel_rdpdr_client_free(pClientContext* pc) +{ + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->interceptContextMap); + HashTable_Remove(pc->interceptContextMap, RDPDR_SVC_CHANNEL_NAME); +} + +static void pf_channel_rdpdr_server_context_free(InterceptContextMapEntry* base) +{ + pf_channel_server_context* entry = (pf_channel_server_context*)base; + if (!entry) + return; + + (void)WTSVirtualChannelClose(entry->handle); + pf_channel_rdpdr_common_context_free(&entry->common); + ArrayList_Free(entry->blockedDevices); + free(entry); +} + +static const char* pf_channel_rdpdr_server_context(void* arg) +{ + pServerContext* ps = arg; + if (!ps) + return "ps=null"; + if (!ps->pdata) + return "ps->pdata=null"; + return ps->pdata->session_id; +} + +BOOL pf_channel_rdpdr_server_new(pServerContext* ps) +{ + pf_channel_server_context* rdpdr = NULL; + PULONG pSessionId = NULL; + DWORD BytesReturned = 0; + + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->interceptContextMap); + + rdpdr = calloc(1, sizeof(pf_channel_server_context)); + if (!rdpdr) + return FALSE; + rdpdr->log = WLog_Get(RTAG); + WINPR_ASSERT(rdpdr->log); + WLog_SetContext(rdpdr->log, pf_channel_rdpdr_server_context, ps); + + if (!pf_channel_rdpdr_common_context_new(&rdpdr->common, pf_channel_rdpdr_server_context_free)) + goto fail; + rdpdr->state = STATE_SERVER_INITIAL; + + rdpdr->blockedDevices = ArrayList_New(FALSE); + if (!rdpdr->blockedDevices) + goto fail; + + rdpdr->SessionId = WTS_CURRENT_SESSION; + if (WTSQuerySessionInformationA(ps->vcm, WTS_CURRENT_SESSION, WTSSessionId, (LPSTR*)&pSessionId, + &BytesReturned)) + { + rdpdr->SessionId = (DWORD)*pSessionId; + WTSFreeMemory(pSessionId); + } + + rdpdr->handle = WTSVirtualChannelOpenEx(rdpdr->SessionId, RDPDR_SVC_CHANNEL_NAME, 0); + if (rdpdr->handle == 0) + goto fail; + if (!HashTable_Insert(ps->interceptContextMap, RDPDR_SVC_CHANNEL_NAME, rdpdr)) + goto fail; + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership of rdpdr + return TRUE; +fail: + pf_channel_rdpdr_server_context_free(&rdpdr->common.base); + return FALSE; +} + +void pf_channel_rdpdr_server_free(pServerContext* ps) +{ + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->interceptContextMap); + HashTable_Remove(ps->interceptContextMap, RDPDR_SVC_CHANNEL_NAME); +} + +static pf_channel_server_context* get_channel(pServerContext* ps, BOOL send) +{ + pf_channel_server_context* rdpdr = NULL; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->interceptContextMap); + + rdpdr = HashTable_GetItemValue(ps->interceptContextMap, RDPDR_SVC_CHANNEL_NAME); + if (!rdpdr) + { + SERVER_RXTX_LOG(send, WLog_Get(RTAG), WLOG_ERROR, + "Channel %s missing context in interceptContextMap", + RDPDR_SVC_CHANNEL_NAME); + return NULL; + } + + return rdpdr; +} + +BOOL pf_channel_rdpdr_server_handle(pServerContext* ps, UINT16 channelId, const char* channel_name, + const BYTE* xdata, size_t xsize, UINT32 flags, size_t totalSize) +{ + wStream* s = NULL; + pClientContext* pc = NULL; + pf_channel_server_context* rdpdr = get_channel(ps, FALSE); + if (!rdpdr) + return FALSE; + + WINPR_ASSERT(ps->pdata); + pc = ps->pdata->pc; + + s = rdpdr->common.buffer; + + if (flags & CHANNEL_FLAG_FIRST) + Stream_SetPosition(s, 0); + + if (!Stream_EnsureRemainingCapacity(s, xsize)) + return FALSE; + Stream_Write(s, xdata, xsize); + + if ((flags & CHANNEL_FLAG_LAST) == 0) + return TRUE; + + Stream_SealLength(s); + Stream_SetPosition(s, 0); + + if (Stream_Length(s) != totalSize) + { + SERVER_RX_LOG(rdpdr->log, WLOG_WARN, + "Received invalid %s channel data (client -> proxy), expected %" PRIuz + "bytes, got %" PRIuz, + channel_name, totalSize, Stream_Length(s)); + return FALSE; + } + + rdpdr_dump_received_packet(rdpdr->log, WLOG_TRACE, s, proxy_client_rx); + switch (rdpdr->state) + { + case STATE_SERVER_EXPECT_CLIENT_ANNOUNCE_REPLY: + if (rdpdr_process_client_announce_reply(rdpdr, s) != CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_SERVER_EXPECT_CLIENT_NAME_REQUEST; + break; + case STATE_SERVER_EXPECT_CLIENT_NAME_REQUEST: + if (rdpdr_process_client_name_request(rdpdr, s, pc) != CHANNEL_RC_OK) + return FALSE; + if (rdpdr_send_server_capability_request(rdpdr) != CHANNEL_RC_OK) + return FALSE; + if (rdpdr_send_server_clientid_confirm(rdpdr) != CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_SERVER_EXPECT_EXPECT_CLIENT_CAPABILITY_RESPONE; + break; + case STATE_SERVER_EXPECT_EXPECT_CLIENT_CAPABILITY_RESPONE: + if (rdpdr_process_client_capability_response(rdpdr, s) != CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_SERVER_CHANNEL_RUNNING; + break; + case STATE_SERVER_CHANNEL_RUNNING: +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (!pf_channel_smartcard_client_emulate(pc) || + !filter_smartcard_device_list_announce_request(rdpdr, s)) + { + if (!pf_channel_rdpdr_client_pass_message(ps, pc, channelId, channel_name, s)) + return FALSE; + } + else + return pf_channel_smartcard_server_handle(ps, s); +#else + if (!pf_channel_rdpdr_client_pass_message(ps, pc, channelId, channel_name, s)) + return FALSE; +#endif + break; + default: + case STATE_SERVER_INITIAL: + SERVER_RX_LOG(rdpdr->log, WLOG_WARN, "Invalid state %s", + rdpdr_server_state_to_string(rdpdr->state)); + return FALSE; + } + + return TRUE; +} + +BOOL pf_channel_rdpdr_server_announce(pServerContext* ps) +{ + pf_channel_server_context* rdpdr = get_channel(ps, TRUE); + if (!rdpdr) + return FALSE; + + WINPR_ASSERT(rdpdr->state == STATE_SERVER_INITIAL); + if (rdpdr_server_send_announce_request(rdpdr) != CHANNEL_RC_OK) + return FALSE; + rdpdr->state = STATE_SERVER_EXPECT_CLIENT_ANNOUNCE_REPLY; + return TRUE; +} + +BOOL pf_channel_rdpdr_client_reset(pClientContext* pc) +{ + pf_channel_client_context* rdpdr = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + WINPR_ASSERT(pc->interceptContextMap); + + rdpdr = HashTable_GetItemValue(pc->interceptContextMap, RDPDR_SVC_CHANNEL_NAME); + if (!rdpdr) + return TRUE; + + Queue_Clear(rdpdr->queue); + rdpdr->flags = 0; + rdpdr->state = STATE_CLIENT_EXPECT_SERVER_ANNOUNCE_REQUEST; + + return TRUE; +} + +static PfChannelResult pf_rdpdr_back_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + if (!pf_channel_rdpdr_client_handle(pdata->pc, + WINPR_ASSERTING_INT_CAST(UINT16, channel->back_channel_id), + channel->channel_name, xdata, xsize, flags, totalSize)) + return PF_CHANNEL_RESULT_ERROR; + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (pf_channel_smartcard_client_emulate(pdata->pc)) + return PF_CHANNEL_RESULT_DROP; +#endif + return PF_CHANNEL_RESULT_DROP; +} + +static PfChannelResult pf_rdpdr_front_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + if (!pf_channel_rdpdr_server_handle(pdata->ps, + WINPR_ASSERTING_INT_CAST(UINT16, channel->front_channel_id), + channel->channel_name, xdata, xsize, flags, totalSize)) + return PF_CHANNEL_RESULT_ERROR; + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (pf_channel_smartcard_client_emulate(pdata->pc)) + return PF_CHANNEL_RESULT_DROP; +#endif + return PF_CHANNEL_RESULT_DROP; +} + +BOOL pf_channel_setup_rdpdr(pServerContext* ps, pServerStaticChannelContext* channel) +{ + channel->onBackData = pf_rdpdr_back_data; + channel->onFrontData = pf_rdpdr_front_data; + + if (!pf_channel_rdpdr_server_new(ps)) + return FALSE; + if (!pf_channel_rdpdr_server_announce(ps)) + return FALSE; + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.h new file mode 100644 index 0000000000000000000000000000000000000000..dbc2e750694afb634e18aa871a651c8721453242 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_rdpdr.h @@ -0,0 +1,47 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef FREERDP_SERVER_PROXY_RDPDR_H +#define FREERDP_SERVER_PROXY_RDPDR_H + +#include + +BOOL pf_channel_setup_rdpdr(pServerContext* ps, pServerStaticChannelContext* channel); + +void pf_channel_rdpdr_client_free(pClientContext* pc); + +BOOL pf_channel_rdpdr_client_new(pClientContext* pc); + +BOOL pf_channel_rdpdr_client_reset(pClientContext* pc); + +BOOL pf_channel_rdpdr_client_handle(pClientContext* pc, UINT16 channelId, const char* channel_name, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize); + +void pf_channel_rdpdr_server_free(pServerContext* ps); + +BOOL pf_channel_rdpdr_server_new(pServerContext* ps); + +BOOL pf_channel_rdpdr_server_announce(pServerContext* ps); +BOOL pf_channel_rdpdr_server_handle(pServerContext* ps, UINT16 channelId, const char* channel_name, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize); + +#endif /* FREERDP_SERVER_PROXY_RDPDR_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.c new file mode 100644 index 0000000000000000000000000000000000000000..1d2bdfe6be0277d41eb1c4725d62e5182f82aae4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.c @@ -0,0 +1,397 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * 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. + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "pf_channel_smartcard.h" +#include "pf_channel_rdpdr.h" + +#define TAG PROXY_TAG("channel.scard") + +#define SCARD_SVC_CHANNEL_NAME "SCARD" + +typedef struct +{ + InterceptContextMapEntry base; + scard_call_context* callctx; + PTP_POOL ThreadPool; + TP_CALLBACK_ENVIRON ThreadPoolEnv; + wArrayList* workObjects; +} pf_channel_client_context; + +typedef struct +{ + SMARTCARD_OPERATION op; + wStream* out; + pClientContext* pc; + wLog* log; + pf_scard_send_fkt_t send_fkt; +} pf_channel_client_queue_element; + +static pf_channel_client_context* scard_get_client_context(pClientContext* pc) +{ + pf_channel_client_context* scard = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->interceptContextMap); + + scard = HashTable_GetItemValue(pc->interceptContextMap, SCARD_SVC_CHANNEL_NAME); + if (!scard) + WLog_WARN(TAG, "[%s] missing in pc->interceptContextMap", SCARD_SVC_CHANNEL_NAME); + return scard; +} + +static BOOL pf_channel_client_write_iostatus(wStream* out, const SMARTCARD_OPERATION* op, + UINT32 ioStatus) +{ + UINT16 component = 0; + UINT16 packetid = 0; + UINT32 dID = 0; + UINT32 cID = 0; + size_t pos = 0; + + WINPR_ASSERT(op); + WINPR_ASSERT(out); + + pos = Stream_GetPosition(out); + Stream_SetPosition(out, 0); + if (!Stream_CheckAndLogRequiredLength(TAG, out, 16)) + return FALSE; + + Stream_Read_UINT16(out, component); + Stream_Read_UINT16(out, packetid); + + Stream_Read_UINT32(out, dID); + Stream_Read_UINT32(out, cID); + + WINPR_ASSERT(component == RDPDR_CTYP_CORE); + WINPR_ASSERT(packetid == PAKID_CORE_DEVICE_IOCOMPLETION); + WINPR_ASSERT(dID == op->deviceID); + WINPR_ASSERT(cID == op->completionID); + + Stream_Write_UINT32(out, ioStatus); + Stream_SetPosition(out, pos); + return TRUE; +} + +struct thread_arg +{ + pf_channel_client_context* scard; + pf_channel_client_queue_element* e; +}; + +static void queue_free(void* obj); +static void* queue_copy(const void* obj); + +static VOID irp_thread(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work) +{ + struct thread_arg* arg = Context; + pf_channel_client_context* scard = arg->scard; + { + UINT32 ioStatus = 0; + LONG rc = smartcard_irp_device_control_call(arg->scard->callctx, arg->e->out, &ioStatus, + &arg->e->op); + if (rc == CHANNEL_RC_OK) + { + if (pf_channel_client_write_iostatus(arg->e->out, &arg->e->op, ioStatus)) + arg->e->send_fkt(arg->e->log, arg->e->pc, arg->e->out); + } + } + queue_free(arg->e); + free(arg); + ArrayList_Remove(scard->workObjects, Work); +} + +static BOOL start_irp_thread(pf_channel_client_context* scard, + const pf_channel_client_queue_element* e) +{ + PTP_WORK work = NULL; + struct thread_arg* arg = calloc(1, sizeof(struct thread_arg)); + if (!arg) + return FALSE; + arg->scard = scard; + arg->e = queue_copy(e); + if (!arg->e) + goto fail; + + work = CreateThreadpoolWork(irp_thread, arg, &scard->ThreadPoolEnv); + if (!work) + goto fail; + ArrayList_Append(scard->workObjects, work); + SubmitThreadpoolWork(work); + + return TRUE; + +fail: + if (arg) + queue_free(arg->e); + free(arg); + return FALSE; +} + +BOOL pf_channel_smartcard_client_handle(wLog* log, pClientContext* pc, wStream* s, wStream* out, + pf_scard_send_fkt_t send_fkt) +{ + BOOL rc = FALSE; + LONG status = 0; + UINT32 FileId = 0; + UINT32 CompletionId = 0; + UINT32 ioStatus = 0; + pf_channel_client_queue_element e = { 0 }; + pf_channel_client_context* scard = scard_get_client_context(pc); + + WINPR_ASSERT(log); + WINPR_ASSERT(send_fkt); + WINPR_ASSERT(s); + + if (!scard) + return FALSE; + + e.log = log; + e.pc = pc; + e.out = out; + e.send_fkt = send_fkt; + + /* Skip IRP header */ + if (!Stream_CheckAndLogRequiredLength(TAG, s, 20)) + return FALSE; + else + { + UINT32 DeviceId = 0; + UINT32 MajorFunction = 0; + UINT32 MinorFunction = 0; + + Stream_Read_UINT32(s, DeviceId); /* DeviceId (4 bytes) */ + Stream_Read_UINT32(s, FileId); /* FileId (4 bytes) */ + Stream_Read_UINT32(s, CompletionId); /* CompletionId (4 bytes) */ + Stream_Read_UINT32(s, MajorFunction); /* MajorFunction (4 bytes) */ + Stream_Read_UINT32(s, MinorFunction); /* MinorFunction (4 bytes) */ + + if (MajorFunction != IRP_MJ_DEVICE_CONTROL) + { + WLog_WARN(TAG, "[%s] Invalid IRP received, expected %s, got %2", SCARD_SVC_CHANNEL_NAME, + rdpdr_irp_string(IRP_MJ_DEVICE_CONTROL), rdpdr_irp_string(MajorFunction)); + return FALSE; + } + e.op.completionID = CompletionId; + e.op.deviceID = DeviceId; + + if (!rdpdr_write_iocompletion_header(out, DeviceId, CompletionId, 0)) + return FALSE; + } + + status = smartcard_irp_device_control_decode(s, CompletionId, FileId, &e.op); + if (status != 0) + goto fail; + + switch (e.op.ioControlCode) + { + case SCARD_IOCTL_LISTREADERGROUPSA: + case SCARD_IOCTL_LISTREADERGROUPSW: + case SCARD_IOCTL_LISTREADERSA: + case SCARD_IOCTL_LISTREADERSW: + case SCARD_IOCTL_LOCATECARDSA: + case SCARD_IOCTL_LOCATECARDSW: + case SCARD_IOCTL_LOCATECARDSBYATRA: + case SCARD_IOCTL_LOCATECARDSBYATRW: + case SCARD_IOCTL_GETSTATUSCHANGEA: + case SCARD_IOCTL_GETSTATUSCHANGEW: + case SCARD_IOCTL_CONNECTA: + case SCARD_IOCTL_CONNECTW: + case SCARD_IOCTL_RECONNECT: + case SCARD_IOCTL_DISCONNECT: + case SCARD_IOCTL_BEGINTRANSACTION: + case SCARD_IOCTL_ENDTRANSACTION: + case SCARD_IOCTL_STATE: + case SCARD_IOCTL_STATUSA: + case SCARD_IOCTL_STATUSW: + case SCARD_IOCTL_TRANSMIT: + case SCARD_IOCTL_CONTROL: + case SCARD_IOCTL_GETATTRIB: + case SCARD_IOCTL_SETATTRIB: + if (!start_irp_thread(scard, &e)) + goto fail; + return TRUE; + + default: + status = smartcard_irp_device_control_call(scard->callctx, out, &ioStatus, &e.op); + if (status != 0) + goto fail; + if (!pf_channel_client_write_iostatus(out, &e.op, ioStatus)) + goto fail; + break; + } + + rc = send_fkt(log, pc, out) == CHANNEL_RC_OK; + +fail: + smartcard_operation_free(&e.op, FALSE); + return rc; +} + +BOOL pf_channel_smartcard_server_handle(pServerContext* ps, wStream* s) +{ + WLog_ERR(TAG, "TODO: unimplemented"); + return TRUE; +} + +static void channel_stop_and_wait(pf_channel_client_context* scard, BOOL reset) +{ + WINPR_ASSERT(scard); + smartcard_call_context_signal_stop(scard->callctx, FALSE); + + while (ArrayList_Count(scard->workObjects) > 0) + { + PTP_WORK work = ArrayList_GetItem(scard->workObjects, 0); + if (!work) + continue; + WaitForThreadpoolWorkCallbacks(work, TRUE); + } + + smartcard_call_context_signal_stop(scard->callctx, reset); +} + +static void pf_channel_scard_client_context_free(InterceptContextMapEntry* base) +{ + pf_channel_client_context* entry = (pf_channel_client_context*)base; + if (!entry) + return; + + /* Set the stop event. + * All threads waiting in blocking operations will abort at the next + * available polling slot */ + channel_stop_and_wait(entry, FALSE); + ArrayList_Free(entry->workObjects); + CloseThreadpool(entry->ThreadPool); + DestroyThreadpoolEnvironment(&entry->ThreadPoolEnv); + + smartcard_call_context_free(entry->callctx); + free(entry); +} + +static void queue_free(void* obj) +{ + pf_channel_client_queue_element* element = obj; + if (!element) + return; + smartcard_operation_free(&element->op, FALSE); + Stream_Free(element->out, TRUE); + free(element); +} + +static void* queue_copy(const void* obj) +{ + const pf_channel_client_queue_element* other = obj; + pf_channel_client_queue_element* copy = NULL; + if (!other) + return NULL; + copy = calloc(1, sizeof(pf_channel_client_queue_element)); + if (!copy) + return NULL; + + *copy = *other; + copy->out = Stream_New(NULL, Stream_Capacity(other->out)); + if (!copy->out) + goto fail; + Stream_Write(copy->out, Stream_Buffer(other->out), Stream_GetPosition(other->out)); + return copy; +fail: + queue_free(copy); + return NULL; +} + +static void work_object_free(void* arg) +{ + PTP_WORK work = arg; + CloseThreadpoolWork(work); +} + +BOOL pf_channel_smartcard_client_new(pClientContext* pc) +{ + pf_channel_client_context* scard = NULL; + wObject* obj = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->interceptContextMap); + + scard = calloc(1, sizeof(pf_channel_client_context)); + if (!scard) + return FALSE; + scard->base.free = pf_channel_scard_client_context_free; + scard->callctx = smartcard_call_context_new(pc->context.settings); + if (!scard->callctx) + goto fail; + + scard->workObjects = ArrayList_New(TRUE); + if (!scard->workObjects) + goto fail; + obj = ArrayList_Object(scard->workObjects); + WINPR_ASSERT(obj); + obj->fnObjectFree = work_object_free; + + scard->ThreadPool = CreateThreadpool(NULL); + if (!scard->ThreadPool) + goto fail; + InitializeThreadpoolEnvironment(&scard->ThreadPoolEnv); + SetThreadpoolCallbackPool(&scard->ThreadPoolEnv, scard->ThreadPool); + + return HashTable_Insert(pc->interceptContextMap, SCARD_SVC_CHANNEL_NAME, scard); +fail: + pf_channel_scard_client_context_free(&scard->base); + return FALSE; +} + +void pf_channel_smartcard_client_free(pClientContext* pc) +{ + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->interceptContextMap); + HashTable_Remove(pc->interceptContextMap, SCARD_SVC_CHANNEL_NAME); +} + +BOOL pf_channel_smartcard_client_emulate(pClientContext* pc) +{ + pf_channel_client_context* scard = scard_get_client_context(pc); + if (!scard) + return FALSE; + return smartcard_call_is_configured(scard->callctx); +} + +BOOL pf_channel_smartcard_client_reset(pClientContext* pc) +{ + pf_channel_client_context* scard = scard_get_client_context(pc); + if (!scard) + return TRUE; + + channel_stop_and_wait(scard, TRUE); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.h new file mode 100644 index 0000000000000000000000000000000000000000..975636d013e27f39b4853d96fe15ea783e1c18c1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/channels/pf_channel_smartcard.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef FREERDP_SERVER_PROXY_SCARD_H +#define FREERDP_SERVER_PROXY_SCARD_H + +#include +#include + +typedef UINT (*pf_scard_send_fkt_t)(wLog* log, pClientContext*, wStream*); + +BOOL pf_channel_smartcard_client_new(pClientContext* pc); +void pf_channel_smartcard_client_free(pClientContext* pc); + +BOOL pf_channel_smartcard_client_reset(pClientContext* pc); +BOOL pf_channel_smartcard_client_emulate(pClientContext* pc); + +BOOL pf_channel_smartcard_client_handle(wLog* log, pClientContext* pc, wStream* s, wStream* out, + pf_scard_send_fkt_t fkt); +BOOL pf_channel_smartcard_server_handle(pServerContext* ps, wStream* s); + +#endif /* FREERDP_SERVER_PROXY_SCARD_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..95ce3e9051937d508757659c996d1a10ebd0c5ec --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/CMakeLists.txt @@ -0,0 +1,29 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Proxy Server +# +# Copyright 2021 Armin Novak +# 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. + +set(PROXY_APP_SRCS freerdp_proxy.c) + +set(APP_NAME "freerdp-proxy") +addtargetwithresourcefile(${APP_NAME} TRUE "${FREERDP_VERSION}" PROXY_APP_SRCS) + +target_link_libraries(${APP_NAME} ${MODULE_NAME}) +install(TARGETS ${APP_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT server) + +set_property(TARGET ${APP_NAME} PROPERTY FOLDER "Server/proxy") + +generate_and_install_freerdp_man_from_template(${APP_NAME} "1" "${FREERDP_API_VERSION}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp-proxy.1.in b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp-proxy.1.in new file mode 100644 index 0000000000000000000000000000000000000000..ee4434bdad6e46b85285a00498576c51d1af81e6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp-proxy.1.in @@ -0,0 +1,85 @@ +.de URL +\\$2 \(laURL: \\$1 \(ra\\$3 +.. +.if \n[.g] .mso www.tmac +.TH @MANPAGE_NAME@ 1 2023-12-14 "@FREERDP_VERSION_FULL@" "FreeRDP" +.SH NAME +@MANPAGE_NAME@ \- A server binary allowing MITM proxying of RDP connections +.SH SYNOPSIS +.B @MANPAGE_NAME@ +[\fB-h\fP] +[\fB--help\fP] +[\fB--buildconfig\fP] +[\fB--dump-config\fP \fB\fP] +[\fB-v\fP] +[\fB--version\fP] +[\fB\fP] +.SH DESCRIPTION +.B @MANPAGE_NAME@ +can be used to proxy a RDP connection between a target server and connecting clients. +Possible usage scenarios are: +.IP Proxying +Connect outdated/insecure RDP servers from behind a (more secure) proxy +.IP Analysis +Allow detailed protocol analysis of (many) unknown protocol features (channels) +.IP Inspection +MITM proxy for session inspection and recording + +.SH OPTIONS +.IP -h,--help +Display a help text explaining usage. +.IP --buildconfig +Print the build configuration of the proxy and exit. +.IP -v,--version +Print the version of the proxy and exit. +.IP --dump-config \fB\fP +Dump a template configuration to \fB\fP +.IP \fB\fP +Start the proxy with settings read from \fB\fP + +.SH WARNING +The proxy does not support authentication out of the box but acts simply as intermediary. +Only \fBRDP\fP and \fBTLS\fP security modes are supported, \fBNLA\fP will fail for connections to the proxy. +To implement authentication a \fBproxy-module\fP can be implemented that can authenticate against some backend +and map connecting users and credentials to target server users and credentials. + +.SH EXAMPLES +@MANPAGE_NAME@ /some/config/file + +@MANPAGE_NAME@ --dump-config /some/config/file + +.SH PREPARATIONS + +1. generate certificates for proxy + +\fBwinpr-makecert -rdp -path . proxy\fP + +2. generate proxy configuration + +\fB@MANPAGE_NAME@ --dump-config proxy.ini\fP + +3. edit configurartion and: + + * provide (preferably absolute) paths for \fBCertificateFile\fP and \fBPrivateKeyFile\fP generated previously + * remove the \fBCertificateContents\fP and \fBPrivateKeyContents\fP + * Adjust the \fB[Server]\fP settings \fBHost\fP and \fBPort\fP to bind a specific port on a network interface + * Adjust the \fB[Target]\fP \fBHost\fP and \fBPort\fP settings to the \fBRDP\fP target server + * Adjust (or remove if unuse) the \fBPlugins\fP settings + +3. start proxy server + + \fB@MANPAGE_NAME@ proxy.ini\fP + +.SH EXIT STATUS +.TP +.B 0 +Successful program execution. +.TP +.B 1 +Otherwise. + +.SH SEE ALSO +wlog(7) + +.SH AUTHOR +FreeRDP diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp_proxy.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp_proxy.c new file mode 100644 index 0000000000000000000000000000000000000000..099cd35c219b7ccaa4b0b5438ec30604c3d5a6b0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/cli/freerdp_proxy.c @@ -0,0 +1,185 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * + * 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 + +#include +#include + +#include +#include + +#include +#include + +#define TAG PROXY_TAG("server") + +static proxyServer* server = NULL; + +#if defined(_WIN32) +static const char* strsignal(int signum) +{ + switch (signum) + { + case SIGINT: + return "SIGINT"; + case SIGTERM: + return "SIGTERM"; + default: + return "UNKNOWN"; + } +} +#endif + +// NOLINTBEGIN(bugprone-signal-handler,cert-msc54-cpp,cert-sig30-c) +static void cleanup_handler(int signum) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + WLog_INFO(TAG, "caught signal %s [%d], starting cleanup...", strsignal(signum), signum); + + WLog_INFO(TAG, "stopping all connections."); + pf_server_stop(server); +} +// NOLINTEND(bugprone-signal-handler,cert-msc54-cpp,cert-sig30-c) + +static void pf_server_register_signal_handlers(void) +{ + (void)signal(SIGINT, cleanup_handler); + (void)signal(SIGTERM, cleanup_handler); +#ifndef _WIN32 + (void)signal(SIGQUIT, cleanup_handler); + (void)signal(SIGKILL, cleanup_handler); +#endif +} + +static int usage(const char* app) +{ + printf("Usage:\n"); + printf("%s -h Display this help text.\n", app); + printf("%s --help Display this help text.\n", app); + printf("%s --buildconfig Print the build configuration.\n", app); + printf("%s Start the proxy with \n", app); + printf("%s --dump-config Create a template \n", app); + printf("%s -v Print out binary version.\n", app); + printf("%s --version Print out binary version.\n", app); + return 0; +} + +static int version(const char* app) +{ + printf("%s version %s", app, freerdp_get_version_string()); + return 0; +} + +static int buildconfig(const char* app) +{ + printf("This is FreeRDP version %s (%s)\n", FREERDP_VERSION_FULL, FREERDP_GIT_REVISION); + printf("%s", freerdp_get_build_config()); + return 0; +} + +int main(int argc, char* argv[]) +{ + int status = -1; + + pf_server_register_signal_handlers(); + + WLog_INFO(TAG, "freerdp-proxy version info:"); + WLog_INFO(TAG, "\tFreeRDP version: %s", FREERDP_VERSION_FULL); + WLog_INFO(TAG, "\tGit commit: %s", FREERDP_GIT_REVISION); + WLog_DBG(TAG, "\tBuild config: %s", freerdp_get_build_config()); + + if (argc < 2) + { + status = usage(argv[0]); + goto fail; + } + + const char* arg = argv[1]; + + if (_stricmp(arg, "-h") == 0) + { + status = usage(argv[0]); + goto fail; + } + else if (_stricmp(arg, "--help") == 0) + { + status = usage(argv[0]); + goto fail; + } + else if (_stricmp(arg, "--buildconfig") == 0) + { + status = buildconfig(argv[0]); + goto fail; + } + else if (_stricmp(arg, "--dump-config") == 0) + { + if (argc != 3) + { + status = usage(argv[0]); + goto fail; + } + status = pf_server_config_dump(argv[2]) ? 0 : -1; + goto fail; + } + else if (_stricmp(arg, "-v") == 0) + { + status = version(argv[0]); + goto fail; + } + else if (_stricmp(arg, "--version") == 0) + { + status = version(argv[0]); + goto fail; + } + + const char* config_path = argv[1]; + if (argc != 2) + { + status = usage(argv[0]); + goto fail; + } + + proxyConfig* config = pf_server_config_load_file(config_path); + if (!config) + goto fail; + + pf_server_config_print(config); + + server = pf_server_new(config); + pf_server_config_free(config); + + if (!server) + goto fail; + + if (!pf_server_start(server)) + goto fail; + + if (!pf_server_run(server)) + goto fail; + + status = 0; + +fail: + pf_server_free(server); + + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/freerdp-proxy.pc.in b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/freerdp-proxy.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..465507523facb56c6bb797394f70d1ab0baa492e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/freerdp-proxy.pc.in @@ -0,0 +1,16 @@ +prefix=@PKG_CONFIG_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${prefix}/@FREERDP_INCLUDE_DIR@ +libs=-lfreerdp-server-proxy@FREERDP_API_VERSION@ + +Name: FreeRDP proxy +Description: FreeRDP: A Remote Desktop Protocol Implementation +URL: http://www.freerdp.com/ +Version: @FREERDP_VERSION@ +Requires: +Requires.private: @WINPR_PKG_CONFIG_FILENAME@ freerdp@FREERDP_VERSION_MAJOR@ freerdp-server@FREERDP_VERSION_MAJOR@ freerdp-client@FREERDP_VERSION_MAJOR@ + +Libs: -L${libdir} ${libs} +Libs.private: -ldl -lpthread +Cflags: -I${includedir} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e29776e272c46c9d5dd01f4fa273f54c97aea07 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/CMakeLists.txt @@ -0,0 +1,33 @@ +# Copyright 2019 Kobi Mizrachi +# +# 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. + +# The third-party directory is meant for third-party components to be built +# as part of the main FreeRDP build system, making separate maintenance easier. +# Subdirectories of the third-party directory are ignored by git, but are +# automatically included by CMake when the -DWITH_THIRD_PARTY=on option is used. + +# include proxy header files for proxy modules +include_directories("${PROJECT_SOURCE_DIR}/server/proxy") +include_directories("${PROJECT_SOURCE_DIR}/server/proxy/modules") + +# taken from FreeRDP/third-party/CMakeLists.txt +file(GLOB all_valid_subdirs RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*/CMakeLists.txt") + +foreach(dir ${all_valid_subdirs}) + if(${dir} MATCHES "^([^/]*)/+CMakeLists.txt") + string(REGEX REPLACE "^([^/]*)/+CMakeLists.txt" "\\1" dir_trimmed ${dir}) + message(STATUS "Adding proxy module ${dir_trimmed}") + add_subdirectory(${dir_trimmed}) + endif() +endforeach(dir) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/README.md b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/README.md new file mode 100644 index 0000000000000000000000000000000000000000..db4322bac35fadc01757036b941cff1a6e6057f8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/README.md @@ -0,0 +1,66 @@ +# Proxy module API + +`freerdp-proxy` has an API for hooking/filtering certain events/messages. +A module can register callbacks to events, allowing to record the data and control whether to pass/ignore, or right out drop the connection. + +During startup, the proxy reads its modules from the configuration: + +```ini +[Plugins] +Modules = demo,cap +``` + +These modules are loaded in a best effort manner. Additionally there is a configuration field for modules that must be loaded, +so the proxy refuses to start if they are not found: + +```ini +[Plugins] +Required = demo,cap +``` + +Modules must be installed as shared libraries in the `/lib/freerdp3/proxy` folder and match the pattern +`proxy--plugin.` (e.g. `proxy-demo-plugin.so`) to be found. +For security reasons loading by full path is not supported and only the installation path is used for lookup. + +## Currently supported hook events + +### Client + +* ClientInitConnect: Called before the client tries to open a connection +* ClientUninitConnect: Called after the client has disconnected +* ClientPreConnect: Called in client PreConnect callback +* ClientPostConnect: Called in client PostConnect callback +* ClientPostDisconnect: Called in client PostDisconnect callback +* ClientX509Certificate: Called in client X509 certificate verification callback +* ClientLoginFailure: Called in client login failure callback +* ClientEndPaint: Called in client EndPaint callback + +### Server + +* ServerPostConnect: Called after a client has connected +* ServerPeerActivate: Called after a client has activated +* ServerChannelsInit: Called after channels are initialized +* ServerChannelsFree: Called after channels are cleaned up +* ServerSessionEnd: Called after the client connection disconnected + +## Currently supported filter events + +* KeyboardEvent: Keyboard event, e.g. all key press and release events +* MouseEvent: Mouse event, e.g. mouse movement and button press/release events +* ClientChannelData: Client static channel data +* ServerChannelData: Server static channel data +* DynamicChannelCreate: Dynamic channel create +* ServerFetchTargetAddr: Fetch target address (e.g. RDP TargetInfo) +* ServerPeerLogon: A peer is logging on + +## Developing a new module +* Create a new file that includes `freerdp/server/proxy/proxy_modules_api.h`. +* Implement the `proxy_module_entry_point` function and register the callbacks you are interested in. +* Each callback receives two parameters: + * `connectionInfo* info` holds connection info of the raised event. + * `void* param` holds the actual event data. It should be casted by the filter to the suitable struct from `filters_api.h`. +* Each callback must return a `BOOL`: + * `FALSE`: The event will not be proxied. + * `TRUE`: The event will be proxied. + +A demo can be found in `filter_demo.c`. diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6c82fec063a728b81ab96718843b9f75acf7ade --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/CMakeLists.txt @@ -0,0 +1,47 @@ +# +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Proxy Server Demo C++ Module +# +# Copyright 2019 Kobi Mizrachi +# Copyright 2021 Armin Novak +# 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. +# + +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(proxy-bitmap-filter-plugin VERSION ${FREERDP_DEFAULT_PROJECT_VERSION} LANGUAGES CXX) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../../cmake/) +include(CommonConfigOptions) +include(CXXCompilerFlags) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(SRCS bitmap-filter.cpp) +addtargetwithresourcefile(${PROJECT_NAME} FALSE "${PROJECT_VERSION}" SRCS FALSE) + +target_link_libraries(${PROJECT_NAME} winpr freerdp) + +install(TARGETS ${PROJECT_NAME} DESTINATION ${FREERDP_PROXY_PLUGINDIR}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/bitmap-filter.cpp b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/bitmap-filter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49542101eebab1fdf35c7263ac6113475621e25e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/bitmap-filter/bitmap-filter.cpp @@ -0,0 +1,468 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server persist-bitmap-filter Module + * + * this module is designed to deactivate all persistent bitmap cache settings a + * client might send. + * + * Copyright 2023 Armin Novak + * Copyright 2023 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 +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#define TAG MODULE_TAG("persist-bitmap-filter") + +static constexpr char plugin_name[] = "bitmap-filter"; +static constexpr char plugin_desc[] = + "this plugin deactivates and filters persistent bitmap cache."; + +static const std::vector& plugin_static_intercept() +{ + static std::vector vec; + if (vec.empty()) + vec.emplace_back(DRDYNVC_SVC_CHANNEL_NAME); + return vec; +} + +static const std::vector& plugin_dyn_intercept() +{ + static std::vector vec; + if (vec.empty()) + vec.emplace_back(RDPGFX_DVC_CHANNEL_NAME); + return vec; +} + +class DynChannelState +{ + + public: + [[nodiscard]] bool skip() const + { + return _toSkip != 0; + } + + [[nodiscard]] bool skip(size_t s) + { + if (s > _toSkip) + _toSkip = 0; + else + _toSkip -= s; + return skip(); + } + + [[nodiscard]] size_t remaining() const + { + return _toSkip; + } + + [[nodiscard]] size_t total() const + { + return _totalSkipSize; + } + + void setSkipSize(size_t len) + { + _toSkip = _totalSkipSize = len; + } + + [[nodiscard]] bool drop() const + { + return _drop; + } + + void setDrop(bool d) + { + _drop = d; + } + + [[nodiscard]] uint32_t channelId() const + { + return _channelId; + } + + void setChannelId(uint32_t id) + { + _channelId = id; + } + + private: + size_t _toSkip = 0; + size_t _totalSkipSize = 0; + bool _drop = false; + uint32_t _channelId = 0; +}; + +static BOOL filter_client_pre_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(pdata->pc); + WINPR_ASSERT(custom); + + auto settings = pdata->pc->context.settings; + + /* We do not want persistent bitmap cache to be used with proxy */ + return freerdp_settings_set_bool(settings, FreeRDP_BitmapCachePersistEnabled, FALSE); +} + +static BOOL filter_dyn_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + auto intercept = std::find(plugin_dyn_intercept().begin(), plugin_dyn_intercept().end(), + data->name) != plugin_dyn_intercept().end(); + if (intercept) + data->intercept = TRUE; + return TRUE; +} + +static BOOL filter_static_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + auto intercept = std::find(plugin_static_intercept().begin(), plugin_static_intercept().end(), + data->name) != plugin_static_intercept().end(); + if (intercept) + data->intercept = TRUE; + return TRUE; +} + +static size_t drdynvc_cblen_to_bytes(UINT8 cbLen) +{ + switch (cbLen) + { + case 0: + return 1; + + case 1: + return 2; + + default: + return 4; + } +} + +static UINT32 drdynvc_read_variable_uint(wStream* s, UINT8 cbLen) +{ + UINT32 val = 0; + + switch (cbLen) + { + case 0: + Stream_Read_UINT8(s, val); + break; + + case 1: + Stream_Read_UINT16(s, val); + break; + + default: + Stream_Read_UINT32(s, val); + break; + } + + return val; +} + +static BOOL drdynvc_try_read_header(wStream* s, uint32_t& channelId, size_t& length) +{ + UINT8 value = 0; + Stream_SetPosition(s, 0); + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + Stream_Read_UINT8(s, value); + + const UINT8 cmd = (value & 0xf0) >> 4; + const UINT8 Sp = (value & 0x0c) >> 2; + const UINT8 cbChId = (value & 0x03); + + switch (cmd) + { + case DATA_PDU: + case DATA_FIRST_PDU: + break; + default: + return FALSE; + } + + const size_t channelIdLen = drdynvc_cblen_to_bytes(cbChId); + if (Stream_GetRemainingLength(s) < channelIdLen) + return FALSE; + + channelId = drdynvc_read_variable_uint(s, cbChId); + length = Stream_Length(s); + if (cmd == DATA_FIRST_PDU) + { + const size_t dataLen = drdynvc_cblen_to_bytes(Sp); + if (Stream_GetRemainingLength(s) < dataLen) + return FALSE; + + length = drdynvc_read_variable_uint(s, Sp); + } + + return TRUE; +} + +static DynChannelState* filter_get_plugin_data(proxyPlugin* plugin, proxyData* pdata) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto mgr = static_cast(plugin->custom); + WINPR_ASSERT(mgr); + + WINPR_ASSERT(mgr->GetPluginData); + return static_cast(mgr->GetPluginData(mgr, plugin_name, pdata)); +} + +static BOOL filter_set_plugin_data(proxyPlugin* plugin, proxyData* pdata, DynChannelState* data) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto mgr = static_cast(plugin->custom); + WINPR_ASSERT(mgr); + + WINPR_ASSERT(mgr->SetPluginData); + return mgr->SetPluginData(mgr, plugin_name, pdata, data); +} + +static UINT8 drdynvc_value_to_cblen(UINT32 value) +{ + if (value <= 0xFF) + return 0; + if (value <= 0xFFFF) + return 1; + return 2; +} + +static BOOL drdynvc_write_variable_uint(wStream* s, UINT32 value, UINT8 cbLen) +{ + switch (cbLen) + { + case 0: + Stream_Write_UINT8(s, static_cast(value)); + break; + + case 1: + Stream_Write_UINT16(s, static_cast(value)); + break; + + default: + Stream_Write_UINT32(s, value); + break; + } + + return TRUE; +} + +static BOOL drdynvc_write_header(wStream* s, UINT32 channelId) +{ + const UINT8 cbChId = drdynvc_value_to_cblen(channelId); + const UINT8 value = (DATA_PDU << 4) | cbChId; + const size_t len = drdynvc_cblen_to_bytes(cbChId) + 1; + + if (!Stream_EnsureRemainingCapacity(s, len)) + return FALSE; + + Stream_Write_UINT8(s, value); + return drdynvc_write_variable_uint(s, value, cbChId); +} + +static BOOL filter_forward_empty_offer(const char* sessionID, proxyDynChannelInterceptData* data, + size_t startPosition, UINT32 channelId) +{ + WINPR_ASSERT(data); + + Stream_SetPosition(data->data, startPosition); + if (!drdynvc_write_header(data->data, channelId)) + return FALSE; + + if (!Stream_EnsureRemainingCapacity(data->data, sizeof(UINT16))) + return FALSE; + Stream_Write_UINT16(data->data, 0); + Stream_SealLength(data->data); + + WLog_INFO(TAG, "[SessionID=%s][%s] forwarding empty %s", sessionID, plugin_name, + rdpgfx_get_cmd_id_string(RDPGFX_CMDID_CACHEIMPORTOFFER)); + data->rewritten = TRUE; + return TRUE; +} + +static BOOL filter_dyn_channel_intercept(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + data->result = PF_CHANNEL_RESULT_PASS; + if (!data->isBackData && + (strncmp(data->name, RDPGFX_DVC_CHANNEL_NAME, ARRAYSIZE(RDPGFX_DVC_CHANNEL_NAME)) == 0)) + { + auto state = filter_get_plugin_data(plugin, pdata); + if (!state) + { + WLog_ERR(TAG, "[SessionID=%s][%s] missing custom data, aborting!", pdata->session_id, + plugin_name); + return FALSE; + } + const size_t inputDataLength = Stream_Length(data->data); + UINT16 cmdId = RDPGFX_CMDID_UNUSED_0000; + + const auto pos = Stream_GetPosition(data->data); + if (!state->skip()) + { + if (data->first) + { + uint32_t channelId = 0; + size_t length = 0; + if (drdynvc_try_read_header(data->data, channelId, length)) + { + if (Stream_GetRemainingLength(data->data) >= 2) + { + Stream_Read_UINT16(data->data, cmdId); + state->setSkipSize(length); + state->setDrop(false); + } + } + + switch (cmdId) + { + case RDPGFX_CMDID_CACHEIMPORTOFFER: + state->setDrop(true); + state->setChannelId(channelId); + break; + default: + break; + } + Stream_SetPosition(data->data, pos); + } + } + + if (state->skip()) + { + if (!state->skip(inputDataLength)) + return FALSE; + + if (state->drop()) + { + WLog_WARN(TAG, + "[SessionID=%s][%s] dropping %s packet [total:%" PRIuz ", current:%" PRIuz + ", remaining: %" PRIuz "]", + pdata->session_id, plugin_name, + rdpgfx_get_cmd_id_string(RDPGFX_CMDID_CACHEIMPORTOFFER), state->total(), + inputDataLength, state->remaining()); + data->result = PF_CHANNEL_RESULT_DROP; + +#if 0 // TODO: Sending this does screw up some windows RDP server versions :/ + if (state->remaining() == 0) + { + if (!filter_forward_empty_offer(pdata->session_id, data, pos, + state->channelId())) + return FALSE; + } +#endif + } + } + } + + return TRUE; +} + +static BOOL filter_server_session_started(proxyPlugin* plugin, proxyData* pdata, void* /*unused*/) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto state = filter_get_plugin_data(plugin, pdata); + delete state; + + auto newstate = new DynChannelState(); + if (!filter_set_plugin_data(plugin, pdata, newstate)) + { + delete newstate; + return FALSE; + } + + return TRUE; +} + +static BOOL filter_server_session_end(proxyPlugin* plugin, proxyData* pdata, void* /*unused*/) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto state = filter_get_plugin_data(plugin, pdata); + delete state; + filter_set_plugin_data(plugin, pdata, nullptr); + return TRUE; +} + +#ifdef __cplusplus +extern "C" +{ +#endif + FREERDP_API BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, void* userdata); +#ifdef __cplusplus +} +#endif + +BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, void* userdata) +{ + proxyPlugin plugin = {}; + + plugin.name = plugin_name; + plugin.description = plugin_desc; + + plugin.ServerSessionStarted = filter_server_session_started; + plugin.ServerSessionEnd = filter_server_session_end; + + plugin.ClientPreConnect = filter_client_pre_connect; + + plugin.StaticChannelToIntercept = filter_static_channel_intercept_list; + plugin.DynChannelToIntercept = filter_dyn_channel_intercept_list; + plugin.DynChannelIntercept = filter_dyn_channel_intercept; + + plugin.custom = plugins_manager; + if (!plugin.custom) + return FALSE; + plugin.userdata = userdata; + + return plugins_manager->RegisterPlugin(plugins_manager, &plugin); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5502afa4f93cf215fd6cc45382c7ec0eb5476eaf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/CMakeLists.txt @@ -0,0 +1,47 @@ +# +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Proxy Server Demo C++ Module +# +# Copyright 2019 Kobi Mizrachi +# Copyright 2021 Armin Novak +# 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. +# + +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(proxy-demo-plugin VERSION ${FREERDP_DEFAULT_PROJECT_VERSION} LANGUAGES CXX) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../../cmake/) +include(CommonConfigOptions) +include(CXXCompilerFlags) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(SRCS demo.cpp) +addtargetwithresourcefile(${PROJECT_NAME} FALSE "${PROJECT_VERSION}" SRCS FALSE) + +target_link_libraries(${PROJECT_NAME} winpr) + +install(TARGETS ${PROJECT_NAME} DESTINATION ${FREERDP_PROXY_PLUGINDIR}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/demo.cpp b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/demo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cfff27dc2a52edb16ec4cba7324c2b924f9be73 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/demo/demo.cpp @@ -0,0 +1,422 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server Demo C++ Module + * + * Copyright 2019 Kobi Mizrachi + * Copyright 2021 Armin Novak + * 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. + */ + +#include + +#include +#include +#include + +#define TAG MODULE_TAG("demo") + +struct demo_custom_data +{ + proxyPluginsManager* mgr; + int somesetting; +}; + +static constexpr char plugin_name[] = "demo"; +static constexpr char plugin_desc[] = "this is a test plugin"; + +static BOOL demo_plugin_unload(proxyPlugin* plugin) +{ + WINPR_ASSERT(plugin); + + std::cout << "C++ demo plugin: unloading..." << std::endl; + + /* Here we have to free up our custom data storage. */ + if (plugin) + delete static_cast(plugin->custom); + + return TRUE; +} + +static BOOL demo_client_init_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_uninit_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_pre_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_post_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_post_disconnect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_x509_certificate(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_login_failure(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_end_paint(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_client_redirect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_server_post_connect(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_server_peer_activate(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_server_channels_init(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_server_channels_free(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_server_session_end(proxyPlugin* plugin, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(custom); + + WLog_INFO(TAG, "called"); + return TRUE; +} + +static BOOL demo_filter_keyboard_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + proxyPluginsManager* mgr = nullptr; + auto event_data = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + mgr = plugin->mgr; + WINPR_ASSERT(mgr); + + if (event_data == nullptr) + return FALSE; + + if (event_data->rdp_scan_code == RDP_SCANCODE_KEY_B) + { + /* user typed 'B', that means bye :) */ + std::cout << "C++ demo plugin: aborting connection" << std::endl; + mgr->AbortConnect(mgr, pdata); + } + + return TRUE; +} + +static BOOL demo_filter_unicode_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + proxyPluginsManager* mgr = nullptr; + auto event_data = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + mgr = plugin->mgr; + WINPR_ASSERT(mgr); + + if (event_data == nullptr) + return FALSE; + + if (event_data->code == 'b') + { + /* user typed 'B', that means bye :) */ + std::cout << "C++ demo plugin: aborting connection" << std::endl; + mgr->AbortConnect(mgr, pdata); + } + + return TRUE; +} + +static BOOL demo_mouse_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + auto event_data = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WLog_INFO(TAG, "called %p", event_data); + return TRUE; +} + +static BOOL demo_mouse_ex_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + auto event_data = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WLog_INFO(TAG, "called %p", event_data); + return TRUE; +} + +static BOOL demo_client_channel_data(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + const auto* channel = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + WLog_INFO(TAG, "%s [0x%04" PRIx16 "] got %" PRIuz, channel->channel_name, channel->channel_id, + channel->data_len); + return TRUE; +} + +static BOOL demo_server_channel_data(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + const auto* channel = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + WLog_WARN(TAG, "%s [0x%04" PRIx16 "] got %" PRIuz, channel->channel_name, channel->channel_id, + channel->data_len); + return TRUE; +} + +static BOOL demo_dynamic_channel_create(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + const auto* channel = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + WLog_WARN(TAG, "%s [0x%04" PRIx16 "]", channel->channel_name, channel->channel_id); + return TRUE; +} + +static BOOL demo_server_fetch_target_addr(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + auto event_data = static_cast(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WLog_INFO(TAG, "called %p", event_data); + return TRUE; +} + +static BOOL demo_server_peer_logon(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + auto info = static_cast(param); + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(info); + WINPR_ASSERT(info->identity); + + WLog_INFO(TAG, "%d", info->automatic); + return TRUE; +} + +static BOOL demo_dyn_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + WLog_INFO(TAG, "%s: %p", __func__, data); + return TRUE; +} + +static BOOL demo_static_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + WLog_INFO(TAG, "%s: %p", __func__, data); + return TRUE; +} + +static BOOL demo_dyn_channel_intercept(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + WLog_INFO(TAG, "%s: %p", __func__, data); + return TRUE; +} + +#ifdef __cplusplus +extern "C" +{ +#endif + FREERDP_API BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, void* userdata); +#ifdef __cplusplus +} +#endif + +BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, void* userdata) +{ + struct demo_custom_data* custom = nullptr; + proxyPlugin plugin = {}; + + plugin.name = plugin_name; + plugin.description = plugin_desc; + plugin.PluginUnload = demo_plugin_unload; + plugin.ClientInitConnect = demo_client_init_connect; + plugin.ClientUninitConnect = demo_client_uninit_connect; + plugin.ClientPreConnect = demo_client_pre_connect; + plugin.ClientPostConnect = demo_client_post_connect; + plugin.ClientPostDisconnect = demo_client_post_disconnect; + plugin.ClientX509Certificate = demo_client_x509_certificate; + plugin.ClientLoginFailure = demo_client_login_failure; + plugin.ClientEndPaint = demo_client_end_paint; + plugin.ClientRedirect = demo_client_redirect; + plugin.ServerPostConnect = demo_server_post_connect; + plugin.ServerPeerActivate = demo_server_peer_activate; + plugin.ServerChannelsInit = demo_server_channels_init; + plugin.ServerChannelsFree = demo_server_channels_free; + plugin.ServerSessionEnd = demo_server_session_end; + plugin.KeyboardEvent = demo_filter_keyboard_event; + plugin.UnicodeEvent = demo_filter_unicode_event; + plugin.MouseEvent = demo_mouse_event; + plugin.MouseExEvent = demo_mouse_ex_event; + plugin.ClientChannelData = demo_client_channel_data; + plugin.ServerChannelData = demo_server_channel_data; + plugin.DynamicChannelCreate = demo_dynamic_channel_create; + plugin.ServerFetchTargetAddr = demo_server_fetch_target_addr; + plugin.ServerPeerLogon = demo_server_peer_logon; + + plugin.StaticChannelToIntercept = demo_static_channel_intercept_list; + plugin.DynChannelToIntercept = demo_dyn_channel_intercept_list; + plugin.DynChannelIntercept = demo_dyn_channel_intercept; + + plugin.userdata = userdata; + + custom = new (struct demo_custom_data); + if (!custom) + return FALSE; + + custom->mgr = plugins_manager; + custom->somesetting = 42; + + plugin.custom = custom; + plugin.userdata = userdata; + + return plugins_manager->RegisterPlugin(plugins_manager, &plugin); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3eb6f6ed4181b1a9d79b813abbe8746ea3a98160 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/CMakeLists.txt @@ -0,0 +1,46 @@ +# +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Proxy Server Demo C++ Module +# +# Copyright 2023 Armin Novak +# Copyright 2023 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. +# + +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(proxy-dyn-channel-dump-plugin VERSION ${FREERDP_DEFAULT_PROJECT_VERSION} LANGUAGES CXX) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../../cmake/) +include(CommonConfigOptions) +include(CXXCompilerFlags) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(SRCS dyn-channel-dump.cpp) +addtargetwithresourcefile(${PROJECT_NAME} FALSE "${PROJECT_VERSION}" SRCS FALSE) + +target_link_libraries(${PROJECT_NAME} PRIVATE winpr freerdp freerdp-client freerdp-server freerdp-server-proxy) + +install(TARGETS ${PROJECT_NAME} DESTINATION ${FREERDP_PROXY_PLUGINDIR}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/dyn-channel-dump.cpp b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/dyn-channel-dump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40fb12f0080458f610bebbd52d4d0faef76b0248 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/modules/dyn-channel-dump/dyn-channel-dump.cpp @@ -0,0 +1,449 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server persist-bitmap-filter Module + * + * this module is designed to deactivate all persistent bitmap cache settings a + * client might send. + * + * Copyright 2023 Armin Novak + * Copyright 2023 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if __has_include() +#include +namespace fs = std::filesystem; +#elif __has_include() +#include +namespace fs = std::experimental::filesystem; +#else +#error Could not find system header "" or "" +#endif + +#include +#include + +#include +#include +#include + +#define TAG MODULE_TAG("dyn-channel-dump") + +static constexpr char plugin_name[] = "dyn-channel-dump"; +static constexpr char plugin_desc[] = + "This plugin dumps configurable dynamic channel data to a file."; + +static const std::vector& plugin_static_intercept() +{ + static std::vector vec; + if (vec.empty()) + vec.emplace_back(DRDYNVC_SVC_CHANNEL_NAME); + return vec; +} + +static constexpr char key_path[] = "path"; +static constexpr char key_channels[] = "channels"; + +class PluginData +{ + public: + explicit PluginData(proxyPluginsManager* mgr) : _mgr(mgr) + { + } + + [[nodiscard]] proxyPluginsManager* mgr() const + { + return _mgr; + } + + uint64_t session() + { + return _sessionid++; + } + + private: + proxyPluginsManager* _mgr; + uint64_t _sessionid{ 0 }; +}; + +class ChannelData +{ + public: + ChannelData(const std::string& base, std::vector list, uint64_t sessionid) + : _base(base), _channels_to_dump(std::move(list)), _session_id(sessionid) + { + char str[64] = {}; + (void)_snprintf(str, sizeof(str), "session-%016" PRIx64, _session_id); + _base /= str; + } + + bool add(const std::string& name, bool back) + { + std::lock_guard guard(_mux); + if (_map.find(name) == _map.end()) + { + WLog_INFO(TAG, "adding '%s' to dump list", name.c_str()); + _map.insert({ name, 0 }); + } + return true; + } + + std::ofstream stream(const std::string& name, bool back) + { + std::lock_guard guard(_mux); + auto& atom = _map[name]; + auto count = atom++; + auto path = filepath(name, back, count); + WLog_DBG(TAG, "[%s] writing file '%s'", name.c_str(), path.c_str()); + return std::ofstream(path); + } + + [[nodiscard]] bool dump_enabled(const std::string& name) const + { + if (name.empty()) + { + WLog_WARN(TAG, "empty dynamic channel name, skipping"); + return false; + } + + auto enabled = std::find(_channels_to_dump.begin(), _channels_to_dump.end(), name) != + _channels_to_dump.end(); + WLog_DBG(TAG, "channel '%s' dumping %s", name.c_str(), enabled ? "enabled" : "disabled"); + return enabled; + } + + bool ensure_path_exists() + { + if (!fs::exists(_base)) + { + if (!fs::create_directories(_base)) + { + WLog_ERR(TAG, "Failed to create dump directory %s", _base.c_str()); + return false; + } + } + else if (!fs::is_directory(_base)) + { + WLog_ERR(TAG, "dump path %s is not a directory", _base.c_str()); + return false; + } + return true; + } + + bool create() + { + if (!ensure_path_exists()) + return false; + + if (_channels_to_dump.empty()) + { + WLog_ERR(TAG, "Empty configuration entry [%s/%s], can not continue", plugin_name, + key_channels); + return false; + } + return true; + } + + [[nodiscard]] uint64_t session() const + { + return _session_id; + } + + private: + [[nodiscard]] fs::path filepath(const std::string& channel, bool back, uint64_t count) const + { + auto name = idstr(channel, back); + char cstr[32] = {}; + (void)_snprintf(cstr, sizeof(cstr), "%016" PRIx64 "-", count); + auto path = _base / cstr; + path += name; + path += ".dump"; + return path; + } + + [[nodiscard]] static std::string idstr(const std::string& name, bool back) + { + std::stringstream ss; + ss << name << "."; + if (back) + ss << "back"; + else + ss << "front"; + return ss.str(); + } + + fs::path _base; + std::vector _channels_to_dump; + + std::mutex _mux; + std::map _map; + uint64_t _session_id; +}; + +static PluginData* dump_get_plugin_data(proxyPlugin* plugin) +{ + WINPR_ASSERT(plugin); + + auto plugindata = static_cast(plugin->custom); + WINPR_ASSERT(plugindata); + return plugindata; +} + +static ChannelData* dump_get_plugin_data(proxyPlugin* plugin, proxyData* pdata) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto plugindata = dump_get_plugin_data(plugin); + WINPR_ASSERT(plugindata); + + auto mgr = plugindata->mgr(); + WINPR_ASSERT(mgr); + + WINPR_ASSERT(mgr->GetPluginData); + return static_cast(mgr->GetPluginData(mgr, plugin_name, pdata)); +} + +static BOOL dump_set_plugin_data(proxyPlugin* plugin, proxyData* pdata, ChannelData* data) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto plugindata = dump_get_plugin_data(plugin); + WINPR_ASSERT(plugindata); + + auto mgr = plugindata->mgr(); + WINPR_ASSERT(mgr); + + auto cdata = dump_get_plugin_data(plugin, pdata); + delete cdata; + + WINPR_ASSERT(mgr->SetPluginData); + return mgr->SetPluginData(mgr, plugin_name, pdata, data); +} + +static bool dump_channel_enabled(proxyPlugin* plugin, proxyData* pdata, const std::string& name) +{ + auto config = dump_get_plugin_data(plugin, pdata); + if (!config) + { + WLog_ERR(TAG, "Missing channel data"); + return false; + } + return config->dump_enabled(name); +} + +static BOOL dump_dyn_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + data->intercept = dump_channel_enabled(plugin, pdata, data->name); + if (data->intercept) + { + auto cdata = dump_get_plugin_data(plugin, pdata); + if (!cdata) + return FALSE; + + if (!cdata->add(data->name, false)) + { + WLog_ERR(TAG, "failed to create files for '%s'", data->name); + } + if (!cdata->add(data->name, true)) + { + WLog_ERR(TAG, "failed to create files for '%s'", data->name); + } + WLog_INFO(TAG, "Dumping channel '%s'", data->name); + } + return TRUE; +} + +static BOOL dump_static_channel_intercept_list(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + auto intercept = std::find(plugin_static_intercept().begin(), plugin_static_intercept().end(), + data->name) != plugin_static_intercept().end(); + if (intercept) + { + WLog_INFO(TAG, "intercepting channel '%s'", data->name); + data->intercept = TRUE; + } + + return TRUE; +} + +static BOOL dump_dyn_channel_intercept(proxyPlugin* plugin, proxyData* pdata, void* arg) +{ + auto data = static_cast(arg); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(data); + + data->result = PF_CHANNEL_RESULT_PASS; + if (dump_channel_enabled(plugin, pdata, data->name)) + { + WLog_DBG(TAG, "intercepting channel '%s'", data->name); + auto cdata = dump_get_plugin_data(plugin, pdata); + if (!cdata) + { + WLog_ERR(TAG, "Missing channel data"); + return FALSE; + } + + if (!cdata->ensure_path_exists()) + return FALSE; + + auto stream = cdata->stream(data->name, data->isBackData); + auto buffer = reinterpret_cast(Stream_ConstBuffer(data->data)); + if (!stream.is_open() || !stream.good()) + { + WLog_ERR(TAG, "Could not write to stream"); + return FALSE; + } + const auto s = Stream_Length(data->data); + if (s > std::numeric_limits::max()) + { + WLog_ERR(TAG, "Stream length %" PRIuz " exceeds std::streamsize::max", s); + return FALSE; + } + stream.write(buffer, static_cast(s)); + if (stream.fail()) + { + WLog_ERR(TAG, "Could not write to stream"); + return FALSE; + } + stream.flush(); + } + + return TRUE; +} + +static std::vector split(const std::string& input, const std::string& regex) +{ + // passing -1 as the submatch index parameter performs splitting + std::regex re(regex); + std::sregex_token_iterator first{ input.begin(), input.end(), re, -1 }; + std::sregex_token_iterator last; + return { first, last }; +} + +static BOOL dump_session_started(proxyPlugin* plugin, proxyData* pdata, void* /*unused*/) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto custom = dump_get_plugin_data(plugin); + WINPR_ASSERT(custom); + + auto config = pdata->config; + WINPR_ASSERT(config); + + auto cpath = pf_config_get(config, plugin_name, key_path); + if (!cpath) + { + WLog_ERR(TAG, "Missing configuration entry [%s/%s], can not continue", plugin_name, + key_path); + return FALSE; + } + auto cchannels = pf_config_get(config, plugin_name, key_channels); + if (!cchannels) + { + WLog_ERR(TAG, "Missing configuration entry [%s/%s], can not continue", plugin_name, + key_channels); + return FALSE; + } + + std::string path(cpath); + std::string channels(cchannels); + std::vector list = split(channels, "[;,]"); + auto cfg = new ChannelData(path, std::move(list), custom->session()); + if (!cfg || !cfg->create()) + { + delete cfg; + return FALSE; + } + + dump_set_plugin_data(plugin, pdata, cfg); + + WLog_DBG(TAG, "starting session dump %" PRIu64, cfg->session()); + return TRUE; +} + +static BOOL dump_session_end(proxyPlugin* plugin, proxyData* pdata, void* /*unused*/) +{ + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + + auto cfg = dump_get_plugin_data(plugin, pdata); + if (cfg) + WLog_DBG(TAG, "ending session dump %" PRIu64, cfg->session()); + dump_set_plugin_data(plugin, pdata, nullptr); + return TRUE; +} + +static BOOL dump_unload(proxyPlugin* plugin) +{ + if (!plugin) + return TRUE; + delete static_cast(plugin->custom); + return TRUE; +} + +extern "C" FREERDP_API BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, + void* userdata); + +BOOL proxy_module_entry_point(proxyPluginsManager* plugins_manager, void* userdata) +{ + proxyPlugin plugin = {}; + + plugin.name = plugin_name; + plugin.description = plugin_desc; + + plugin.PluginUnload = dump_unload; + plugin.ServerSessionStarted = dump_session_started; + plugin.ServerSessionEnd = dump_session_end; + + plugin.StaticChannelToIntercept = dump_static_channel_intercept_list; + plugin.DynChannelToIntercept = dump_dyn_channel_intercept_list; + plugin.DynChannelIntercept = dump_dyn_channel_intercept; + + plugin.custom = new PluginData(plugins_manager); + if (!plugin.custom) + return FALSE; + plugin.userdata = userdata; + + return plugins_manager->RegisterPlugin(plugins_manager, &plugin); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.c new file mode 100644 index 0000000000000000000000000000000000000000..23473d502b08c54f12ab62565d295c458e92db62 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.c @@ -0,0 +1,359 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2022 David Fort + * + * 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 +#include + +#include +#include + +#include "proxy_modules.h" +#include "pf_channel.h" + +#define TAG PROXY_TAG("channel") + +/** @brief a tracker for channel packets */ +struct _ChannelStateTracker +{ + pServerStaticChannelContext* channel; + ChannelTrackerMode mode; + wStream* currentPacket; + size_t currentPacketReceived; + size_t currentPacketSize; + size_t currentPacketFragments; + + ChannelTrackerPeekFn peekFn; + void* trackerData; + proxyData* pdata; +}; + +static BOOL channelTracker_resetCurrentPacket(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + + BOOL create = TRUE; + if (tracker->currentPacket) + { + const size_t cap = Stream_Capacity(tracker->currentPacket); + if (cap < 1ULL * 1000ULL * 1000ULL) + create = FALSE; + else + Stream_Free(tracker->currentPacket, TRUE); + } + + if (create) + tracker->currentPacket = Stream_New(NULL, 10ULL * 1024ULL); + if (!tracker->currentPacket) + return FALSE; + Stream_SetPosition(tracker->currentPacket, 0); + return TRUE; +} + +ChannelStateTracker* channelTracker_new(pServerStaticChannelContext* channel, + ChannelTrackerPeekFn fn, void* data) +{ + ChannelStateTracker* ret = calloc(1, sizeof(ChannelStateTracker)); + if (!ret) + return ret; + + WINPR_ASSERT(fn); + + ret->channel = channel; + ret->peekFn = fn; + + if (!channelTracker_setCustomData(ret, data)) + goto fail; + + if (!channelTracker_resetCurrentPacket(ret)) + goto fail; + + return ret; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + channelTracker_free(ret); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +PfChannelResult channelTracker_update(ChannelStateTracker* tracker, const BYTE* xdata, size_t xsize, + UINT32 flags, size_t totalSize) +{ + PfChannelResult result = PF_CHANNEL_RESULT_ERROR; + BOOL firstPacket = (flags & CHANNEL_FLAG_FIRST) != 0; + BOOL lastPacket = (flags & CHANNEL_FLAG_LAST) != 0; + + WINPR_ASSERT(tracker); + + WLog_VRB(TAG, "channelTracker_update(%s): sz=%" PRIuz " first=%d last=%d", + tracker->channel->channel_name, xsize, firstPacket, lastPacket); + if (flags & CHANNEL_FLAG_FIRST) + { + if (!channelTracker_resetCurrentPacket(tracker)) + return FALSE; + channelTracker_setCurrentPacketSize(tracker, totalSize); + tracker->currentPacketReceived = 0; + tracker->currentPacketFragments = 0; + } + + { + const size_t currentPacketSize = channelTracker_getCurrentPacketSize(tracker); + if (tracker->currentPacketReceived + xsize > currentPacketSize) + WLog_INFO(TAG, "cumulated size is bigger (%" PRIuz ") than total size (%" PRIuz ")", + tracker->currentPacketReceived + xsize, currentPacketSize); + } + + tracker->currentPacketReceived += xsize; + tracker->currentPacketFragments++; + + switch (channelTracker_getMode(tracker)) + { + case CHANNEL_TRACKER_PEEK: + { + wStream* currentPacket = channelTracker_getCurrentPacket(tracker); + if (!Stream_EnsureRemainingCapacity(currentPacket, xsize)) + return PF_CHANNEL_RESULT_ERROR; + + Stream_Write(currentPacket, xdata, xsize); + + WINPR_ASSERT(tracker->peekFn); + result = tracker->peekFn(tracker, firstPacket, lastPacket); + } + break; + case CHANNEL_TRACKER_PASS: + result = PF_CHANNEL_RESULT_PASS; + break; + case CHANNEL_TRACKER_DROP: + result = PF_CHANNEL_RESULT_DROP; + break; + default: + break; + } + + if (lastPacket) + { + const size_t currentPacketSize = channelTracker_getCurrentPacketSize(tracker); + channelTracker_setMode(tracker, CHANNEL_TRACKER_PEEK); + + if (tracker->currentPacketReceived != currentPacketSize) + WLog_INFO(TAG, "cumulated size(%" PRIuz ") does not match total size (%" PRIuz ")", + tracker->currentPacketReceived, currentPacketSize); + } + + return result; +} + +void channelTracker_free(ChannelStateTracker* t) +{ + if (!t) + return; + + Stream_Free(t->currentPacket, TRUE); + free(t); +} + +/** + * Flushes the current accumulated tracker content, if it's the first packet, then + * when can just return that the packet shall be passed, otherwise to have to refragment + * the accumulated current packet. + */ + +PfChannelResult channelTracker_flushCurrent(ChannelStateTracker* t, BOOL first, BOOL last, + BOOL toBack) +{ + proxyData* pdata = NULL; + pServerContext* ps = NULL; + pServerStaticChannelContext* channel = NULL; + UINT32 flags = CHANNEL_FLAG_FIRST; + BOOL r = 0; + const char* direction = toBack ? "F->B" : "B->F"; + const size_t currentPacketSize = channelTracker_getCurrentPacketSize(t); + wStream* currentPacket = channelTracker_getCurrentPacket(t); + + WINPR_ASSERT(t); + + WLog_VRB(TAG, "channelTracker_flushCurrent(%s): %s sz=%" PRIuz " first=%d last=%d", + t->channel->channel_name, direction, Stream_GetPosition(currentPacket), first, last); + + if (first) + return PF_CHANNEL_RESULT_PASS; + + pdata = t->pdata; + channel = t->channel; + if (last) + flags |= CHANNEL_FLAG_LAST; + + if (toBack) + { + proxyChannelDataEventInfo ev = { 0 }; + + ev.channel_id = WINPR_ASSERTING_INT_CAST(UINT16, channel->front_channel_id); + ev.channel_name = channel->channel_name; + ev.data = Stream_Buffer(currentPacket); + ev.data_len = Stream_GetPosition(currentPacket); + ev.flags = flags; + ev.total_size = currentPacketSize; + + if (!pdata->pc->sendChannelData) + return PF_CHANNEL_RESULT_ERROR; + + return pdata->pc->sendChannelData(pdata->pc, &ev) ? PF_CHANNEL_RESULT_DROP + : PF_CHANNEL_RESULT_ERROR; + } + + ps = pdata->ps; + r = ps->context.peer->SendChannelPacket( + ps->context.peer, WINPR_ASSERTING_INT_CAST(UINT16, channel->front_channel_id), + currentPacketSize, flags, Stream_Buffer(currentPacket), Stream_GetPosition(currentPacket)); + + return r ? PF_CHANNEL_RESULT_DROP : PF_CHANNEL_RESULT_ERROR; +} + +static PfChannelResult pf_channel_generic_back_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + proxyChannelDataEventInfo ev = { 0 }; + + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + switch (channel->channelMode) + { + case PF_UTILS_CHANNEL_PASSTHROUGH: + ev.channel_id = WINPR_ASSERTING_INT_CAST(UINT16, channel->back_channel_id); + ev.channel_name = channel->channel_name; + ev.data = xdata; + ev.data_len = xsize; + ev.flags = flags; + ev.total_size = totalSize; + + if (!pf_modules_run_filter(pdata->module, FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_DATA, + pdata, &ev)) + return PF_CHANNEL_RESULT_DROP; /* Silently drop */ + + return PF_CHANNEL_RESULT_PASS; + + case PF_UTILS_CHANNEL_INTERCEPT: + /* TODO */ + case PF_UTILS_CHANNEL_BLOCK: + default: + return PF_CHANNEL_RESULT_DROP; + } +} + +static PfChannelResult pf_channel_generic_front_data(proxyData* pdata, + const pServerStaticChannelContext* channel, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + proxyChannelDataEventInfo ev = { 0 }; + + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + switch (channel->channelMode) + { + case PF_UTILS_CHANNEL_PASSTHROUGH: + ev.channel_id = WINPR_ASSERTING_INT_CAST(UINT16, channel->front_channel_id); + ev.channel_name = channel->channel_name; + ev.data = xdata; + ev.data_len = xsize; + ev.flags = flags; + ev.total_size = totalSize; + + if (!pf_modules_run_filter(pdata->module, FILTER_TYPE_SERVER_PASSTHROUGH_CHANNEL_DATA, + pdata, &ev)) + return PF_CHANNEL_RESULT_DROP; /* Silently drop */ + + return PF_CHANNEL_RESULT_PASS; + + case PF_UTILS_CHANNEL_INTERCEPT: + /* TODO */ + case PF_UTILS_CHANNEL_BLOCK: + default: + return PF_CHANNEL_RESULT_DROP; + } +} + +BOOL pf_channel_setup_generic(pServerStaticChannelContext* channel) +{ + WINPR_ASSERT(channel); + channel->onBackData = pf_channel_generic_back_data; + channel->onFrontData = pf_channel_generic_front_data; + return TRUE; +} + +BOOL channelTracker_setMode(ChannelStateTracker* tracker, ChannelTrackerMode mode) +{ + WINPR_ASSERT(tracker); + tracker->mode = mode; + return TRUE; +} + +ChannelTrackerMode channelTracker_getMode(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + return tracker->mode; +} + +BOOL channelTracker_setPData(ChannelStateTracker* tracker, proxyData* pdata) +{ + WINPR_ASSERT(tracker); + tracker->pdata = pdata; + return TRUE; +} + +proxyData* channelTracker_getPData(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + return tracker->pdata; +} + +wStream* channelTracker_getCurrentPacket(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + return tracker->currentPacket; +} + +BOOL channelTracker_setCustomData(ChannelStateTracker* tracker, void* data) +{ + WINPR_ASSERT(tracker); + tracker->trackerData = data; + return TRUE; +} + +void* channelTracker_getCustomData(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + return tracker->trackerData; +} + +size_t channelTracker_getCurrentPacketSize(ChannelStateTracker* tracker) +{ + WINPR_ASSERT(tracker); + return tracker->currentPacketSize; +} + +BOOL channelTracker_setCurrentPacketSize(ChannelStateTracker* tracker, size_t size) +{ + WINPR_ASSERT(tracker); + tracker->currentPacketSize = size; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..7414b61fcc0bb5ec391e582f89dfe5f46d2b5bf0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_channel.h @@ -0,0 +1,64 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * + * Copyright 2022 David Fort + * + * 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 SERVER_PROXY_PF_CHANNEL_H_ +#define SERVER_PROXY_PF_CHANNEL_H_ + +#include + +/** @brief operating mode of a channel tracker */ +typedef enum +{ + CHANNEL_TRACKER_PEEK, /*!< inquiring content, accumulating packet fragments */ + CHANNEL_TRACKER_PASS, /*!< pass all the fragments of the current packet */ + CHANNEL_TRACKER_DROP /*!< drop all the fragments of the current packet */ +} ChannelTrackerMode; + +typedef struct _ChannelStateTracker ChannelStateTracker; +typedef PfChannelResult (*ChannelTrackerPeekFn)(ChannelStateTracker* tracker, BOOL first, + BOOL lastPacket); + +void channelTracker_free(ChannelStateTracker* t); + +WINPR_ATTR_MALLOC(channelTracker_free, 1) +ChannelStateTracker* channelTracker_new(pServerStaticChannelContext* channel, + ChannelTrackerPeekFn fn, void* data); + +BOOL channelTracker_setMode(ChannelStateTracker* tracker, ChannelTrackerMode mode); +ChannelTrackerMode channelTracker_getMode(ChannelStateTracker* tracker); + +BOOL channelTracker_setPData(ChannelStateTracker* tracker, proxyData* pdata); +proxyData* channelTracker_getPData(ChannelStateTracker* tracker); + +BOOL channelTracker_setCustomData(ChannelStateTracker* tracker, void* data); +void* channelTracker_getCustomData(ChannelStateTracker* tracker); + +wStream* channelTracker_getCurrentPacket(ChannelStateTracker* tracker); + +size_t channelTracker_getCurrentPacketSize(ChannelStateTracker* tracker); +BOOL channelTracker_setCurrentPacketSize(ChannelStateTracker* tracker, size_t size); + +PfChannelResult channelTracker_update(ChannelStateTracker* tracker, const BYTE* xdata, size_t xsize, + UINT32 flags, size_t totalSize); + +PfChannelResult channelTracker_flushCurrent(ChannelStateTracker* t, BOOL first, BOOL last, + BOOL toBack); + +BOOL pf_channel_setup_generic(pServerStaticChannelContext* channel); + +#endif /* SERVER_PROXY_PF_CHANNEL_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.c new file mode 100644 index 0000000000000000000000000000000000000000..ed79a0bfaa6a850b2e54d61d1b602e2cbfd4b4b8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.c @@ -0,0 +1,1112 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "pf_client.h" +#include "pf_channel.h" +#include +#include "pf_update.h" +#include "pf_input.h" +#include +#include "proxy_modules.h" +#include "pf_utils.h" +#include "channels/pf_channel_rdpdr.h" +#include "channels/pf_channel_smartcard.h" + +#define TAG PROXY_TAG("client") + +static void channel_data_free(void* obj); +static BOOL proxy_server_reactivate(rdpContext* ps, const rdpContext* pc) +{ + WINPR_ASSERT(ps); + WINPR_ASSERT(pc); + + if (!pf_context_copy_settings(ps->settings, pc->settings)) + return FALSE; + + /* + * DesktopResize causes internal function rdp_server_reactivate to be called, + * which causes the reactivation. + */ + WINPR_ASSERT(ps->update); + if (!ps->update->DesktopResize(ps)) + return FALSE; + + return TRUE; +} + +static void pf_client_on_error_info(void* ctx, const ErrorInfoEventArgs* e) +{ + pClientContext* pc = (pClientContext*)ctx; + pServerContext* ps = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + WINPR_ASSERT(e); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + + if (e->code == ERRINFO_NONE) + return; + + PROXY_LOG_WARN(TAG, pc, "received ErrorInfo PDU. code=0x%08" PRIu32 ", message: %s", e->code, + freerdp_get_error_info_string(e->code)); + + /* forward error back to client */ + freerdp_set_error_info(ps->context.rdp, e->code); + freerdp_send_error_info(ps->context.rdp); +} + +static void pf_client_on_activated(void* ctx, const ActivatedEventArgs* e) +{ + pClientContext* pc = (pClientContext*)ctx; + pServerContext* ps = NULL; + freerdp_peer* peer = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + WINPR_ASSERT(e); + + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + peer = ps->context.peer; + WINPR_ASSERT(peer); + WINPR_ASSERT(peer->context); + + PROXY_LOG_INFO(TAG, pc, "client activated, registering server input callbacks"); + + /* Register server input/update callbacks only after proxy client is fully activated */ + pf_server_register_input_callbacks(peer->context->input); + pf_server_register_update_callbacks(peer->context->update); +} + +static BOOL pf_client_load_rdpsnd(pClientContext* pc) +{ + rdpContext* context = (rdpContext*)pc; + pServerContext* ps = NULL; + const proxyConfig* config = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + config = pc->pdata->config; + WINPR_ASSERT(config); + + /* + * if AudioOutput is enabled in proxy and client connected with rdpsnd, use proxy as rdpsnd + * backend. Otherwise, use sys:fake. + */ + if (!freerdp_static_channel_collection_find(context->settings, RDPSND_CHANNEL_NAME)) + { + const char* params[2] = { RDPSND_CHANNEL_NAME, "sys:fake" }; + + if (!freerdp_client_add_static_channel(context->settings, ARRAYSIZE(params), params)) + return FALSE; + } + + return TRUE; +} + +static BOOL pf_client_use_peer_load_balance_info(pClientContext* pc) +{ + pServerContext* ps = NULL; + rdpSettings* settings = NULL; + DWORD lb_info_len = 0; + const char* lb_info = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + settings = pc->context.settings; + WINPR_ASSERT(settings); + + lb_info = freerdp_nego_get_routing_token(&ps->context, &lb_info_len); + if (!lb_info) + return TRUE; + + return freerdp_settings_set_pointer_len(settings, FreeRDP_LoadBalanceInfo, lb_info, + lb_info_len); +} + +static BOOL str_is_empty(const char* str) +{ + if (!str) + return TRUE; + if (strlen(str) == 0) + return TRUE; + return FALSE; +} + +static BOOL pf_client_use_proxy_smartcard_auth(const rdpSettings* settings) +{ + BOOL enable = freerdp_settings_get_bool(settings, FreeRDP_SmartcardLogon); + const char* key = freerdp_settings_get_string(settings, FreeRDP_SmartcardPrivateKey); + const char* cert = freerdp_settings_get_string(settings, FreeRDP_SmartcardCertificate); + + if (!enable) + return FALSE; + + if (str_is_empty(key)) + return FALSE; + + if (str_is_empty(cert)) + return FALSE; + + return TRUE; +} + +static BOOL freerdp_client_load_static_channel_addin(rdpChannels* channels, rdpSettings* settings, + const char* name, void* data) +{ + PVIRTUALCHANNELENTRY entry = NULL; + PVIRTUALCHANNELENTRY lentry = freerdp_load_channel_addin_entry( + name, NULL, NULL, FREERDP_ADDIN_CHANNEL_STATIC | FREERDP_ADDIN_CHANNEL_ENTRYEX); + PVIRTUALCHANNELENTRYEX entryEx = WINPR_FUNC_PTR_CAST(lentry, PVIRTUALCHANNELENTRYEX); + if (!entryEx) + entry = freerdp_load_channel_addin_entry(name, NULL, NULL, FREERDP_ADDIN_CHANNEL_STATIC); + + if (entryEx) + { + if (freerdp_channels_client_load_ex(channels, settings, entryEx, data) == 0) + { + WLog_INFO(TAG, "loading channelEx %s", name); + return TRUE; + } + } + else if (entry) + { + if (freerdp_channels_client_load(channels, settings, entry, data) == 0) + { + WLog_INFO(TAG, "loading channel %s", name); + return TRUE; + } + } + + return FALSE; +} + +static BOOL pf_client_pre_connect(freerdp* instance) +{ + pClientContext* pc = NULL; + pServerContext* ps = NULL; + const proxyConfig* config = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(instance); + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + config = ps->pdata->config; + WINPR_ASSERT(config); + settings = instance->context->settings; + WINPR_ASSERT(settings); + + /* + * as the client's settings are copied from the server's, GlyphSupportLevel might not be + * GLYPH_SUPPORT_NONE. the proxy currently do not support GDI & GLYPH_SUPPORT_CACHE, so + * GlyphCacheSupport must be explicitly set to GLYPH_SUPPORT_NONE. + * + * Also, OrderSupport need to be zeroed, because it is currently not supported. + */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_GlyphSupportLevel, GLYPH_SUPPORT_NONE)) + return FALSE; + + void* OrderSupport = freerdp_settings_get_pointer_writable(settings, FreeRDP_OrderSupport); + ZeroMemory(OrderSupport, 32); + + if (WTSVirtualChannelManagerIsChannelJoined(ps->vcm, DRDYNVC_SVC_CHANNEL_NAME)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportDynamicChannels, TRUE)) + return FALSE; + } + + /* Multimon */ + if (!freerdp_settings_set_bool(settings, FreeRDP_UseMultimon, TRUE)) + return FALSE; + + /* Sound */ + if (!freerdp_settings_set_bool(settings, FreeRDP_AudioCapture, config->AudioInput) || + !freerdp_settings_set_bool(settings, FreeRDP_AudioPlayback, config->AudioOutput) || + !freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, + config->DeviceRedirection) || + !freerdp_settings_set_bool(settings, FreeRDP_SupportDisplayControl, + config->DisplayControl) || + !freerdp_settings_set_bool(settings, FreeRDP_MultiTouchInput, config->Multitouch)) + return FALSE; + + if (config->RemoteApp) + { + if (WTSVirtualChannelManagerIsChannelJoined(ps->vcm, RAIL_SVC_CHANNEL_NAME)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteApplicationMode, TRUE)) + return FALSE; + } + } + + if (config->DeviceRedirection) + { + if (WTSVirtualChannelManagerIsChannelJoined(ps->vcm, RDPDR_SVC_CHANNEL_NAME)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + } + } + + /* Display control */ + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportDisplayControl, config->DisplayControl)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DynamicResolutionUpdate, + config->DisplayControl)) + return FALSE; + + if (WTSVirtualChannelManagerIsChannelJoined(ps->vcm, ENCOMSP_SVC_CHANNEL_NAME)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_EncomspVirtualChannel, TRUE)) + return FALSE; + } + + if (config->Clipboard) + { + if (WTSVirtualChannelManagerIsChannelJoined(ps->vcm, CLIPRDR_SVC_CHANNEL_NAME)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectClipboard, config->Clipboard)) + return FALSE; + } + } + + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoReconnectionEnabled, TRUE)) + return FALSE; + + PubSub_SubscribeErrorInfo(instance->context->pubSub, pf_client_on_error_info); + PubSub_SubscribeActivated(instance->context->pubSub, pf_client_on_activated); + if (!pf_client_use_peer_load_balance_info(pc)) + return FALSE; + + return pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_PRE_CONNECT, pc->pdata, pc); +} + +/** @brief arguments for updateBackIdFn */ +typedef struct +{ + pServerContext* ps; + const char* name; + UINT32 backId; +} UpdateBackIdArgs; + +static BOOL updateBackIdFn(const void* key, void* value, void* arg) +{ + pServerStaticChannelContext* current = (pServerStaticChannelContext*)value; + UpdateBackIdArgs* updateArgs = (UpdateBackIdArgs*)arg; + + if (strcmp(updateArgs->name, current->channel_name) != 0) + return TRUE; + + current->back_channel_id = updateArgs->backId; + if (!HashTable_Insert(updateArgs->ps->channelsByBackId, ¤t->back_channel_id, current)) + { + WLog_ERR(TAG, "error inserting channel in channelsByBackId table"); + } + return FALSE; +} + +static BOOL pf_client_update_back_id(pServerContext* ps, const char* name, UINT32 backId) +{ + UpdateBackIdArgs res = { ps, name, backId }; + + return HashTable_Foreach(ps->channelsByFrontId, updateBackIdFn, &res) == FALSE; +} + +static BOOL pf_client_load_channels(freerdp* instance) +{ + pClientContext* pc = NULL; + pServerContext* ps = NULL; + const proxyConfig* config = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(instance); + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + config = ps->pdata->config; + WINPR_ASSERT(config); + settings = instance->context->settings; + WINPR_ASSERT(settings); + /** + * Load all required plugins / channels / libraries specified by current + * settings. + */ + PROXY_LOG_INFO(TAG, pc, "Loading addins"); + + if (!pf_client_load_rdpsnd(pc)) + { + PROXY_LOG_ERR(TAG, pc, "Failed to load rdpsnd client"); + return FALSE; + } + + if (!pf_utils_is_passthrough(config)) + { + if (!freerdp_client_load_addins(instance->context->channels, settings)) + { + PROXY_LOG_ERR(TAG, pc, "Failed to load addins"); + return FALSE; + } + } + else + { + if (!pf_channel_rdpdr_client_new(pc)) + return FALSE; +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + if (!pf_channel_smartcard_client_new(pc)) + return FALSE; +#endif + /* Copy the current channel settings from the peer connection to the client. */ + if (!freerdp_channels_from_mcs(settings, &ps->context)) + return FALSE; + + /* Filter out channels we do not want */ + { + CHANNEL_DEF* channels = (CHANNEL_DEF*)freerdp_settings_get_pointer_array_writable( + settings, FreeRDP_ChannelDefArray, 0); + UINT32 size = freerdp_settings_get_uint32(settings, FreeRDP_ChannelCount); + UINT32 id = MCS_GLOBAL_CHANNEL_ID + 1; + + WINPR_ASSERT(channels || (size == 0)); + + UINT32 x = 0; + for (; x < size;) + { + CHANNEL_DEF* cur = &channels[x]; + proxyChannelDataEventInfo dev = { 0 }; + + dev.channel_name = cur->name; + dev.flags = cur->options; + + /* Filter out channels blocked by config */ + if (!pf_modules_run_filter(pc->pdata->module, + FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_CREATE, pc->pdata, + &dev)) + { + const size_t s = size - MIN(size, x + 1); + memmove(cur, &cur[1], sizeof(CHANNEL_DEF) * s); + size--; + } + else + { + if (!pf_client_update_back_id(ps, cur->name, id++)) + { + WLog_ERR(TAG, "unable to update backid for channel %s", cur->name); + return FALSE; + } + x++; + } + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ChannelCount, x)) + return FALSE; + } + } + return pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_LOAD_CHANNELS, pc->pdata, pc); +} + +static BOOL pf_client_receive_channel_data_hook(freerdp* instance, UINT16 channelId, + const BYTE* xdata, size_t xsize, UINT32 flags, + size_t totalSize) +{ + pClientContext* pc = NULL; + pServerContext* ps = NULL; + proxyData* pdata = NULL; + pServerStaticChannelContext* channel = NULL; + UINT64 channelId64 = channelId; + + WINPR_ASSERT(instance); + WINPR_ASSERT(xdata || (xsize == 0)); + + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + + channel = HashTable_GetItemValue(ps->channelsByBackId, &channelId64); + if (!channel) + return TRUE; + + WINPR_ASSERT(channel->onBackData); + switch (channel->onBackData(pdata, channel, xdata, xsize, flags, totalSize)) + { + case PF_CHANNEL_RESULT_PASS: + /* Ignore messages for channels that can not be mapped. + * The client might not have enabled support for this specific channel, + * so just drop the message. */ + if (channel->front_channel_id == 0) + return TRUE; + + return ps->context.peer->SendChannelPacket( + ps->context.peer, WINPR_ASSERTING_INT_CAST(UINT16, channel->front_channel_id), + totalSize, flags, xdata, xsize); + case PF_CHANNEL_RESULT_DROP: + return TRUE; + case PF_CHANNEL_RESULT_ERROR: + default: + return FALSE; + } +} + +static BOOL pf_client_on_server_heartbeat(freerdp* instance, BYTE period, BYTE count1, BYTE count2) +{ + pClientContext* pc = NULL; + pServerContext* ps = NULL; + + WINPR_ASSERT(instance); + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = pc->pdata->ps; + WINPR_ASSERT(ps); + + return freerdp_heartbeat_send_heartbeat_pdu(ps->context.peer, period, count1, count2); +} + +static BOOL pf_client_send_channel_data(pClientContext* pc, const proxyChannelDataEventInfo* ev) +{ + WINPR_ASSERT(pc); + WINPR_ASSERT(ev); + + return Queue_Enqueue(pc->cached_server_channel_data, ev); +} + +static BOOL sendQueuedChannelData(pClientContext* pc) +{ + BOOL rc = TRUE; + + WINPR_ASSERT(pc); + + if (pc->connected) + { + proxyChannelDataEventInfo* ev = NULL; + + Queue_Lock(pc->cached_server_channel_data); + while (rc && (ev = Queue_Dequeue(pc->cached_server_channel_data))) + { + UINT16 channelId = 0; + WINPR_ASSERT(pc->context.instance); + + channelId = freerdp_channels_get_id_by_name(pc->context.instance, ev->channel_name); + /* Ignore unmappable channels */ + if ((channelId == 0) || (channelId == UINT16_MAX)) + rc = TRUE; + else + { + WINPR_ASSERT(pc->context.instance->SendChannelPacket); + rc = pc->context.instance->SendChannelPacket(pc->context.instance, channelId, + ev->total_size, ev->flags, ev->data, + ev->data_len); + } + channel_data_free(ev); + } + + Queue_Unlock(pc->cached_server_channel_data); + } + + return rc; +} + +/** + * Called after a RDP connection was successfully established. + * Settings might have changed during negotiation of client / server feature + * support. + * + * Set up local framebuffers and painting callbacks. + * If required, register pointer callbacks to change the local mouse cursor + * when hovering over the RDP window + */ +static BOOL pf_client_post_connect(freerdp* instance) +{ + rdpContext* context = NULL; + rdpSettings* settings = NULL; + rdpUpdate* update = NULL; + rdpContext* ps = NULL; + pClientContext* pc = NULL; + const proxyConfig* config = NULL; + + WINPR_ASSERT(instance); + context = instance->context; + WINPR_ASSERT(context); + settings = context->settings; + WINPR_ASSERT(settings); + update = context->update; + WINPR_ASSERT(update); + pc = (pClientContext*)context; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + ps = (rdpContext*)pc->pdata->ps; + WINPR_ASSERT(ps); + config = pc->pdata->config; + WINPR_ASSERT(config); + + if (!pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_POST_CONNECT, pc->pdata, pc)) + return FALSE; + + if (!gdi_init(instance, PIXEL_FORMAT_BGRA32)) + return FALSE; + + WINPR_ASSERT(freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)); + + pf_client_register_update_callbacks(update); + + /* virtual channels receive data hook */ + pc->client_receive_channel_data_original = instance->ReceiveChannelData; + instance->ReceiveChannelData = pf_client_receive_channel_data_hook; + + instance->heartbeat->ServerHeartbeat = pf_client_on_server_heartbeat; + + pc->connected = TRUE; + + /* Send cached channel data */ + sendQueuedChannelData(pc); + + /* + * after the connection fully established and settings were negotiated with target server, + * send a reactivation sequence to the client with the negotiated settings. This way, + * settings are synchorinized between proxy's peer and and remote target. + */ + return proxy_server_reactivate(ps, context); +} + +/* This function is called whether a session ends by failure or success. + * Clean up everything allocated by pre_connect and post_connect. + */ +static void pf_client_post_disconnect(freerdp* instance) +{ + pClientContext* pc = NULL; + proxyData* pdata = NULL; + + if (!instance) + return; + + if (!instance->context) + return; + + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + pf_channel_smartcard_client_free(pc); +#endif + + pf_channel_rdpdr_client_free(pc); + + pc->connected = FALSE; + pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_POST_DISCONNECT, pc->pdata, pc); + + PubSub_UnsubscribeErrorInfo(instance->context->pubSub, pf_client_on_error_info); + gdi_free(instance); + + /* Only close the connection if NLA fallback process is done */ + if (!pc->allow_next_conn_failure) + proxy_data_abort_connect(pdata); +} + +static BOOL pf_client_redirect(freerdp* instance) +{ + pClientContext* pc = NULL; + proxyData* pdata = NULL; + + if (!instance) + return FALSE; + + if (!instance->context) + return FALSE; + + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + +#if defined(WITH_PROXY_EMULATE_SMARTCARD) + pf_channel_smartcard_client_reset(pc); +#endif + pf_channel_rdpdr_client_reset(pc); + + return pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_REDIRECT, pc->pdata, pc); +} + +/* + * pf_client_should_retry_without_nla: + * + * returns TRUE if in case of connection failure, the client should try again without NLA. + * Otherwise, returns FALSE. + */ +static BOOL pf_client_should_retry_without_nla(pClientContext* pc) +{ + rdpSettings* settings = NULL; + const proxyConfig* config = NULL; + + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + settings = pc->context.settings; + WINPR_ASSERT(settings); + config = pc->pdata->config; + WINPR_ASSERT(config); + + if (!config->ClientAllowFallbackToTls || + !freerdp_settings_get_bool(settings, FreeRDP_NlaSecurity)) + return FALSE; + + return config->ClientTlsSecurity || config->ClientRdpSecurity; +} + +static BOOL pf_client_set_security_settings(pClientContext* pc) +{ + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->pdata); + rdpSettings* settings = pc->context.settings; + WINPR_ASSERT(settings); + const proxyConfig* config = pc->pdata->config; + WINPR_ASSERT(config); + + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, config->ClientRdpSecurity)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, config->ClientTlsSecurity)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, config->ClientNlaSecurity)) + return FALSE; + + if (pf_client_use_proxy_smartcard_auth(settings)) + { + /* Smartcard authentication requires smartcard redirection to be enabled */ + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectSmartCards, TRUE)) + return FALSE; + + /* Reset username/domain, we will get that info later from the sc cert */ + if (!freerdp_settings_set_string(settings, FreeRDP_Username, NULL)) + return FALSE; + if (!freerdp_settings_set_string(settings, FreeRDP_Domain, NULL)) + return FALSE; + } + + return TRUE; +} + +static BOOL pf_client_connect_without_nla(pClientContext* pc) +{ + freerdp* instance = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(pc); + instance = pc->context.instance; + WINPR_ASSERT(instance); + + if (!freerdp_context_reset(instance)) + return FALSE; + + settings = pc->context.settings; + WINPR_ASSERT(settings); + + /* If already disabled abort early. */ + if (!freerdp_settings_get_bool(settings, FreeRDP_NlaSecurity)) + return FALSE; + + /* disable NLA */ + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return FALSE; + + /* do not allow next connection failure */ + pc->allow_next_conn_failure = FALSE; + return freerdp_connect(instance); +} + +static BOOL pf_client_connect(freerdp* instance) +{ + pClientContext* pc = NULL; + rdpSettings* settings = NULL; + BOOL rc = FALSE; + BOOL retry = FALSE; + + WINPR_ASSERT(instance); + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + settings = instance->context->settings; + WINPR_ASSERT(settings); + + PROXY_LOG_INFO(TAG, pc, "connecting using client info: Username: %s, Domain: %s", + freerdp_settings_get_string(settings, FreeRDP_Username), + freerdp_settings_get_string(settings, FreeRDP_Domain)); + + if (!pf_client_set_security_settings(pc)) + return FALSE; + + if (pf_client_should_retry_without_nla(pc)) + retry = pc->allow_next_conn_failure = TRUE; + + PROXY_LOG_INFO(TAG, pc, "connecting using security settings: rdp=%d, tls=%d, nla=%d", + freerdp_settings_get_bool(settings, FreeRDP_RdpSecurity), + freerdp_settings_get_bool(settings, FreeRDP_TlsSecurity), + freerdp_settings_get_bool(settings, FreeRDP_NlaSecurity)); + + if (!freerdp_connect(instance)) + { + if (!pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_LOGIN_FAILURE, pc->pdata, pc)) + goto out; + + if (!retry) + goto out; + + PROXY_LOG_ERR(TAG, pc, "failed to connect with NLA. retrying to connect without NLA"); + if (!pf_client_connect_without_nla(pc)) + { + PROXY_LOG_ERR(TAG, pc, "pf_client_connect_without_nla failed!"); + goto out; + } + } + + rc = TRUE; +out: + pc->allow_next_conn_failure = FALSE; + return rc; +} + +/** + * RDP main loop. + * Connects RDP, loops while running and handles event and dispatch, cleans up + * after the connection ends. + */ +static DWORD WINAPI pf_client_thread_proc(pClientContext* pc) +{ + freerdp* instance = NULL; + proxyData* pdata = NULL; + DWORD nCount = 0; + DWORD status = 0; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + + WINPR_ASSERT(pc); + + instance = pc->context.instance; + WINPR_ASSERT(instance); + + pdata = pc->pdata; + WINPR_ASSERT(pdata); + /* + * during redirection, freerdp's abort event might be overridden (reset) by the library, after + * the server set it in order to shutdown the connection. it means that the server might signal + * the client to abort, but the library code will override the signal and the client will + * continue its work instead of exiting. That's why the client must wait on `pdata->abort_event` + * too, which will never be modified by the library. + */ + handles[nCount++] = pdata->abort_event; + + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_CLIENT_INIT_CONNECT, pdata, pc)) + { + proxy_data_abort_connect(pdata); + goto end; + } + + if (!pf_client_connect(instance)) + { + proxy_data_abort_connect(pdata); + goto end; + } + handles[nCount++] = Queue_Event(pc->cached_server_channel_data); + + while (!freerdp_shall_disconnect_context(instance->context)) + { + UINT32 tmp = freerdp_get_event_handles(instance->context, &handles[nCount], + ARRAYSIZE(handles) - nCount); + + if (tmp == 0) + { + PROXY_LOG_ERR(TAG, pc, "freerdp_get_event_handles failed!"); + break; + } + + status = WaitForMultipleObjects(nCount + tmp, handles, FALSE, INFINITE); + + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed with %" PRIu32 "", status); + break; + } + + /* abort_event triggered */ + if (status == WAIT_OBJECT_0) + break; + + if (freerdp_shall_disconnect_context(instance->context)) + break; + + if (proxy_data_shall_disconnect(pdata)) + break; + + if (!freerdp_check_event_handles(instance->context)) + { + if (freerdp_get_last_error(instance->context) == FREERDP_ERROR_SUCCESS) + WLog_ERR(TAG, "Failed to check FreeRDP event handles"); + + break; + } + sendQueuedChannelData(pc); + } + + freerdp_disconnect(instance); + +end: + pf_modules_run_hook(pdata->module, HOOK_TYPE_CLIENT_UNINIT_CONNECT, pdata, pc); + + return 0; +} + +static int pf_logon_error_info(freerdp* instance, UINT32 data, UINT32 type) +{ + const char* str_data = freerdp_get_logon_error_info_data(data); + const char* str_type = freerdp_get_logon_error_info_type(type); + + if (!instance || !instance->context) + return -1; + + WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type); + return 1; +} + +static void pf_client_context_free(freerdp* instance, rdpContext* context) +{ + pClientContext* pc = (pClientContext*)context; + WINPR_UNUSED(instance); + + if (!pc) + return; + + pc->sendChannelData = NULL; + Queue_Free(pc->cached_server_channel_data); + Stream_Free(pc->remote_pem, TRUE); + free(pc->remote_hostname); + free(pc->computerName.v); + HashTable_Free(pc->interceptContextMap); +} + +static int pf_client_verify_X509_certificate(freerdp* instance, const BYTE* data, size_t length, + const char* hostname, UINT16 port, DWORD flags) +{ + pClientContext* pc = NULL; + + WINPR_ASSERT(instance); + WINPR_ASSERT(data); + WINPR_ASSERT(length > 0); + WINPR_ASSERT(hostname); + + pc = (pClientContext*)instance->context; + WINPR_ASSERT(pc); + + if (!Stream_EnsureCapacity(pc->remote_pem, length)) + return 0; + Stream_SetPosition(pc->remote_pem, 0); + + free(pc->remote_hostname); + pc->remote_hostname = NULL; + + if (length > 0) + Stream_Write(pc->remote_pem, data, length); + + if (hostname) + pc->remote_hostname = _strdup(hostname); + pc->remote_port = port; + pc->remote_flags = flags; + + Stream_SealLength(pc->remote_pem); + if (!pf_modules_run_hook(pc->pdata->module, HOOK_TYPE_CLIENT_VERIFY_X509, pc->pdata, pc)) + return 0; + return 1; +} + +void channel_data_free(void* obj) +{ + union + { + const void* cpv; + void* pv; + } cnv; + proxyChannelDataEventInfo* dst = obj; + if (dst) + { + cnv.cpv = dst->data; + free(cnv.pv); + + cnv.cpv = dst->channel_name; + free(cnv.pv); + free(dst); + } +} + +static void* channel_data_copy(const void* obj) +{ + union + { + const void* cpv; + void* pv; + } cnv; + const proxyChannelDataEventInfo* src = obj; + proxyChannelDataEventInfo* dst = NULL; + + WINPR_ASSERT(src); + + dst = calloc(1, sizeof(proxyChannelDataEventInfo)); + if (!dst) + goto fail; + + *dst = *src; + if (src->channel_name) + { + dst->channel_name = _strdup(src->channel_name); + if (!dst->channel_name) + goto fail; + } + dst->data = malloc(src->data_len); + if (!dst->data) + goto fail; + + cnv.cpv = dst->data; + memcpy(cnv.pv, src->data, src->data_len); + return dst; + +fail: + channel_data_free(dst); + return NULL; +} + +static BOOL pf_client_client_new(freerdp* instance, rdpContext* context) +{ + wObject* obj = NULL; + pClientContext* pc = (pClientContext*)context; + + if (!instance || !context) + return FALSE; + + instance->LoadChannels = pf_client_load_channels; + instance->PreConnect = pf_client_pre_connect; + instance->PostConnect = pf_client_post_connect; + instance->PostDisconnect = pf_client_post_disconnect; + instance->Redirect = pf_client_redirect; + instance->LogonErrorInfo = pf_logon_error_info; + instance->VerifyX509Certificate = pf_client_verify_X509_certificate; + + pc->remote_pem = Stream_New(NULL, 4096); + if (!pc->remote_pem) + return FALSE; + + pc->sendChannelData = pf_client_send_channel_data; + pc->cached_server_channel_data = Queue_New(TRUE, -1, -1); + if (!pc->cached_server_channel_data) + return FALSE; + obj = Queue_Object(pc->cached_server_channel_data); + WINPR_ASSERT(obj); + obj->fnObjectNew = channel_data_copy; + obj->fnObjectFree = channel_data_free; + + pc->interceptContextMap = HashTable_New(FALSE); + if (!pc->interceptContextMap) + return FALSE; + + if (!HashTable_SetupForStringData(pc->interceptContextMap, FALSE)) + return FALSE; + + obj = HashTable_ValueObject(pc->interceptContextMap); + WINPR_ASSERT(obj); + obj->fnObjectFree = intercept_context_entry_free; + + return TRUE; +} + +static int pf_client_client_stop(rdpContext* context) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + + PROXY_LOG_DBG(TAG, pc, "aborting client connection"); + proxy_data_abort_connect(pdata); + freerdp_abort_connect_context(context); + + return 0; +} + +int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + + ZeroMemory(pEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS)); + pEntryPoints->Version = RDP_CLIENT_INTERFACE_VERSION; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->ContextSize = sizeof(pClientContext); + /* Client init and finish */ + pEntryPoints->ClientNew = pf_client_client_new; + pEntryPoints->ClientFree = pf_client_context_free; + pEntryPoints->ClientStop = pf_client_client_stop; + return 0; +} + +/** + * Starts running a client connection towards target server. + */ +DWORD WINAPI pf_client_start(LPVOID arg) +{ + DWORD rc = 1; + pClientContext* pc = (pClientContext*)arg; + + WINPR_ASSERT(pc); + if (freerdp_client_start(&pc->context) == 0) + rc = pf_client_thread_proc(pc); + freerdp_client_stop(&pc->context); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.h new file mode 100644 index 0000000000000000000000000000000000000000..cda87a8f3b9ce4dae7e162dd4761f137f22d88ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_client.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * + * 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 FREERDP_SERVER_PROXY_PFCLIENT_H +#define FREERDP_SERVER_PROXY_PFCLIENT_H + +#include +#include + +int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints); +DWORD WINAPI pf_client_start(LPVOID arg); + +#endif /* FREERDP_SERVER_PROXY_PFCLIENT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_config.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_config.c new file mode 100644 index 0000000000000000000000000000000000000000..90616ae8106ad8ed71cd64c0cb10450229c5b28d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_config.c @@ -0,0 +1,1305 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021,2023 Armin Novak + * Copyright 2021,2023 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 +#include +#include +#include +#include +#include + +#include "pf_server.h" +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pf_utils.h" + +#define TAG PROXY_TAG("config") + +#define CONFIG_PRINT_SECTION(section) WLog_INFO(TAG, "\t%s:", section) +#define CONFIG_PRINT_SECTION_KEY(section, key) WLog_INFO(TAG, "\t%s/%s:", section, key) +#define CONFIG_PRINT_STR(config, key) WLog_INFO(TAG, "\t\t%s: %s", #key, (config)->key) +#define CONFIG_PRINT_STR_CONTENT(config, key) \ + WLog_INFO(TAG, "\t\t%s: %s", #key, (config)->key ? "set" : NULL) +#define CONFIG_PRINT_BOOL(config, key) WLog_INFO(TAG, "\t\t%s: %s", #key, boolstr((config)->key)) +#define CONFIG_PRINT_UINT16(config, key) WLog_INFO(TAG, "\t\t%s: %" PRIu16 "", #key, (config)->key) +#define CONFIG_PRINT_UINT32(config, key) WLog_INFO(TAG, "\t\t%s: %" PRIu32 "", #key, (config)->key) + +static const char* bool_str_true = "true"; +static const char* bool_str_false = "false"; +static const char* boolstr(BOOL rc) +{ + return rc ? bool_str_true : bool_str_false; +} + +static const char* section_server = "Server"; +static const char* key_host = "Host"; +static const char* key_port = "Port"; + +static const char* section_target = "Target"; +static const char* key_target_fixed = "FixedTarget"; +static const char* key_target_user = "User"; +static const char* key_target_pwd = "Password"; +static const char* key_target_domain = "Domain"; +static const char* key_target_tls_seclevel = "TlsSecLevel"; + +static const char* section_plugins = "Plugins"; +static const char* key_plugins_modules = "Modules"; +static const char* key_plugins_required = "Required"; + +static const char* section_channels = "Channels"; +static const char* key_channels_gfx = "GFX"; +static const char* key_channels_disp = "DisplayControl"; +static const char* key_channels_clip = "Clipboard"; +static const char* key_channels_mic = "AudioInput"; +static const char* key_channels_sound = "AudioOutput"; +static const char* key_channels_rdpdr = "DeviceRedirection"; +static const char* key_channels_video = "VideoRedirection"; +static const char* key_channels_camera = "CameraRedirection"; +static const char* key_channels_rails = "RemoteApp"; +static const char* key_channels_blacklist = "PassthroughIsBlacklist"; +static const char* key_channels_pass = "Passthrough"; +static const char* key_channels_intercept = "Intercept"; + +static const char* section_input = "Input"; +static const char* key_input_kbd = "Keyboard"; +static const char* key_input_mouse = "Mouse"; +static const char* key_input_multitouch = "Multitouch"; + +static const char* section_security = "Security"; +static const char* key_security_server_nla = "ServerNlaSecurity"; +static const char* key_security_server_tls = "ServerTlsSecurity"; +static const char* key_security_server_rdp = "ServerRdpSecurity"; +static const char* key_security_client_nla = "ClientNlaSecurity"; +static const char* key_security_client_tls = "ClientTlsSecurity"; +static const char* key_security_client_rdp = "ClientRdpSecurity"; +static const char* key_security_client_fallback = "ClientAllowFallbackToTls"; + +static const char* section_certificates = "Certificates"; +static const char* key_private_key_file = "PrivateKeyFile"; +static const char* key_private_key_content = "PrivateKeyContent"; +static const char* key_cert_file = "CertificateFile"; +static const char* key_cert_content = "CertificateContent"; + +WINPR_ATTR_MALLOC(CommandLineParserFree, 1) +static char** pf_config_parse_comma_separated_list(const char* list, size_t* count) +{ + if (!list || !count) + return NULL; + + if (strlen(list) == 0) + { + *count = 0; + return NULL; + } + + return CommandLineParseCommaSeparatedValues(list, count); +} + +static BOOL pf_config_get_uint16(wIniFile* ini, const char* section, const char* key, + UINT16* result, BOOL required) +{ + int val = 0; + const char* strval = NULL; + + WINPR_ASSERT(result); + + strval = IniFile_GetKeyValueString(ini, section, key); + if (!strval && required) + { + WLog_ERR(TAG, "key '%s.%s' does not exist.", section, key); + return FALSE; + } + val = IniFile_GetKeyValueInt(ini, section, key); + if ((val <= 0) || (val > UINT16_MAX)) + { + WLog_ERR(TAG, "invalid value %d for key '%s.%s'.", val, section, key); + return FALSE; + } + + *result = (UINT16)val; + return TRUE; +} + +static BOOL pf_config_get_uint32(wIniFile* ini, const char* section, const char* key, + UINT32* result, BOOL required) +{ + WINPR_ASSERT(result); + + const char* strval = IniFile_GetKeyValueString(ini, section, key); + if (!strval) + { + if (required) + WLog_ERR(TAG, "key '%s.%s' does not exist.", section, key); + return !required; + } + + const int val = IniFile_GetKeyValueInt(ini, section, key); + if (val < 0) + { + WLog_ERR(TAG, "invalid value %d for key '%s.%s'.", val, section, key); + return FALSE; + } + + *result = (UINT32)val; + return TRUE; +} + +static BOOL pf_config_get_bool(wIniFile* ini, const char* section, const char* key, BOOL fallback) +{ + int num_value = 0; + const char* str_value = NULL; + + str_value = IniFile_GetKeyValueString(ini, section, key); + if (!str_value) + { + WLog_WARN(TAG, "key '%s.%s' not found, value defaults to %s.", section, key, + fallback ? bool_str_true : bool_str_false); + return fallback; + } + + if (_stricmp(str_value, bool_str_true) == 0) + return TRUE; + if (_stricmp(str_value, bool_str_false) == 0) + return FALSE; + + num_value = IniFile_GetKeyValueInt(ini, section, key); + + if (num_value != 0) + return TRUE; + + return FALSE; +} + +static const char* pf_config_get_str(wIniFile* ini, const char* section, const char* key, + BOOL required) +{ + const char* value = NULL; + + value = IniFile_GetKeyValueString(ini, section, key); + + if (!value) + { + if (required) + WLog_ERR(TAG, "key '%s.%s' not found.", section, key); + return NULL; + } + + return value; +} + +static BOOL pf_config_load_server(wIniFile* ini, proxyConfig* config) +{ + const char* host = NULL; + + WINPR_ASSERT(config); + host = pf_config_get_str(ini, section_server, key_host, FALSE); + + if (!host) + return TRUE; + + config->Host = _strdup(host); + + if (!config->Host) + return FALSE; + + if (!pf_config_get_uint16(ini, section_server, key_port, &config->Port, TRUE)) + return FALSE; + + return TRUE; +} + +static BOOL pf_config_load_target(wIniFile* ini, proxyConfig* config) +{ + const char* target_value = NULL; + + WINPR_ASSERT(config); + config->FixedTarget = pf_config_get_bool(ini, section_target, key_target_fixed, FALSE); + + if (!pf_config_get_uint16(ini, section_target, key_port, &config->TargetPort, + config->FixedTarget)) + return FALSE; + + if (!pf_config_get_uint32(ini, section_target, key_target_tls_seclevel, + &config->TargetTlsSecLevel, FALSE)) + return FALSE; + + if (config->FixedTarget) + { + target_value = pf_config_get_str(ini, section_target, key_host, TRUE); + if (!target_value) + return FALSE; + + config->TargetHost = _strdup(target_value); + if (!config->TargetHost) + return FALSE; + } + + target_value = pf_config_get_str(ini, section_target, key_target_user, FALSE); + if (target_value) + { + config->TargetUser = _strdup(target_value); + if (!config->TargetUser) + return FALSE; + } + + target_value = pf_config_get_str(ini, section_target, key_target_pwd, FALSE); + if (target_value) + { + config->TargetPassword = _strdup(target_value); + if (!config->TargetPassword) + return FALSE; + } + + target_value = pf_config_get_str(ini, section_target, key_target_domain, FALSE); + if (target_value) + { + config->TargetDomain = _strdup(target_value); + if (!config->TargetDomain) + return FALSE; + } + + return TRUE; +} + +static BOOL pf_config_load_channels(wIniFile* ini, proxyConfig* config) +{ + WINPR_ASSERT(config); + config->GFX = pf_config_get_bool(ini, section_channels, key_channels_gfx, TRUE); + config->DisplayControl = pf_config_get_bool(ini, section_channels, key_channels_disp, TRUE); + config->Clipboard = pf_config_get_bool(ini, section_channels, key_channels_clip, FALSE); + config->AudioOutput = pf_config_get_bool(ini, section_channels, key_channels_mic, TRUE); + config->AudioInput = pf_config_get_bool(ini, section_channels, key_channels_sound, TRUE); + config->DeviceRedirection = pf_config_get_bool(ini, section_channels, key_channels_rdpdr, TRUE); + config->VideoRedirection = pf_config_get_bool(ini, section_channels, key_channels_video, TRUE); + config->CameraRedirection = + pf_config_get_bool(ini, section_channels, key_channels_camera, TRUE); + config->RemoteApp = pf_config_get_bool(ini, section_channels, key_channels_rails, FALSE); + config->PassthroughIsBlacklist = + pf_config_get_bool(ini, section_channels, key_channels_blacklist, FALSE); + config->Passthrough = pf_config_parse_comma_separated_list( + pf_config_get_str(ini, section_channels, key_channels_pass, FALSE), + &config->PassthroughCount); + config->Intercept = pf_config_parse_comma_separated_list( + pf_config_get_str(ini, section_channels, key_channels_intercept, FALSE), + &config->InterceptCount); + + return TRUE; +} + +static BOOL pf_config_load_input(wIniFile* ini, proxyConfig* config) +{ + WINPR_ASSERT(config); + config->Keyboard = pf_config_get_bool(ini, section_input, key_input_kbd, TRUE); + config->Mouse = pf_config_get_bool(ini, section_input, key_input_mouse, TRUE); + config->Multitouch = pf_config_get_bool(ini, section_input, key_input_multitouch, TRUE); + return TRUE; +} + +static BOOL pf_config_load_security(wIniFile* ini, proxyConfig* config) +{ + WINPR_ASSERT(config); + config->ServerTlsSecurity = + pf_config_get_bool(ini, section_security, key_security_server_tls, TRUE); + config->ServerNlaSecurity = + pf_config_get_bool(ini, section_security, key_security_server_nla, FALSE); + config->ServerRdpSecurity = + pf_config_get_bool(ini, section_security, key_security_server_rdp, TRUE); + + config->ClientTlsSecurity = + pf_config_get_bool(ini, section_security, key_security_client_tls, TRUE); + config->ClientNlaSecurity = + pf_config_get_bool(ini, section_security, key_security_client_nla, TRUE); + config->ClientRdpSecurity = + pf_config_get_bool(ini, section_security, key_security_client_rdp, TRUE); + config->ClientAllowFallbackToTls = + pf_config_get_bool(ini, section_security, key_security_client_fallback, TRUE); + return TRUE; +} + +static BOOL pf_config_load_modules(wIniFile* ini, proxyConfig* config) +{ + const char* modules_to_load = NULL; + const char* required_modules = NULL; + + modules_to_load = pf_config_get_str(ini, section_plugins, key_plugins_modules, FALSE); + required_modules = pf_config_get_str(ini, section_plugins, key_plugins_required, FALSE); + + WINPR_ASSERT(config); + config->Modules = pf_config_parse_comma_separated_list(modules_to_load, &config->ModulesCount); + + config->RequiredPlugins = + pf_config_parse_comma_separated_list(required_modules, &config->RequiredPluginsCount); + return TRUE; +} + +static char* pf_config_decode_base64(const char* data, const char* name, size_t* pLength) +{ + const char* headers[] = { "-----BEGIN PUBLIC KEY-----", "-----BEGIN RSA PUBLIC KEY-----", + "-----BEGIN CERTIFICATE-----", "-----BEGIN PRIVATE KEY-----", + "-----BEGIN RSA PRIVATE KEY-----" }; + + size_t decoded_length = 0; + char* decoded = NULL; + if (!data) + { + WLog_ERR(TAG, "Invalid base64 data [%p] for %s", data, name); + return NULL; + } + + WINPR_ASSERT(name); + WINPR_ASSERT(pLength); + + const size_t length = strlen(data); + + if (strncmp(data, "-----", 5) == 0) + { + BOOL expected = FALSE; + for (size_t x = 0; x < ARRAYSIZE(headers); x++) + { + const char* header = headers[x]; + + if (strncmp(data, header, strlen(header)) == 0) + expected = TRUE; + } + + if (!expected) + { + /* Extract header for log message + * expected format is '----- SOMETEXT -----' + */ + char hdr[128] = { 0 }; + const char* end = strchr(&data[5], '-'); + if (end) + { + while (*end == '-') + end++; + + const size_t s = MIN(ARRAYSIZE(hdr) - 1ULL, (size_t)(end - data)); + memcpy(hdr, data, s); + } + + WLog_WARN(TAG, "PEM has unexpected header '%s'. Known supported headers are:", hdr); + for (size_t x = 0; x < ARRAYSIZE(headers); x++) + { + const char* header = headers[x]; + WLog_WARN(TAG, "%s", header); + } + } + + *pLength = length + 1; + return _strdup(data); + } + + crypto_base64_decode(data, length, (BYTE**)&decoded, &decoded_length); + if (!decoded || decoded_length == 0) + { + WLog_ERR(TAG, "Failed to decode base64 data of length %" PRIuz " for %s", length, name); + free(decoded); + return NULL; + } + + *pLength = strnlen(decoded, decoded_length) + 1; + return decoded; +} + +static BOOL pf_config_load_certificates(wIniFile* ini, proxyConfig* config) +{ + const char* tmp1 = NULL; + const char* tmp2 = NULL; + + WINPR_ASSERT(ini); + WINPR_ASSERT(config); + + tmp1 = pf_config_get_str(ini, section_certificates, key_cert_file, FALSE); + if (tmp1) + { + if (!winpr_PathFileExists(tmp1)) + { + WLog_ERR(TAG, "%s/%s file %s does not exist", section_certificates, key_cert_file, + tmp1); + return FALSE; + } + config->CertificateFile = _strdup(tmp1); + config->CertificatePEM = + crypto_read_pem(config->CertificateFile, &config->CertificatePEMLength); + if (!config->CertificatePEM) + return FALSE; + config->CertificatePEMLength += 1; + } + tmp2 = pf_config_get_str(ini, section_certificates, key_cert_content, FALSE); + if (tmp2) + { + if (strlen(tmp2) < 1) + { + WLog_ERR(TAG, "%s/%s has invalid empty value", section_certificates, key_cert_content); + return FALSE; + } + config->CertificateContent = _strdup(tmp2); + config->CertificatePEM = pf_config_decode_base64( + config->CertificateContent, "CertificateContent", &config->CertificatePEMLength); + if (!config->CertificatePEM) + return FALSE; + } + if (tmp1 && tmp2) + { + WLog_ERR(TAG, + "%s/%s and %s/%s are " + "mutually exclusive options", + section_certificates, key_cert_file, section_certificates, key_cert_content); + return FALSE; + } + else if (!tmp1 && !tmp2) + { + WLog_ERR(TAG, + "%s/%s or %s/%s are " + "required settings", + section_certificates, key_cert_file, section_certificates, key_cert_content); + return FALSE; + } + + tmp1 = pf_config_get_str(ini, section_certificates, key_private_key_file, FALSE); + if (tmp1) + { + if (!winpr_PathFileExists(tmp1)) + { + WLog_ERR(TAG, "%s/%s file %s does not exist", section_certificates, + key_private_key_file, tmp1); + return FALSE; + } + config->PrivateKeyFile = _strdup(tmp1); + config->PrivateKeyPEM = + crypto_read_pem(config->PrivateKeyFile, &config->PrivateKeyPEMLength); + if (!config->PrivateKeyPEM) + return FALSE; + config->PrivateKeyPEMLength += 1; + } + tmp2 = pf_config_get_str(ini, section_certificates, key_private_key_content, FALSE); + if (tmp2) + { + if (strlen(tmp2) < 1) + { + WLog_ERR(TAG, "%s/%s has invalid empty value", section_certificates, + key_private_key_content); + return FALSE; + } + config->PrivateKeyContent = _strdup(tmp2); + config->PrivateKeyPEM = pf_config_decode_base64( + config->PrivateKeyContent, "PrivateKeyContent", &config->PrivateKeyPEMLength); + if (!config->PrivateKeyPEM) + return FALSE; + } + + if (tmp1 && tmp2) + { + WLog_ERR(TAG, + "%s/%s and %s/%s are " + "mutually exclusive options", + section_certificates, key_private_key_file, section_certificates, + key_private_key_content); + return FALSE; + } + else if (!tmp1 && !tmp2) + { + WLog_ERR(TAG, + "%s/%s or %s/%s are " + "are required settings", + section_certificates, key_private_key_file, section_certificates, + key_private_key_content); + return FALSE; + } + + return TRUE; +} + +proxyConfig* server_config_load_ini(wIniFile* ini) +{ + proxyConfig* config = NULL; + + WINPR_ASSERT(ini); + + config = calloc(1, sizeof(proxyConfig)); + if (config) + { + /* Set default values != 0 */ + config->TargetTlsSecLevel = 1; + + /* Load from ini */ + if (!pf_config_load_server(ini, config)) + goto out; + + if (!pf_config_load_target(ini, config)) + goto out; + + if (!pf_config_load_channels(ini, config)) + goto out; + + if (!pf_config_load_input(ini, config)) + goto out; + + if (!pf_config_load_security(ini, config)) + goto out; + + if (!pf_config_load_modules(ini, config)) + goto out; + + if (!pf_config_load_certificates(ini, config)) + goto out; + config->ini = IniFile_Clone(ini); + if (!config->ini) + goto out; + } + return config; +out: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + pf_server_config_free(config); + WINPR_PRAGMA_DIAG_POP + + return NULL; +} + +BOOL pf_server_config_dump(const char* file) +{ + BOOL rc = FALSE; + wIniFile* ini = IniFile_New(); + if (!ini) + return FALSE; + + /* Proxy server configuration */ + if (IniFile_SetKeyValueString(ini, section_server, key_host, "0.0.0.0") < 0) + goto fail; + if (IniFile_SetKeyValueInt(ini, section_server, key_port, 3389) < 0) + goto fail; + + /* Target configuration */ + if (IniFile_SetKeyValueString(ini, section_target, key_host, "somehost.example.com") < 0) + goto fail; + if (IniFile_SetKeyValueInt(ini, section_target, key_port, 3389) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_target, key_target_fixed, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueInt(ini, section_target, key_target_tls_seclevel, 1) < 0) + goto fail; + + /* Channel configuration */ + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_gfx, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_disp, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_clip, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_mic, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_sound, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_rdpdr, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_video, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_camera, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_rails, bool_str_false) < 0) + goto fail; + + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_blacklist, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_pass, "") < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_channels, key_channels_intercept, "") < 0) + goto fail; + + /* Input configuration */ + if (IniFile_SetKeyValueString(ini, section_input, key_input_kbd, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_input, key_input_mouse, bool_str_true) < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_input, key_input_multitouch, bool_str_true) < 0) + goto fail; + + /* Security settings */ + if (IniFile_SetKeyValueString(ini, section_security, key_security_server_tls, bool_str_true) < + 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_security, key_security_server_nla, bool_str_false) < + 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_security, key_security_server_rdp, bool_str_true) < + 0) + goto fail; + + if (IniFile_SetKeyValueString(ini, section_security, key_security_client_tls, bool_str_true) < + 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_security, key_security_client_nla, bool_str_true) < + 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_security, key_security_client_rdp, bool_str_true) < + 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_security, key_security_client_fallback, + bool_str_true) < 0) + goto fail; + + /* Module configuration */ + if (IniFile_SetKeyValueString(ini, section_plugins, key_plugins_modules, + "module1,module2,...") < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_plugins, key_plugins_required, + "module1,module2,...") < 0) + goto fail; + + /* Certificate configuration */ + if (IniFile_SetKeyValueString(ini, section_certificates, key_cert_file, + " OR") < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_certificates, key_cert_content, + "") < 0) + goto fail; + + if (IniFile_SetKeyValueString(ini, section_certificates, key_private_key_file, + " OR") < 0) + goto fail; + if (IniFile_SetKeyValueString(ini, section_certificates, key_private_key_content, + "") < 0) + goto fail; + + /* store configuration */ + if (IniFile_WriteFile(ini, file) < 0) + goto fail; + + rc = TRUE; + +fail: + IniFile_Free(ini); + return rc; +} + +proxyConfig* pf_server_config_load_buffer(const char* buffer) +{ + proxyConfig* config = NULL; + wIniFile* ini = NULL; + + ini = IniFile_New(); + + if (!ini) + { + WLog_ERR(TAG, "IniFile_New() failed!"); + return NULL; + } + + if (IniFile_ReadBuffer(ini, buffer) < 0) + { + WLog_ERR(TAG, "failed to parse ini: '%s'", buffer); + goto out; + } + + config = server_config_load_ini(ini); +out: + IniFile_Free(ini); + return config; +} + +proxyConfig* pf_server_config_load_file(const char* path) +{ + proxyConfig* config = NULL; + wIniFile* ini = IniFile_New(); + + if (!ini) + { + WLog_ERR(TAG, "IniFile_New() failed!"); + return NULL; + } + + if (IniFile_ReadFile(ini, path) < 0) + { + WLog_ERR(TAG, "failed to parse ini file: '%s'", path); + goto out; + } + + config = server_config_load_ini(ini); +out: + IniFile_Free(ini); + return config; +} + +static void pf_server_config_print_list(char** list, size_t count) +{ + WINPR_ASSERT(list); + for (size_t i = 0; i < count; i++) + WLog_INFO(TAG, "\t\t- %s", list[i]); +} + +void pf_server_config_print(const proxyConfig* config) +{ + WINPR_ASSERT(config); + WLog_INFO(TAG, "Proxy configuration:"); + + CONFIG_PRINT_SECTION(section_server); + CONFIG_PRINT_STR(config, Host); + CONFIG_PRINT_UINT16(config, Port); + + if (config->FixedTarget) + { + CONFIG_PRINT_SECTION(section_target); + CONFIG_PRINT_STR(config, TargetHost); + CONFIG_PRINT_UINT16(config, TargetPort); + CONFIG_PRINT_UINT32(config, TargetTlsSecLevel); + + if (config->TargetUser) + CONFIG_PRINT_STR(config, TargetUser); + if (config->TargetDomain) + CONFIG_PRINT_STR(config, TargetDomain); + } + + CONFIG_PRINT_SECTION(section_input); + CONFIG_PRINT_BOOL(config, Keyboard); + CONFIG_PRINT_BOOL(config, Mouse); + CONFIG_PRINT_BOOL(config, Multitouch); + + CONFIG_PRINT_SECTION(section_security); + CONFIG_PRINT_BOOL(config, ServerNlaSecurity); + CONFIG_PRINT_BOOL(config, ServerTlsSecurity); + CONFIG_PRINT_BOOL(config, ServerRdpSecurity); + CONFIG_PRINT_BOOL(config, ClientNlaSecurity); + CONFIG_PRINT_BOOL(config, ClientTlsSecurity); + CONFIG_PRINT_BOOL(config, ClientRdpSecurity); + CONFIG_PRINT_BOOL(config, ClientAllowFallbackToTls); + + CONFIG_PRINT_SECTION(section_channels); + CONFIG_PRINT_BOOL(config, GFX); + CONFIG_PRINT_BOOL(config, DisplayControl); + CONFIG_PRINT_BOOL(config, Clipboard); + CONFIG_PRINT_BOOL(config, AudioOutput); + CONFIG_PRINT_BOOL(config, AudioInput); + CONFIG_PRINT_BOOL(config, DeviceRedirection); + CONFIG_PRINT_BOOL(config, VideoRedirection); + CONFIG_PRINT_BOOL(config, CameraRedirection); + CONFIG_PRINT_BOOL(config, RemoteApp); + CONFIG_PRINT_BOOL(config, PassthroughIsBlacklist); + + if (config->PassthroughCount) + { + WLog_INFO(TAG, "\tStatic Channels Proxy:"); + pf_server_config_print_list(config->Passthrough, config->PassthroughCount); + } + + if (config->InterceptCount) + { + WLog_INFO(TAG, "\tStatic Channels Proxy-Intercept:"); + pf_server_config_print_list(config->Intercept, config->InterceptCount); + } + + /* modules */ + CONFIG_PRINT_SECTION_KEY(section_plugins, key_plugins_modules); + for (size_t x = 0; x < config->ModulesCount; x++) + CONFIG_PRINT_STR(config, Modules[x]); + + /* Required plugins */ + CONFIG_PRINT_SECTION_KEY(section_plugins, key_plugins_required); + for (size_t x = 0; x < config->RequiredPluginsCount; x++) + CONFIG_PRINT_STR(config, RequiredPlugins[x]); + + CONFIG_PRINT_SECTION(section_certificates); + CONFIG_PRINT_STR(config, CertificateFile); + CONFIG_PRINT_STR_CONTENT(config, CertificateContent); + CONFIG_PRINT_STR(config, PrivateKeyFile); + CONFIG_PRINT_STR_CONTENT(config, PrivateKeyContent); +} + +void pf_server_config_free(proxyConfig* config) +{ + if (config == NULL) + return; + + CommandLineParserFree(config->Passthrough); + CommandLineParserFree(config->Intercept); + CommandLineParserFree(config->RequiredPlugins); + CommandLineParserFree(config->Modules); + free(config->TargetHost); + free(config->Host); + free(config->CertificateFile); + free(config->CertificateContent); + if (config->CertificatePEM) + memset(config->CertificatePEM, 0, config->CertificatePEMLength); + free(config->CertificatePEM); + free(config->PrivateKeyFile); + free(config->PrivateKeyContent); + if (config->PrivateKeyPEM) + memset(config->PrivateKeyPEM, 0, config->PrivateKeyPEMLength); + free(config->PrivateKeyPEM); + IniFile_Free(config->ini); + free(config); +} + +size_t pf_config_required_plugins_count(const proxyConfig* config) +{ + WINPR_ASSERT(config); + return config->RequiredPluginsCount; +} + +const char* pf_config_required_plugin(const proxyConfig* config, size_t index) +{ + WINPR_ASSERT(config); + if (index >= config->RequiredPluginsCount) + return NULL; + + return config->RequiredPlugins[index]; +} + +size_t pf_config_modules_count(const proxyConfig* config) +{ + WINPR_ASSERT(config); + return config->ModulesCount; +} + +const char** pf_config_modules(const proxyConfig* config) +{ + union + { + char** ppc; + const char** cppc; + } cnv; + + WINPR_ASSERT(config); + + cnv.ppc = config->Modules; + return cnv.cppc; +} + +static BOOL pf_config_copy_string(char** dst, const char* src) +{ + *dst = NULL; + if (src) + *dst = _strdup(src); + return TRUE; +} + +static BOOL pf_config_copy_string_n(char** dst, const char* src, size_t size) +{ + *dst = NULL; + + if (src && (size > 0)) + { + WINPR_ASSERT(strnlen(src, size) == size - 1); + *dst = calloc(size, sizeof(char)); + if (!*dst) + return FALSE; + memcpy(*dst, src, size); + } + + return TRUE; +} + +static BOOL pf_config_copy_string_list(char*** dst, size_t* size, char** src, size_t srcSize) +{ + WINPR_ASSERT(dst); + WINPR_ASSERT(size); + WINPR_ASSERT(src || (srcSize == 0)); + + *dst = NULL; + *size = 0; + if (srcSize > INT32_MAX) + return FALSE; + + if (srcSize != 0) + { + char* csv = CommandLineToCommaSeparatedValues((INT32)srcSize, src); + *dst = CommandLineParseCommaSeparatedValues(csv, size); + free(csv); + } + + return TRUE; +} + +BOOL pf_config_clone(proxyConfig** dst, const proxyConfig* config) +{ + proxyConfig* tmp = calloc(1, sizeof(proxyConfig)); + + WINPR_ASSERT(dst); + WINPR_ASSERT(config); + + if (!tmp) + return FALSE; + + *tmp = *config; + + if (!pf_config_copy_string(&tmp->Host, config->Host)) + goto fail; + if (!pf_config_copy_string(&tmp->TargetHost, config->TargetHost)) + goto fail; + + if (!pf_config_copy_string_list(&tmp->Passthrough, &tmp->PassthroughCount, config->Passthrough, + config->PassthroughCount)) + goto fail; + if (!pf_config_copy_string_list(&tmp->Intercept, &tmp->InterceptCount, config->Intercept, + config->InterceptCount)) + goto fail; + if (!pf_config_copy_string_list(&tmp->Modules, &tmp->ModulesCount, config->Modules, + config->ModulesCount)) + goto fail; + if (!pf_config_copy_string_list(&tmp->RequiredPlugins, &tmp->RequiredPluginsCount, + config->RequiredPlugins, config->RequiredPluginsCount)) + goto fail; + if (!pf_config_copy_string(&tmp->CertificateFile, config->CertificateFile)) + goto fail; + if (!pf_config_copy_string(&tmp->CertificateContent, config->CertificateContent)) + goto fail; + if (!pf_config_copy_string_n(&tmp->CertificatePEM, config->CertificatePEM, + config->CertificatePEMLength)) + goto fail; + if (!pf_config_copy_string(&tmp->PrivateKeyFile, config->PrivateKeyFile)) + goto fail; + if (!pf_config_copy_string(&tmp->PrivateKeyContent, config->PrivateKeyContent)) + goto fail; + if (!pf_config_copy_string_n(&tmp->PrivateKeyPEM, config->PrivateKeyPEM, + config->PrivateKeyPEMLength)) + goto fail; + + tmp->ini = IniFile_Clone(config->ini); + if (!tmp->ini) + goto fail; + + *dst = tmp; + return TRUE; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + pf_server_config_free(tmp); + WINPR_PRAGMA_DIAG_POP + return FALSE; +} + +struct config_plugin_data +{ + proxyPluginsManager* mgr; + const proxyConfig* config; +}; + +static const char config_plugin_name[] = "config"; +static const char config_plugin_desc[] = + "A plugin filtering according to proxy configuration file rules"; + +static BOOL config_plugin_unload(proxyPlugin* plugin) +{ + WINPR_ASSERT(plugin); + + /* Here we have to free up our custom data storage. */ + if (plugin) + { + free(plugin->custom); + plugin->custom = NULL; + } + + return TRUE; +} + +static BOOL config_plugin_keyboard_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL rc = 0; + const struct config_plugin_data* custom = NULL; + const proxyConfig* cfg = NULL; + const proxyKeyboardEventInfo* event_data = (const proxyKeyboardEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WINPR_UNUSED(event_data); + + custom = plugin->custom; + WINPR_ASSERT(custom); + + cfg = custom->config; + WINPR_ASSERT(cfg); + + rc = cfg->Keyboard; + WLog_DBG(TAG, "%s", boolstr(rc)); + return rc; +} + +static BOOL config_plugin_unicode_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL rc = 0; + const struct config_plugin_data* custom = NULL; + const proxyConfig* cfg = NULL; + const proxyUnicodeEventInfo* event_data = (const proxyUnicodeEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WINPR_UNUSED(event_data); + + custom = plugin->custom; + WINPR_ASSERT(custom); + + cfg = custom->config; + WINPR_ASSERT(cfg); + + rc = cfg->Keyboard; + WLog_DBG(TAG, "%s", boolstr(rc)); + return rc; +} + +static BOOL config_plugin_mouse_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL rc = 0; + const struct config_plugin_data* custom = NULL; + const proxyConfig* cfg = NULL; + const proxyMouseEventInfo* event_data = (const proxyMouseEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WINPR_UNUSED(event_data); + + custom = plugin->custom; + WINPR_ASSERT(custom); + + cfg = custom->config; + WINPR_ASSERT(cfg); + + rc = cfg->Mouse; + return rc; +} + +static BOOL config_plugin_mouse_ex_event(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL rc = 0; + const struct config_plugin_data* custom = NULL; + const proxyConfig* cfg = NULL; + const proxyMouseExEventInfo* event_data = (const proxyMouseExEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(event_data); + + WINPR_UNUSED(event_data); + + custom = plugin->custom; + WINPR_ASSERT(custom); + + cfg = custom->config; + WINPR_ASSERT(cfg); + + rc = cfg->Mouse; + return rc; +} + +static BOOL config_plugin_client_channel_data(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + const proxyChannelDataEventInfo* channel = (const proxyChannelDataEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + WLog_DBG(TAG, "%s [0x%04" PRIx16 "] got %" PRIuz, channel->channel_name, channel->channel_id, + channel->data_len); + return TRUE; +} + +static BOOL config_plugin_server_channel_data(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + const proxyChannelDataEventInfo* channel = (const proxyChannelDataEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + WLog_DBG(TAG, "%s [0x%04" PRIx16 "] got %" PRIuz, channel->channel_name, channel->channel_id, + channel->data_len); + return TRUE; +} + +static BOOL config_plugin_dynamic_channel_create(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL accept = 0; + const proxyChannelDataEventInfo* channel = (const proxyChannelDataEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + const struct config_plugin_data* custom = plugin->custom; + WINPR_ASSERT(custom); + + const proxyConfig* cfg = custom->config; + WINPR_ASSERT(cfg); + + pf_utils_channel_mode rc = pf_utils_get_channel_mode(cfg, channel->channel_name); + switch (rc) + { + + case PF_UTILS_CHANNEL_INTERCEPT: + case PF_UTILS_CHANNEL_PASSTHROUGH: + accept = TRUE; + break; + case PF_UTILS_CHANNEL_BLOCK: + default: + accept = FALSE; + break; + } + + if (accept) + { + if (strncmp(RDPGFX_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPGFX_DVC_CHANNEL_NAME)) == 0) + accept = cfg->GFX; + else if (strncmp(RDPSND_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPSND_DVC_CHANNEL_NAME)) == 0) + accept = cfg->AudioOutput; + else if (strncmp(RDPSND_LOSSY_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPSND_LOSSY_DVC_CHANNEL_NAME)) == 0) + accept = cfg->AudioOutput; + else if (strncmp(AUDIN_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(AUDIN_DVC_CHANNEL_NAME)) == 0) + accept = cfg->AudioInput; + else if (strncmp(RDPEI_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPEI_DVC_CHANNEL_NAME)) == 0) + accept = cfg->Multitouch; + else if (strncmp(TSMF_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(TSMF_DVC_CHANNEL_NAME)) == 0) + accept = cfg->VideoRedirection; + else if (strncmp(VIDEO_CONTROL_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(VIDEO_CONTROL_DVC_CHANNEL_NAME)) == 0) + accept = cfg->VideoRedirection; + else if (strncmp(VIDEO_DATA_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(VIDEO_DATA_DVC_CHANNEL_NAME)) == 0) + accept = cfg->VideoRedirection; + else if (strncmp(RDPECAM_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPECAM_DVC_CHANNEL_NAME)) == 0) + accept = cfg->CameraRedirection; + } + + WLog_DBG(TAG, "%s [0x%04" PRIx16 "]: %s", channel->channel_name, channel->channel_id, + boolstr(accept)); + return accept; +} + +static BOOL config_plugin_channel_create(proxyPlugin* plugin, proxyData* pdata, void* param) +{ + BOOL accept = 0; + const proxyChannelDataEventInfo* channel = (const proxyChannelDataEventInfo*)(param); + + WINPR_ASSERT(plugin); + WINPR_ASSERT(pdata); + WINPR_ASSERT(channel); + + const struct config_plugin_data* custom = plugin->custom; + WINPR_ASSERT(custom); + + const proxyConfig* cfg = custom->config; + WINPR_ASSERT(cfg); + + pf_utils_channel_mode rc = pf_utils_get_channel_mode(cfg, channel->channel_name); + switch (rc) + { + case PF_UTILS_CHANNEL_INTERCEPT: + case PF_UTILS_CHANNEL_PASSTHROUGH: + accept = TRUE; + break; + case PF_UTILS_CHANNEL_BLOCK: + default: + accept = FALSE; + break; + } + if (accept) + { + if (strncmp(CLIPRDR_SVC_CHANNEL_NAME, channel->channel_name, + sizeof(CLIPRDR_SVC_CHANNEL_NAME)) == 0) + accept = cfg->Clipboard; + else if (strncmp(RDPSND_CHANNEL_NAME, channel->channel_name, sizeof(RDPSND_CHANNEL_NAME)) == + 0) + accept = cfg->AudioOutput; + else if (strncmp(RDPDR_SVC_CHANNEL_NAME, channel->channel_name, + sizeof(RDPDR_SVC_CHANNEL_NAME)) == 0) + accept = cfg->DeviceRedirection; + else if (strncmp(DISP_DVC_CHANNEL_NAME, channel->channel_name, + sizeof(DISP_DVC_CHANNEL_NAME)) == 0) + accept = cfg->DisplayControl; + else if (strncmp(RAIL_SVC_CHANNEL_NAME, channel->channel_name, + sizeof(RAIL_SVC_CHANNEL_NAME)) == 0) + accept = cfg->RemoteApp; + } + + WLog_DBG(TAG, "%s [static]: %s", channel->channel_name, boolstr(accept)); + return accept; +} + +BOOL pf_config_plugin(proxyPluginsManager* plugins_manager, void* userdata) +{ + struct config_plugin_data* custom = NULL; + proxyPlugin plugin = { 0 }; + + plugin.name = config_plugin_name; + plugin.description = config_plugin_desc; + plugin.PluginUnload = config_plugin_unload; + + plugin.KeyboardEvent = config_plugin_keyboard_event; + plugin.UnicodeEvent = config_plugin_unicode_event; + plugin.MouseEvent = config_plugin_mouse_event; + plugin.MouseExEvent = config_plugin_mouse_ex_event; + plugin.ClientChannelData = config_plugin_client_channel_data; + plugin.ServerChannelData = config_plugin_server_channel_data; + plugin.ChannelCreate = config_plugin_channel_create; + plugin.DynamicChannelCreate = config_plugin_dynamic_channel_create; + plugin.userdata = userdata; + + custom = calloc(1, sizeof(struct config_plugin_data)); + if (!custom) + return FALSE; + + custom->mgr = plugins_manager; + custom->config = userdata; + + plugin.custom = custom; + plugin.userdata = userdata; + + return plugins_manager->RegisterPlugin(plugins_manager, &plugin); +} + +const char* pf_config_get(const proxyConfig* config, const char* section, const char* key) +{ + WINPR_ASSERT(config); + WINPR_ASSERT(config->ini); + WINPR_ASSERT(section); + WINPR_ASSERT(key); + + return IniFile_GetKeyValueString(config->ini, section, key); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_context.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_context.c new file mode 100644 index 0000000000000000000000000000000000000000..7b8e4bf0afaf3c93a03fc873869976e0088364f1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_context.c @@ -0,0 +1,422 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include +#include + +#include +#include +#include + +#include "pf_client.h" +#include "pf_utils.h" +#include "proxy_modules.h" + +#include + +#include "channels/pf_channel_rdpdr.h" + +#define TAG PROXY_TAG("server") + +static UINT32 ChannelId_Hash(const void* key) +{ + const UINT32* v = (const UINT32*)key; + return *v; +} + +static BOOL ChannelId_Compare(const void* pv1, const void* pv2) +{ + const UINT32* v1 = pv1; + const UINT32* v2 = pv2; + WINPR_ASSERT(v1); + WINPR_ASSERT(v2); + return (*v1 == *v2); +} + +static BOOL dyn_intercept(pServerContext* ps, const char* name) +{ + if (strncmp(DRDYNVC_SVC_CHANNEL_NAME, name, sizeof(DRDYNVC_SVC_CHANNEL_NAME)) != 0) + return FALSE; + + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + const proxyConfig* cfg = ps->pdata->config; + WINPR_ASSERT(cfg); + if (!cfg->GFX) + return TRUE; + if (!cfg->AudioOutput) + return TRUE; + if (!cfg->AudioInput) + return TRUE; + if (!cfg->Multitouch) + return TRUE; + if (!cfg->VideoRedirection) + return TRUE; + if (!cfg->CameraRedirection) + return TRUE; + return FALSE; +} + +pServerStaticChannelContext* StaticChannelContext_new(pServerContext* ps, const char* name, + UINT32 id) +{ + pServerStaticChannelContext* ret = calloc(1, sizeof(*ret)); + if (!ret) + { + PROXY_LOG_ERR(TAG, ps, "error allocating channel context for '%s'", name); + return NULL; + } + + ret->front_channel_id = id; + ret->channel_name = _strdup(name); + if (!ret->channel_name) + { + PROXY_LOG_ERR(TAG, ps, "error allocating name in channel context for '%s'", name); + free(ret); + return NULL; + } + + proxyChannelToInterceptData channel = { .name = name, .channelId = id, .intercept = FALSE }; + + if (pf_modules_run_filter(ps->pdata->module, FILTER_TYPE_STATIC_INTERCEPT_LIST, ps->pdata, + &channel) && + channel.intercept) + ret->channelMode = PF_UTILS_CHANNEL_INTERCEPT; + else if (dyn_intercept(ps, name)) + ret->channelMode = PF_UTILS_CHANNEL_INTERCEPT; + else + ret->channelMode = pf_utils_get_channel_mode(ps->pdata->config, name); + return ret; +} + +void StaticChannelContext_free(pServerStaticChannelContext* ctx) +{ + if (!ctx) + return; + + IFCALL(ctx->contextDtor, ctx->context); + + free(ctx->channel_name); + free(ctx); +} + +static void HashStaticChannelContext_free(void* ptr) +{ + pServerStaticChannelContext* ctx = (pServerStaticChannelContext*)ptr; + StaticChannelContext_free(ctx); +} + +/* Proxy context initialization callback */ +static void client_to_proxy_context_free(freerdp_peer* client, rdpContext* ctx); +static BOOL client_to_proxy_context_new(freerdp_peer* client, rdpContext* ctx) +{ + wObject* obj = NULL; + pServerContext* context = (pServerContext*)ctx; + + WINPR_ASSERT(client); + WINPR_ASSERT(context); + + context->dynvcReady = NULL; + + context->vcm = WTSOpenServerA((LPSTR)client->context); + + if (!context->vcm || context->vcm == INVALID_HANDLE_VALUE) + goto error; + + if (!(context->dynvcReady = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto error; + + context->interceptContextMap = HashTable_New(FALSE); + if (!context->interceptContextMap) + goto error; + if (!HashTable_SetupForStringData(context->interceptContextMap, FALSE)) + goto error; + obj = HashTable_ValueObject(context->interceptContextMap); + WINPR_ASSERT(obj); + obj->fnObjectFree = intercept_context_entry_free; + + /* channels by ids */ + context->channelsByFrontId = HashTable_New(FALSE); + if (!context->channelsByFrontId) + goto error; + if (!HashTable_SetHashFunction(context->channelsByFrontId, ChannelId_Hash)) + goto error; + + obj = HashTable_KeyObject(context->channelsByFrontId); + obj->fnObjectEquals = ChannelId_Compare; + + obj = HashTable_ValueObject(context->channelsByFrontId); + obj->fnObjectFree = HashStaticChannelContext_free; + + context->channelsByBackId = HashTable_New(FALSE); + if (!context->channelsByBackId) + goto error; + if (!HashTable_SetHashFunction(context->channelsByBackId, ChannelId_Hash)) + goto error; + + obj = HashTable_KeyObject(context->channelsByBackId); + obj->fnObjectEquals = ChannelId_Compare; + + return TRUE; + +error: + client_to_proxy_context_free(client, ctx); + + return FALSE; +} + +/* Proxy context free callback */ +void client_to_proxy_context_free(freerdp_peer* client, rdpContext* ctx) +{ + pServerContext* context = (pServerContext*)ctx; + + WINPR_UNUSED(client); + + if (!context) + return; + + if (context->dynvcReady) + { + (void)CloseHandle(context->dynvcReady); + context->dynvcReady = NULL; + } + + HashTable_Free(context->interceptContextMap); + HashTable_Free(context->channelsByFrontId); + HashTable_Free(context->channelsByBackId); + + if (context->vcm && (context->vcm != INVALID_HANDLE_VALUE)) + WTSCloseServer(context->vcm); + context->vcm = NULL; +} + +BOOL pf_context_init_server_context(freerdp_peer* client) +{ + WINPR_ASSERT(client); + + client->ContextSize = sizeof(pServerContext); + client->ContextNew = client_to_proxy_context_new; + client->ContextFree = client_to_proxy_context_free; + + return freerdp_peer_context_new(client); +} + +static BOOL pf_context_revert_str_settings(rdpSettings* dst, const rdpSettings* before, size_t nr, + const FreeRDP_Settings_Keys_String* ids) +{ + WINPR_ASSERT(dst); + WINPR_ASSERT(before); + WINPR_ASSERT(ids || (nr == 0)); + + for (size_t x = 0; x < nr; x++) + { + FreeRDP_Settings_Keys_String id = ids[x]; + const char* what = freerdp_settings_get_string(before, id); + if (!freerdp_settings_set_string(dst, id, what)) + return FALSE; + } + + return TRUE; +} + +void intercept_context_entry_free(void* obj) +{ + InterceptContextMapEntry* entry = obj; + if (!entry) + return; + if (!entry->free) + return; + entry->free(entry); +} + +BOOL pf_context_copy_settings(rdpSettings* dst, const rdpSettings* src) +{ + BOOL rc = FALSE; + rdpSettings* before_copy = NULL; + const FreeRDP_Settings_Keys_String to_revert[] = { FreeRDP_ConfigPath, + FreeRDP_CertificateName }; + + if (!dst || !src) + return FALSE; + + before_copy = freerdp_settings_clone(dst); + if (!before_copy) + return FALSE; + + if (!freerdp_settings_copy(dst, src)) + goto out_fail; + + /* keep original ServerMode value */ + if (!freerdp_settings_copy_item(dst, before_copy, FreeRDP_ServerMode)) + goto out_fail; + + /* revert some values that must not be changed */ + if (!pf_context_revert_str_settings(dst, before_copy, ARRAYSIZE(to_revert), to_revert)) + goto out_fail; + + if (!freerdp_settings_get_bool(dst, FreeRDP_ServerMode)) + { + /* adjust instance pointer */ + if (!freerdp_settings_copy_item(dst, before_copy, FreeRDP_instance)) + goto out_fail; + + /* + * RdpServerRsaKey must be set to NULL if `dst` is client's context + * it must be freed before setting it to NULL to avoid a memory leak! + */ + + if (!freerdp_settings_set_pointer_len(dst, FreeRDP_RdpServerRsaKey, NULL, 1)) + goto out_fail; + } + + /* We handle certificate management for this client ourselves. */ + rc = freerdp_settings_set_bool(dst, FreeRDP_ExternalCertificateManagement, TRUE); + +out_fail: + freerdp_settings_free(before_copy); + return rc; +} + +pClientContext* pf_context_create_client_context(const rdpSettings* clientSettings) +{ + RDP_CLIENT_ENTRY_POINTS clientEntryPoints; + pClientContext* pc = NULL; + rdpContext* context = NULL; + + WINPR_ASSERT(clientSettings); + + RdpClientEntry(&clientEntryPoints); + context = freerdp_client_context_new(&clientEntryPoints); + + if (!context) + return NULL; + + pc = (pClientContext*)context; + + if (!pf_context_copy_settings(context->settings, clientSettings)) + goto error; + + return pc; +error: + freerdp_client_context_free(context); + return NULL; +} + +proxyData* proxy_data_new(void) +{ + BYTE temp[16]; + char* hex = NULL; + proxyData* pdata = NULL; + + pdata = calloc(1, sizeof(proxyData)); + if (!pdata) + return NULL; + + if (!(pdata->abort_event = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto error; + + if (!(pdata->gfx_server_ready = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto error; + + winpr_RAND(&temp, 16); + hex = winpr_BinToHexString(temp, 16, FALSE); + if (!hex) + goto error; + + CopyMemory(pdata->session_id, hex, PROXY_SESSION_ID_LENGTH); + pdata->session_id[PROXY_SESSION_ID_LENGTH] = '\0'; + free(hex); + + if (!(pdata->modules_info = HashTable_New(FALSE))) + goto error; + + /* modules_info maps between plugin name to custom data */ + if (!HashTable_SetupForStringData(pdata->modules_info, FALSE)) + goto error; + + return pdata; +error: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + proxy_data_free(pdata); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +/* updates circular pointers between proxyData and pClientContext instances */ +void proxy_data_set_client_context(proxyData* pdata, pClientContext* context) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(context); + pdata->pc = context; + context->pdata = pdata; +} + +/* updates circular pointers between proxyData and pServerContext instances */ +void proxy_data_set_server_context(proxyData* pdata, pServerContext* context) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(context); + pdata->ps = context; + context->pdata = pdata; +} + +void proxy_data_free(proxyData* pdata) +{ + if (!pdata) + return; + + if (pdata->abort_event) + (void)CloseHandle(pdata->abort_event); + + if (pdata->client_thread) + (void)CloseHandle(pdata->client_thread); + + if (pdata->gfx_server_ready) + (void)CloseHandle(pdata->gfx_server_ready); + + if (pdata->modules_info) + HashTable_Free(pdata->modules_info); + + if (pdata->pc) + freerdp_client_context_free(&pdata->pc->context); + + free(pdata); +} + +void proxy_data_abort_connect(proxyData* pdata) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(pdata->abort_event); + (void)SetEvent(pdata->abort_event); + if (pdata->pc) + freerdp_abort_connect_context(&pdata->pc->context); +} + +BOOL proxy_data_shall_disconnect(proxyData* pdata) +{ + WINPR_ASSERT(pdata); + WINPR_ASSERT(pdata->abort_event); + return WaitForSingleObject(pdata->abort_event, 0) == WAIT_OBJECT_0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.c new file mode 100644 index 0000000000000000000000000000000000000000..f883761265b4d53cf87368c05794609e6ad14de7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.c @@ -0,0 +1,205 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include + +#include "pf_input.h" +#include +#include + +#include "proxy_modules.h" + +static BOOL pf_server_check_and_sync_input_state(pClientContext* pc) +{ + WINPR_ASSERT(pc); + + if (!freerdp_is_active_state(&pc->context)) + return FALSE; + if (pc->input_state_sync_pending) + { + BOOL rc = freerdp_input_send_synchronize_event(pc->context.input, pc->input_state); + if (rc) + pc->input_state_sync_pending = FALSE; + } + return TRUE; +} + +static BOOL pf_server_synchronize_event(rdpInput* input, UINT32 flags) +{ + pServerContext* ps = NULL; + pClientContext* pc = NULL; + + WINPR_ASSERT(input); + ps = (pServerContext*)input->context; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + pc = ps->pdata->pc; + WINPR_ASSERT(pc); + + pc->input_state = flags; + pc->input_state_sync_pending = TRUE; + + return pf_server_check_and_sync_input_state(pc); +} + +static BOOL pf_server_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + const proxyConfig* config = NULL; + proxyKeyboardEventInfo event = { 0 }; + pServerContext* ps = NULL; + pClientContext* pc = NULL; + + WINPR_ASSERT(input); + ps = (pServerContext*)input->context; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + pc = ps->pdata->pc; + WINPR_ASSERT(pc); + + config = ps->pdata->config; + WINPR_ASSERT(config); + + if (!pf_server_check_and_sync_input_state(pc)) + return TRUE; + + if (!config->Keyboard) + return TRUE; + + event.flags = flags; + event.rdp_scan_code = code; + + if (pf_modules_run_filter(pc->pdata->module, FILTER_TYPE_KEYBOARD, pc->pdata, &event)) + return freerdp_input_send_keyboard_event(pc->context.input, flags, code); + + return TRUE; +} + +static BOOL pf_server_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + const proxyConfig* config = NULL; + proxyUnicodeEventInfo event = { 0 }; + pServerContext* ps = NULL; + pClientContext* pc = NULL; + + WINPR_ASSERT(input); + ps = (pServerContext*)input->context; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + pc = ps->pdata->pc; + WINPR_ASSERT(pc); + + config = ps->pdata->config; + WINPR_ASSERT(config); + + if (!pf_server_check_and_sync_input_state(pc)) + return TRUE; + + if (!config->Keyboard) + return TRUE; + + event.flags = flags; + event.code = code; + if (pf_modules_run_filter(pc->pdata->module, FILTER_TYPE_UNICODE, pc->pdata, &event)) + return freerdp_input_send_unicode_keyboard_event(pc->context.input, flags, code); + return TRUE; +} + +static BOOL pf_server_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + proxyMouseEventInfo event = { 0 }; + const proxyConfig* config = NULL; + pServerContext* ps = NULL; + pClientContext* pc = NULL; + + WINPR_ASSERT(input); + ps = (pServerContext*)input->context; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + pc = ps->pdata->pc; + WINPR_ASSERT(pc); + + config = ps->pdata->config; + WINPR_ASSERT(config); + + if (!pf_server_check_and_sync_input_state(pc)) + return TRUE; + + if (!config->Mouse) + return TRUE; + + event.flags = flags; + event.x = x; + event.y = y; + + if (pf_modules_run_filter(pc->pdata->module, FILTER_TYPE_MOUSE, pc->pdata, &event)) + return freerdp_input_send_mouse_event(pc->context.input, flags, x, y); + + return TRUE; +} + +static BOOL pf_server_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + const proxyConfig* config = NULL; + proxyMouseExEventInfo event = { 0 }; + pServerContext* ps = NULL; + pClientContext* pc = NULL; + + WINPR_ASSERT(input); + ps = (pServerContext*)input->context; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + pc = ps->pdata->pc; + WINPR_ASSERT(pc); + + config = ps->pdata->config; + WINPR_ASSERT(config); + + if (!pf_server_check_and_sync_input_state(pc)) + return TRUE; + + if (!config->Mouse) + return TRUE; + + event.flags = flags; + event.x = x; + event.y = y; + if (pf_modules_run_filter(pc->pdata->module, FILTER_TYPE_MOUSE, pc->pdata, &event)) + return freerdp_input_send_extended_mouse_event(pc->context.input, flags, x, y); + return TRUE; +} + +void pf_server_register_input_callbacks(rdpInput* input) +{ + WINPR_ASSERT(input); + + input->SynchronizeEvent = pf_server_synchronize_event; + input->KeyboardEvent = pf_server_keyboard_event; + input->UnicodeKeyboardEvent = pf_server_unicode_keyboard_event; + input->MouseEvent = pf_server_mouse_event; + input->ExtendedMouseEvent = pf_server_extended_mouse_event; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.h new file mode 100644 index 0000000000000000000000000000000000000000..ea9c542fab08a44df74c7a9282b312636d45770a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_input.h @@ -0,0 +1,29 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * + * 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 FREERDP_SERVER_PROXY_PFINPUT_H +#define FREERDP_SERVER_PROXY_PFINPUT_H + +#include + +void pf_server_register_input_callbacks(rdpInput* input); + +#endif /* FREERDP_SERVER_PROXY_PFINPUT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_modules.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_modules.c new file mode 100644 index 0000000000000000000000000000000000000000..9ae969cbb6b372fd0b566672538a9a976124126a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_modules.c @@ -0,0 +1,632 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server modules API + * + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include "proxy_modules.h" + +#define TAG PROXY_TAG("modules") + +#define MODULE_ENTRY_POINT "proxy_module_entry_point" + +struct proxy_module +{ + proxyPluginsManager mgr; + wArrayList* plugins; + wArrayList* handles; +}; + +static const char* pf_modules_get_filter_type_string(PF_FILTER_TYPE result) +{ + switch (result) + { + case FILTER_TYPE_KEYBOARD: + return "FILTER_TYPE_KEYBOARD"; + case FILTER_TYPE_UNICODE: + return "FILTER_TYPE_UNICODE"; + case FILTER_TYPE_MOUSE: + return "FILTER_TYPE_MOUSE"; + case FILTER_TYPE_MOUSE_EX: + return "FILTER_TYPE_MOUSE_EX"; + case FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_DATA: + return "FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_DATA"; + case FILTER_TYPE_SERVER_PASSTHROUGH_CHANNEL_DATA: + return "FILTER_TYPE_SERVER_PASSTHROUGH_CHANNEL_DATA"; + case FILTER_TYPE_CLIENT_PASSTHROUGH_DYN_CHANNEL_CREATE: + return "FILTER_TYPE_CLIENT_PASSTHROUGH_DYN_CHANNEL_CREATE"; + case FILTER_TYPE_SERVER_FETCH_TARGET_ADDR: + return "FILTER_TYPE_SERVER_FETCH_TARGET_ADDR"; + case FILTER_TYPE_SERVER_PEER_LOGON: + return "FILTER_TYPE_SERVER_PEER_LOGON"; + case FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_CREATE: + return "FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_CREATE"; + case FILTER_LAST: + return "FILTER_LAST"; + default: + return "FILTER_UNKNOWN"; + } +} + +static const char* pf_modules_get_hook_type_string(PF_HOOK_TYPE result) +{ + switch (result) + { + case HOOK_TYPE_CLIENT_INIT_CONNECT: + return "HOOK_TYPE_CLIENT_INIT_CONNECT"; + case HOOK_TYPE_CLIENT_UNINIT_CONNECT: + return "HOOK_TYPE_CLIENT_UNINIT_CONNECT"; + case HOOK_TYPE_CLIENT_PRE_CONNECT: + return "HOOK_TYPE_CLIENT_PRE_CONNECT"; + case HOOK_TYPE_CLIENT_POST_CONNECT: + return "HOOK_TYPE_CLIENT_POST_CONNECT"; + case HOOK_TYPE_CLIENT_POST_DISCONNECT: + return "HOOK_TYPE_CLIENT_POST_DISCONNECT"; + case HOOK_TYPE_CLIENT_REDIRECT: + return "HOOK_TYPE_CLIENT_REDIRECT"; + case HOOK_TYPE_CLIENT_VERIFY_X509: + return "HOOK_TYPE_CLIENT_VERIFY_X509"; + case HOOK_TYPE_CLIENT_LOGIN_FAILURE: + return "HOOK_TYPE_CLIENT_LOGIN_FAILURE"; + case HOOK_TYPE_CLIENT_END_PAINT: + return "HOOK_TYPE_CLIENT_END_PAINT"; + case HOOK_TYPE_SERVER_POST_CONNECT: + return "HOOK_TYPE_SERVER_POST_CONNECT"; + case HOOK_TYPE_SERVER_ACTIVATE: + return "HOOK_TYPE_SERVER_ACTIVATE"; + case HOOK_TYPE_SERVER_CHANNELS_INIT: + return "HOOK_TYPE_SERVER_CHANNELS_INIT"; + case HOOK_TYPE_SERVER_CHANNELS_FREE: + return "HOOK_TYPE_SERVER_CHANNELS_FREE"; + case HOOK_TYPE_SERVER_SESSION_END: + return "HOOK_TYPE_SERVER_SESSION_END"; + case HOOK_TYPE_CLIENT_LOAD_CHANNELS: + return "HOOK_TYPE_CLIENT_LOAD_CHANNELS"; + case HOOK_TYPE_SERVER_SESSION_INITIALIZE: + return "HOOK_TYPE_SERVER_SESSION_INITIALIZE"; + case HOOK_TYPE_SERVER_SESSION_STARTED: + return "HOOK_TYPE_SERVER_SESSION_STARTED"; + case HOOK_LAST: + return "HOOK_LAST"; + default: + return "HOOK_TYPE_UNKNOWN"; + } +} + +static BOOL pf_modules_proxy_ArrayList_ForEachFkt(void* data, size_t index, va_list ap) +{ + proxyPlugin* plugin = (proxyPlugin*)data; + BOOL ok = FALSE; + + WINPR_UNUSED(index); + + PF_HOOK_TYPE type = va_arg(ap, PF_HOOK_TYPE); + proxyData* pdata = va_arg(ap, proxyData*); + void* custom = va_arg(ap, void*); + + WLog_VRB(TAG, "running hook %s.%s", plugin->name, pf_modules_get_hook_type_string(type)); + + switch (type) + { + case HOOK_TYPE_CLIENT_INIT_CONNECT: + ok = IFCALLRESULT(TRUE, plugin->ClientInitConnect, plugin, pdata, custom); + break; + case HOOK_TYPE_CLIENT_UNINIT_CONNECT: + ok = IFCALLRESULT(TRUE, plugin->ClientUninitConnect, plugin, pdata, custom); + break; + case HOOK_TYPE_CLIENT_PRE_CONNECT: + ok = IFCALLRESULT(TRUE, plugin->ClientPreConnect, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_POST_CONNECT: + ok = IFCALLRESULT(TRUE, plugin->ClientPostConnect, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_REDIRECT: + ok = IFCALLRESULT(TRUE, plugin->ClientRedirect, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_POST_DISCONNECT: + ok = IFCALLRESULT(TRUE, plugin->ClientPostDisconnect, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_VERIFY_X509: + ok = IFCALLRESULT(TRUE, plugin->ClientX509Certificate, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_LOGIN_FAILURE: + ok = IFCALLRESULT(TRUE, plugin->ClientLoginFailure, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_END_PAINT: + ok = IFCALLRESULT(TRUE, plugin->ClientEndPaint, plugin, pdata, custom); + break; + + case HOOK_TYPE_CLIENT_LOAD_CHANNELS: + ok = IFCALLRESULT(TRUE, plugin->ClientLoadChannels, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_POST_CONNECT: + ok = IFCALLRESULT(TRUE, plugin->ServerPostConnect, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_ACTIVATE: + ok = IFCALLRESULT(TRUE, plugin->ServerPeerActivate, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_CHANNELS_INIT: + ok = IFCALLRESULT(TRUE, plugin->ServerChannelsInit, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_CHANNELS_FREE: + ok = IFCALLRESULT(TRUE, plugin->ServerChannelsFree, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_SESSION_END: + ok = IFCALLRESULT(TRUE, plugin->ServerSessionEnd, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_SESSION_INITIALIZE: + ok = IFCALLRESULT(TRUE, plugin->ServerSessionInitialize, plugin, pdata, custom); + break; + + case HOOK_TYPE_SERVER_SESSION_STARTED: + ok = IFCALLRESULT(TRUE, plugin->ServerSessionStarted, plugin, pdata, custom); + break; + + case HOOK_LAST: + default: + WLog_ERR(TAG, "invalid hook called"); + } + + if (!ok) + { + WLog_INFO(TAG, "plugin %s, hook %s failed!", plugin->name, + pf_modules_get_hook_type_string(type)); + return FALSE; + } + return TRUE; +} + +/* + * runs all hooks of type `type`. + * + * @type: hook type to run. + * @server: pointer of server's rdpContext struct of the current session. + */ +BOOL pf_modules_run_hook(proxyModule* module, PF_HOOK_TYPE type, proxyData* pdata, void* custom) +{ + WINPR_ASSERT(module); + WINPR_ASSERT(module->plugins); + return ArrayList_ForEach(module->plugins, pf_modules_proxy_ArrayList_ForEachFkt, type, pdata, + custom); +} + +static BOOL pf_modules_ArrayList_ForEachFkt(void* data, size_t index, va_list ap) +{ + proxyPlugin* plugin = (proxyPlugin*)data; + BOOL result = FALSE; + + WINPR_UNUSED(index); + + PF_FILTER_TYPE type = va_arg(ap, PF_FILTER_TYPE); + proxyData* pdata = va_arg(ap, proxyData*); + void* param = va_arg(ap, void*); + + WLog_VRB(TAG, "running filter: %s", plugin->name); + + switch (type) + { + case FILTER_TYPE_KEYBOARD: + result = IFCALLRESULT(TRUE, plugin->KeyboardEvent, plugin, pdata, param); + break; + + case FILTER_TYPE_UNICODE: + result = IFCALLRESULT(TRUE, plugin->UnicodeEvent, plugin, pdata, param); + break; + + case FILTER_TYPE_MOUSE: + result = IFCALLRESULT(TRUE, plugin->MouseEvent, plugin, pdata, param); + break; + + case FILTER_TYPE_MOUSE_EX: + result = IFCALLRESULT(TRUE, plugin->MouseExEvent, plugin, pdata, param); + break; + + case FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_DATA: + result = IFCALLRESULT(TRUE, plugin->ClientChannelData, plugin, pdata, param); + break; + + case FILTER_TYPE_SERVER_PASSTHROUGH_CHANNEL_DATA: + result = IFCALLRESULT(TRUE, plugin->ServerChannelData, plugin, pdata, param); + break; + + case FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_CREATE: + result = IFCALLRESULT(TRUE, plugin->ChannelCreate, plugin, pdata, param); + break; + + case FILTER_TYPE_CLIENT_PASSTHROUGH_DYN_CHANNEL_CREATE: + result = IFCALLRESULT(TRUE, plugin->DynamicChannelCreate, plugin, pdata, param); + break; + + case FILTER_TYPE_SERVER_FETCH_TARGET_ADDR: + result = IFCALLRESULT(TRUE, plugin->ServerFetchTargetAddr, plugin, pdata, param); + break; + + case FILTER_TYPE_SERVER_PEER_LOGON: + result = IFCALLRESULT(TRUE, plugin->ServerPeerLogon, plugin, pdata, param); + break; + + case FILTER_TYPE_INTERCEPT_CHANNEL: + result = IFCALLRESULT(TRUE, plugin->DynChannelIntercept, plugin, pdata, param); + break; + + case FILTER_TYPE_DYN_INTERCEPT_LIST: + result = IFCALLRESULT(TRUE, plugin->DynChannelToIntercept, plugin, pdata, param); + break; + + case FILTER_TYPE_STATIC_INTERCEPT_LIST: + result = IFCALLRESULT(TRUE, plugin->StaticChannelToIntercept, plugin, pdata, param); + break; + + case FILTER_LAST: + default: + WLog_ERR(TAG, "invalid filter called"); + } + + if (!result) + { + /* current filter return FALSE, no need to run other filters. */ + WLog_DBG(TAG, "plugin %s, filter type [%s] returned FALSE", plugin->name, + pf_modules_get_filter_type_string(type)); + } + return result; +} + +/* + * runs all filters of type `type`. + * + * @type: filter type to run. + * @server: pointer of server's rdpContext struct of the current session. + */ +BOOL pf_modules_run_filter(proxyModule* module, PF_FILTER_TYPE type, proxyData* pdata, void* param) +{ + WINPR_ASSERT(module); + WINPR_ASSERT(module->plugins); + + return ArrayList_ForEach(module->plugins, pf_modules_ArrayList_ForEachFkt, type, pdata, param); +} + +/* + * stores per-session data needed by a plugin. + * + * @context: current session server's rdpContext instance. + * @info: pointer to per-session data. + */ +static BOOL pf_modules_set_plugin_data(proxyPluginsManager* mgr, const char* plugin_name, + proxyData* pdata, void* data) +{ + union + { + const char* ccp; + char* cp; + } ccharconv; + + WINPR_ASSERT(plugin_name); + + ccharconv.ccp = plugin_name; + if (data == NULL) /* no need to store anything */ + return FALSE; + + if (!HashTable_Insert(pdata->modules_info, ccharconv.cp, data)) + { + WLog_ERR(TAG, "[%s]: HashTable_Insert failed!"); + return FALSE; + } + + return TRUE; +} + +/* + * returns per-session data needed a plugin. + * + * @context: current session server's rdpContext instance. + * if there's no data related to `plugin_name` in `context` (current session), a NULL will be + * returned. + */ +static void* pf_modules_get_plugin_data(proxyPluginsManager* mgr, const char* plugin_name, + proxyData* pdata) +{ + union + { + const char* ccp; + char* cp; + } ccharconv; + WINPR_ASSERT(plugin_name); + WINPR_ASSERT(pdata); + ccharconv.ccp = plugin_name; + + return HashTable_GetItemValue(pdata->modules_info, ccharconv.cp); +} + +static void pf_modules_abort_connect(proxyPluginsManager* mgr, proxyData* pdata) +{ + WINPR_ASSERT(pdata); + WLog_DBG(TAG, "is called!"); + proxy_data_abort_connect(pdata); +} + +static BOOL pf_modules_register_ArrayList_ForEachFkt(void* data, size_t index, va_list ap) +{ + proxyPlugin* plugin = (proxyPlugin*)data; + proxyPlugin* plugin_to_register = va_arg(ap, proxyPlugin*); + + WINPR_UNUSED(index); + + if (strcmp(plugin->name, plugin_to_register->name) == 0) + { + WLog_ERR(TAG, "can not register plugin '%s', it is already registered!", plugin->name); + return FALSE; + } + return TRUE; +} + +static BOOL pf_modules_register_plugin(proxyPluginsManager* mgr, + const proxyPlugin* plugin_to_register) +{ + proxyPlugin internal = { 0 }; + proxyModule* module = (proxyModule*)mgr; + WINPR_ASSERT(module); + + if (!plugin_to_register) + return FALSE; + + internal = *plugin_to_register; + internal.mgr = mgr; + + /* make sure there's no other loaded plugin with the same name of `plugin_to_register`. */ + if (!ArrayList_ForEach(module->plugins, pf_modules_register_ArrayList_ForEachFkt, &internal)) + return FALSE; + + if (!ArrayList_Append(module->plugins, &internal)) + { + WLog_ERR(TAG, "failed adding plugin to list: %s", plugin_to_register->name); + return FALSE; + } + + return TRUE; +} + +static BOOL pf_modules_load_ArrayList_ForEachFkt(void* data, size_t index, va_list ap) +{ + proxyPlugin* plugin = (proxyPlugin*)data; + const char* plugin_name = va_arg(ap, const char*); + BOOL* res = va_arg(ap, BOOL*); + + WINPR_UNUSED(index); + WINPR_UNUSED(ap); + WINPR_ASSERT(res); + + if (strcmp(plugin->name, plugin_name) == 0) + *res = TRUE; + return TRUE; +} + +BOOL pf_modules_is_plugin_loaded(proxyModule* module, const char* plugin_name) +{ + BOOL rc = FALSE; + WINPR_ASSERT(module); + if (ArrayList_Count(module->plugins) < 1) + return FALSE; + if (!ArrayList_ForEach(module->plugins, pf_modules_load_ArrayList_ForEachFkt, plugin_name, &rc)) + return FALSE; + return rc; +} + +static BOOL pf_modules_print_ArrayList_ForEachFkt(void* data, size_t index, va_list ap) +{ + proxyPlugin* plugin = (proxyPlugin*)data; + + WINPR_UNUSED(index); + WINPR_UNUSED(ap); + + WLog_INFO(TAG, "\tName: %s", plugin->name); + WLog_INFO(TAG, "\tDescription: %s", plugin->description); + return TRUE; +} + +void pf_modules_list_loaded_plugins(proxyModule* module) +{ + size_t count = 0; + + WINPR_ASSERT(module); + WINPR_ASSERT(module->plugins); + + count = ArrayList_Count(module->plugins); + + if (count > 0) + WLog_INFO(TAG, "Loaded plugins:"); + + ArrayList_ForEach(module->plugins, pf_modules_print_ArrayList_ForEachFkt); +} + +static BOOL pf_modules_load_module(const char* module_path, proxyModule* module, void* userdata) +{ + WINPR_ASSERT(module); + + HANDLE handle = LoadLibraryX(module_path); + + if (handle == NULL) + { + WLog_ERR(TAG, "failed loading external library: %s", module_path); + return FALSE; + } + + proxyModuleEntryPoint pEntryPoint = + GetProcAddressAs(handle, MODULE_ENTRY_POINT, proxyModuleEntryPoint); + if (!pEntryPoint) + { + WLog_ERR(TAG, "GetProcAddress failed while loading %s", module_path); + goto error; + } + if (!ArrayList_Append(module->handles, handle)) + { + WLog_ERR(TAG, "ArrayList_Append failed!"); + goto error; + } + return pf_modules_add(module, pEntryPoint, userdata); + +error: + FreeLibrary(handle); + return FALSE; +} + +static void free_handle(void* obj) +{ + HANDLE handle = (HANDLE)obj; + if (handle) + FreeLibrary(handle); +} + +static void free_plugin(void* obj) +{ + proxyPlugin* plugin = (proxyPlugin*)obj; + WINPR_ASSERT(plugin); + + if (!IFCALLRESULT(TRUE, plugin->PluginUnload, plugin)) + WLog_WARN(TAG, "PluginUnload failed for plugin '%s'", plugin->name); + + free(plugin); +} + +static void* new_plugin(const void* obj) +{ + const proxyPlugin* src = obj; + proxyPlugin* proxy = calloc(1, sizeof(proxyPlugin)); + if (!proxy) + return NULL; + *proxy = *src; + return proxy; +} + +proxyModule* pf_modules_new(const char* root_dir, const char** modules, size_t count) +{ + wObject* obj = NULL; + char* path = NULL; + proxyModule* module = calloc(1, sizeof(proxyModule)); + if (!module) + return NULL; + + module->mgr.RegisterPlugin = pf_modules_register_plugin; + module->mgr.SetPluginData = pf_modules_set_plugin_data; + module->mgr.GetPluginData = pf_modules_get_plugin_data; + module->mgr.AbortConnect = pf_modules_abort_connect; + module->plugins = ArrayList_New(FALSE); + + if (module->plugins == NULL) + { + WLog_ERR(TAG, "ArrayList_New failed!"); + goto error; + } + obj = ArrayList_Object(module->plugins); + WINPR_ASSERT(obj); + + obj->fnObjectFree = free_plugin; + obj->fnObjectNew = new_plugin; + + module->handles = ArrayList_New(FALSE); + if (module->handles == NULL) + { + + WLog_ERR(TAG, "ArrayList_New failed!"); + goto error; + } + ArrayList_Object(module->handles)->fnObjectFree = free_handle; + + if (count > 0) + { + WINPR_ASSERT(root_dir); + if (!winpr_PathFileExists(root_dir)) + path = GetCombinedPath(FREERDP_INSTALL_PREFIX, root_dir); + else + path = _strdup(root_dir); + + if (!winpr_PathFileExists(path)) + { + if (!winpr_PathMakePath(path, NULL)) + { + WLog_ERR(TAG, "error occurred while creating modules directory: %s", root_dir); + goto error; + } + } + + if (winpr_PathFileExists(path)) + WLog_DBG(TAG, "modules root directory: %s", path); + + for (size_t i = 0; i < count; i++) + { + char name[8192] = { 0 }; + char* fullpath = NULL; + (void)_snprintf(name, sizeof(name), "proxy-%s-plugin%s", modules[i], + FREERDP_SHARED_LIBRARY_SUFFIX); + fullpath = GetCombinedPath(path, name); + pf_modules_load_module(fullpath, module, NULL); + free(fullpath); + } + } + + free(path); + return module; + +error: + free(path); + pf_modules_free(module); + return NULL; +} + +void pf_modules_free(proxyModule* module) +{ + if (!module) + return; + + ArrayList_Free(module->plugins); + ArrayList_Free(module->handles); + free(module); +} + +BOOL pf_modules_add(proxyModule* module, proxyModuleEntryPoint ep, void* userdata) +{ + WINPR_ASSERT(module); + WINPR_ASSERT(ep); + + return ep(&module->mgr, userdata); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.c new file mode 100644 index 0000000000000000000000000000000000000000..d7d05bdf8adebd64d5e31b4b2d353b4db34ba2c9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.c @@ -0,0 +1,1094 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include "pf_server.h" +#include "pf_channel.h" +#include +#include "pf_client.h" +#include +#include "pf_update.h" +#include "proxy_modules.h" +#include "pf_utils.h" +#include "channels/pf_channel_drdynvc.h" +#include "channels/pf_channel_rdpdr.h" + +#define TAG PROXY_TAG("server") + +typedef struct +{ + HANDLE thread; + freerdp_peer* client; +} peer_thread_args; + +static BOOL pf_server_parse_target_from_routing_token(rdpContext* context, rdpSettings* settings, + FreeRDP_Settings_Keys_String targetID, + FreeRDP_Settings_Keys_UInt32 portID) +{ +#define TARGET_MAX (100) +#define ROUTING_TOKEN_PREFIX "Cookie: msts=" + char* colon = NULL; + size_t len = 0; + DWORD routing_token_length = 0; + const size_t prefix_len = strnlen(ROUTING_TOKEN_PREFIX, sizeof(ROUTING_TOKEN_PREFIX)); + const char* routing_token = freerdp_nego_get_routing_token(context, &routing_token_length); + pServerContext* ps = (pServerContext*)context; + + if (!routing_token) + return FALSE; + + if ((routing_token_length <= prefix_len) || (routing_token_length >= TARGET_MAX)) + { + PROXY_LOG_ERR(TAG, ps, "invalid routing token length: %" PRIu32 "", routing_token_length); + return FALSE; + } + + len = routing_token_length - prefix_len; + + if (!freerdp_settings_set_string_len(settings, targetID, routing_token + prefix_len, len)) + return FALSE; + + const char* target = freerdp_settings_get_string(settings, targetID); + colon = strchr(target, ':'); + + if (colon) + { + /* port is specified */ + unsigned long p = strtoul(colon + 1, NULL, 10); + + if (p > USHRT_MAX) + return FALSE; + + if (!freerdp_settings_set_uint32(settings, portID, (USHORT)p)) + return FALSE; + } + + return TRUE; +} + +static BOOL pf_server_get_target_info(rdpContext* context, rdpSettings* settings, + const proxyConfig* config) +{ + pServerContext* ps = (pServerContext*)context; + proxyFetchTargetEventInfo ev = { 0 }; + + WINPR_ASSERT(settings); + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + + ev.fetch_method = config->FixedTarget ? PROXY_FETCH_TARGET_METHOD_CONFIG + : PROXY_FETCH_TARGET_METHOD_LOAD_BALANCE_INFO; + + if (!pf_modules_run_filter(ps->pdata->module, FILTER_TYPE_SERVER_FETCH_TARGET_ADDR, ps->pdata, + &ev)) + return FALSE; + + switch (ev.fetch_method) + { + case PROXY_FETCH_TARGET_METHOD_DEFAULT: + case PROXY_FETCH_TARGET_METHOD_LOAD_BALANCE_INFO: + return pf_server_parse_target_from_routing_token( + context, settings, FreeRDP_ServerHostname, FreeRDP_ServerPort); + + case PROXY_FETCH_TARGET_METHOD_CONFIG: + { + WINPR_ASSERT(config); + + if (config->TargetPort > 0) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, config->TargetPort)) + return FALSE; + } + else + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, 3389)) + return FALSE; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_TlsSecLevel, + config->TargetTlsSecLevel)) + return FALSE; + + if (!freerdp_settings_set_string(settings, FreeRDP_ServerHostname, config->TargetHost)) + { + PROXY_LOG_ERR(TAG, ps, "strdup failed!"); + return FALSE; + } + + if (config->TargetUser) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Username, config->TargetUser)) + return FALSE; + } + + if (config->TargetDomain) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Domain, config->TargetDomain)) + return FALSE; + } + + if (config->TargetPassword) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Password, + config->TargetPassword)) + return FALSE; + } + + return TRUE; + } + case PROXY_FETCH_TARGET_USE_CUSTOM_ADDR: + { + if (!ev.target_address) + { + PROXY_LOG_ERR(TAG, ps, + "router: using CUSTOM_ADDR fetch method, but target_address == NULL"); + return FALSE; + } + + if (!freerdp_settings_set_string(settings, FreeRDP_ServerHostname, ev.target_address)) + { + PROXY_LOG_ERR(TAG, ps, "strdup failed!"); + return FALSE; + } + + free(ev.target_address); + return freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, ev.target_port); + } + default: + PROXY_LOG_ERR(TAG, ps, "unknown target fetch method: %d", ev.fetch_method); + return FALSE; + } + + return TRUE; +} + +static BOOL pf_server_setup_channels(freerdp_peer* peer) +{ + BOOL rc = FALSE; + char** accepted_channels = NULL; + size_t accepted_channels_count = 0; + pServerContext* ps = (pServerContext*)peer->context; + + accepted_channels = WTSGetAcceptedChannelNames(peer, &accepted_channels_count); + if (!accepted_channels) + return TRUE; + + for (size_t i = 0; i < accepted_channels_count; i++) + { + pServerStaticChannelContext* channelContext = NULL; + const char* cname = accepted_channels[i]; + UINT16 channelId = WTSChannelGetId(peer, cname); + + PROXY_LOG_INFO(TAG, ps, "Accepted channel: %s (%" PRIu16 ")", cname, channelId); + channelContext = StaticChannelContext_new(ps, cname, channelId); + if (!channelContext) + { + PROXY_LOG_ERR(TAG, ps, "error setting up channelContext for '%s'", cname); + goto fail; + } + + if ((strcmp(cname, DRDYNVC_SVC_CHANNEL_NAME) == 0) && + (channelContext->channelMode == PF_UTILS_CHANNEL_INTERCEPT)) + { + if (!pf_channel_setup_drdynvc(ps->pdata, channelContext)) + { + PROXY_LOG_ERR(TAG, ps, "error while setting up dynamic channel"); + StaticChannelContext_free(channelContext); + goto fail; + } + } + else if (strcmp(cname, RDPDR_SVC_CHANNEL_NAME) == 0 && + (channelContext->channelMode == PF_UTILS_CHANNEL_INTERCEPT)) + { + if (!pf_channel_setup_rdpdr(ps, channelContext)) + { + PROXY_LOG_ERR(TAG, ps, "error while setting up redirection channel"); + StaticChannelContext_free(channelContext); + goto fail; + } + } + else + { + if (!pf_channel_setup_generic(channelContext)) + { + PROXY_LOG_ERR(TAG, ps, "error while setting up generic channel"); + StaticChannelContext_free(channelContext); + goto fail; + } + } + + if (!HashTable_Insert(ps->channelsByFrontId, &channelContext->front_channel_id, + channelContext)) + { + StaticChannelContext_free(channelContext); + PROXY_LOG_ERR(TAG, ps, "error inserting channelContext in byId table for '%s'", cname); + goto fail; + } + } + + rc = TRUE; +fail: + free((void*)accepted_channels); + return rc; +} + +/* Event callbacks */ + +/** + * This callback is called when the entire connection sequence is done (as + * described in MS-RDPBCGR section 1.3) + * + * The server may start sending graphics output and receiving keyboard/mouse + * input after this callback returns. + */ +static BOOL pf_server_post_connect(freerdp_peer* peer) +{ + pServerContext* ps = NULL; + pClientContext* pc = NULL; + rdpSettings* client_settings = NULL; + proxyData* pdata = NULL; + rdpSettings* frontSettings = NULL; + + WINPR_ASSERT(peer); + + ps = (pServerContext*)peer->context; + WINPR_ASSERT(ps); + + frontSettings = peer->context->settings; + WINPR_ASSERT(frontSettings); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + + const char* ClientHostname = freerdp_settings_get_string(frontSettings, FreeRDP_ClientHostname); + PROXY_LOG_INFO(TAG, ps, "Accepted client: %s", ClientHostname); + if (!pf_server_setup_channels(peer)) + { + PROXY_LOG_ERR(TAG, ps, "error setting up channels"); + return FALSE; + } + + pc = pf_context_create_client_context(frontSettings); + if (pc == NULL) + { + PROXY_LOG_ERR(TAG, ps, "failed to create client context!"); + return FALSE; + } + + client_settings = pc->context.settings; + + /* keep both sides of the connection in pdata */ + proxy_data_set_client_context(pdata, pc); + + if (!pf_server_get_target_info(peer->context, client_settings, pdata->config)) + { + PROXY_LOG_INFO(TAG, ps, "pf_server_get_target_info failed!"); + return FALSE; + } + + PROXY_LOG_INFO(TAG, ps, "remote target is %s:%" PRIu32 "", + freerdp_settings_get_string(client_settings, FreeRDP_ServerHostname), + freerdp_settings_get_uint32(client_settings, FreeRDP_ServerPort)); + + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_SERVER_POST_CONNECT, pdata, peer)) + return FALSE; + + /* Start a proxy's client in it's own thread */ + if (!(pdata->client_thread = CreateThread(NULL, 0, pf_client_start, pc, 0, NULL))) + { + PROXY_LOG_ERR(TAG, ps, "failed to create client thread"); + return FALSE; + } + + return TRUE; +} + +static BOOL pf_server_activate(freerdp_peer* peer) +{ + pServerContext* ps = NULL; + proxyData* pdata = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(peer); + + ps = (pServerContext*)peer->context; + WINPR_ASSERT(ps); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + + settings = peer->context->settings; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_CompressionLevel, PACKET_COMPR_TYPE_RDP8)) + return FALSE; + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_SERVER_ACTIVATE, pdata, peer)) + return FALSE; + + return TRUE; +} + +static BOOL pf_server_logon(freerdp_peer* peer, const SEC_WINNT_AUTH_IDENTITY* identity, + BOOL automatic) +{ + pServerContext* ps = NULL; + proxyData* pdata = NULL; + proxyServerPeerLogon info = { 0 }; + + WINPR_ASSERT(peer); + + ps = (pServerContext*)peer->context; + WINPR_ASSERT(ps); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + WINPR_ASSERT(identity); + + info.identity = identity; + info.automatic = automatic; + if (!pf_modules_run_filter(pdata->module, FILTER_TYPE_SERVER_PEER_LOGON, pdata, &info)) + return FALSE; + return TRUE; +} + +static BOOL pf_server_adjust_monitor_layout(freerdp_peer* peer) +{ + WINPR_ASSERT(peer); + /* proxy as is, there's no need to do anything here */ + return TRUE; +} + +static BOOL pf_server_receive_channel_data_hook(freerdp_peer* peer, UINT16 channelId, + const BYTE* data, size_t size, UINT32 flags, + size_t totalSize) +{ + pServerContext* ps = NULL; + pClientContext* pc = NULL; + proxyData* pdata = NULL; + const proxyConfig* config = NULL; + const pServerStaticChannelContext* channel = NULL; + UINT64 channelId64 = channelId; + + WINPR_ASSERT(peer); + + ps = (pServerContext*)peer->context; + WINPR_ASSERT(ps); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + + pc = pdata->pc; + config = pdata->config; + WINPR_ASSERT(config); + /* + * client side is not initialized yet, call original callback. + * this is probably a drdynvc message between peer and proxy server, + * which doesn't need to be proxied. + */ + if (!pc) + goto original_cb; + + channel = HashTable_GetItemValue(ps->channelsByFrontId, &channelId64); + if (!channel) + { + PROXY_LOG_ERR(TAG, ps, "channel id=%" PRIu64 " not registered here, dropping", channelId64); + return TRUE; + } + + WINPR_ASSERT(channel->onFrontData); + switch (channel->onFrontData(pdata, channel, data, size, flags, totalSize)) + { + case PF_CHANNEL_RESULT_PASS: + { + proxyChannelDataEventInfo ev = { 0 }; + + ev.channel_id = channelId; + ev.channel_name = channel->channel_name; + ev.data = data; + ev.data_len = size; + ev.flags = flags; + ev.total_size = totalSize; + return IFCALLRESULT(TRUE, pc->sendChannelData, pc, &ev); + } + case PF_CHANNEL_RESULT_DROP: + return TRUE; + case PF_CHANNEL_RESULT_ERROR: + default: + return FALSE; + } + +original_cb: + WINPR_ASSERT(pdata->server_receive_channel_data_original); + return pdata->server_receive_channel_data_original(peer, channelId, data, size, flags, + totalSize); +} + +static BOOL pf_server_initialize_peer_connection(freerdp_peer* peer) +{ + WINPR_ASSERT(peer); + + pServerContext* ps = (pServerContext*)peer->context; + if (!ps) + return FALSE; + + rdpSettings* settings = peer->context->settings; + WINPR_ASSERT(settings); + + proxyData* pdata = proxy_data_new(); + if (!pdata) + return FALSE; + proxyServer* server = (proxyServer*)peer->ContextExtra; + WINPR_ASSERT(server); + proxy_data_set_server_context(pdata, ps); + + pdata->module = server->module; + const proxyConfig* config = pdata->config = server->config; + + rdpPrivateKey* key = freerdp_key_new_from_pem(config->PrivateKeyPEM); + if (!key) + return FALSE; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerRsaKey, key, 1)) + return FALSE; + + rdpCertificate* cert = freerdp_certificate_new_from_pem(config->CertificatePEM); + if (!cert) + return FALSE; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerCertificate, cert, 1)) + return FALSE; + + /* currently not supporting GDI orders */ + { + void* OrderSupport = freerdp_settings_get_pointer_writable(settings, FreeRDP_OrderSupport); + ZeroMemory(OrderSupport, 32); + } + + WINPR_ASSERT(peer->context->update); + peer->context->update->autoCalculateBitmapData = FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportMonitorLayoutPdu, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, config->GFX)) + return FALSE; + + if (pf_utils_is_passthrough(config)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_DeactivateClientDecoding, TRUE)) + return FALSE; + } + + if (config->RemoteApp) + { + const UINT32 mask = + RAIL_LEVEL_SUPPORTED | RAIL_LEVEL_DOCKED_LANGBAR_SUPPORTED | + RAIL_LEVEL_SHELL_INTEGRATION_SUPPORTED | RAIL_LEVEL_LANGUAGE_IME_SYNC_SUPPORTED | + RAIL_LEVEL_SERVER_TO_CLIENT_IME_SYNC_SUPPORTED | + RAIL_LEVEL_HIDE_MINIMIZED_APPS_SUPPORTED | RAIL_LEVEL_WINDOW_CLOAKING_SUPPORTED | + RAIL_LEVEL_HANDSHAKE_EX_SUPPORTED; + if (!freerdp_settings_set_uint32(settings, FreeRDP_RemoteApplicationSupportLevel, mask)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteAppLanguageBarSupported, TRUE)) + return FALSE; + } + + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, config->ServerRdpSecurity)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, config->ServerTlsSecurity)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, config->ServerNlaSecurity)) + return FALSE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_EncryptionLevel, + ENCRYPTION_LEVEL_CLIENT_COMPATIBLE)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SuppressOutput, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RefreshRect, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DesktopResize, TRUE)) + return FALSE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_MultifragMaxRequestSize, + 0xFFFFFF)) /* FIXME */ + return FALSE; + + peer->PostConnect = pf_server_post_connect; + peer->Activate = pf_server_activate; + peer->Logon = pf_server_logon; + peer->AdjustMonitorsLayout = pf_server_adjust_monitor_layout; + + /* virtual channels receive data hook */ + pdata->server_receive_channel_data_original = peer->ReceiveChannelData; + peer->ReceiveChannelData = pf_server_receive_channel_data_hook; + + if (!stream_dump_register_handlers(peer->context, CONNECTION_STATE_NEGO, TRUE)) + return FALSE; + return TRUE; +} + +/** + * Handles an incoming client connection, to be run in it's own thread. + * + * arg is a pointer to a freerdp_peer representing the client. + */ +static DWORD WINAPI pf_server_handle_peer(LPVOID arg) +{ + HANDLE eventHandles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + pServerContext* ps = NULL; + proxyData* pdata = NULL; + peer_thread_args* args = arg; + + WINPR_ASSERT(args); + + freerdp_peer* client = args->client; + WINPR_ASSERT(client); + + proxyServer* server = (proxyServer*)client->ContextExtra; + WINPR_ASSERT(server); + + size_t count = ArrayList_Count(server->peer_list); + + if (!pf_context_init_server_context(client)) + goto out_free_peer; + + if (!pf_server_initialize_peer_connection(client)) + goto out_free_peer; + + ps = (pServerContext*)client->context; + WINPR_ASSERT(ps); + PROXY_LOG_DBG(TAG, ps, "Added peer, %" PRIuz " connected", count); + + pdata = ps->pdata; + WINPR_ASSERT(pdata); + + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_SERVER_SESSION_INITIALIZE, pdata, client)) + goto out_free_peer; + + WINPR_ASSERT(client->Initialize); + client->Initialize(client); + + PROXY_LOG_INFO(TAG, ps, "new connection: proxy address: %s, client address: %s", + pdata->config->Host, client->hostname); + + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_SERVER_SESSION_STARTED, pdata, client)) + goto out_free_peer; + + while (1) + { + HANDLE ChannelEvent = INVALID_HANDLE_VALUE; + DWORD eventCount = 0; + { + WINPR_ASSERT(client->GetEventHandles); + const DWORD tmp = client->GetEventHandles(client, &eventHandles[eventCount], + ARRAYSIZE(eventHandles) - eventCount); + + if (tmp == 0) + { + PROXY_LOG_ERR(TAG, ps, "Failed to get FreeRDP transport event handles"); + break; + } + + eventCount += tmp; + } + /* Main client event handling loop */ + ChannelEvent = WTSVirtualChannelManagerGetEventHandle(ps->vcm); + + WINPR_ASSERT(ChannelEvent && (ChannelEvent != INVALID_HANDLE_VALUE)); + WINPR_ASSERT(pdata->abort_event && (pdata->abort_event != INVALID_HANDLE_VALUE)); + eventHandles[eventCount++] = ChannelEvent; + eventHandles[eventCount++] = pdata->abort_event; + eventHandles[eventCount++] = server->stopEvent; + + const DWORD status = WaitForMultipleObjects( + eventCount, eventHandles, FALSE, 1000); /* Do periodic polling to avoid client hang */ + + if (status == WAIT_FAILED) + { + PROXY_LOG_ERR(TAG, ps, "WaitForMultipleObjects failed (status: %" PRIu32 ")", status); + break; + } + + WINPR_ASSERT(client->CheckFileDescriptor); + if (client->CheckFileDescriptor(client) != TRUE) + break; + + if (WaitForSingleObject(ChannelEvent, 0) == WAIT_OBJECT_0) + { + if (!WTSVirtualChannelManagerCheckFileDescriptor(ps->vcm)) + { + PROXY_LOG_ERR(TAG, ps, "WTSVirtualChannelManagerCheckFileDescriptor failure"); + goto fail; + } + } + + /* only disconnect after checking client's and vcm's file descriptors */ + if (proxy_data_shall_disconnect(pdata)) + { + PROXY_LOG_INFO(TAG, ps, "abort event is set, closing connection with peer %s", + client->hostname); + break; + } + + if (WaitForSingleObject(server->stopEvent, 0) == WAIT_OBJECT_0) + { + PROXY_LOG_INFO(TAG, ps, "Server shutting down, terminating peer"); + break; + } + + switch (WTSVirtualChannelManagerGetDrdynvcState(ps->vcm)) + { + /* Dynamic channel status may have been changed after processing */ + case DRDYNVC_STATE_NONE: + + /* Initialize drdynvc channel */ + if (!WTSVirtualChannelManagerCheckFileDescriptor(ps->vcm)) + { + PROXY_LOG_ERR(TAG, ps, "Failed to initialize drdynvc channel"); + goto fail; + } + + break; + + case DRDYNVC_STATE_READY: + if (WaitForSingleObject(ps->dynvcReady, 0) == WAIT_TIMEOUT) + { + (void)SetEvent(ps->dynvcReady); + } + + break; + + default: + break; + } + } + +fail: + + PROXY_LOG_INFO(TAG, ps, "starting shutdown of connection"); + PROXY_LOG_INFO(TAG, ps, "stopping proxy's client"); + + /* Abort the client. */ + proxy_data_abort_connect(pdata); + + pf_modules_run_hook(pdata->module, HOOK_TYPE_SERVER_SESSION_END, pdata, client); + + PROXY_LOG_INFO(TAG, ps, "freeing server's channels"); + + WINPR_ASSERT(client->Close); + client->Close(client); + + WINPR_ASSERT(client->Disconnect); + client->Disconnect(client); + +out_free_peer: + PROXY_LOG_INFO(TAG, ps, "freeing proxy data"); + + if (pdata && pdata->client_thread) + { + proxy_data_abort_connect(pdata); + (void)WaitForSingleObject(pdata->client_thread, INFINITE); + } + + { + ArrayList_Lock(server->peer_list); + ArrayList_Remove(server->peer_list, args->thread); + count = ArrayList_Count(server->peer_list); + ArrayList_Unlock(server->peer_list); + } + PROXY_LOG_DBG(TAG, ps, "Removed peer, %" PRIuz " connected", count); + freerdp_peer_context_free(client); + freerdp_peer_free(client); + proxy_data_free(pdata); + +#if defined(WITH_DEBUG_EVENTS) + DumpEventHandles(); +#endif + free(args); + ExitThread(0); + return 0; +} + +static BOOL pf_server_start_peer(freerdp_peer* client) +{ + HANDLE hThread = NULL; + proxyServer* server = NULL; + peer_thread_args* args = calloc(1, sizeof(peer_thread_args)); + if (!args) + return FALSE; + + WINPR_ASSERT(client); + args->client = client; + + server = (proxyServer*)client->ContextExtra; + WINPR_ASSERT(server); + + hThread = CreateThread(NULL, 0, pf_server_handle_peer, args, CREATE_SUSPENDED, NULL); + if (!hThread) + return FALSE; + + args->thread = hThread; + if (!ArrayList_Append(server->peer_list, hThread)) + { + (void)CloseHandle(hThread); + return FALSE; + } + + return ResumeThread(hThread) != (DWORD)-1; +} + +static BOOL pf_server_peer_accepted(freerdp_listener* listener, freerdp_peer* client) +{ + WINPR_ASSERT(listener); + WINPR_ASSERT(client); + + client->ContextExtra = listener->info; + + return pf_server_start_peer(client); +} + +BOOL pf_server_start(proxyServer* server) +{ + WSADATA wsaData; + + WINPR_ASSERT(server); + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) + goto error; + + WINPR_ASSERT(server->config); + WINPR_ASSERT(server->listener); + WINPR_ASSERT(server->listener->Open); + if (!server->listener->Open(server->listener, server->config->Host, server->config->Port)) + { + switch (errno) + { + case EADDRINUSE: + WLog_ERR(TAG, "failed to start listener: address already in use!"); + break; + case EACCES: + WLog_ERR(TAG, "failed to start listener: insufficient permissions!"); + break; + default: + WLog_ERR(TAG, "failed to start listener: errno=%d", errno); + break; + } + + goto error; + } + + return TRUE; + +error: + WSACleanup(); + return FALSE; +} + +BOOL pf_server_start_from_socket(proxyServer* server, int socket) +{ + WSADATA wsaData; + + WINPR_ASSERT(server); + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) + goto error; + + WINPR_ASSERT(server->listener); + WINPR_ASSERT(server->listener->OpenFromSocket); + if (!server->listener->OpenFromSocket(server->listener, socket)) + { + switch (errno) + { + case EADDRINUSE: + WLog_ERR(TAG, "failed to start listener: address already in use!"); + break; + case EACCES: + WLog_ERR(TAG, "failed to start listener: insufficient permissions!"); + break; + default: + WLog_ERR(TAG, "failed to start listener: errno=%d", errno); + break; + } + + goto error; + } + + return TRUE; + +error: + WSACleanup(); + return FALSE; +} + +BOOL pf_server_start_with_peer_socket(proxyServer* server, int peer_fd) +{ + struct sockaddr_storage peer_addr; + socklen_t len = sizeof(peer_addr); + freerdp_peer* client = NULL; + + WINPR_ASSERT(server); + + if (WaitForSingleObject(server->stopEvent, 0) == WAIT_OBJECT_0) + goto fail; + + client = freerdp_peer_new(peer_fd); + if (!client) + goto fail; + + if (getpeername(peer_fd, (struct sockaddr*)&peer_addr, &len) != 0) + goto fail; + + if (!freerdp_peer_set_local_and_hostname(client, &peer_addr)) + goto fail; + + client->ContextExtra = server; + + if (!pf_server_start_peer(client)) + goto fail; + + return TRUE; + +fail: + WLog_ERR(TAG, "PeerAccepted callback failed"); + freerdp_peer_free(client); + return FALSE; +} + +static BOOL are_all_required_modules_loaded(proxyModule* module, const proxyConfig* config) +{ + for (size_t i = 0; i < pf_config_required_plugins_count(config); i++) + { + const char* plugin_name = pf_config_required_plugin(config, i); + + if (!pf_modules_is_plugin_loaded(module, plugin_name)) + { + WLog_ERR(TAG, "Required plugin '%s' is not loaded. stopping.", plugin_name); + return FALSE; + } + } + + return TRUE; +} + +static void peer_free(void* obj) +{ + HANDLE hdl = (HANDLE)obj; + (void)CloseHandle(hdl); +} + +proxyServer* pf_server_new(const proxyConfig* config) +{ + wObject* obj = NULL; + proxyServer* server = NULL; + + WINPR_ASSERT(config); + + server = calloc(1, sizeof(proxyServer)); + if (!server) + return NULL; + + if (!pf_config_clone(&server->config, config)) + goto out; + + server->module = pf_modules_new(FREERDP_PROXY_PLUGINDIR, pf_config_modules(server->config), + pf_config_modules_count(server->config)); + if (!server->module) + { + WLog_ERR(TAG, "failed to initialize proxy modules!"); + goto out; + } + + pf_modules_list_loaded_plugins(server->module); + if (!are_all_required_modules_loaded(server->module, server->config)) + goto out; + + server->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!server->stopEvent) + goto out; + + server->listener = freerdp_listener_new(); + if (!server->listener) + goto out; + + server->peer_list = ArrayList_New(FALSE); + if (!server->peer_list) + goto out; + + obj = ArrayList_Object(server->peer_list); + WINPR_ASSERT(obj); + + obj->fnObjectFree = peer_free; + + server->listener->info = server; + server->listener->PeerAccepted = pf_server_peer_accepted; + + if (!pf_modules_add(server->module, pf_config_plugin, (void*)server->config)) + goto out; + + return server; + +out: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + pf_server_free(server); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +BOOL pf_server_run(proxyServer* server) +{ + BOOL rc = TRUE; + HANDLE eventHandles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD eventCount = 0; + DWORD status = 0; + freerdp_listener* listener = NULL; + + WINPR_ASSERT(server); + + listener = server->listener; + WINPR_ASSERT(listener); + + while (1) + { + WINPR_ASSERT(listener->GetEventHandles); + eventCount = listener->GetEventHandles(listener, eventHandles, ARRAYSIZE(eventHandles)); + + if ((0 == eventCount) || (eventCount >= ARRAYSIZE(eventHandles))) + { + WLog_ERR(TAG, "Failed to get FreeRDP event handles"); + break; + } + + WINPR_ASSERT(server->stopEvent); + eventHandles[eventCount++] = server->stopEvent; + status = WaitForMultipleObjects(eventCount, eventHandles, FALSE, 1000); + + if (WAIT_FAILED == status) + break; + + if (WaitForSingleObject(server->stopEvent, 0) == WAIT_OBJECT_0) + break; + + if (WAIT_FAILED == status) + { + WLog_ERR(TAG, "select failed"); + rc = FALSE; + break; + } + + WINPR_ASSERT(listener->CheckFileDescriptor); + if (listener->CheckFileDescriptor(listener) != TRUE) + { + WLog_ERR(TAG, "Failed to accept new peer"); + // TODO: Set out of resource error + continue; + } + } + + WINPR_ASSERT(listener->Close); + listener->Close(listener); + return rc; +} + +void pf_server_stop(proxyServer* server) +{ + + if (!server) + return; + + /* signal main thread to stop and wait for the thread to exit */ + (void)SetEvent(server->stopEvent); +} + +void pf_server_free(proxyServer* server) +{ + if (!server) + return; + + pf_server_stop(server); + + if (server->peer_list) + { + while (ArrayList_Count(server->peer_list) > 0) + { + /* pf_server_stop triggers the threads to shut down. + * loop here until all of them stopped. + * + * This must be done before ArrayList_Free otherwise the thread removal + * in pf_server_handle_peer will deadlock due to both threads trying to + * lock the list. + */ + Sleep(100); + } + } + ArrayList_Free(server->peer_list); + freerdp_listener_free(server->listener); + + if (server->stopEvent) + (void)CloseHandle(server->stopEvent); + + pf_server_config_free(server->config); + pf_modules_free(server->module); + free(server); + +#if defined(WITH_DEBUG_EVENTS) + DumpEventHandles(); +#endif +} + +BOOL pf_server_add_module(proxyServer* server, proxyModuleEntryPoint ep, void* userdata) +{ + WINPR_ASSERT(server); + WINPR_ASSERT(ep); + + return pf_modules_add(server->module, ep, userdata); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.h new file mode 100644 index 0000000000000000000000000000000000000000..2ac84f22465d393572197862bb70b9002a7ca497 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_server.h @@ -0,0 +1,43 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef INT_FREERDP_SERVER_PROXY_SERVER_H +#define INT_FREERDP_SERVER_PROXY_SERVER_H + +#include +#include + +#include +#include "proxy_modules.h" + +struct proxy_server +{ + proxyModule* module; + proxyConfig* config; + + freerdp_listener* listener; + HANDLE stopEvent; /* an event used to signal the main thread to stop */ + wArrayList* peer_list; +}; + +#endif /* INT_FREERDP_SERVER_PROXY_SERVER_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.c new file mode 100644 index 0000000000000000000000000000000000000000..e57281039328fbab8f3de68bf274a10411efdb77 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.c @@ -0,0 +1,629 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * Copyright 2021 Armin Novak + * 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. + */ + +#include +#include +#include +#include +#include + +#include + +#include "pf_update.h" +#include +#include "proxy_modules.h" + +#define TAG PROXY_TAG("update") + +static BOOL pf_server_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) +{ + pServerContext* ps = (pServerContext*)context; + rdpContext* pc = NULL; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + pc = (rdpContext*)ps->pdata->pc; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->update); + WINPR_ASSERT(pc->update->RefreshRect); + return pc->update->RefreshRect(pc, count, areas); +} + +static BOOL pf_server_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) +{ + pServerContext* ps = (pServerContext*)context; + rdpContext* pc = NULL; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->pdata); + pc = (rdpContext*)ps->pdata->pc; + WINPR_ASSERT(pc); + WINPR_ASSERT(pc->update); + WINPR_ASSERT(pc->update->SuppressOutput); + return pc->update->SuppressOutput(pc, allow, area); +} + +/* Proxy from PC to PS */ + +/** + * This function is called whenever a new frame starts. + * It can be used to reset invalidated areas. + */ +static BOOL pf_client_begin_paint(rdpContext* context) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->BeginPaint); + WLog_DBG(TAG, "called"); + return ps->update->BeginPaint(ps); +} + +/** + * This function is called when the library completed composing a new + * frame. Read out the changed areas and blit them to your output device. + * The image buffer will have the format specified by gdi_init + */ +static BOOL pf_client_end_paint(rdpContext* context) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->EndPaint); + + WLog_DBG(TAG, "called"); + + /* proxy end paint */ + if (!ps->update->EndPaint(ps)) + return FALSE; + + if (!pf_modules_run_hook(pdata->module, HOOK_TYPE_CLIENT_END_PAINT, pdata, context)) + return FALSE; + + return TRUE; +} + +static BOOL pf_client_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmap) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->BitmapUpdate); + WLog_DBG(TAG, "called"); + return ps->update->BitmapUpdate(ps, bitmap); +} + +static BOOL pf_client_desktop_resize(rdpContext* context) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->DesktopResize); + WINPR_ASSERT(context->settings); + WINPR_ASSERT(ps->settings); + WLog_DBG(TAG, "called"); + if (!freerdp_settings_copy_item(ps->settings, context->settings, FreeRDP_DesktopWidth)) + return FALSE; + if (!freerdp_settings_copy_item(ps->settings, context->settings, FreeRDP_DesktopHeight)) + return FALSE; + return ps->update->DesktopResize(ps); +} + +static BOOL pf_client_remote_monitors(rdpContext* context, UINT32 count, + const MONITOR_DEF* monitors) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WLog_DBG(TAG, "called"); + return freerdp_display_send_monitor_layout(ps, count, monitors); +} + +static BOOL pf_client_send_pointer_system(rdpContext* context, + const POINTER_SYSTEM_UPDATE* pointer_system) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerSystem); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerSystem(ps, pointer_system); +} + +static BOOL pf_client_send_pointer_position(rdpContext* context, + const POINTER_POSITION_UPDATE* pointerPosition) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerPosition); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerPosition(ps, pointerPosition); +} + +static BOOL pf_client_send_pointer_color(rdpContext* context, + const POINTER_COLOR_UPDATE* pointer_color) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerColor); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerColor(ps, pointer_color); +} + +static BOOL pf_client_send_pointer_large(rdpContext* context, + const POINTER_LARGE_UPDATE* pointer_large) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerLarge); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerLarge(ps, pointer_large); +} + +static BOOL pf_client_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerNew); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerNew(ps, pointer_new); +} + +static BOOL pf_client_send_pointer_cached(rdpContext* context, + const POINTER_CACHED_UPDATE* pointer_cached) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->pointer); + WINPR_ASSERT(ps->update->pointer->PointerCached); + WLog_DBG(TAG, "called"); + return ps->update->pointer->PointerCached(ps, pointer_cached); +} + +static BOOL pf_client_save_session_info(rdpContext* context, UINT32 type, void* data) +{ + logon_info* logonInfo = NULL; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->SaveSessionInfo); + + WLog_DBG(TAG, "called"); + + switch (type) + { + case INFO_TYPE_LOGON: + case INFO_TYPE_LOGON_LONG: + { + logonInfo = (logon_info*)data; + PROXY_LOG_INFO(TAG, pc, "client logon info: Username: %s, Domain: %s", + logonInfo->username, logonInfo->domain); + break; + } + + default: + break; + } + + return ps->update->SaveSessionInfo(ps, type, data); +} + +static BOOL pf_client_server_status_info(rdpContext* context, UINT32 status) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->ServerStatusInfo); + + WLog_DBG(TAG, "called"); + return ps->update->ServerStatusInfo(ps, status); +} + +static BOOL pf_client_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->SetKeyboardIndicators); + + WLog_DBG(TAG, "called"); + return ps->update->SetKeyboardIndicators(ps, led_flags); +} + +static BOOL pf_client_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, + UINT32 imeConvMode) +{ + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->SetKeyboardImeStatus); + + WLog_DBG(TAG, "called"); + return ps->update->SetKeyboardImeStatus(ps, imeId, imeState, imeConvMode); +} + +static BOOL pf_client_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_STATE_ORDER* windowState) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->WindowCreate); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->WindowCreate(ps, orderInfo, windowState); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_STATE_ORDER* windowState) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->WindowUpdate); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->WindowUpdate(ps, orderInfo, windowState); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_ICON_ORDER* windowIcon) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->WindowIcon); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->WindowIcon(ps, orderInfo, windowIcon); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_CACHED_ICON_ORDER* windowCachedIcon) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->WindowCachedIcon); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->WindowCachedIcon(ps, orderInfo, windowCachedIcon); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->WindowDelete); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->WindowDelete(ps, orderInfo); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->NotifyIconCreate); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->NotifyIconCreate(ps, orderInfo, notifyIconState); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->NotifyIconUpdate); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->NotifyIconUpdate(ps, orderInfo, notifyIconState); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + BOOL rc = 0; + + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->NotifyIconDelete); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->NotifyIconDelete(ps, orderInfo); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const MONITORED_DESKTOP_ORDER* monitoredDesktop) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->MonitoredDesktop); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->MonitoredDesktop(ps, orderInfo, monitoredDesktop); + rdp_update_unlock(ps->update); + return rc; +} + +static BOOL pf_client_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + BOOL rc = 0; + pClientContext* pc = (pClientContext*)context; + proxyData* pdata = NULL; + rdpContext* ps = NULL; + WINPR_ASSERT(pc); + pdata = pc->pdata; + WINPR_ASSERT(pdata); + ps = (rdpContext*)pdata->ps; + WINPR_ASSERT(ps); + WINPR_ASSERT(ps->update); + WINPR_ASSERT(ps->update->window); + WINPR_ASSERT(ps->update->window->NonMonitoredDesktop); + + WLog_DBG(TAG, "called"); + rdp_update_lock(ps->update); + rc = ps->update->window->NonMonitoredDesktop(ps, orderInfo); + rdp_update_unlock(ps->update); + return rc; +} + +void pf_server_register_update_callbacks(rdpUpdate* update) +{ + WINPR_ASSERT(update); + update->RefreshRect = pf_server_refresh_rect; + update->SuppressOutput = pf_server_suppress_output; +} + +void pf_client_register_update_callbacks(rdpUpdate* update) +{ + WINPR_ASSERT(update); + update->BeginPaint = pf_client_begin_paint; + update->EndPaint = pf_client_end_paint; + update->BitmapUpdate = pf_client_bitmap_update; + update->DesktopResize = pf_client_desktop_resize; + update->RemoteMonitors = pf_client_remote_monitors; + update->SaveSessionInfo = pf_client_save_session_info; + update->ServerStatusInfo = pf_client_server_status_info; + update->SetKeyboardIndicators = pf_client_set_keyboard_indicators; + update->SetKeyboardImeStatus = pf_client_set_keyboard_ime_status; + + /* Rail window updates */ + update->window->WindowCreate = pf_client_window_create; + update->window->WindowUpdate = pf_client_window_update; + update->window->WindowIcon = pf_client_window_icon; + update->window->WindowCachedIcon = pf_client_window_cached_icon; + update->window->WindowDelete = pf_client_window_delete; + update->window->NotifyIconCreate = pf_client_notify_icon_create; + update->window->NotifyIconUpdate = pf_client_notify_icon_update; + update->window->NotifyIconDelete = pf_client_notify_icon_delete; + update->window->MonitoredDesktop = pf_client_monitored_desktop; + update->window->NonMonitoredDesktop = pf_client_non_monitored_desktop; + + /* Pointer updates */ + update->pointer->PointerSystem = pf_client_send_pointer_system; + update->pointer->PointerPosition = pf_client_send_pointer_position; + update->pointer->PointerColor = pf_client_send_pointer_color; + update->pointer->PointerLarge = pf_client_send_pointer_large; + update->pointer->PointerNew = pf_client_send_pointer_new; + update->pointer->PointerCached = pf_client_send_pointer_cached; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.h new file mode 100644 index 0000000000000000000000000000000000000000..81a9c321d0dff05c31712dc633c622891ff61e9b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_update.h @@ -0,0 +1,34 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Mati Shabtay + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * + * 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 FREERDP_SERVER_PROXY_PFUPDATE_H +#define FREERDP_SERVER_PROXY_PFUPDATE_H + +#include +#include +#include + +#include + +void pf_server_register_update_callbacks(rdpUpdate* update); +void pf_client_register_update_callbacks(rdpUpdate* update); + +#endif /* FREERDP_SERVER_PROXY_PFUPDATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.c b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..f8c17af9b3caacc029b6ca6a6169e864c9d89101 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.c @@ -0,0 +1,95 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * * 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. + */ + +#include +#include +#include + +#include +#include "pf_utils.h" + +#define TAG PROXY_TAG("utils") + +pf_utils_channel_mode pf_utils_get_channel_mode(const proxyConfig* config, const char* name) +{ + pf_utils_channel_mode rc = PF_UTILS_CHANNEL_NOT_HANDLED; + BOOL found = FALSE; + + WINPR_ASSERT(config); + WINPR_ASSERT(name); + + for (size_t i = 0; i < config->InterceptCount; i++) + { + const char* channel_name = config->Intercept[i]; + if (strcmp(name, channel_name) == 0) + { + rc = PF_UTILS_CHANNEL_INTERCEPT; + goto end; + } + } + + for (size_t i = 0; i < config->PassthroughCount; i++) + { + const char* channel_name = config->Passthrough[i]; + if (strcmp(name, channel_name) == 0) + { + found = TRUE; + break; + } + } + + if (found) + { + if (config->PassthroughIsBlacklist) + rc = PF_UTILS_CHANNEL_BLOCK; + else + rc = PF_UTILS_CHANNEL_PASSTHROUGH; + } + else if (config->PassthroughIsBlacklist) + rc = PF_UTILS_CHANNEL_PASSTHROUGH; + +end: + WLog_DBG(TAG, "%s -> %s", name, pf_utils_channel_mode_string(rc)); + return rc; +} + +BOOL pf_utils_is_passthrough(const proxyConfig* config) +{ + WINPR_ASSERT(config); + + /* TODO: For the time being only passthrough mode is supported. */ + return TRUE; +} + +const char* pf_utils_channel_mode_string(pf_utils_channel_mode mode) +{ + switch (mode) + { + case PF_UTILS_CHANNEL_BLOCK: + return "blocked"; + case PF_UTILS_CHANNEL_PASSTHROUGH: + return "passthrough"; + case PF_UTILS_CHANNEL_INTERCEPT: + return "intercepted"; + case PF_UTILS_CHANNEL_NOT_HANDLED: + default: + return "ignored"; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0e899e94a67dd9f39162e7c59e1fc0707693db9a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/pf_utils.h @@ -0,0 +1,43 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef FREERDP_SERVER_PROXY_PFUTILS_H +#define FREERDP_SERVER_PROXY_PFUTILS_H + +#include +#include + +/** + * @brief pf_utils_channel_is_passthrough Checks of a channel identified by 'name' + * should be handled as passthrough. + * + * @param config The proxy configuration to check against. Must NOT be NULL. + * @param name The name of the channel. Must NOT be NULL. + * @return -1 if the channel is not handled, 0 if the channel should be ignored, + * 1 if the channel should be passed, 2 the channel will be intercepted + * e.g. proxy client and server are termination points and data passed + * between. + */ +pf_utils_channel_mode pf_utils_get_channel_mode(const proxyConfig* config, const char* name); +const char* pf_utils_channel_mode_string(pf_utils_channel_mode mode); + +BOOL pf_utils_is_passthrough(const proxyConfig* config); + +#endif /* FREERDP_SERVER_PROXY_PFUTILS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/proxy/proxy_modules.h b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/proxy_modules.h new file mode 100644 index 0000000000000000000000000000000000000000..d5883a5c2d3a946cccccbe64ebd4d161bbd6c22f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/proxy/proxy_modules.h @@ -0,0 +1,100 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Proxy Server + * + * Copyright 2019 Kobi Mizrachi + * Copyright 2019 Idan Freiberg + * + * 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 FREERDP_SERVER_PROXY_MODULES_H +#define FREERDP_SERVER_PROXY_MODULES_H + +#include +#include + +#include + +typedef enum +{ + FILTER_TYPE_KEYBOARD, /* proxyKeyboardEventInfo */ + FILTER_TYPE_UNICODE, /* proxyUnicodeEventInfo */ + FILTER_TYPE_MOUSE, /* proxyMouseEventInfo */ + FILTER_TYPE_MOUSE_EX, /* proxyMouseExEventInfo */ + FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_DATA, /* proxyChannelDataEventInfo */ + FILTER_TYPE_SERVER_PASSTHROUGH_CHANNEL_DATA, /* proxyChannelDataEventInfo */ + FILTER_TYPE_CLIENT_PASSTHROUGH_DYN_CHANNEL_CREATE, /* proxyChannelDataEventInfo */ + FILTER_TYPE_SERVER_FETCH_TARGET_ADDR, /* proxyFetchTargetEventInfo */ + FILTER_TYPE_SERVER_PEER_LOGON, /* proxyServerPeerLogon */ + FILTER_TYPE_CLIENT_PASSTHROUGH_CHANNEL_CREATE, /* proxyChannelDataEventInfo */ + + FILTER_TYPE_STATIC_INTERCEPT_LIST, /* proxyChannelToInterceptData */ + FILTER_TYPE_DYN_INTERCEPT_LIST, /* proxyChannelToInterceptData */ + FILTER_TYPE_INTERCEPT_CHANNEL, /* proxyDynChannelInterceptData */ + FILTER_LAST +} PF_FILTER_TYPE; + +typedef enum +{ + HOOK_TYPE_CLIENT_INIT_CONNECT, + HOOK_TYPE_CLIENT_UNINIT_CONNECT, + HOOK_TYPE_CLIENT_PRE_CONNECT, + HOOK_TYPE_CLIENT_POST_CONNECT, + HOOK_TYPE_CLIENT_POST_DISCONNECT, + HOOK_TYPE_CLIENT_REDIRECT, + HOOK_TYPE_CLIENT_VERIFY_X509, + HOOK_TYPE_CLIENT_LOGIN_FAILURE, + HOOK_TYPE_CLIENT_END_PAINT, + HOOK_TYPE_CLIENT_LOAD_CHANNELS, + + HOOK_TYPE_SERVER_POST_CONNECT, + HOOK_TYPE_SERVER_ACTIVATE, + HOOK_TYPE_SERVER_CHANNELS_INIT, + HOOK_TYPE_SERVER_CHANNELS_FREE, + HOOK_TYPE_SERVER_SESSION_END, + HOOK_TYPE_SERVER_SESSION_INITIALIZE, + HOOK_TYPE_SERVER_SESSION_STARTED, + + HOOK_LAST +} PF_HOOK_TYPE; + +#ifdef __cplusplus +extern "C" +{ +#endif + + proxyModule* pf_modules_new(const char* root_dir, const char** modules, size_t count); + + /** + * @brief pf_modules_add Registers a new plugin + * @param ep A module entry point function, must NOT be NULL + * @return TRUE for success, FALSE otherwise + */ + BOOL pf_modules_add(proxyModule* module, proxyModuleEntryPoint ep, void* userdata); + + BOOL pf_modules_is_plugin_loaded(proxyModule* module, const char* plugin_name); + void pf_modules_list_loaded_plugins(proxyModule* module); + + BOOL pf_modules_run_filter(proxyModule* module, PF_FILTER_TYPE type, proxyData* pdata, + void* param); + BOOL pf_modules_run_hook(proxyModule* module, PF_HOOK_TYPE type, proxyData* pdata, + void* custom); + + void pf_modules_free(proxyModule* module); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_PROXY_MODULES_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea10b649be075edb9ed5b7b5f4bdea247e39ca8b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/CMakeLists.txt @@ -0,0 +1,167 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Shadow Server cmake build script +# +# Copyright 2014 Marc-Andre Moreau +# +# 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. + +# freerdp-shadow library + +set(MODULE_NAME "freerdp-shadow") + +set(SRCS + shadow_client.c + shadow_client.h + shadow_lobby.c + shadow_lobby.h + shadow_input.c + shadow_input.h + shadow_screen.c + shadow_screen.h + shadow_surface.c + shadow_surface.h + shadow_encoder.c + shadow_encoder.h + shadow_capture.c + shadow_capture.h + shadow_channels.c + shadow_channels.h + shadow_encomsp.c + shadow_encomsp.h + shadow_remdesk.c + shadow_remdesk.h + shadow_rdpsnd.c + shadow_rdpsnd.h + shadow_audin.c + shadow_audin.h + shadow_rdpgfx.c + shadow_rdpgfx.h + shadow_subsystem.c + shadow_subsystem.h + shadow_mcevent.c + shadow_mcevent.h + shadow_server.c + shadow.h +) + +if(NOT FREERDP_UNIFIED_BUILD) + find_package(rdtk 0 REQUIRED) + include_directories(SYSTEM ${RDTK_INCLUDE_DIR}) +else() + if(NOT WITH_RDTK) + message(FATAL_ERROR "-DWITH_RDTK=ON is required for unified FreeRDP build with shadow server") + endif() + include_directories(${PROJECT_SOURCE_DIR}/rdtk/include) + include_directories(${PROJECT_BINARY_DIR}/rdtk/include) +endif() + +addtargetwithresourcefile(${MODULE_NAME} "FALSE" "${FREERDP_VERSION}" SRCS) + +list( + APPEND + LIBS + freerdp + freerdp-server + winpr + winpr-tools + rdtk +) + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${LIBS}) + +install(TARGETS ${MODULE_NAME} COMPONENT server EXPORT FreeRDP-ShadowTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/shadow") + +# subsystem library + +set(MODULE_NAME "freerdp-shadow-subsystem") + +set(SRCS shadow_subsystem_builtin.c) + +if(WIN32) + add_subdirectory(Win) +elseif(NOT APPLE) + add_subdirectory(X11) +elseif(APPLE AND NOT IOS) + add_subdirectory(Mac) +endif() + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" SRCS) + +list(APPEND LIBS freerdp-shadow-subsystem-impl freerdp-shadow freerdp winpr) + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${LIBS}) + +if(NOT BUILD_SHARED_LIBS) + install(TARGETS freerdp-shadow-subsystem-impl DESTINATION ${CMAKE_INSTALL_LIBDIR} EXPORT FreeRDP-ShadowTargets) +endif() + +install(TARGETS ${MODULE_NAME} COMPONENT server EXPORT FreeRDP-ShadowTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/shadow") + +# command-line executable + +set(MODULE_NAME "freerdp-shadow-cli") + +set(SRCS shadow.c) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${FREERDP_VERSION}" SRCS) + +list(APPEND LIBS freerdp-shadow-subsystem freerdp-shadow freerdp winpr) + +target_link_libraries(${MODULE_NAME} PRIVATE ${LIBS}) + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT server) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Server/shadow") + +include(pkg-config-install-prefix) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/freerdp-shadow.pc.in + ${CMAKE_CURRENT_BINARY_DIR}/freerdp-shadow${FREERDP_VERSION_MAJOR}.pc @ONLY +) + +generate_and_install_freerdp_man_from_template(${MODULE_NAME} "1" "${FREERDP_API_VERSION}") + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/freerdp-shadow${FREERDP_VERSION_MAJOR}.pc + DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR} +) + +export(PACKAGE freerdp-shadow) + +setfreerdpcmakeinstalldir(FREERDP_SERVER_CMAKE_INSTALL_DIR "FreeRDP-Shadow${FREERDP_VERSION_MAJOR}") + +configure_package_config_file( + FreeRDP-ShadowConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ShadowConfig.cmake + INSTALL_DESTINATION ${FREERDP_SERVER_CMAKE_INSTALL_DIR} PATH_VARS FREERDP_INCLUDE_DIR +) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ShadowConfigVersion.cmake VERSION ${FREERDP_VERSION} + COMPATIBILITY SameMajorVersion +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ShadowConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ShadowConfigVersion.cmake + DESTINATION ${FREERDP_SERVER_CMAKE_INSTALL_DIR} +) + +install(EXPORT FreeRDP-ShadowTargets DESTINATION ${FREERDP_SERVER_CMAKE_INSTALL_DIR}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/FreeRDP-ShadowConfig.cmake.in b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/FreeRDP-ShadowConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..9b6f24c0e1cdfec64ae8b7002554c7df4ae31fe5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/FreeRDP-ShadowConfig.cmake.in @@ -0,0 +1,14 @@ +include(CMakeFindDependencyMacro) +find_dependency(WinPR @FREERDP_VERSION@) +find_dependency(FreeRDP @FREERDP_VERSION@) +find_dependency(FreeRDP-Server @FREERDP_VERSION@) + +@PACKAGE_INIT@ + +set(FreeRDP-Shadow_VERSION_MAJOR "@FREERDP_VERSION_MAJOR@") +set(FreeRDP-Shadow_VERSION_MINOR "@FREERDP_VERSION_MINOR@") +set(FreeRDP-Shadow_VERSION_REVISION "@FREERDP_VERSION_REVISION@") + +set_and_check(FreeRDP-Shadow_INCLUDE_DIR "@PACKAGE_FREERDP_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/FreeRDP-ShadowTargets.cmake") diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a66015683490db3f279dcf4c5425556c55bf98f2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/CMakeLists.txt @@ -0,0 +1,21 @@ +include(WarnUnmaintained) +warn_unmaintained("mac shadow server subsystem") + +find_library(IOKIT IOKit REQUIRED) +find_library(IOSURFACE IOSurface REQUIRED) +find_library(CARBON Carbon REQUIRED) +find_package(PAM) + +set(LIBS ${IOKIT} ${IOSURFACE} ${CARBON}) + +if(PAM_FOUND) + add_compile_definitions(WITH_PAM) + include_directories(SYSTEM ${PAM_INCLUDE_DIR}) + list(APPEND LIBS ${PAM_LIBRARY}) +else() + message("building without PAM authentication support") +endif() + +add_compile_definitions(WITH_SHADOW_MAC) +add_library(freerdp-shadow-subsystem-impl STATIC mac_shadow.h mac_shadow.c) +target_link_libraries(freerdp-shadow-subsystem-impl PRIVATE ${LIBS}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.c new file mode 100644 index 0000000000000000000000000000000000000000..54384d022ad7e728d341f607518b75b883b01335 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.c @@ -0,0 +1,680 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 +#include +#include +#include + +#include +#include +#include +#include + +#include "mac_shadow.h" + +#define TAG SERVER_TAG("shadow.mac") + +static macShadowSubsystem* g_Subsystem = NULL; + +static BOOL mac_shadow_input_synchronize_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT32 flags) +{ + if (!subsystem || !client) + return FALSE; + + return TRUE; +} + +static BOOL mac_shadow_input_keyboard_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT8 code) +{ + DWORD vkcode; + DWORD keycode; + BOOL extended; + CGEventRef kbdEvent; + CGEventSourceRef source; + extended = (flags & KBD_FLAGS_EXTENDED) ? TRUE : FALSE; + + if (!subsystem || !client) + return FALSE; + + if (extended) + code |= KBDEXT; + + vkcode = GetVirtualKeyCodeFromVirtualScanCode(code, 4); + + if (extended) + vkcode |= KBDEXT; + + keycode = GetKeycodeFromVirtualKeyCode(vkcode, WINPR_KEYCODE_TYPE_APPLE); + + source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + + if (flags & KBD_FLAGS_DOWN) + { + kbdEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keycode, TRUE); + CGEventPost(kCGHIDEventTap, kbdEvent); + CFRelease(kbdEvent); + } + else if (flags & KBD_FLAGS_RELEASE) + { + kbdEvent = CGEventCreateKeyboardEvent(source, (CGKeyCode)keycode, FALSE); + CGEventPost(kCGHIDEventTap, kbdEvent); + CFRelease(kbdEvent); + } + + CFRelease(source); + return TRUE; +} + +static BOOL mac_shadow_input_unicode_keyboard_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, + UINT16 code) +{ + if (!subsystem || !client) + return FALSE; + + return TRUE; +} + +static BOOL mac_shadow_input_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT16 x, UINT16 y) +{ + macShadowSubsystem* mac = (macShadowSubsystem*)subsystem; + UINT32 scrollX = 0; + UINT32 scrollY = 0; + CGWheelCount wheelCount = 2; + + if (!subsystem || !client) + return FALSE; + + if (flags & PTR_FLAGS_WHEEL) + { + scrollY = flags & WheelRotationMask; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + { + scrollY = -(flags & WheelRotationMask) / 392; + } + else + { + scrollY = (flags & WheelRotationMask) / 120; + } + + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventRef scroll = CGEventCreateScrollWheelEvent(source, kCGScrollEventUnitLine, + wheelCount, scrollY, scrollX); + CGEventPost(kCGHIDEventTap, scroll); + CFRelease(scroll); + CFRelease(source); + } + else + { + CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); + CGEventType mouseType = kCGEventNull; + CGMouseButton mouseButton = kCGMouseButtonLeft; + + if (flags & PTR_FLAGS_MOVE) + { + if (mac->mouseDownLeft) + mouseType = kCGEventLeftMouseDragged; + else if (mac->mouseDownRight) + mouseType = kCGEventRightMouseDragged; + else if (mac->mouseDownOther) + mouseType = kCGEventOtherMouseDragged; + else + mouseType = kCGEventMouseMoved; + + CGEventRef move = + CGEventCreateMouseEvent(source, mouseType, CGPointMake(x, y), mouseButton); + CGEventPost(kCGHIDEventTap, move); + CFRelease(move); + } + + if (flags & PTR_FLAGS_BUTTON1) + { + mouseButton = kCGMouseButtonLeft; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventLeftMouseDown; + mac->mouseDownLeft = TRUE; + } + else + { + mouseType = kCGEventLeftMouseUp; + mac->mouseDownLeft = FALSE; + } + } + else if (flags & PTR_FLAGS_BUTTON2) + { + mouseButton = kCGMouseButtonRight; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventRightMouseDown; + mac->mouseDownRight = TRUE; + } + else + { + mouseType = kCGEventRightMouseUp; + mac->mouseDownRight = FALSE; + } + } + else if (flags & PTR_FLAGS_BUTTON3) + { + mouseButton = kCGMouseButtonCenter; + + if (flags & PTR_FLAGS_DOWN) + { + mouseType = kCGEventOtherMouseDown; + mac->mouseDownOther = TRUE; + } + else + { + mouseType = kCGEventOtherMouseUp; + mac->mouseDownOther = FALSE; + } + } + + CGEventRef mouseEvent = + CGEventCreateMouseEvent(source, mouseType, CGPointMake(x, y), mouseButton); + CGEventPost(kCGHIDEventTap, mouseEvent); + CFRelease(mouseEvent); + CFRelease(source); + } + + return TRUE; +} + +static BOOL mac_shadow_input_extended_mouse_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, UINT16 x, + UINT16 y) +{ + if (!subsystem || !client) + return FALSE; + + return TRUE; +} + +static int mac_shadow_detect_monitors(macShadowSubsystem* subsystem) +{ + size_t wide, high; + MONITOR_DEF* monitor; + CGDirectDisplayID displayId; + displayId = CGMainDisplayID(); + CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayId); + subsystem->pixelWidth = CGDisplayModeGetPixelWidth(mode); + subsystem->pixelHeight = CGDisplayModeGetPixelHeight(mode); + wide = CGDisplayPixelsWide(displayId); + high = CGDisplayPixelsHigh(displayId); + CGDisplayModeRelease(mode); + subsystem->retina = ((subsystem->pixelWidth / wide) == 2) ? TRUE : FALSE; + + if (subsystem->retina) + { + subsystem->width = wide; + subsystem->height = high; + } + else + { + subsystem->width = subsystem->pixelWidth; + subsystem->height = subsystem->pixelHeight; + } + + subsystem->common.numMonitors = 1; + monitor = &(subsystem->common.monitors[0]); + monitor->left = 0; + monitor->top = 0; + monitor->right = subsystem->width; + monitor->bottom = subsystem->height; + monitor->flags = 1; + return 1; +} + +static int mac_shadow_capture_start(macShadowSubsystem* subsystem) +{ + CGError err; + err = CGDisplayStreamStart(subsystem->stream); + + if (err != kCGErrorSuccess) + return -1; + + return 1; +} + +static int mac_shadow_capture_stop(macShadowSubsystem* subsystem) +{ + CGError err; + err = CGDisplayStreamStop(subsystem->stream); + + if (err != kCGErrorSuccess) + return -1; + + return 1; +} + +static int mac_shadow_capture_get_dirty_region(macShadowSubsystem* subsystem) +{ + size_t numRects; + const CGRect* rects; + RECTANGLE_16 invalidRect; + rdpShadowSurface* surface = subsystem->common.server->surface; + rects = CGDisplayStreamUpdateGetRects(subsystem->lastUpdate, kCGDisplayStreamUpdateDirtyRects, + &numRects); + + if (!numRects) + return -1; + + for (size_t index = 0; index < numRects; index++) + { + invalidRect.left = (UINT16)rects[index].origin.x; + invalidRect.top = (UINT16)rects[index].origin.y; + invalidRect.right = invalidRect.left + (UINT16)rects[index].size.width; + invalidRect.bottom = invalidRect.top + (UINT16)rects[index].size.height; + + if (subsystem->retina) + { + /* scale invalid rect */ + invalidRect.left /= 2; + invalidRect.top /= 2; + invalidRect.right /= 2; + invalidRect.bottom /= 2; + } + + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + } + + return 0; +} + +static int freerdp_image_copy_from_retina(BYTE* pDstData, DWORD DstFormat, int nDstStep, int nXDst, + int nYDst, int nWidth, int nHeight, BYTE* pSrcData, + int nSrcStep, int nXSrc, int nYSrc) +{ + BYTE* pSrcPixel; + BYTE* pDstPixel; + int nSrcPad; + int nDstPad; + int srcBitsPerPixel; + int srcBytesPerPixel; + int dstBitsPerPixel; + int dstBytesPerPixel; + srcBitsPerPixel = 24; + srcBytesPerPixel = 8; + + if (nSrcStep < 0) + nSrcStep = srcBytesPerPixel * nWidth; + + dstBitsPerPixel = FreeRDPGetBitsPerPixel(DstFormat); + dstBytesPerPixel = FreeRDPGetBytesPerPixel(DstFormat); + + if (nDstStep < 0) + nDstStep = dstBytesPerPixel * nWidth; + + nSrcPad = (nSrcStep - (nWidth * srcBytesPerPixel)); + nDstPad = (nDstStep - (nWidth * dstBytesPerPixel)); + pSrcPixel = &pSrcData[(nYSrc * nSrcStep) + (nXSrc * 4)]; + pDstPixel = &pDstData[(nYDst * nDstStep) + (nXDst * 4)]; + + for (int y = 0; y < nHeight; y++) + { + for (int x = 0; x < nWidth; x++) + { + UINT32 R, G, B; + UINT32 color; + /* simple box filter scaling, could be improved with better algorithm */ + B = pSrcPixel[0] + pSrcPixel[4] + pSrcPixel[nSrcStep + 0] + pSrcPixel[nSrcStep + 4]; + G = pSrcPixel[1] + pSrcPixel[5] + pSrcPixel[nSrcStep + 1] + pSrcPixel[nSrcStep + 5]; + R = pSrcPixel[2] + pSrcPixel[6] + pSrcPixel[nSrcStep + 2] + pSrcPixel[nSrcStep + 6]; + pSrcPixel += 8; + color = FreeRDPGetColor(DstFormat, R >> 2, G >> 2, B >> 2, 0xFF); + FreeRDPWriteColor(pDstPixel, DstFormat, color); + pDstPixel += dstBytesPerPixel; + } + + pSrcPixel = &pSrcPixel[nSrcPad + nSrcStep]; + pDstPixel = &pDstPixel[nDstPad]; + } + + return 1; +} + +static void (^mac_capture_stream_handler)( + CGDisplayStreamFrameStatus, uint64_t, IOSurfaceRef, + CGDisplayStreamUpdateRef) = ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, + IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef) { + int x, y; + int count; + int width; + int height; + int nSrcStep; + BOOL empty; + BYTE* pSrcData; + RECTANGLE_16 surfaceRect; + const RECTANGLE_16* extents; + macShadowSubsystem* subsystem = g_Subsystem; + rdpShadowServer* server = subsystem->common.server; + rdpShadowSurface* surface = server->surface; + count = ArrayList_Count(server->clients); + + if (count < 1) + return; + + EnterCriticalSection(&(surface->lock)); + mac_shadow_capture_get_dirty_region(subsystem); + surfaceRect.left = 0; + surfaceRect.top = 0; + surfaceRect.right = surface->width; + surfaceRect.bottom = surface->height; + region16_intersect_rect(&(surface->invalidRegion), &(surface->invalidRegion), &surfaceRect); + empty = region16_is_empty(&(surface->invalidRegion)); + LeaveCriticalSection(&(surface->lock)); + + if (!empty) + { + extents = region16_extents(&(surface->invalidRegion)); + x = extents->left; + y = extents->top; + width = extents->right - extents->left; + height = extents->bottom - extents->top; + IOSurfaceLock(frameSurface, kIOSurfaceLockReadOnly, NULL); + pSrcData = (BYTE*)IOSurfaceGetBaseAddress(frameSurface); + nSrcStep = (int)IOSurfaceGetBytesPerRow(frameSurface); + + if (subsystem->retina) + { + freerdp_image_copy_from_retina(surface->data, surface->format, surface->scanline, x, y, + width, height, pSrcData, nSrcStep, x, y); + } + else + { + freerdp_image_copy_no_overlap(surface->data, surface->format, surface->scanline, x, y, + width, height, pSrcData, PIXEL_FORMAT_BGRX32, nSrcStep, x, + y, NULL, FREERDP_FLIP_NONE); + } + LeaveCriticalSection(&(surface->lock)); + + IOSurfaceUnlock(frameSurface, kIOSurfaceLockReadOnly, NULL); + ArrayList_Lock(server->clients); + count = ArrayList_Count(server->clients); + shadow_subsystem_frame_update(&subsystem->common); + + if (count == 1) + { + rdpShadowClient* client; + client = (rdpShadowClient*)ArrayList_GetItem(server->clients, 0); + + if (client) + { + subsystem->common.captureFrameRate = shadow_encoder_preferred_fps(client->encoder); + } + } + + ArrayList_Unlock(server->clients); + EnterCriticalSection(&(surface->lock)); + region16_clear(&(surface->invalidRegion)); + LeaveCriticalSection(&(surface->lock)); + } + + if (status != kCGDisplayStreamFrameStatusFrameComplete) + { + switch (status) + { + case kCGDisplayStreamFrameStatusFrameIdle: + break; + + case kCGDisplayStreamFrameStatusStopped: + break; + + case kCGDisplayStreamFrameStatusFrameBlank: + break; + + default: + break; + } + } + else if (!subsystem->lastUpdate) + { + CFRetain(updateRef); + subsystem->lastUpdate = updateRef; + } + else + { + CGDisplayStreamUpdateRef tmpRef = subsystem->lastUpdate; + subsystem->lastUpdate = CGDisplayStreamUpdateCreateMergedUpdate(tmpRef, updateRef); + CFRelease(tmpRef); + } +}; + +static int mac_shadow_capture_init(macShadowSubsystem* subsystem) +{ + void* keys[2]; + void* values[2]; + CFDictionaryRef opts; + CGDirectDisplayID displayId; + displayId = CGMainDisplayID(); + subsystem->captureQueue = dispatch_queue_create("mac.shadow.capture", NULL); + keys[0] = (void*)kCGDisplayStreamShowCursor; + values[0] = (void*)kCFBooleanFalse; + opts = CFDictionaryCreate(kCFAllocatorDefault, (const void**)keys, (const void**)values, 1, + NULL, NULL); + subsystem->stream = CGDisplayStreamCreateWithDispatchQueue( + displayId, subsystem->pixelWidth, subsystem->pixelHeight, 'BGRA', opts, + subsystem->captureQueue, mac_capture_stream_handler); + CFRelease(opts); + return 1; +} + +static int mac_shadow_screen_grab(macShadowSubsystem* subsystem) +{ + return 1; +} + +static int mac_shadow_subsystem_process_message(macShadowSubsystem* subsystem, wMessage* message) +{ + rdpShadowServer* server = subsystem->common.server; + rdpShadowSurface* surface = server->surface; + + switch (message->id) + { + case SHADOW_MSG_IN_REFRESH_REQUEST_ID: + EnterCriticalSection(&(surface->lock)); + shadow_subsystem_frame_update((rdpShadowSubsystem*)subsystem); + LeaveCriticalSection(&(surface->lock)); + break; + + default: + WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", message->id); + break; + } + + if (message->Free) + message->Free(message); + + return 1; +} + +static DWORD WINAPI mac_shadow_subsystem_thread(LPVOID arg) +{ + macShadowSubsystem* subsystem = (macShadowSubsystem*)arg; + DWORD status; + DWORD nCount; + UINT64 cTime; + DWORD dwTimeout; + DWORD dwInterval; + UINT64 frameTime; + HANDLE events[32]; + wMessage message; + wMessagePipe* MsgPipe; + MsgPipe = subsystem->common.MsgPipe; + nCount = 0; + events[nCount++] = MessageQueue_Event(MsgPipe->In); + subsystem->common.captureFrameRate = 16; + dwInterval = 1000 / subsystem->common.captureFrameRate; + frameTime = GetTickCount64() + dwInterval; + + while (1) + { + cTime = GetTickCount64(); + dwTimeout = (cTime > frameTime) ? 0 : frameTime - cTime; + status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout); + + if (WaitForSingleObject(MessageQueue_Event(MsgPipe->In), 0) == WAIT_OBJECT_0) + { + if (MessageQueue_Peek(MsgPipe->In, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + break; + + mac_shadow_subsystem_process_message(subsystem, &message); + } + } + + if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime)) + { + mac_shadow_screen_grab(subsystem); + dwInterval = 1000 / subsystem->common.captureFrameRate; + frameTime += dwInterval; + } + } + + ExitThread(0); + return 0; +} + +static UINT32 mac_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors) +{ + int index; + size_t wide, high; + UINT32 numMonitors = 0; + MONITOR_DEF* monitor; + CGDirectDisplayID displayId; + displayId = CGMainDisplayID(); + CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayId); + wide = CGDisplayPixelsWide(displayId); + high = CGDisplayPixelsHigh(displayId); + CGDisplayModeRelease(mode); + index = 0; + numMonitors = 1; + monitor = &monitors[index]; + monitor->left = 0; + monitor->top = 0; + monitor->right = (int)wide; + monitor->bottom = (int)high; + monitor->flags = 1; + return numMonitors; +} + +static int mac_shadow_subsystem_init(rdpShadowSubsystem* rdpsubsystem) +{ + macShadowSubsystem* subsystem = (macShadowSubsystem*)rdpsubsystem; + g_Subsystem = subsystem; + + mac_shadow_detect_monitors(subsystem); + mac_shadow_capture_init(subsystem); + return 1; +} + +static int mac_shadow_subsystem_uninit(rdpShadowSubsystem* rdpsubsystem) +{ + macShadowSubsystem* subsystem = (macShadowSubsystem*)rdpsubsystem; + if (!subsystem) + return -1; + + if (subsystem->lastUpdate) + { + CFRelease(subsystem->lastUpdate); + subsystem->lastUpdate = NULL; + } + + return 1; +} + +static int mac_shadow_subsystem_start(rdpShadowSubsystem* rdpsubsystem) +{ + macShadowSubsystem* subsystem = (macShadowSubsystem*)rdpsubsystem; + HANDLE thread; + + if (!subsystem) + return -1; + + mac_shadow_capture_start(subsystem); + + if (!(thread = CreateThread(NULL, 0, mac_shadow_subsystem_thread, (void*)subsystem, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create thread"); + return -1; + } + + return 1; +} + +static int mac_shadow_subsystem_stop(rdpShadowSubsystem* subsystem) +{ + if (!subsystem) + return -1; + + return 1; +} + +static void mac_shadow_subsystem_free(rdpShadowSubsystem* subsystem) +{ + if (!subsystem) + return; + + mac_shadow_subsystem_uninit(subsystem); + free(subsystem); +} + +static rdpShadowSubsystem* mac_shadow_subsystem_new(void) +{ + macShadowSubsystem* subsystem = calloc(1, sizeof(macShadowSubsystem)); + + if (!subsystem) + return NULL; + + subsystem->common.SynchronizeEvent = mac_shadow_input_synchronize_event; + subsystem->common.KeyboardEvent = mac_shadow_input_keyboard_event; + subsystem->common.UnicodeKeyboardEvent = mac_shadow_input_unicode_keyboard_event; + subsystem->common.MouseEvent = mac_shadow_input_mouse_event; + subsystem->common.ExtendedMouseEvent = mac_shadow_input_extended_mouse_event; + return &subsystem->common; +} + +FREERDP_API const char* ShadowSubsystemName(void) +{ + return "Mac"; +} + +FREERDP_API int ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints) +{ + char name[] = "mac shadow subsystem"; + char* arg[] = { name }; + + freerdp_server_warn_unmaintained(ARRAYSIZE(arg), arg); + pEntryPoints->New = mac_shadow_subsystem_new; + pEntryPoints->Free = mac_shadow_subsystem_free; + pEntryPoints->Init = mac_shadow_subsystem_init; + pEntryPoints->Uninit = mac_shadow_subsystem_uninit; + pEntryPoints->Start = mac_shadow_subsystem_start; + pEntryPoints->Stop = mac_shadow_subsystem_stop; + pEntryPoints->EnumMonitors = mac_shadow_enum_monitors; + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.h new file mode 100644 index 0000000000000000000000000000000000000000..2c31572e360194a4e9bd54c169e62ee77829379b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Mac/mac_shadow.h @@ -0,0 +1,64 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_MAC_SHADOW_H +#define FREERDP_SERVER_SHADOW_MAC_SHADOW_H + +#include + +typedef struct mac_shadow_subsystem macShadowSubsystem; + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +struct mac_shadow_subsystem +{ + rdpShadowSubsystem common; + + int width; + int height; + BOOL retina; + int pixelWidth; + int pixelHeight; + BOOL mouseDownLeft; + BOOL mouseDownRight; + BOOL mouseDownOther; + CGDisplayStreamRef stream; + dispatch_queue_t captureQueue; + CGDisplayStreamUpdateRef lastUpdate; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_MAC_SHADOW_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..48f5d14c4c97676cc2dc6833671cc2505bef6e83 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/CMakeLists.txt @@ -0,0 +1,16 @@ +include(WarnUnmaintained) +warn_unmaintained("windows shadow server subsystem") + +add_compile_definitions(WITH_SHADOW_WIN) +add_library( + freerdp-shadow-subsystem-impl STATIC + win_dxgi.c + win_dxgi.h + win_rdp.c + win_rdp.h + win_shadow.c + win_shadow.h + win_wds.c + win_wds.h +) +target_link_libraries(freerdp-shadow-subsystem-impl PRIVATE freerdp-client freerdp winpr) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.c new file mode 100644 index 0000000000000000000000000000000000000000..9ea8e2bc5bc05bc00e4d7eabd008222b5fdbde61 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.c @@ -0,0 +1,795 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "win_dxgi.h" + +#define TAG SERVER_TAG("shadow.win") + +#ifdef WITH_DXGI_1_2 + +static D3D_DRIVER_TYPE DriverTypes[] = { + D3D_DRIVER_TYPE_HARDWARE, + D3D_DRIVER_TYPE_WARP, + D3D_DRIVER_TYPE_REFERENCE, +}; + +static UINT NumDriverTypes = ARRAYSIZE(DriverTypes); + +static D3D_FEATURE_LEVEL FeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_1 }; + +static UINT NumFeatureLevels = ARRAYSIZE(FeatureLevels); + +static HMODULE d3d11_module = NULL; + +typedef HRESULT(WINAPI* fnD3D11CreateDevice)(IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, + HMODULE Software, UINT Flags, + CONST D3D_FEATURE_LEVEL* pFeatureLevels, + UINT FeatureLevels, UINT SDKVersion, + ID3D11Device** ppDevice, + D3D_FEATURE_LEVEL* pFeatureLevel, + ID3D11DeviceContext** ppImmediateContext); + +static fnD3D11CreateDevice pfnD3D11CreateDevice = NULL; + +#undef DEFINE_GUID +#define INITGUID + +#include + +/* d3d11.h GUIDs */ + +DEFINE_GUID(IID_ID3D11DeviceChild, 0x1841e5c8, 0x16b0, 0x489b, 0xbc, 0xc8, 0x44, 0xcf, 0xb0, 0xd5, + 0xde, 0xae); +DEFINE_GUID(IID_ID3D11DepthStencilState, 0x03823efb, 0x8d8f, 0x4e1c, 0x9a, 0xa2, 0xf6, 0x4b, 0xb2, + 0xcb, 0xfd, 0xf1); +DEFINE_GUID(IID_ID3D11BlendState, 0x75b68faa, 0x347d, 0x4159, 0x8f, 0x45, 0xa0, 0x64, 0x0f, 0x01, + 0xcd, 0x9a); +DEFINE_GUID(IID_ID3D11RasterizerState, 0x9bb4ab81, 0xab1a, 0x4d8f, 0xb5, 0x06, 0xfc, 0x04, 0x20, + 0x0b, 0x6e, 0xe7); +DEFINE_GUID(IID_ID3D11Resource, 0xdc8e63f3, 0xd12b, 0x4952, 0xb4, 0x7b, 0x5e, 0x45, 0x02, 0x6a, + 0x86, 0x2d); +DEFINE_GUID(IID_ID3D11Buffer, 0x48570b85, 0xd1ee, 0x4fcd, 0xa2, 0x50, 0xeb, 0x35, 0x07, 0x22, 0xb0, + 0x37); +DEFINE_GUID(IID_ID3D11Texture1D, 0xf8fb5c27, 0xc6b3, 0x4f75, 0xa4, 0xc8, 0x43, 0x9a, 0xf2, 0xef, + 0x56, 0x4c); +DEFINE_GUID(IID_ID3D11Texture2D, 0x6f15aaf2, 0xd208, 0x4e89, 0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, + 0x4f, 0x9c); +DEFINE_GUID(IID_ID3D11Texture3D, 0x037e866e, 0xf56d, 0x4357, 0xa8, 0xaf, 0x9d, 0xab, 0xbe, 0x6e, + 0x25, 0x0e); +DEFINE_GUID(IID_ID3D11View, 0x839d1216, 0xbb2e, 0x412b, 0xb7, 0xf4, 0xa9, 0xdb, 0xeb, 0xe0, 0x8e, + 0xd1); +DEFINE_GUID(IID_ID3D11ShaderResourceView, 0xb0e06fe0, 0x8192, 0x4e1a, 0xb1, 0xca, 0x36, 0xd7, 0x41, + 0x47, 0x10, 0xb2); +DEFINE_GUID(IID_ID3D11RenderTargetView, 0xdfdba067, 0x0b8d, 0x4865, 0x87, 0x5b, 0xd7, 0xb4, 0x51, + 0x6c, 0xc1, 0x64); +DEFINE_GUID(IID_ID3D11DepthStencilView, 0x9fdac92a, 0x1876, 0x48c3, 0xaf, 0xad, 0x25, 0xb9, 0x4f, + 0x84, 0xa9, 0xb6); +DEFINE_GUID(IID_ID3D11UnorderedAccessView, 0x28acf509, 0x7f5c, 0x48f6, 0x86, 0x11, 0xf3, 0x16, 0x01, + 0x0a, 0x63, 0x80); +DEFINE_GUID(IID_ID3D11VertexShader, 0x3b301d64, 0xd678, 0x4289, 0x88, 0x97, 0x22, 0xf8, 0x92, 0x8b, + 0x72, 0xf3); +DEFINE_GUID(IID_ID3D11HullShader, 0x8e5c6061, 0x628a, 0x4c8e, 0x82, 0x64, 0xbb, 0xe4, 0x5c, 0xb3, + 0xd5, 0xdd); +DEFINE_GUID(IID_ID3D11DomainShader, 0xf582c508, 0x0f36, 0x490c, 0x99, 0x77, 0x31, 0xee, 0xce, 0x26, + 0x8c, 0xfa); +DEFINE_GUID(IID_ID3D11GeometryShader, 0x38325b96, 0xeffb, 0x4022, 0xba, 0x02, 0x2e, 0x79, 0x5b, + 0x70, 0x27, 0x5c); +DEFINE_GUID(IID_ID3D11PixelShader, 0xea82e40d, 0x51dc, 0x4f33, 0x93, 0xd4, 0xdb, 0x7c, 0x91, 0x25, + 0xae, 0x8c); +DEFINE_GUID(IID_ID3D11ComputeShader, 0x4f5b196e, 0xc2bd, 0x495e, 0xbd, 0x01, 0x1f, 0xde, 0xd3, 0x8e, + 0x49, 0x69); +DEFINE_GUID(IID_ID3D11InputLayout, 0xe4819ddc, 0x4cf0, 0x4025, 0xbd, 0x26, 0x5d, 0xe8, 0x2a, 0x3e, + 0x07, 0xb7); +DEFINE_GUID(IID_ID3D11SamplerState, 0xda6fea51, 0x564c, 0x4487, 0x98, 0x10, 0xf0, 0xd0, 0xf9, 0xb4, + 0xe3, 0xa5); +DEFINE_GUID(IID_ID3D11Asynchronous, 0x4b35d0cd, 0x1e15, 0x4258, 0x9c, 0x98, 0x1b, 0x13, 0x33, 0xf6, + 0xdd, 0x3b); +DEFINE_GUID(IID_ID3D11Query, 0xd6c00747, 0x87b7, 0x425e, 0xb8, 0x4d, 0x44, 0xd1, 0x08, 0x56, 0x0a, + 0xfd); +DEFINE_GUID(IID_ID3D11Predicate, 0x9eb576dd, 0x9f77, 0x4d86, 0x81, 0xaa, 0x8b, 0xab, 0x5f, 0xe4, + 0x90, 0xe2); +DEFINE_GUID(IID_ID3D11Counter, 0x6e8c49fb, 0xa371, 0x4770, 0xb4, 0x40, 0x29, 0x08, 0x60, 0x22, 0xb7, + 0x41); +DEFINE_GUID(IID_ID3D11ClassInstance, 0xa6cd7faa, 0xb0b7, 0x4a2f, 0x94, 0x36, 0x86, 0x62, 0xa6, 0x57, + 0x97, 0xcb); +DEFINE_GUID(IID_ID3D11ClassLinkage, 0xddf57cba, 0x9543, 0x46e4, 0xa1, 0x2b, 0xf2, 0x07, 0xa0, 0xfe, + 0x7f, 0xed); +DEFINE_GUID(IID_ID3D11CommandList, 0xa24bc4d1, 0x769e, 0x43f7, 0x80, 0x13, 0x98, 0xff, 0x56, 0x6c, + 0x18, 0xe2); +DEFINE_GUID(IID_ID3D11DeviceContext, 0xc0bfa96c, 0xe089, 0x44fb, 0x8e, 0xaf, 0x26, 0xf8, 0x79, 0x61, + 0x90, 0xda); +DEFINE_GUID(IID_ID3D11VideoDecoder, 0x3C9C5B51, 0x995D, 0x48d1, 0x9B, 0x8D, 0xFA, 0x5C, 0xAE, 0xDE, + 0xD6, 0x5C); +DEFINE_GUID(IID_ID3D11VideoProcessorEnumerator, 0x31627037, 0x53AB, 0x4200, 0x90, 0x61, 0x05, 0xFA, + 0xA9, 0xAB, 0x45, 0xF9); +DEFINE_GUID(IID_ID3D11VideoProcessor, 0x1D7B0652, 0x185F, 0x41c6, 0x85, 0xCE, 0x0C, 0x5B, 0xE3, + 0xD4, 0xAE, 0x6C); +DEFINE_GUID(IID_ID3D11AuthenticatedChannel, 0x3015A308, 0xDCBD, 0x47aa, 0xA7, 0x47, 0x19, 0x24, + 0x86, 0xD1, 0x4D, 0x4A); +DEFINE_GUID(IID_ID3D11CryptoSession, 0x9B32F9AD, 0xBDCC, 0x40a6, 0xA3, 0x9D, 0xD5, 0xC8, 0x65, 0x84, + 0x57, 0x20); +DEFINE_GUID(IID_ID3D11VideoDecoderOutputView, 0xC2931AEA, 0x2A85, 0x4f20, 0x86, 0x0F, 0xFB, 0xA1, + 0xFD, 0x25, 0x6E, 0x18); +DEFINE_GUID(IID_ID3D11VideoProcessorInputView, 0x11EC5A5F, 0x51DC, 0x4945, 0xAB, 0x34, 0x6E, 0x8C, + 0x21, 0x30, 0x0E, 0xA5); +DEFINE_GUID(IID_ID3D11VideoProcessorOutputView, 0xA048285E, 0x25A9, 0x4527, 0xBD, 0x93, 0xD6, 0x8B, + 0x68, 0xC4, 0x42, 0x54); +DEFINE_GUID(IID_ID3D11VideoContext, 0x61F21C45, 0x3C0E, 0x4a74, 0x9C, 0xEA, 0x67, 0x10, 0x0D, 0x9A, + 0xD5, 0xE4); +DEFINE_GUID(IID_ID3D11VideoDevice, 0x10EC4D5B, 0x975A, 0x4689, 0xB9, 0xE4, 0xD0, 0xAA, 0xC3, 0x0F, + 0xE3, 0x33); +DEFINE_GUID(IID_ID3D11Device, 0xdb6f6ddb, 0xac77, 0x4e88, 0x82, 0x53, 0x81, 0x9d, 0xf9, 0xbb, 0xf1, + 0x40); + +/* dxgi.h GUIDs */ + +DEFINE_GUID(IID_IDXGIObject, 0xaec22fb8, 0x76f3, 0x4639, 0x9b, 0xe0, 0x28, 0xeb, 0x43, 0xa6, 0x7a, + 0x2e); +DEFINE_GUID(IID_IDXGIDeviceSubObject, 0x3d3e0379, 0xf9de, 0x4d58, 0xbb, 0x6c, 0x18, 0xd6, 0x29, + 0x92, 0xf1, 0xa6); +DEFINE_GUID(IID_IDXGIResource, 0x035f3ab4, 0x482e, 0x4e50, 0xb4, 0x1f, 0x8a, 0x7f, 0x8b, 0xd8, 0x96, + 0x0b); +DEFINE_GUID(IID_IDXGIKeyedMutex, 0x9d8e1289, 0xd7b3, 0x465f, 0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, + 0xf8, 0x5d); +DEFINE_GUID(IID_IDXGISurface, 0xcafcb56c, 0x6ac3, 0x4889, 0xbf, 0x47, 0x9e, 0x23, 0xbb, 0xd2, 0x60, + 0xec); +DEFINE_GUID(IID_IDXGISurface1, 0x4AE63092, 0x6327, 0x4c1b, 0x80, 0xAE, 0xBF, 0xE1, 0x2E, 0xA3, 0x2B, + 0x86); +DEFINE_GUID(IID_IDXGIAdapter, 0x2411e7e1, 0x12ac, 0x4ccf, 0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, + 0xc0); +DEFINE_GUID(IID_IDXGIOutput, 0xae02eedb, 0xc735, 0x4690, 0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, + 0xaa); +DEFINE_GUID(IID_IDXGISwapChain, 0x310d36a0, 0xd2e7, 0x4c0a, 0xaa, 0x04, 0x6a, 0x9d, 0x23, 0xb8, + 0x88, 0x6a); +DEFINE_GUID(IID_IDXGIFactory, 0x7b7166ec, 0x21c7, 0x44ae, 0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, + 0x69); +DEFINE_GUID(IID_IDXGIDevice, 0x54ec77fa, 0x1377, 0x44e6, 0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, + 0x4c); +DEFINE_GUID(IID_IDXGIFactory1, 0x770aae78, 0xf26f, 0x4dba, 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, + 0x87); +DEFINE_GUID(IID_IDXGIAdapter1, 0x29038f61, 0x3839, 0x4626, 0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, + 0x05); +DEFINE_GUID(IID_IDXGIDevice1, 0x77db970f, 0x6276, 0x48ba, 0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, + 0x2c); + +/* dxgi1_2.h GUIDs */ + +DEFINE_GUID(IID_IDXGIDisplayControl, 0xea9dbf1a, 0xc88e, 0x4486, 0x85, 0x4a, 0x98, 0xaa, 0x01, 0x38, + 0xf3, 0x0c); +DEFINE_GUID(IID_IDXGIOutputDuplication, 0x191cfac3, 0xa341, 0x470d, 0xb2, 0x6e, 0xa8, 0x64, 0xf4, + 0x28, 0x31, 0x9c); +DEFINE_GUID(IID_IDXGISurface2, 0xaba496dd, 0xb617, 0x4cb8, 0xa8, 0x66, 0xbc, 0x44, 0xd7, 0xeb, 0x1f, + 0xa2); +DEFINE_GUID(IID_IDXGIResource1, 0x30961379, 0x4609, 0x4a41, 0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, + 0xe0, 0xc1); +DEFINE_GUID(IID_IDXGIDevice2, 0x05008617, 0xfbfd, 0x4051, 0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, + 0xa9); +DEFINE_GUID(IID_IDXGISwapChain1, 0x790a45f7, 0x0d42, 0x4876, 0x98, 0x3a, 0x0a, 0x55, 0xcf, 0xe6, + 0xf4, 0xaa); +DEFINE_GUID(IID_IDXGIFactory2, 0x50c83a1c, 0xe072, 0x4c48, 0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, + 0xd0); +DEFINE_GUID(IID_IDXGIAdapter2, 0x0AA1AE0A, 0xFA0E, 0x4B84, 0x86, 0x44, 0xE0, 0x5F, 0xF8, 0xE5, 0xAC, + 0xB5); +DEFINE_GUID(IID_IDXGIOutput1, 0x00cddea8, 0x939b, 0x4b83, 0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, + 0xcc); + +const char* GetDxgiErrorString(HRESULT hr) +{ + switch (hr) + { + case DXGI_STATUS_OCCLUDED: + return "DXGI_STATUS_OCCLUDED"; + case DXGI_STATUS_CLIPPED: + return "DXGI_STATUS_CLIPPED"; + case DXGI_STATUS_NO_REDIRECTION: + return "DXGI_STATUS_NO_REDIRECTION"; + case DXGI_STATUS_NO_DESKTOP_ACCESS: + return "DXGI_STATUS_NO_DESKTOP_ACCESS"; + case DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: + return "DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE"; + case DXGI_STATUS_MODE_CHANGED: + return "DXGI_STATUS_MODE_CHANGED"; + case DXGI_STATUS_MODE_CHANGE_IN_PROGRESS: + return "DXGI_STATUS_MODE_CHANGE_IN_PROGRESS"; + case DXGI_ERROR_INVALID_CALL: + return "DXGI_ERROR_INVALID_CALL"; + case DXGI_ERROR_NOT_FOUND: + return "DXGI_ERROR_NOT_FOUND"; + case DXGI_ERROR_MORE_DATA: + return "DXGI_ERROR_MORE_DATA"; + case DXGI_ERROR_UNSUPPORTED: + return "DXGI_ERROR_UNSUPPORTED"; + case DXGI_ERROR_DEVICE_REMOVED: + return "DXGI_ERROR_DEVICE_REMOVED"; + case DXGI_ERROR_DEVICE_HUNG: + return "DXGI_ERROR_DEVICE_HUNG"; + case DXGI_ERROR_DEVICE_RESET: + return "DXGI_ERROR_DEVICE_RESET"; + case DXGI_ERROR_WAS_STILL_DRAWING: + return "DXGI_ERROR_WAS_STILL_DRAWING"; + case DXGI_ERROR_FRAME_STATISTICS_DISJOINT: + return "DXGI_ERROR_FRAME_STATISTICS_DISJOINT"; + case DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: + return "DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE"; + case DXGI_ERROR_DRIVER_INTERNAL_ERROR: + return "DXGI_ERROR_DRIVER_INTERNAL_ERROR"; + case DXGI_ERROR_NONEXCLUSIVE: + return "DXGI_ERROR_NONEXCLUSIVE"; + case DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: + return "DXGI_ERROR_NOT_CURRENTLY_AVAILABLE"; + case DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED: + return "DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED"; + case DXGI_ERROR_REMOTE_OUTOFMEMORY: + return "DXGI_ERROR_REMOTE_OUTOFMEMORY"; + case DXGI_ERROR_ACCESS_LOST: + return "DXGI_ERROR_ACCESS_LOST"; + case DXGI_ERROR_WAIT_TIMEOUT: + return "DXGI_ERROR_WAIT_TIMEOUT"; + case DXGI_ERROR_SESSION_DISCONNECTED: + return "DXGI_ERROR_SESSION_DISCONNECTED"; + case DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE: + return "DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE"; + case DXGI_ERROR_CANNOT_PROTECT_CONTENT: + return "DXGI_ERROR_CANNOT_PROTECT_CONTENT"; + case DXGI_ERROR_ACCESS_DENIED: + return "DXGI_ERROR_ACCESS_DENIED"; + case DXGI_ERROR_NAME_ALREADY_EXISTS: + return "DXGI_ERROR_NAME_ALREADY_EXISTS"; + case DXGI_ERROR_SDK_COMPONENT_MISSING: + return "DXGI_ERROR_SDK_COMPONENT_MISSING"; + case DXGI_STATUS_UNOCCLUDED: + return "DXGI_STATUS_UNOCCLUDED"; + case DXGI_STATUS_DDA_WAS_STILL_DRAWING: + return "DXGI_STATUS_DDA_WAS_STILL_DRAWING"; + case DXGI_ERROR_MODE_CHANGE_IN_PROGRESS: + return "DXGI_ERROR_MODE_CHANGE_IN_PROGRESS"; + case DXGI_DDI_ERR_WASSTILLDRAWING: + return "DXGI_DDI_ERR_WASSTILLDRAWING"; + case DXGI_DDI_ERR_UNSUPPORTED: + return "DXGI_DDI_ERR_UNSUPPORTED"; + case DXGI_DDI_ERR_NONEXCLUSIVE: + return "DXGI_DDI_ERR_NONEXCLUSIVE"; + case 0x80070005: + return "DXGI_ERROR_ACCESS_DENIED"; + } + + return "DXGI_ERROR_UNKNOWN"; +} + +static void win_shadow_d3d11_module_init() +{ + if (d3d11_module) + return; + + d3d11_module = LoadLibraryA("d3d11.dll"); + + if (!d3d11_module) + return; + + pfnD3D11CreateDevice = GetProcAddressAs(d3d11_module, "D3D11CreateDevice", fnD3D11CreateDevice); +} + +int win_shadow_dxgi_init_duplication(winShadowSubsystem* subsystem) +{ + HRESULT hr; + UINT dTop, i = 0; + IDXGIOutput* pOutput; + DXGI_OUTPUT_DESC outputDesc = { 0 }; + DXGI_OUTPUT_DESC* pOutputDesc; + D3D11_TEXTURE2D_DESC textureDesc; + IDXGIDevice* dxgiDevice = NULL; + IDXGIAdapter* dxgiAdapter = NULL; + IDXGIOutput* dxgiOutput = NULL; + IDXGIOutput1* dxgiOutput1 = NULL; + + hr = subsystem->dxgiDevice->lpVtbl->QueryInterface(subsystem->dxgiDevice, &IID_IDXGIDevice, + (void**)&dxgiDevice); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "ID3D11Device::QueryInterface(IDXGIDevice) failure: %s (0x%08lX)", + GetDxgiErrorString(hr), hr); + return -1; + } + + hr = dxgiDevice->lpVtbl->GetParent(dxgiDevice, &IID_IDXGIAdapter, (void**)&dxgiAdapter); + + if (dxgiDevice) + { + dxgiDevice->lpVtbl->Release(dxgiDevice); + dxgiDevice = NULL; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIDevice::GetParent(IDXGIAdapter) failure: %s (0x%08lX)", + GetDxgiErrorString(hr), hr); + return -1; + } + + pOutput = NULL; + + while (dxgiAdapter->lpVtbl->EnumOutputs(dxgiAdapter, i, &pOutput) != DXGI_ERROR_NOT_FOUND) + { + pOutputDesc = &outputDesc; + + hr = pOutput->lpVtbl->GetDesc(pOutput, pOutputDesc); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIOutput::GetDesc failure: %s (0x%08lX)", GetDxgiErrorString(hr), hr); + return -1; + } + + if (pOutputDesc->AttachedToDesktop) + dTop = i; + + pOutput->lpVtbl->Release(pOutput); + i++; + } + + dTop = 0; /* screen id */ + + hr = dxgiAdapter->lpVtbl->EnumOutputs(dxgiAdapter, dTop, &dxgiOutput); + + if (dxgiAdapter) + { + dxgiAdapter->lpVtbl->Release(dxgiAdapter); + dxgiAdapter = NULL; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIAdapter::EnumOutputs failure: %s (0x%08lX)", GetDxgiErrorString(hr), + hr); + return -1; + } + + hr = dxgiOutput->lpVtbl->QueryInterface(dxgiOutput, &IID_IDXGIOutput1, (void**)&dxgiOutput1); + + if (dxgiOutput) + { + dxgiOutput->lpVtbl->Release(dxgiOutput); + dxgiOutput = NULL; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIOutput::QueryInterface(IDXGIOutput1) failure: %s (0x%08lX)", + GetDxgiErrorString(hr), hr); + return -1; + } + + hr = dxgiOutput1->lpVtbl->DuplicateOutput(dxgiOutput1, (IUnknown*)subsystem->dxgiDevice, + &(subsystem->dxgiOutputDuplication)); + + if (dxgiOutput1) + { + dxgiOutput1->lpVtbl->Release(dxgiOutput1); + dxgiOutput1 = NULL; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIOutput1::DuplicateOutput failure: %s (0x%08lX)", GetDxgiErrorString(hr), + hr); + return -1; + } + + textureDesc.Width = subsystem->width; + textureDesc.Height = subsystem->height; + textureDesc.MipLevels = 1; + textureDesc.ArraySize = 1; + textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + textureDesc.SampleDesc.Count = 1; + textureDesc.SampleDesc.Quality = 0; + textureDesc.Usage = D3D11_USAGE_STAGING; + textureDesc.BindFlags = 0; + textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + textureDesc.MiscFlags = 0; + + hr = subsystem->dxgiDevice->lpVtbl->CreateTexture2D(subsystem->dxgiDevice, &textureDesc, NULL, + &(subsystem->dxgiStage)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "ID3D11Device::CreateTexture2D failure: %s (0x%08lX)", GetDxgiErrorString(hr), + hr); + return -1; + } + + return 1; +} + +int win_shadow_dxgi_init(winShadowSubsystem* subsystem) +{ + UINT i = 0; + HRESULT hr; + int status; + UINT DriverTypeIndex; + IDXGIDevice* DxgiDevice = NULL; + IDXGIAdapter* DxgiAdapter = NULL; + IDXGIOutput* DxgiOutput = NULL; + IDXGIOutput1* DxgiOutput1 = NULL; + + win_shadow_d3d11_module_init(); + + if (!pfnD3D11CreateDevice) + return -1; + + for (DriverTypeIndex = 0; DriverTypeIndex < NumDriverTypes; ++DriverTypeIndex) + { + hr = pfnD3D11CreateDevice(NULL, DriverTypes[DriverTypeIndex], NULL, 0, FeatureLevels, + NumFeatureLevels, D3D11_SDK_VERSION, &(subsystem->dxgiDevice), + &(subsystem->featureLevel), &(subsystem->dxgiDeviceContext)); + + if (SUCCEEDED(hr)) + break; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "D3D11CreateDevice failure: 0x%08lX", hr); + return -1; + } + + status = win_shadow_dxgi_init_duplication(subsystem); + + return status; +} + +int win_shadow_dxgi_uninit(winShadowSubsystem* subsystem) +{ + if (subsystem->dxgiStage) + { + subsystem->dxgiStage->lpVtbl->Release(subsystem->dxgiStage); + subsystem->dxgiStage = NULL; + } + + if (subsystem->dxgiDesktopImage) + { + subsystem->dxgiDesktopImage->lpVtbl->Release(subsystem->dxgiDesktopImage); + subsystem->dxgiDesktopImage = NULL; + } + + if (subsystem->dxgiOutputDuplication) + { + subsystem->dxgiOutputDuplication->lpVtbl->Release(subsystem->dxgiOutputDuplication); + subsystem->dxgiOutputDuplication = NULL; + } + + if (subsystem->dxgiDeviceContext) + { + subsystem->dxgiDeviceContext->lpVtbl->Release(subsystem->dxgiDeviceContext); + subsystem->dxgiDeviceContext = NULL; + } + + if (subsystem->dxgiDevice) + { + subsystem->dxgiDevice->lpVtbl->Release(subsystem->dxgiDevice); + subsystem->dxgiDevice = NULL; + } + + return 1; +} + +int win_shadow_dxgi_fetch_frame_data(winShadowSubsystem* subsystem, BYTE** ppDstData, + int* pnDstStep, int x, int y, int width, int height) +{ + int status; + HRESULT hr; + D3D11_BOX Box; + DXGI_MAPPED_RECT mappedRect; + + if ((width * height) < 1) + return 0; + + Box.top = x; + Box.left = y; + Box.right = x + width; + Box.bottom = y + height; + Box.front = 0; + Box.back = 1; + + subsystem->dxgiDeviceContext->lpVtbl->CopySubresourceRegion( + subsystem->dxgiDeviceContext, (ID3D11Resource*)subsystem->dxgiStage, 0, 0, 0, 0, + (ID3D11Resource*)subsystem->dxgiDesktopImage, 0, &Box); + + hr = subsystem->dxgiStage->lpVtbl->QueryInterface(subsystem->dxgiStage, &IID_IDXGISurface, + (void**)&(subsystem->dxgiSurface)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "ID3D11Texture2D::QueryInterface(IDXGISurface) failure: %s 0x%08lX", + GetDxgiErrorString(hr), hr); + return -1; + } + + hr = subsystem->dxgiSurface->lpVtbl->Map(subsystem->dxgiSurface, &mappedRect, DXGI_MAP_READ); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGISurface::Map failure: %s 0x%08lX", GetDxgiErrorString(hr), hr); + + if (hr == DXGI_ERROR_DEVICE_REMOVED) + { + win_shadow_dxgi_uninit(subsystem); + + status = win_shadow_dxgi_init(subsystem); + + if (status < 0) + return -1; + + return 0; + } + + return -1; + } + + subsystem->dxgiSurfaceMapped = TRUE; + + *ppDstData = mappedRect.pBits; + *pnDstStep = mappedRect.Pitch; + + return 1; +} + +int win_shadow_dxgi_release_frame_data(winShadowSubsystem* subsystem) +{ + if (subsystem->dxgiSurface) + { + if (subsystem->dxgiSurfaceMapped) + { + subsystem->dxgiSurface->lpVtbl->Unmap(subsystem->dxgiSurface); + subsystem->dxgiSurfaceMapped = FALSE; + } + + subsystem->dxgiSurface->lpVtbl->Release(subsystem->dxgiSurface); + subsystem->dxgiSurface = NULL; + } + + if (subsystem->dxgiOutputDuplication) + { + if (subsystem->dxgiFrameAcquired) + { + subsystem->dxgiOutputDuplication->lpVtbl->ReleaseFrame( + subsystem->dxgiOutputDuplication); + subsystem->dxgiFrameAcquired = FALSE; + } + } + + subsystem->pendingFrames = 0; + + return 1; +} + +int win_shadow_dxgi_get_next_frame(winShadowSubsystem* subsystem) +{ + UINT i = 0; + int status; + HRESULT hr = 0; + UINT timeout = 15; + UINT DataBufferSize = 0; + BYTE* DataBuffer = NULL; + + if (subsystem->dxgiFrameAcquired) + { + win_shadow_dxgi_release_frame_data(subsystem); + } + + if (subsystem->dxgiDesktopImage) + { + subsystem->dxgiDesktopImage->lpVtbl->Release(subsystem->dxgiDesktopImage); + subsystem->dxgiDesktopImage = NULL; + } + + hr = subsystem->dxgiOutputDuplication->lpVtbl->AcquireNextFrame( + subsystem->dxgiOutputDuplication, timeout, &(subsystem->dxgiFrameInfo), + &(subsystem->dxgiResource)); + + if (SUCCEEDED(hr)) + { + subsystem->dxgiFrameAcquired = TRUE; + subsystem->pendingFrames = subsystem->dxgiFrameInfo.AccumulatedFrames; + } + + if (hr == DXGI_ERROR_WAIT_TIMEOUT) + return 0; + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIOutputDuplication::AcquireNextFrame failure: %s (0x%08lX)", + GetDxgiErrorString(hr), hr); + + if (hr == DXGI_ERROR_ACCESS_LOST) + { + win_shadow_dxgi_release_frame_data(subsystem); + + if (subsystem->dxgiDesktopImage) + { + subsystem->dxgiDesktopImage->lpVtbl->Release(subsystem->dxgiDesktopImage); + subsystem->dxgiDesktopImage = NULL; + } + + if (subsystem->dxgiOutputDuplication) + { + subsystem->dxgiOutputDuplication->lpVtbl->Release(subsystem->dxgiOutputDuplication); + subsystem->dxgiOutputDuplication = NULL; + } + + status = win_shadow_dxgi_init_duplication(subsystem); + + if (status < 0) + return -1; + + return 0; + } + else if (hr == DXGI_ERROR_INVALID_CALL) + { + win_shadow_dxgi_uninit(subsystem); + + status = win_shadow_dxgi_init(subsystem); + + if (status < 0) + return -1; + + return 0; + } + + return -1; + } + + hr = subsystem->dxgiResource->lpVtbl->QueryInterface( + subsystem->dxgiResource, &IID_ID3D11Texture2D, (void**)&(subsystem->dxgiDesktopImage)); + + if (subsystem->dxgiResource) + { + subsystem->dxgiResource->lpVtbl->Release(subsystem->dxgiResource); + subsystem->dxgiResource = NULL; + } + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IDXGIResource::QueryInterface(ID3D11Texture2D) failure: %s (0x%08lX)", + GetDxgiErrorString(hr), hr); + return -1; + } + + return 1; +} + +int win_shadow_dxgi_get_invalid_region(winShadowSubsystem* subsystem) +{ + HRESULT hr; + POINT* pSrcPt; + RECT* pDstRect; + RECT* pDirtyRect; + UINT numMoveRects; + UINT numDirtyRects; + UINT UsedBufferSize; + RECTANGLE_16 invalidRect; + UINT MetadataBufferSize; + UINT MoveRectsBufferSize; + UINT DirtyRectsBufferSize; + RECT* pDirtyRectsBuffer; + DXGI_OUTDUPL_MOVE_RECT* pMoveRect; + DXGI_OUTDUPL_MOVE_RECT* pMoveRectBuffer; + rdpShadowSurface* surface = subsystem->server->surface; + + if (subsystem->dxgiFrameInfo.AccumulatedFrames == 0) + return 0; + + if (subsystem->dxgiFrameInfo.TotalMetadataBufferSize == 0) + return 0; + + MetadataBufferSize = subsystem->dxgiFrameInfo.TotalMetadataBufferSize; + + if (MetadataBufferSize > subsystem->MetadataBufferSize) + { + subsystem->MetadataBuffer = (BYTE*)realloc(subsystem->MetadataBuffer, MetadataBufferSize); + + if (!subsystem->MetadataBuffer) + return -1; + + subsystem->MetadataBufferSize = MetadataBufferSize; + } + + /* GetFrameMoveRects */ + + UsedBufferSize = 0; + + MoveRectsBufferSize = MetadataBufferSize - UsedBufferSize; + pMoveRectBuffer = (DXGI_OUTDUPL_MOVE_RECT*)&(subsystem->MetadataBuffer[UsedBufferSize]); + + hr = subsystem->dxgiOutputDuplication->lpVtbl->GetFrameMoveRects( + subsystem->dxgiOutputDuplication, MoveRectsBufferSize, pMoveRectBuffer, + &MoveRectsBufferSize); + + if (FAILED(hr)) + { + WLog_ERR(TAG, + "IDXGIOutputDuplication::GetFrameMoveRects failure: %s (0x%08lX) Size: %u Total " + "%u Used: %u", + GetDxgiErrorString(hr), hr, MoveRectsBufferSize, MetadataBufferSize, + UsedBufferSize); + return -1; + } + + /* GetFrameDirtyRects */ + + UsedBufferSize += MoveRectsBufferSize; + + DirtyRectsBufferSize = MetadataBufferSize - UsedBufferSize; + pDirtyRectsBuffer = (RECT*)&(subsystem->MetadataBuffer[UsedBufferSize]); + + hr = subsystem->dxgiOutputDuplication->lpVtbl->GetFrameDirtyRects( + subsystem->dxgiOutputDuplication, DirtyRectsBufferSize, pDirtyRectsBuffer, + &DirtyRectsBufferSize); + + if (FAILED(hr)) + { + WLog_ERR(TAG, + "IDXGIOutputDuplication::GetFrameDirtyRects failure: %s (0x%08lX) Size: %u Total " + "%u Used: %u", + GetDxgiErrorString(hr), hr, DirtyRectsBufferSize, MetadataBufferSize, + UsedBufferSize); + return -1; + } + + numMoveRects = MoveRectsBufferSize / sizeof(DXGI_OUTDUPL_MOVE_RECT); + + for (UINT i = 0; i < numMoveRects; i++) + { + pMoveRect = &pMoveRectBuffer[i]; + pSrcPt = &(pMoveRect->SourcePoint); + pDstRect = &(pMoveRect->DestinationRect); + + invalidRect.left = (UINT16)pDstRect->left; + invalidRect.top = (UINT16)pDstRect->top; + invalidRect.right = (UINT16)pDstRect->right; + invalidRect.bottom = (UINT16)pDstRect->bottom; + + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + } + + numDirtyRects = DirtyRectsBufferSize / sizeof(RECT); + + for (UINT i = 0; i < numDirtyRects; i++) + { + pDirtyRect = &pDirtyRectsBuffer[i]; + + invalidRect.left = (UINT16)pDirtyRect->left; + invalidRect.top = (UINT16)pDirtyRect->top; + invalidRect.right = (UINT16)pDirtyRect->right; + invalidRect.bottom = (UINT16)pDirtyRect->bottom; + + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + } + + return 1; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.h new file mode 100644 index 0000000000000000000000000000000000000000..ffe80a049d14603fa9e98dbba0758e4a1f297726 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_dxgi.h @@ -0,0 +1,61 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_WIN_DXGI_H +#define FREERDP_SERVER_SHADOW_WIN_DXGI_H + +#if _WIN32_WINNT >= 0x0602 +//#define WITH_DXGI_1_2 1 +#endif + +#ifdef WITH_DXGI_1_2 + +#ifndef CINTERFACE +#define CINTERFACE +#endif + +#include +#include + +#endif + +#include "win_shadow.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef WITH_DXGI_1_2 + + int win_shadow_dxgi_init(winShadowSubsystem* subsystem); + int win_shadow_dxgi_uninit(winShadowSubsystem* subsystem); + + int win_shadow_dxgi_fetch_frame_data(winShadowSubsystem* subsystem, BYTE** ppDstData, + int* pnDstStep, int x, int y, int width, int height); + + int win_shadow_dxgi_get_next_frame(winShadowSubsystem* subsystem); + int win_shadow_dxgi_get_invalid_region(winShadowSubsystem* subsystem); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_WIN_DXGI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.c new file mode 100644 index 0000000000000000000000000000000000000000..3332f1e64cf1b893542237511dcacd53ab9d64fc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.c @@ -0,0 +1,440 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include + +#include "win_rdp.h" + +#define TAG SERVER_TAG("shadow.win") + +static void shw_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e) +{ + shwContext* shw = (shwContext*)context; + WINPR_ASSERT(e); + WLog_INFO(TAG, "OnChannelConnected: %s", e->name); +} + +static void shw_OnChannelDisconnectedEventHandler(void* context, + const ChannelDisconnectedEventArgs* e) +{ + shwContext* shw = (shwContext*)context; + WINPR_ASSERT(e); + WLog_INFO(TAG, "OnChannelDisconnected: %s", e->name); +} + +static BOOL shw_begin_paint(rdpContext* context) +{ + shwContext* shw; + rdpGdi* gdi; + + WINPR_ASSERT(context); + gdi = context->gdi; + WINPR_ASSERT(gdi); + shw = (shwContext*)context; + gdi->primary->hdc->hwnd->invalid->null = TRUE; + gdi->primary->hdc->hwnd->ninvalid = 0; + return TRUE; +} + +static BOOL shw_end_paint(rdpContext* context) +{ + int ninvalid; + HGDI_RGN cinvalid; + RECTANGLE_16 invalidRect; + rdpGdi* gdi = context->gdi; + shwContext* shw = (shwContext*)context; + winShadowSubsystem* subsystem = shw->subsystem; + rdpShadowSurface* surface = subsystem->base.server->surface; + ninvalid = gdi->primary->hdc->hwnd->ninvalid; + cinvalid = gdi->primary->hdc->hwnd->cinvalid; + + for (int index = 0; index < ninvalid; index++) + { + invalidRect.left = cinvalid[index].x; + invalidRect.top = cinvalid[index].y; + invalidRect.right = cinvalid[index].x + cinvalid[index].w; + invalidRect.bottom = cinvalid[index].y + cinvalid[index].h; + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + } + + (void)SetEvent(subsystem->RdpUpdateEnterEvent); + (void)WaitForSingleObject(subsystem->RdpUpdateLeaveEvent, INFINITE); + (void)ResetEvent(subsystem->RdpUpdateLeaveEvent); + return TRUE; +} + +BOOL shw_desktop_resize(rdpContext* context) +{ + WLog_WARN(TAG, "Desktop resizing not implemented!"); + return TRUE; +} + +static BOOL shw_surface_frame_marker(rdpContext* context, + const SURFACE_FRAME_MARKER* surfaceFrameMarker) +{ + shwContext* shw = (shwContext*)context; + return TRUE; +} + +static BOOL shw_authenticate(freerdp* instance, char** username, char** password, char** domain) +{ + WLog_WARN(TAG, "Authentication not implemented, access granted to everyone!"); + return TRUE; +} + +static int shw_verify_x509_certificate(freerdp* instance, const BYTE* data, size_t length, + const char* hostname, UINT16 port, DWORD flags) +{ + WLog_WARN(TAG, "Certificate checks not implemented, access granted to everyone!"); + return 1; +} + +static void shw_OnConnectionResultEventHandler(void* context, const ConnectionResultEventArgs* e) +{ + shwContext* shw = (shwContext*)context; + WINPR_ASSERT(e); + WLog_INFO(TAG, "OnConnectionResult: %d", e->result); +} + +static BOOL shw_pre_connect(freerdp* instance) +{ + shwContext* shw; + rdpContext* context = instance->context; + shw = (shwContext*)context; + PubSub_SubscribeConnectionResult(context->pubSub, shw_OnConnectionResultEventHandler); + PubSub_SubscribeChannelConnected(context->pubSub, shw_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(context->pubSub, shw_OnChannelDisconnectedEventHandler); + + return TRUE; +} + +static BOOL shw_post_connect(freerdp* instance) +{ + rdpGdi* gdi; + shwContext* shw; + rdpUpdate* update; + rdpSettings* settings; + + WINPR_ASSERT(instance); + + shw = (shwContext*)instance->context; + WINPR_ASSERT(shw); + + update = instance->context->update; + WINPR_ASSERT(update); + + settings = instance->context->settings; + WINPR_ASSERT(settings); + + if (!gdi_init(instance, PIXEL_FORMAT_BGRX32)) + return FALSE; + + gdi = instance->context->gdi; + update->BeginPaint = shw_begin_paint; + update->EndPaint = shw_end_paint; + update->DesktopResize = shw_desktop_resize; + update->SurfaceFrameMarker = shw_surface_frame_marker; + return TRUE; +} + +static DWORD WINAPI shw_client_thread(LPVOID arg) +{ + int index; + BOOL bSuccess; + shwContext* shw; + rdpContext* context; + rdpChannels* channels; + + freerdp* instance = (freerdp*)arg; + WINPR_ASSERT(instance); + + context = (rdpContext*)instance->context; + WINPR_ASSERT(context); + + shw = (shwContext*)context; + + bSuccess = freerdp_connect(instance); + WLog_INFO(TAG, "freerdp_connect: %d", bSuccess); + + if (!bSuccess) + { + ExitThread(0); + return 0; + } + + channels = context->channels; + WINPR_ASSERT(channels); + + while (1) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = freerdp_get_event_handles(instance->context, handles, ARRAYSIZE(handles)); + + if ((count == 0) || (count == MAXIMUM_WAIT_OBJECTS)) + { + WLog_ERR(TAG, "Failed to get FreeRDP event handles"); + break; + } + + handles[count++] = freerdp_channels_get_event_handle(instance); + + if (MsgWaitForMultipleObjects(count, handles, FALSE, 1000, QS_ALLINPUT) == WAIT_FAILED) + { + WLog_ERR(TAG, "MsgWaitForMultipleObjects failure: 0x%08lX", GetLastError()); + break; + } + + if (!freerdp_check_fds(instance)) + { + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + break; + } + + if (freerdp_shall_disconnect_context(instance->context)) + { + break; + } + + if (!freerdp_channels_check_fds(channels, instance)) + { + WLog_ERR(TAG, "Failed to check channels file descriptor"); + break; + } + } + + freerdp_free(instance); + ExitThread(0); + return 0; +} + +/** + * Client Interface + */ + +static BOOL shw_freerdp_client_global_init(void) +{ + return TRUE; +} + +static void shw_freerdp_client_global_uninit(void) +{ +} + +static int shw_freerdp_client_start(rdpContext* context) +{ + shwContext* shw; + freerdp* instance = context->instance; + shw = (shwContext*)context; + + if (!(shw->common.thread = CreateThread(NULL, 0, shw_client_thread, instance, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create thread"); + return -1; + } + + return 0; +} + +static int shw_freerdp_client_stop(rdpContext* context) +{ + shwContext* shw = (shwContext*)context; + (void)SetEvent(shw->StopEvent); + return 0; +} + +static BOOL shw_freerdp_client_new(freerdp* instance, rdpContext* context) +{ + shwContext* shw; + rdpSettings* settings; + + WINPR_ASSERT(instance); + WINPR_ASSERT(context); + + shw = (shwContext*)instance->context; + WINPR_ASSERT(shw); + + if (!(shw->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + return FALSE; + + instance->LoadChannels = freerdp_client_load_channels; + instance->PreConnect = shw_pre_connect; + instance->PostConnect = shw_post_connect; + instance->Authenticate = shw_authenticate; + instance->VerifyX509Certificate = shw_verify_x509_certificate; + + settings = context->settings; + WINPR_ASSERT(settings); + + shw->settings = settings; + if (!freerdp_settings_set_bool(settings, FreeRDP_AsyncChannels, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_AsyncUpdate, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_IgnoreCertificate, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_ExternalCertificateManagement, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheEnabled, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheV3Enabled, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_OffscreenSupportLevel, FALSE)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_GlyphSupportLevel, GLYPH_SUPPORT_NONE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_BrushSupportLevel, FALSE)) + return FALSE; + ZeroMemory(freerdp_settings_get_pointer_writable(settings, FreeRDP_OrderSupport), 32); + if (!freerdp_settings_set_bool(settings, FreeRDP_FrameMarkerCommandEnabled, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SurfaceFrameMarkerEnabled, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_AltSecFrameMarkerSupport, TRUE)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_FastPathInput, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_FastPathOutput, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_LargePointerFlag, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_CompressionEnabled, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoReconnectionEnabled, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_NetworkAutoDetect, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportHeartbeatPdu, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportMultitransport, FALSE)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_ConnectionType, CONNECTION_TYPE_LAN)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_AllowFontSmoothing, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_AllowDesktopComposition, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DisableWallpaper, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DisableFullWindowDrag, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DisableMenuAnims, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DisableThemes, FALSE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectClipboard, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportDynamicChannels, TRUE)) + return FALSE; + return TRUE; +} + +static void shw_freerdp_client_free(freerdp* instance, rdpContext* context) +{ + shwContext* shw = (shwContext*)instance->context; +} + +int shw_RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + pEntryPoints->Version = 1; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->settings = NULL; + pEntryPoints->ContextSize = sizeof(shwContext); + pEntryPoints->GlobalInit = shw_freerdp_client_global_init; + pEntryPoints->GlobalUninit = shw_freerdp_client_global_uninit; + pEntryPoints->ClientNew = shw_freerdp_client_new; + pEntryPoints->ClientFree = shw_freerdp_client_free; + pEntryPoints->ClientStart = shw_freerdp_client_start; + pEntryPoints->ClientStop = shw_freerdp_client_stop; + return 0; +} + +int win_shadow_rdp_init(winShadowSubsystem* subsystem) +{ + rdpContext* context; + RDP_CLIENT_ENTRY_POINTS clientEntryPoints = { 0 }; + + clientEntryPoints.Size = sizeof(RDP_CLIENT_ENTRY_POINTS); + clientEntryPoints.Version = RDP_CLIENT_INTERFACE_VERSION; + shw_RdpClientEntry(&clientEntryPoints); + + if (!(subsystem->RdpUpdateEnterEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail_enter_event; + + if (!(subsystem->RdpUpdateLeaveEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail_leave_event; + + if (!(context = freerdp_client_context_new(&clientEntryPoints))) + goto fail_context; + + subsystem->shw = (shwContext*)context; + subsystem->shw->settings = context->settings; + subsystem->shw->subsystem = subsystem; + return 1; +fail_context: + (void)CloseHandle(subsystem->RdpUpdateLeaveEvent); +fail_leave_event: + (void)CloseHandle(subsystem->RdpUpdateEnterEvent); +fail_enter_event: + return -1; +} + +int win_shadow_rdp_start(winShadowSubsystem* subsystem) +{ + int status; + shwContext* shw = subsystem->shw; + rdpContext* context = (rdpContext*)shw; + status = freerdp_client_start(context); + return status; +} + +int win_shadow_rdp_stop(winShadowSubsystem* subsystem) +{ + int status; + shwContext* shw = subsystem->shw; + rdpContext* context = (rdpContext*)shw; + status = freerdp_client_stop(context); + return status; +} + +int win_shadow_rdp_uninit(winShadowSubsystem* subsystem) +{ + win_shadow_rdp_stop(subsystem); + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.h new file mode 100644 index 0000000000000000000000000000000000000000..07dbf3bb91cb424030cac37f8a17456dfb08f855 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_rdp.h @@ -0,0 +1,56 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_WIN_RDP_H +#define FREERDP_SERVER_SHADOW_WIN_RDP_H + +#include +#include +#include +#include + +typedef struct shw_context shwContext; + +#include "win_shadow.h" + +struct shw_context +{ + rdpClientContext common; + + HANDLE StopEvent; + freerdp* instance; + rdpSettings* settings; + winShadowSubsystem* subsystem; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int win_shadow_rdp_init(winShadowSubsystem* subsystem); + int win_shadow_rdp_uninit(winShadowSubsystem* subsystem); + + int win_shadow_rdp_start(winShadowSubsystem* subsystem); + int win_shadow_rdp_stop(winShadowSubsystem* subsystem); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_WIN_RDP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.c new file mode 100644 index 0000000000000000000000000000000000000000..2a6d62347adfa30fd753b8980d8e12bf876668a6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.c @@ -0,0 +1,561 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include + +#include "win_shadow.h" + +#define TAG SERVER_TAG("shadow.win") + +/* https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event + * does not mention this flag is only supported if building for _WIN32_WINNT >= 0x0600 + */ +#ifndef MOUSEEVENTF_HWHEEL +#define MOUSEEVENTF_HWHEEL 0x1000 +#endif + +static BOOL win_shadow_input_synchronize_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT32 flags) +{ + WLog_WARN(TAG, "TODO: Implement!"); + return TRUE; +} + +static BOOL win_shadow_input_keyboard_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT8 code) +{ + UINT rc; + INPUT event; + event.type = INPUT_KEYBOARD; + event.ki.wVk = 0; + event.ki.wScan = code; + event.ki.dwFlags = KEYEVENTF_SCANCODE; + event.ki.dwExtraInfo = 0; + event.ki.time = 0; + + if (flags & KBD_FLAGS_RELEASE) + event.ki.dwFlags |= KEYEVENTF_KEYUP; + + if (flags & KBD_FLAGS_EXTENDED) + event.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; + + rc = SendInput(1, &event, sizeof(INPUT)); + if (rc == 0) + return FALSE; + return TRUE; +} + +static BOOL win_shadow_input_unicode_keyboard_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, + UINT16 code) +{ + UINT rc; + INPUT event; + event.type = INPUT_KEYBOARD; + event.ki.wVk = 0; + event.ki.wScan = code; + event.ki.dwFlags = KEYEVENTF_UNICODE; + event.ki.dwExtraInfo = 0; + event.ki.time = 0; + + if (flags & KBD_FLAGS_RELEASE) + event.ki.dwFlags |= KEYEVENTF_KEYUP; + + rc = SendInput(1, &event, sizeof(INPUT)); + if (rc == 0) + return FALSE; + return TRUE; +} + +static BOOL win_shadow_input_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT16 x, UINT16 y) +{ + UINT rc = 1; + INPUT event = { 0 }; + float width; + float height; + + event.type = INPUT_MOUSE; + + if (flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL)) + { + if (flags & PTR_FLAGS_WHEEL) + event.mi.dwFlags = MOUSEEVENTF_WHEEL; + else + event.mi.dwFlags = MOUSEEVENTF_HWHEEL; + event.mi.mouseData = flags & WheelRotationMask; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + event.mi.mouseData *= -1; + + rc = SendInput(1, &event, sizeof(INPUT)); + + /* The build target is a system that did not support MOUSEEVENTF_HWHEEL + * but it may run on newer systems supporting it. + * Ignore the return value in these cases. + */ +#if (_WIN32_WINNT < 0x0600) + if (flags & PTR_FLAGS_HWHEEL) + rc = 1; +#endif + } + else + { + width = (float)GetSystemMetrics(SM_CXSCREEN); + height = (float)GetSystemMetrics(SM_CYSCREEN); + event.mi.dx = (LONG)((float)x * (65535.0f / width)); + event.mi.dy = (LONG)((float)y * (65535.0f / height)); + event.mi.dwFlags = MOUSEEVENTF_ABSOLUTE; + + if (flags & PTR_FLAGS_MOVE) + { + event.mi.dwFlags |= MOUSEEVENTF_MOVE; + rc = SendInput(1, &event, sizeof(INPUT)); + if (rc == 0) + return FALSE; + } + + event.mi.dwFlags = MOUSEEVENTF_ABSOLUTE; + + if (flags & PTR_FLAGS_BUTTON1) + { + if (flags & PTR_FLAGS_DOWN) + event.mi.dwFlags |= MOUSEEVENTF_LEFTDOWN; + else + event.mi.dwFlags |= MOUSEEVENTF_LEFTUP; + + rc = SendInput(1, &event, sizeof(INPUT)); + } + else if (flags & PTR_FLAGS_BUTTON2) + { + if (flags & PTR_FLAGS_DOWN) + event.mi.dwFlags |= MOUSEEVENTF_RIGHTDOWN; + else + event.mi.dwFlags |= MOUSEEVENTF_RIGHTUP; + + rc = SendInput(1, &event, sizeof(INPUT)); + } + else if (flags & PTR_FLAGS_BUTTON3) + { + if (flags & PTR_FLAGS_DOWN) + event.mi.dwFlags |= MOUSEEVENTF_MIDDLEDOWN; + else + event.mi.dwFlags |= MOUSEEVENTF_MIDDLEUP; + + rc = SendInput(1, &event, sizeof(INPUT)); + } + } + + if (rc == 0) + return FALSE; + return TRUE; +} + +static BOOL win_shadow_input_extended_mouse_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, UINT16 x, + UINT16 y) +{ + UINT rc = 1; + INPUT event = { 0 }; + float width; + float height; + + if ((flags & PTR_XFLAGS_BUTTON1) || (flags & PTR_XFLAGS_BUTTON2)) + { + event.type = INPUT_MOUSE; + + if (flags & PTR_FLAGS_MOVE) + { + width = (float)GetSystemMetrics(SM_CXSCREEN); + height = (float)GetSystemMetrics(SM_CYSCREEN); + event.mi.dx = (LONG)((float)x * (65535.0f / width)); + event.mi.dy = (LONG)((float)y * (65535.0f / height)); + event.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; + rc = SendInput(1, &event, sizeof(INPUT)); + if (rc == 0) + return FALSE; + } + + event.mi.dx = event.mi.dy = event.mi.dwFlags = 0; + + if (flags & PTR_XFLAGS_DOWN) + event.mi.dwFlags |= MOUSEEVENTF_XDOWN; + else + event.mi.dwFlags |= MOUSEEVENTF_XUP; + + if (flags & PTR_XFLAGS_BUTTON1) + event.mi.mouseData = XBUTTON1; + else if (flags & PTR_XFLAGS_BUTTON2) + event.mi.mouseData = XBUTTON2; + + rc = SendInput(1, &event, sizeof(INPUT)); + } + + if (rc == 0) + return FALSE; + return TRUE; +} + +static int win_shadow_invalidate_region(winShadowSubsystem* subsystem, int x, int y, int width, + int height) +{ + rdpShadowServer* server; + rdpShadowSurface* surface; + RECTANGLE_16 invalidRect; + server = subsystem->base.server; + surface = server->surface; + invalidRect.left = x; + invalidRect.top = y; + invalidRect.right = x + width; + invalidRect.bottom = y + height; + EnterCriticalSection(&(surface->lock)); + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + LeaveCriticalSection(&(surface->lock)); + return 1; +} + +static int win_shadow_surface_copy(winShadowSubsystem* subsystem) +{ + int x, y; + int width; + int height; + int count; + int status = 1; + int nDstStep = 0; + DWORD DstFormat; + BYTE* pDstData = NULL; + rdpShadowServer* server; + rdpShadowSurface* surface; + RECTANGLE_16 surfaceRect; + RECTANGLE_16 invalidRect; + const RECTANGLE_16* extents; + server = subsystem->base.server; + surface = server->surface; + + if (ArrayList_Count(server->clients) < 1) + return 1; + + surfaceRect.left = surface->x; + surfaceRect.top = surface->y; + surfaceRect.right = surface->x + surface->width; + surfaceRect.bottom = surface->y + surface->height; + region16_intersect_rect(&(surface->invalidRegion), &(surface->invalidRegion), &surfaceRect); + + if (region16_is_empty(&(surface->invalidRegion))) + return 1; + + extents = region16_extents(&(surface->invalidRegion)); + CopyMemory(&invalidRect, extents, sizeof(RECTANGLE_16)); + shadow_capture_align_clip_rect(&invalidRect, &surfaceRect); + x = invalidRect.left; + y = invalidRect.top; + width = invalidRect.right - invalidRect.left; + height = invalidRect.bottom - invalidRect.top; + + if (0) + { + x = 0; + y = 0; + width = surface->width; + height = surface->height; + } + + WLog_INFO(TAG, "SurfaceCopy x: %d y: %d width: %d height: %d right: %d bottom: %d", x, y, width, + height, x + width, y + height); +#if defined(WITH_WDS_API) + { + rdpGdi* gdi; + shwContext* shw; + rdpContext* context; + + WINPR_ASSERT(subsystem); + shw = subsystem->shw; + WINPR_ASSERT(shw); + + context = &shw->common.context; + WINPR_ASSERT(context); + + gdi = context->gdi; + WINPR_ASSERT(gdi); + + pDstData = gdi->primary_buffer; + nDstStep = gdi->width * 4; + DstFormat = gdi->dstFormat; + } +#elif defined(WITH_DXGI_1_2) + DstFormat = PIXEL_FORMAT_BGRX32; + status = win_shadow_dxgi_fetch_frame_data(subsystem, &pDstData, &nDstStep, x, y, width, height); +#endif + + if (status <= 0) + return status; + + if (!freerdp_image_copy_no_overlap(surface->data, surface->format, surface->scanline, x, y, + width, height, pDstData, DstFormat, nDstStep, x, y, NULL, + FREERDP_FLIP_NONE)) + return ERROR_INTERNAL_ERROR; + + ArrayList_Lock(server->clients); + count = ArrayList_Count(server->clients); + shadow_subsystem_frame_update(&subsystem->base); + ArrayList_Unlock(server->clients); + region16_clear(&(surface->invalidRegion)); + return 1; +} + +#if defined(WITH_WDS_API) + +static DWORD WINAPI win_shadow_subsystem_thread(LPVOID arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + DWORD status; + DWORD nCount; + HANDLE events[32]; + HANDLE StopEvent; + StopEvent = subsystem->base.server->StopEvent; + nCount = 0; + events[nCount++] = StopEvent; + events[nCount++] = subsystem->RdpUpdateEnterEvent; + + while (1) + { + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0) + { + break; + } + + if (WaitForSingleObject(subsystem->RdpUpdateEnterEvent, 0) == WAIT_OBJECT_0) + { + win_shadow_surface_copy(subsystem); + (void)ResetEvent(subsystem->RdpUpdateEnterEvent); + (void)SetEvent(subsystem->RdpUpdateLeaveEvent); + } + } + + ExitThread(0); + return 0; +} + +#elif defined(WITH_DXGI_1_2) + +static DWORD WINAPI win_shadow_subsystem_thread(LPVOID arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + int fps; + DWORD status; + DWORD nCount; + UINT64 cTime; + DWORD dwTimeout; + DWORD dwInterval; + UINT64 frameTime; + HANDLE events[32]; + HANDLE StopEvent; + StopEvent = subsystem->server->StopEvent; + nCount = 0; + events[nCount++] = StopEvent; + fps = 16; + dwInterval = 1000 / fps; + frameTime = GetTickCount64() + dwInterval; + + while (1) + { + dwTimeout = INFINITE; + cTime = GetTickCount64(); + dwTimeout = (DWORD)((cTime > frameTime) ? 0 : frameTime - cTime); + status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout); + + if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0) + { + break; + } + + if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime)) + { + int dxgi_status; + dxgi_status = win_shadow_dxgi_get_next_frame(subsystem); + + if (dxgi_status > 0) + dxgi_status = win_shadow_dxgi_get_invalid_region(subsystem); + + if (dxgi_status > 0) + win_shadow_surface_copy(subsystem); + + dwInterval = 1000 / fps; + frameTime += dwInterval; + } + } + + ExitThread(0); + return 0; +} + +#endif + +static UINT32 win_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors) +{ + HDC hdc; + int index; + int desktopWidth; + int desktopHeight; + DWORD iDevNum = 0; + int numMonitors = 0; + MONITOR_DEF* monitor; + DISPLAY_DEVICE displayDevice = { 0 }; + + displayDevice.cb = sizeof(DISPLAY_DEVICE); + + if (EnumDisplayDevices(NULL, iDevNum, &displayDevice, 0)) + { + hdc = CreateDC(displayDevice.DeviceName, NULL, NULL, NULL); + desktopWidth = GetDeviceCaps(hdc, HORZRES); + desktopHeight = GetDeviceCaps(hdc, VERTRES); + index = 0; + numMonitors = 1; + monitor = &monitors[index]; + monitor->left = 0; + monitor->top = 0; + monitor->right = desktopWidth; + monitor->bottom = desktopHeight; + monitor->flags = 1; + DeleteDC(hdc); + } + + return numMonitors; +} + +static int win_shadow_subsystem_init(rdpShadowSubsystem* arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + int status; + MONITOR_DEF* virtualScreen; + subsystem->base.numMonitors = win_shadow_enum_monitors(subsystem->base.monitors, 16); +#if defined(WITH_WDS_API) + status = win_shadow_wds_init(subsystem); +#elif defined(WITH_DXGI_1_2) + status = win_shadow_dxgi_init(subsystem); +#endif + virtualScreen = &(subsystem->base.virtualScreen); + virtualScreen->left = 0; + virtualScreen->top = 0; + virtualScreen->right = subsystem->width; + virtualScreen->bottom = subsystem->height; + virtualScreen->flags = 1; + WLog_INFO(TAG, "width: %d height: %d", subsystem->width, subsystem->height); + return 1; +} + +static int win_shadow_subsystem_uninit(rdpShadowSubsystem* arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + + if (!subsystem) + return -1; + +#if defined(WITH_WDS_API) + win_shadow_wds_uninit(subsystem); +#elif defined(WITH_DXGI_1_2) + win_shadow_dxgi_uninit(subsystem); +#endif + return 1; +} + +static int win_shadow_subsystem_start(rdpShadowSubsystem* arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + HANDLE thread; + + if (!subsystem) + return -1; + + if (!(thread = CreateThread(NULL, 0, win_shadow_subsystem_thread, (void*)subsystem, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create thread"); + return -1; + } + + return 1; +} + +static int win_shadow_subsystem_stop(rdpShadowSubsystem* arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + + if (!subsystem) + return -1; + + return 1; +} + +static void win_shadow_subsystem_free(rdpShadowSubsystem* arg) +{ + winShadowSubsystem* subsystem = (winShadowSubsystem*)arg; + + if (!subsystem) + return; + + win_shadow_subsystem_uninit(arg); + free(subsystem); +} + +static rdpShadowSubsystem* win_shadow_subsystem_new(void) +{ + winShadowSubsystem* subsystem; + subsystem = (winShadowSubsystem*)calloc(1, sizeof(winShadowSubsystem)); + + if (!subsystem) + return NULL; + + subsystem->base.SynchronizeEvent = win_shadow_input_synchronize_event; + subsystem->base.KeyboardEvent = win_shadow_input_keyboard_event; + subsystem->base.UnicodeKeyboardEvent = win_shadow_input_unicode_keyboard_event; + subsystem->base.MouseEvent = win_shadow_input_mouse_event; + subsystem->base.ExtendedMouseEvent = win_shadow_input_extended_mouse_event; + return &subsystem->base; +} + +FREERDP_API const char* ShadowSubsystemName(void) +{ + return "Win"; +} + +FREERDP_API int ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints) +{ + const char name[] = "windows shadow subsystem"; + const char* arg[] = { name }; + + freerdp_server_warn_unmaintained(ARRAYSIZE(arg), arg); + pEntryPoints->New = win_shadow_subsystem_new; + pEntryPoints->Free = win_shadow_subsystem_free; + pEntryPoints->Init = win_shadow_subsystem_init; + pEntryPoints->Uninit = win_shadow_subsystem_uninit; + pEntryPoints->Start = win_shadow_subsystem_start; + pEntryPoints->Stop = win_shadow_subsystem_stop; + pEntryPoints->EnumMonitors = win_shadow_enum_monitors; + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.h new file mode 100644 index 0000000000000000000000000000000000000000..835bb6612d996a8876ab47217426ef0f724f4983 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_shadow.h @@ -0,0 +1,89 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_WIN_H +#define FREERDP_SERVER_SHADOW_WIN_H + +#include + +#include + +typedef struct win_shadow_subsystem winShadowSubsystem; + +#include +#include +#include +#include +#include + +#include "win_rdp.h" +#include "win_wds.h" +#include "win_dxgi.h" + +struct win_shadow_subsystem +{ + rdpShadowSubsystem base; + + int bpp; + int width; + int height; + +#ifdef WITH_WDS_API + HWND hWnd; + shwContext* shw; + HANDLE RdpUpdateEnterEvent; + HANDLE RdpUpdateLeaveEvent; + rdpAssistanceFile* pAssistanceFile; + _IRDPSessionEvents* pSessionEvents; + IRDPSRAPISharingSession* pSharingSession; + IRDPSRAPIInvitation* pInvitation; + IRDPSRAPIInvitationManager* pInvitationMgr; + IRDPSRAPISessionProperties* pSessionProperties; + IRDPSRAPIVirtualChannelManager* pVirtualChannelMgr; + IRDPSRAPIApplicationFilter* pApplicationFilter; + IRDPSRAPIAttendeeManager* pAttendeeMgr; +#endif + +#ifdef WITH_DXGI_1_2 + UINT pendingFrames; + BYTE* MetadataBuffer; + UINT MetadataBufferSize; + BOOL dxgiSurfaceMapped; + BOOL dxgiFrameAcquired; + ID3D11Device* dxgiDevice; + IDXGISurface* dxgiSurface; + ID3D11Texture2D* dxgiStage; + IDXGIResource* dxgiResource; + D3D_FEATURE_LEVEL featureLevel; + ID3D11Texture2D* dxgiDesktopImage; + DXGI_OUTDUPL_FRAME_INFO dxgiFrameInfo; + ID3D11DeviceContext* dxgiDeviceContext; + IDXGIOutputDuplication* dxgiOutputDuplication; +#endif +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_WIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.c new file mode 100644 index 0000000000000000000000000000000000000000..39c4980566140fd194c986eb0165a90c342f5657 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.c @@ -0,0 +1,855 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "win_rdp.h" + +#include "win_wds.h" + +/** + * Windows Desktop Sharing API: + * http://blogs.msdn.com/b/rds/archive/2007/03/08/windows-desktop-sharing-api.aspx + * + * Windows Desktop Sharing Interfaces: + * http://msdn.microsoft.com/en-us/library/aa373871%28v=vs.85%29.aspx + * + * Offer Remote Assistance Sample C: + * http://msdn.microsoft.com/en-us/library/ms811079.aspx#remoteassistanceapi_topic2b + * + * Remote Assistance in XP: Programmatically establish an RDP session: + * http://www.codeproject.com/Articles/29939/Remote-Assistance-in-XP-Programmatically-establish + */ + +#undef DEFINE_GUID +#define INITGUID + +#include + +#include + +#define TAG SERVER_TAG("shadow.win") + +DEFINE_GUID(CLSID_RDPSession, 0x9B78F0E6, 0x3E05, 0x4A5B, 0xB2, 0xE8, 0xE7, 0x43, 0xA8, 0x95, 0x6B, + 0x65); +DEFINE_GUID(DIID__IRDPSessionEvents, 0x98a97042, 0x6698, 0x40e9, 0x8e, 0xfd, 0xb3, 0x20, 0x09, 0x90, + 0x00, 0x4b); +DEFINE_GUID(IID_IRDPSRAPISharingSession, 0xeeb20886, 0xe470, 0x4cf6, 0x84, 0x2b, 0x27, 0x39, 0xc0, + 0xec, 0x5c, 0xfb); +DEFINE_GUID(IID_IRDPSRAPIAttendee, 0xec0671b3, 0x1b78, 0x4b80, 0xa4, 0x64, 0x91, 0x32, 0x24, 0x75, + 0x43, 0xe3); +DEFINE_GUID(IID_IRDPSRAPIAttendeeManager, 0xba3a37e8, 0x33da, 0x4749, 0x8d, 0xa0, 0x07, 0xfa, 0x34, + 0xda, 0x79, 0x44); +DEFINE_GUID(IID_IRDPSRAPISessionProperties, 0x339b24f2, 0x9bc0, 0x4f16, 0x9a, 0xac, 0xf1, 0x65, + 0x43, 0x3d, 0x13, 0xd4); +DEFINE_GUID(CLSID_RDPSRAPIApplicationFilter, 0xe35ace89, 0xc7e8, 0x427e, 0xa4, 0xf9, 0xb9, 0xda, + 0x07, 0x28, 0x26, 0xbd); +DEFINE_GUID(CLSID_RDPSRAPIInvitationManager, 0x53d9c9db, 0x75ab, 0x4271, 0x94, 0x8a, 0x4c, 0x4e, + 0xb3, 0x6a, 0x8f, 0x2b); + +static ULONG Shadow_IRDPSessionEvents_RefCount = 0; + +const char* GetRDPSessionEventString(DISPID id) +{ + switch (id) + { + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_CONNECTED: + return "OnAttendeeConnected"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_DISCONNECTED: + return "OnAttendeeDisconnected"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_UPDATE: + return "OnAttendeeUpdate"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_ERROR: + return "OnError"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTED: + return "OnConnectionEstablished"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_DISCONNECTED: + return "OnConnectionTerminated"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_AUTHENTICATED: + return "OnConnectionAuthenticated"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTFAILED: + return "OnConnectionFailed"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_REQUEST: + return "OnControlLevelChangeRequest"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_PAUSED: + return "OnGraphicsStreamPaused"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_RESUMED: + return "OnGraphicsStreamResumed"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_JOIN: + return "OnChannelJoin"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_LEAVE: + return "OnChannelLeave"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_DATARECEIVED: + return "OnChannelDataReceived"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_SENDCOMPLETED: + return "OnChannelDataSent"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_OPEN: + return "OnApplicationOpen"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_CLOSE: + return "OnApplicationClose"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_UPDATE: + return "OnApplicationUpdate"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_OPEN: + return "OnWindowOpen"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_CLOSE: + return "OnWindowClose"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_UPDATE: + return "OnWindowUpdate"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPFILTER_UPDATE: + return "OnAppFilterUpdate"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_SHARED_RECT_CHANGED: + return "OnSharedRectChanged"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_FOCUSRELEASED: + return "OnFocusReleased"; + break; + + case DISPID_RDPSRAPI_EVENT_ON_SHARED_DESKTOP_SETTINGS_CHANGED: + return "OnSharedDesktopSettingsChanged"; + break; + + case DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED: + return "OnViewingSizeChanged"; + break; + } + + return "OnUnknown"; +} + +static HRESULT STDMETHODCALLTYPE +Shadow_IRDPSessionEvents_QueryInterface(__RPC__in _IRDPSessionEvents* This, + /* [in] */ __RPC__in REFIID riid, + /* [annotation][iid_is][out] */ + _COM_Outptr_ void** ppvObject) +{ + *ppvObject = NULL; + + if (IsEqualIID(riid, &DIID__IRDPSessionEvents) || IsEqualIID(riid, &IID_IDispatch) || + IsEqualIID(riid, &IID_IUnknown)) + { + *ppvObject = This; + } + + if (!(*ppvObject)) + return E_NOINTERFACE; + + This->lpVtbl->AddRef(This); + return S_OK; +} + +static ULONG STDMETHODCALLTYPE Shadow_IRDPSessionEvents_AddRef(__RPC__in _IRDPSessionEvents* This) +{ + Shadow_IRDPSessionEvents_RefCount++; + return Shadow_IRDPSessionEvents_RefCount; +} + +static ULONG STDMETHODCALLTYPE Shadow_IRDPSessionEvents_Release(__RPC__in _IRDPSessionEvents* This) +{ + if (!Shadow_IRDPSessionEvents_RefCount) + return 0; + + Shadow_IRDPSessionEvents_RefCount--; + return Shadow_IRDPSessionEvents_RefCount; +} + +static HRESULT STDMETHODCALLTYPE +Shadow_IRDPSessionEvents_GetTypeInfoCount(__RPC__in _IRDPSessionEvents* This, + /* [out] */ __RPC__out UINT* pctinfo) +{ + WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetTypeInfoCount"); + *pctinfo = 1; + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE +Shadow_IRDPSessionEvents_GetTypeInfo(__RPC__in _IRDPSessionEvents* This, + /* [in] */ UINT iTInfo, + /* [in] */ LCID lcid, + /* [out] */ __RPC__deref_out_opt ITypeInfo** ppTInfo) +{ + WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetTypeInfo"); + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_GetIDsOfNames( + __RPC__in _IRDPSessionEvents* This, + /* [in] */ __RPC__in REFIID riid, + /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR* rgszNames, + /* [range][in] */ __RPC__in_range(0, 16384) UINT cNames, + /* [in] */ LCID lcid, + /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID* rgDispId) +{ + WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetIDsOfNames"); + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_Invoke(_IRDPSessionEvents* This, + /* [annotation][in] */ + _In_ DISPID dispIdMember, + /* [annotation][in] */ + _In_ REFIID riid, + /* [annotation][in] */ + _In_ LCID lcid, + /* [annotation][in] */ + _In_ WORD wFlags, + /* [annotation][out][in] */ + _In_ DISPPARAMS* pDispParams, + /* [annotation][out] */ + _Out_opt_ VARIANT* pVarResult, + /* [annotation][out] */ + _Out_opt_ EXCEPINFO* pExcepInfo, + /* [annotation][out] */ + _Out_opt_ UINT* puArgErr) +{ + HRESULT hr; + VARIANT vr; + UINT uArgErr; + WLog_INFO(TAG, "%s (%ld)", GetRDPSessionEventString(dispIdMember), dispIdMember); + + switch (dispIdMember) + { + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_CONNECTED: + { + int level; + IDispatch* pDispatch; + IRDPSRAPIAttendee* pAttendee; + vr.vt = VT_DISPATCH; + vr.pdispVal = NULL; + hr = DispGetParam(pDispParams, 0, VT_DISPATCH, &vr, &uArgErr); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "%s DispGetParam(0, VT_DISPATCH) failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + pDispatch = vr.pdispVal; + hr = pDispatch->lpVtbl->QueryInterface(pDispatch, &IID_IRDPSRAPIAttendee, + (void**)&pAttendee); + + if (FAILED(hr)) + { + WLog_INFO(TAG, "%s IDispatch::QueryInterface(IRDPSRAPIAttendee) failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + level = CTRL_LEVEL_VIEW; + // level = CTRL_LEVEL_INTERACTIVE; + hr = pAttendee->lpVtbl->put_ControlLevel(pAttendee, level); + + if (FAILED(hr)) + { + WLog_INFO(TAG, "%s IRDPSRAPIAttendee::put_ControlLevel() failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + pAttendee->lpVtbl->Release(pAttendee); + } + break; + + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_DISCONNECTED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_UPDATE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_ERROR: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_DISCONNECTED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_AUTHENTICATED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTFAILED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_REQUEST: + { + int level; + IDispatch* pDispatch; + IRDPSRAPIAttendee* pAttendee; + vr.vt = VT_INT; + vr.pdispVal = NULL; + hr = DispGetParam(pDispParams, 1, VT_INT, &vr, &uArgErr); + + if (FAILED(hr)) + { + WLog_INFO(TAG, "%s DispGetParam(1, VT_INT) failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + level = vr.intVal; + vr.vt = VT_DISPATCH; + vr.pdispVal = NULL; + hr = DispGetParam(pDispParams, 0, VT_DISPATCH, &vr, &uArgErr); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "%s DispGetParam(0, VT_DISPATCH) failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + pDispatch = vr.pdispVal; + hr = pDispatch->lpVtbl->QueryInterface(pDispatch, &IID_IRDPSRAPIAttendee, + (void**)&pAttendee); + + if (FAILED(hr)) + { + WLog_INFO(TAG, "%s IDispatch::QueryInterface(IRDPSRAPIAttendee) failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + hr = pAttendee->lpVtbl->put_ControlLevel(pAttendee, level); + + if (FAILED(hr)) + { + WLog_INFO(TAG, "%s IRDPSRAPIAttendee::put_ControlLevel() failure: 0x%08lX", + GetRDPSessionEventString(dispIdMember), hr); + return hr; + } + + pAttendee->lpVtbl->Release(pAttendee); + } + break; + + case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_PAUSED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_RESUMED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_JOIN: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_LEAVE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_DATARECEIVED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_SENDCOMPLETED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_OPEN: + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_CLOSE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_UPDATE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_OPEN: + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_CLOSE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_WINDOW_UPDATE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_APPFILTER_UPDATE: + break; + + case DISPID_RDPSRAPI_EVENT_ON_SHARED_RECT_CHANGED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_FOCUSRELEASED: + break; + + case DISPID_RDPSRAPI_EVENT_ON_SHARED_DESKTOP_SETTINGS_CHANGED: + break; + + case DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED: + break; + } + + return S_OK; +} + +static _IRDPSessionEventsVtbl Shadow_IRDPSessionEventsVtbl = { + /* IUnknown */ + Shadow_IRDPSessionEvents_QueryInterface, Shadow_IRDPSessionEvents_AddRef, + Shadow_IRDPSessionEvents_Release, + + /* IDispatch */ + Shadow_IRDPSessionEvents_GetTypeInfoCount, Shadow_IRDPSessionEvents_GetTypeInfo, + Shadow_IRDPSessionEvents_GetIDsOfNames, Shadow_IRDPSessionEvents_Invoke +}; + +static _IRDPSessionEvents Shadow_IRDPSessionEvents = { &Shadow_IRDPSessionEventsVtbl }; + +static LRESULT CALLBACK ShadowWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch (uMsg) + { + case WM_CLOSE: + DestroyWindow(hwnd); + break; + + case WM_DESTROY: + PostQuitMessage(0); + break; + + default: + return DefWindowProc(hwnd, uMsg, wParam, lParam); + break; + } + + return 0; +} + +int win_shadow_wds_wnd_init(winShadowSubsystem* subsystem) +{ + HMODULE hModule; + HINSTANCE hInstance; + WNDCLASSEX wndClassEx = { 0 }; + hModule = GetModuleHandle(NULL); + + wndClassEx.cbSize = sizeof(WNDCLASSEX); + wndClassEx.style = 0; + wndClassEx.lpfnWndProc = ShadowWndProc; + wndClassEx.cbClsExtra = 0; + wndClassEx.cbWndExtra = 0; + wndClassEx.hInstance = hModule; + wndClassEx.hIcon = NULL; + wndClassEx.hCursor = NULL; + wndClassEx.hbrBackground = NULL; + wndClassEx.lpszMenuName = _T("ShadowWndMenu"); + wndClassEx.lpszClassName = _T("ShadowWndClass"); + wndClassEx.hIconSm = NULL; + + if (!RegisterClassEx(&wndClassEx)) + { + WLog_ERR(TAG, "RegisterClassEx failure"); + return -1; + } + + hInstance = wndClassEx.hInstance; + subsystem->hWnd = CreateWindowEx(0, wndClassEx.lpszClassName, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, + hInstance, NULL); + + if (!subsystem->hWnd) + { + WLog_INFO(TAG, "CreateWindowEx failure"); + return -1; + } + + return 1; +} + +int win_shadow_wds_init(winShadowSubsystem* subsystem) +{ + int status = -1; + + long left = 0; + long top = 0; + long right = 0; + long bottom = 0; + BSTR bstrAuthString = NULL; + BSTR bstrGroupName = NULL; + BSTR bstrPassword = NULL; + BSTR bstrPropertyName = NULL; + VARIANT varPropertyValue; + rdpAssistanceFile* file = NULL; + IConnectionPoint* pCP = NULL; + IConnectionPointContainer* pCPC = NULL; + + win_shadow_wds_wnd_init(subsystem); + HRESULT hr = OleInitialize(NULL); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "OleInitialize() failure"); + return -1; + } + + hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "CoInitialize() failure"); + return -1; + } + + hr = CoCreateInstance(&CLSID_RDPSession, NULL, CLSCTX_ALL, &IID_IRDPSRAPISharingSession, + (void**)&(subsystem->pSharingSession)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "CoCreateInstance(IRDPSRAPISharingSession) failure: 0x%08lX", hr); + return -1; + } + + IUnknown* pUnknown = (IUnknown*)subsystem->pSharingSession; + hr = pUnknown->lpVtbl->QueryInterface(pUnknown, &IID_IConnectionPointContainer, (void**)&pCPC); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "QueryInterface(IID_IConnectionPointContainer) failure: 0x%08lX", hr); + return -1; + } + + pCPC->lpVtbl->FindConnectionPoint(pCPC, &DIID__IRDPSessionEvents, &pCP); + + if (FAILED(hr)) + { + WLog_ERR( + TAG, + "IConnectionPointContainer::FindConnectionPoint(_IRDPSessionEvents) failure: 0x%08lX", + hr); + return -1; + } + + DWORD dwCookie = 0; + subsystem->pSessionEvents = &Shadow_IRDPSessionEvents; + subsystem->pSessionEvents->lpVtbl->AddRef(subsystem->pSessionEvents); + hr = pCP->lpVtbl->Advise(pCP, (IUnknown*)subsystem->pSessionEvents, &dwCookie); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IConnectionPoint::Advise(Shadow_IRDPSessionEvents) failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->put_ColorDepth(subsystem->pSharingSession, 32); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::put_ColorDepth() failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->GetDesktopSharedRect(subsystem->pSharingSession, &left, + &top, &right, &bottom); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::GetDesktopSharedRect() failure: 0x%08lX", hr); + return -1; + } + + long width = right - left; + long height = bottom - top; + WLog_INFO( + TAG, + "GetDesktopSharedRect(): left: %ld top: %ld right: %ld bottom: %ld width: %ld height: %ld", + left, top, right, bottom, width, height); + hr = subsystem->pSharingSession->lpVtbl->get_VirtualChannelManager( + subsystem->pSharingSession, &(subsystem->pVirtualChannelMgr)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::get_VirtualChannelManager() failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->get_ApplicationFilter( + subsystem->pSharingSession, &(subsystem->pApplicationFilter)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::get_ApplicationFilter() failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->get_Attendees(subsystem->pSharingSession, + &(subsystem->pAttendeeMgr)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Attendees() failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->get_Properties(subsystem->pSharingSession, + &(subsystem->pSessionProperties)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Properties() failure: 0x%08lX", hr); + return -1; + } + + bstrPropertyName = SysAllocString(L"PortId"); + varPropertyValue.vt = VT_I4; + varPropertyValue.intVal = 40000; + hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties, + bstrPropertyName, varPropertyValue); + SysFreeString(bstrPropertyName); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(PortId) failure: 0x%08lX", hr); + return -1; + } + + bstrPropertyName = SysAllocString(L"DrvConAttach"); + varPropertyValue.vt = VT_BOOL; + varPropertyValue.boolVal = VARIANT_TRUE; + hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties, + bstrPropertyName, varPropertyValue); + SysFreeString(bstrPropertyName); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(DrvConAttach) failure: 0x%08lX", + hr); + return -1; + } + + bstrPropertyName = SysAllocString(L"PortProtocol"); + varPropertyValue.vt = VT_I4; + // varPropertyValue.intVal = 0; // AF_UNSPEC + varPropertyValue.intVal = 2; // AF_INET + // varPropertyValue.intVal = 23; // AF_INET6 + hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties, + bstrPropertyName, varPropertyValue); + SysFreeString(bstrPropertyName); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(PortProtocol) failure: 0x%08lX", + hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->Open(subsystem->pSharingSession); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::Open() failure: 0x%08lX", hr); + return -1; + } + + hr = subsystem->pSharingSession->lpVtbl->get_Invitations(subsystem->pSharingSession, + &(subsystem->pInvitationMgr)); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Invitations() failure"); + return -1; + } + + bstrAuthString = SysAllocString(L"Shadow"); + bstrGroupName = SysAllocString(L"ShadowGroup"); + bstrPassword = SysAllocString(L"Shadow123!"); + hr = subsystem->pInvitationMgr->lpVtbl->CreateInvitation( + subsystem->pInvitationMgr, bstrAuthString, bstrGroupName, bstrPassword, 5, + &(subsystem->pInvitation)); + SysFreeString(bstrAuthString); + SysFreeString(bstrGroupName); + SysFreeString(bstrPassword); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPIInvitationManager::CreateInvitation() failure: 0x%08lX", hr); + return -1; + } + + file = subsystem->pAssistanceFile = freerdp_assistance_file_new(); + + if (!file) + { + WLog_ERR(TAG, "freerdp_assistance_file_new() failed"); + return -1; + } + + { + int status2 = -1; + char* ConnectionString2; + BSTR bstrConnectionString; + hr = subsystem->pInvitation->lpVtbl->get_ConnectionString(subsystem->pInvitation, + &bstrConnectionString); + + if (FAILED(hr)) + { + WLog_ERR(TAG, "IRDPSRAPIInvitation::get_ConnectionString() failure: 0x%08lX", hr); + return -1; + } + + ConnectionString2 = ConvertWCharToUtf8Alloc(bstrConnectionString, NULL); + SysFreeString(bstrConnectionString); + status2 = freerdp_assistance_set_connection_string2(file, ConnectionString2, "Shadow123!"); + free(ConnectionString2); + + if ((!ConnectionString2) || (status2 < 1)) + { + WLog_ERR(TAG, "failed to convert connection string"); + return -1; + } + } + + freerdp_assistance_print_file(file, WLog_Get(TAG), WLOG_INFO); + status = win_shadow_rdp_init(subsystem); + + if (status < 0) + { + WLog_ERR(TAG, "win_shadow_rdp_init() failure: %d", status); + return status; + } + + rdpSettings* settings = subsystem->shw->settings; + if (!freerdp_assistance_populate_settings_from_assistance_file(file, settings)) + return -1; + if (!freerdp_settings_set_string(settings, FreeRDP_Domain, "RDP")) + return -1; + if (!freerdp_settings_set_string(settings, FreeRDP_Username, "Shadow")) + return -1; + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoLogonEnabled, TRUE)) + return -1; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, width)) + return -1; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, height)) + return -1; + status = win_shadow_rdp_start(subsystem); + + if (status < 0) + { + WLog_ERR(TAG, "win_shadow_rdp_start() failure: %d", status); + return status; + } + + return 1; +} + +int win_shadow_wds_uninit(winShadowSubsystem* subsystem) +{ + if (subsystem->pSharingSession) + { + subsystem->pSharingSession->lpVtbl->Close(subsystem->pSharingSession); + subsystem->pSharingSession->lpVtbl->Release(subsystem->pSharingSession); + subsystem->pSharingSession = NULL; + } + + if (subsystem->pVirtualChannelMgr) + { + subsystem->pVirtualChannelMgr->lpVtbl->Release(subsystem->pVirtualChannelMgr); + subsystem->pVirtualChannelMgr = NULL; + } + + if (subsystem->pApplicationFilter) + { + subsystem->pApplicationFilter->lpVtbl->Release(subsystem->pApplicationFilter); + subsystem->pApplicationFilter = NULL; + } + + if (subsystem->pAttendeeMgr) + { + subsystem->pAttendeeMgr->lpVtbl->Release(subsystem->pAttendeeMgr); + subsystem->pAttendeeMgr = NULL; + } + + if (subsystem->pSessionProperties) + { + subsystem->pSessionProperties->lpVtbl->Release(subsystem->pSessionProperties); + subsystem->pSessionProperties = NULL; + } + + if (subsystem->pInvitationMgr) + { + subsystem->pInvitationMgr->lpVtbl->Release(subsystem->pInvitationMgr); + subsystem->pInvitationMgr = NULL; + } + + if (subsystem->pInvitation) + { + subsystem->pInvitation->lpVtbl->Release(subsystem->pInvitation); + subsystem->pInvitation = NULL; + } + + if (subsystem->pAssistanceFile) + { + freerdp_assistance_file_free(subsystem->pAssistanceFile); + subsystem->pAssistanceFile = NULL; + } + + if (subsystem->hWnd) + { + DestroyWindow(subsystem->hWnd); + subsystem->hWnd = NULL; + } + + if (subsystem->shw) + { + win_shadow_rdp_uninit(subsystem); + subsystem->shw = NULL; + } + + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f3d80c0466f146b1417df57c2a3d5055a1a156 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/Win/win_wds.h @@ -0,0 +1,48 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_WIN_WDS_H +#define FREERDP_SERVER_SHADOW_WIN_WDS_H + +#define WITH_WDS_API 1 + +#ifndef CINTERFACE +#define CINTERFACE +#endif + +#include + +#ifndef DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED +#define DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED 340 +#endif + +#include "win_shadow.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + int win_shadow_wds_init(winShadowSubsystem* subsystem); + int win_shadow_wds_uninit(winShadowSubsystem* subsystem); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_WIN_WDS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..24e32566d05120c8c70c95e1001042991083e6f0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/CMakeLists.txt @@ -0,0 +1,67 @@ +find_package(X11 REQUIRED) +if(X11_FOUND) + add_compile_definitions(WITH_X11) + include_directories(SYSTEM ${X11_INCLUDE_DIR}) + list(APPEND LIBS ${X11_LIBRARIES}) +endif() + +if(X11_XShm_FOUND) + add_compile_definitions(WITH_XSHM) + include_directories(SYSTEM ${X11_XShm_INCLUDE_PATH}) + list(APPEND LIBS ${X11_XShm_LIB}) +endif() + +if(X11_Xext_FOUND) + add_compile_definitions(WITH_XEXT) + list(APPEND LIBS ${X11_Xext_LIB}) +endif() + +if(X11_Xinerama_FOUND) + add_compile_definitions(WITH_XINERAMA) + include_directories(SYSTEM ${X11_Xinerama_INCLUDE_PATH}) + list(APPEND LIBS ${X11_Xinerama_LIB}) +endif() + +if(X11_Xdamage_FOUND) + add_compile_definitions(WITH_XDAMAGE) + include_directories(SYSTEM ${X11_Xdamage_INCLUDE_PATH}) + list(APPEND LIBS ${X11_Xdamage_LIB}) +endif() + +if(X11_Xfixes_FOUND) + add_compile_definitions(WITH_XFIXES) + include_directories(SYSTEM ${X11_Xfixes_INCLUDE_PATH}) + list(APPEND LIBS ${X11_Xfixes_LIB}) +endif() + +if(X11_XTest_FOUND) + add_compile_definitions(WITH_XTEST) + include_directories(SYSTEM ${X11_XTest_INCLUDE_PATH}) + list(APPEND LIBS ${X11_XTest_LIB}) +endif() + +# XCursor and XRandr are currently not used so don't link them +#if(X11_Xcursor_FOUND) +# add_compile_definitions(WITH_XCURSOR) +# include_directories(SYSTEM ${X11_Xcursor_INCLUDE_PATH}) +# list(APPEND LIBS ${X11_Xcursor_LIB}) +#endif() + +#if(X11_Xrandr_FOUND) +# add_compile_definitions(WITH_XRANDR) +# include_directories(SYSTEM ${X11_Xrandr_INCLUDE_PATH}) +# list(APPEND LIBS ${X11_Xrandr_LIB}) +#endif() + +find_package(PAM) +if(PAM_FOUND) + add_compile_definitions(WITH_PAM) + include_directories(SYSTEM ${PAM_INCLUDE_DIR}) + list(APPEND LIBS ${PAM_LIBRARY}) +else() + message("building without PAM authentication support") +endif() + +add_compile_definitions(WITH_SHADOW_X11) +add_library(freerdp-shadow-subsystem-impl STATIC x11_shadow.h x11_shadow.c) +target_link_libraries(freerdp-shadow-subsystem-impl PRIVATE ${LIBS}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.c new file mode 100644 index 0000000000000000000000000000000000000000..61315d021b03ea322e159fc5ebdf56a6beb2c7e1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.c @@ -0,0 +1,1546 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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 +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "x11_shadow.h" + +#define TAG SERVER_TAG("shadow.x11") + +static UINT32 x11_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors); + +#ifdef WITH_PAM + +#include + +typedef struct +{ + const char* user; + const char* domain; + const char* password; +} SHADOW_PAM_AUTH_DATA; + +typedef struct +{ + char* service_name; + pam_handle_t* handle; + struct pam_conv pamc; + SHADOW_PAM_AUTH_DATA appdata; +} SHADOW_PAM_AUTH_INFO; + +static int x11_shadow_pam_conv(int num_msg, const struct pam_message** msg, + struct pam_response** resp, void* appdata_ptr) +{ + int pam_status = PAM_CONV_ERR; + SHADOW_PAM_AUTH_DATA* appdata = NULL; + struct pam_response* response = NULL; + WINPR_ASSERT(num_msg >= 0); + appdata = (SHADOW_PAM_AUTH_DATA*)appdata_ptr; + WINPR_ASSERT(appdata); + + if (!(response = (struct pam_response*)calloc((size_t)num_msg, sizeof(struct pam_response)))) + return PAM_BUF_ERR; + + for (int index = 0; index < num_msg; index++) + { + switch (msg[index]->msg_style) + { + case PAM_PROMPT_ECHO_ON: + response[index].resp = _strdup(appdata->user); + + if (!response[index].resp) + goto out_fail; + + response[index].resp_retcode = PAM_SUCCESS; + break; + + case PAM_PROMPT_ECHO_OFF: + response[index].resp = _strdup(appdata->password); + + if (!response[index].resp) + goto out_fail; + + response[index].resp_retcode = PAM_SUCCESS; + break; + + default: + pam_status = PAM_CONV_ERR; + goto out_fail; + } + } + + *resp = response; + return PAM_SUCCESS; +out_fail: + + for (int index = 0; index < num_msg; ++index) + { + if (response[index].resp) + { + memset(response[index].resp, 0, strlen(response[index].resp)); + free(response[index].resp); + } + } + + memset(response, 0, sizeof(struct pam_response) * (size_t)num_msg); + free(response); + *resp = NULL; + return pam_status; +} + +static BOOL x11_shadow_pam_get_service_name(SHADOW_PAM_AUTH_INFO* info) +{ + const char* base = "/etc/pam.d"; + const char* hints[] = { "lightdm", "gdm", "xdm", "login", "sshd" }; + + for (size_t x = 0; x < ARRAYSIZE(hints); x++) + { + char path[MAX_PATH] = { 0 }; + const char* hint = hints[x]; + + (void)_snprintf(path, sizeof(path), "%s/%s", base, hint); + if (winpr_PathFileExists(path)) + { + + info->service_name = _strdup(hint); + return info->service_name != NULL; + } + } + WLog_WARN(TAG, "Could not determine PAM service name"); + return FALSE; +} + +static int x11_shadow_pam_authenticate(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + const char* user, const char* domain, const char* password) +{ + int pam_status = 0; + SHADOW_PAM_AUTH_INFO info = { 0 }; + WINPR_UNUSED(subsystem); + WINPR_UNUSED(client); + + if (!x11_shadow_pam_get_service_name(&info)) + return -1; + + info.appdata.user = user; + info.appdata.domain = domain; + info.appdata.password = password; + info.pamc.conv = &x11_shadow_pam_conv; + info.pamc.appdata_ptr = &info.appdata; + pam_status = pam_start(info.service_name, 0, &info.pamc, &info.handle); + + if (pam_status != PAM_SUCCESS) + { + WLog_ERR(TAG, "pam_start failure: %s", pam_strerror(info.handle, pam_status)); + return -1; + } + + pam_status = pam_authenticate(info.handle, 0); + + if (pam_status != PAM_SUCCESS) + { + WLog_ERR(TAG, "pam_authenticate failure: %s", pam_strerror(info.handle, pam_status)); + return -1; + } + + pam_status = pam_acct_mgmt(info.handle, 0); + + if (pam_status != PAM_SUCCESS) + { + WLog_ERR(TAG, "pam_acct_mgmt failure: %s", pam_strerror(info.handle, pam_status)); + return -1; + } + + return 1; +} + +#endif + +static BOOL x11_shadow_input_synchronize_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT32 flags) +{ + /* TODO: Implement */ + WLog_WARN(TAG, "not implemented"); + return TRUE; +} + +static BOOL x11_shadow_input_keyboard_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT8 code) +{ +#ifdef WITH_XTEST + x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem; + DWORD vkcode = 0; + DWORD keycode = 0; + DWORD scancode = 0; + BOOL extended = FALSE; + + if (!client || !subsystem) + return FALSE; + + if (flags & KBD_FLAGS_EXTENDED) + extended = TRUE; + + scancode = code; + if (extended) + scancode |= KBDEXT; + + vkcode = GetVirtualKeyCodeFromVirtualScanCode(scancode, WINPR_KBD_TYPE_IBM_ENHANCED); + + if (extended) + vkcode |= KBDEXT; + + keycode = GetKeycodeFromVirtualKeyCode(vkcode, WINPR_KEYCODE_TYPE_XKB); + + if (keycode != 0) + { + XLockDisplay(x11->display); + XTestGrabControl(x11->display, True); + + if (flags & KBD_FLAGS_RELEASE) + XTestFakeKeyEvent(x11->display, keycode, False, CurrentTime); + else + XTestFakeKeyEvent(x11->display, keycode, True, CurrentTime); + + XTestGrabControl(x11->display, False); + XFlush(x11->display); + XUnlockDisplay(x11->display); + } + +#endif + return TRUE; +} + +static BOOL x11_shadow_input_unicode_keyboard_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, + UINT16 code) +{ + /* TODO: Implement */ + WLog_WARN(TAG, "not implemented"); + return TRUE; +} + +static BOOL x11_shadow_input_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client, + UINT16 flags, UINT16 x, UINT16 y) +{ +#ifdef WITH_XTEST + x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem; + unsigned int button = 0; + BOOL down = FALSE; + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + + if (!subsystem || !client) + return FALSE; + + server = subsystem->server; + + if (!server) + return FALSE; + + surface = server->surface; + + if (!surface) + return FALSE; + + x11->lastMouseClient = client; + x += surface->x; + y += surface->y; + XLockDisplay(x11->display); + XTestGrabControl(x11->display, True); + + if (flags & PTR_FLAGS_WHEEL) + { + BOOL negative = FALSE; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + negative = TRUE; + + button = (negative) ? 5 : 4; + XTestFakeButtonEvent(x11->display, button, True, (unsigned long)CurrentTime); + XTestFakeButtonEvent(x11->display, button, False, (unsigned long)CurrentTime); + } + else if (flags & PTR_FLAGS_HWHEEL) + { + BOOL negative = FALSE; + + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + negative = TRUE; + + button = (negative) ? 7 : 6; + XTestFakeButtonEvent(x11->display, button, True, (unsigned long)CurrentTime); + XTestFakeButtonEvent(x11->display, button, False, (unsigned long)CurrentTime); + } + else + { + if (flags & PTR_FLAGS_MOVE) + XTestFakeMotionEvent(x11->display, 0, x, y, CurrentTime); + + if (flags & PTR_FLAGS_BUTTON1) + button = 1; + else if (flags & PTR_FLAGS_BUTTON2) + button = 3; + else if (flags & PTR_FLAGS_BUTTON3) + button = 2; + + if (flags & PTR_FLAGS_DOWN) + down = TRUE; + + if (button) + XTestFakeButtonEvent(x11->display, button, down, CurrentTime); + } + + XTestGrabControl(x11->display, False); + XFlush(x11->display); + XUnlockDisplay(x11->display); +#endif + return TRUE; +} + +static BOOL x11_shadow_input_extended_mouse_event(rdpShadowSubsystem* subsystem, + rdpShadowClient* client, UINT16 flags, UINT16 x, + UINT16 y) +{ +#ifdef WITH_XTEST + x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem; + UINT button = 0; + BOOL down = FALSE; + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + + if (!subsystem || !client) + return FALSE; + + server = subsystem->server; + + if (!server) + return FALSE; + + surface = server->surface; + + if (!surface) + return FALSE; + + x11->lastMouseClient = client; + x += surface->x; + y += surface->y; + XLockDisplay(x11->display); + XTestGrabControl(x11->display, True); + XTestFakeMotionEvent(x11->display, 0, x, y, CurrentTime); + + if (flags & PTR_XFLAGS_BUTTON1) + button = 8; + else if (flags & PTR_XFLAGS_BUTTON2) + button = 9; + + if (flags & PTR_XFLAGS_DOWN) + down = TRUE; + + if (button) + XTestFakeButtonEvent(x11->display, button, down, CurrentTime); + + XTestGrabControl(x11->display, False); + XFlush(x11->display); + XUnlockDisplay(x11->display); +#endif + return TRUE; +} + +static void x11_shadow_message_free(UINT32 id, SHADOW_MSG_OUT* msg) +{ + switch (id) + { + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: + free(msg); + break; + + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: + free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->xorMaskData); + free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->andMaskData); + free(msg); + break; + + default: + WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", id); + free(msg); + break; + } +} + +static int x11_shadow_pointer_position_update(x11ShadowSubsystem* subsystem) +{ + UINT32 msgId = SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID; + rdpShadowServer* server = NULL; + SHADOW_MSG_OUT_POINTER_POSITION_UPDATE templateMsg = { 0 }; + int count = 0; + + if (!subsystem || !subsystem->common.server || !subsystem->common.server->clients) + return -1; + + templateMsg.xPos = subsystem->common.pointerX; + templateMsg.yPos = subsystem->common.pointerY; + templateMsg.common.Free = x11_shadow_message_free; + server = subsystem->common.server; + ArrayList_Lock(server->clients); + + for (size_t index = 0; index < ArrayList_Count(server->clients); index++) + { + SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg = NULL; + rdpShadowClient* client = (rdpShadowClient*)ArrayList_GetItem(server->clients, index); + + /* Skip the client which send us the latest mouse event */ + if (client == subsystem->lastMouseClient) + continue; + + msg = malloc(sizeof(templateMsg)); + + if (!msg) + { + count = -1; + break; + } + + memcpy(msg, &templateMsg, sizeof(templateMsg)); + + if (shadow_client_post_msg(client, NULL, msgId, (SHADOW_MSG_OUT*)msg, NULL)) + count++; + } + + ArrayList_Unlock(server->clients); + return count; +} + +static int x11_shadow_pointer_alpha_update(x11ShadowSubsystem* subsystem) +{ + SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg = NULL; + UINT32 msgId = SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID; + msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)calloc(1, + sizeof(SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE)); + + if (!msg) + return -1; + + msg->xHot = subsystem->cursorHotX; + msg->yHot = subsystem->cursorHotY; + msg->width = subsystem->cursorWidth; + msg->height = subsystem->cursorHeight; + + if (shadow_subsystem_pointer_convert_alpha_pointer_data_to_format( + subsystem->cursorPixels, subsystem->format, TRUE, msg->width, msg->height, msg) < 0) + { + free(msg); + return -1; + } + + msg->common.Free = x11_shadow_message_free; + return shadow_client_boardcast_msg(subsystem->common.server, NULL, msgId, (SHADOW_MSG_OUT*)msg, + NULL) + ? 1 + : -1; +} + +static int x11_shadow_query_cursor(x11ShadowSubsystem* subsystem, BOOL getImage) +{ + int x = 0; + int y = 0; + int n = 0; + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + server = subsystem->common.server; + surface = server->surface; + + if (getImage) + { +#ifdef WITH_XFIXES + UINT32* pDstPixel = NULL; + XFixesCursorImage* ci = NULL; + XLockDisplay(subsystem->display); + ci = XFixesGetCursorImage(subsystem->display); + XUnlockDisplay(subsystem->display); + + if (!ci) + return -1; + + x = ci->x; + y = ci->y; + + if (ci->width > subsystem->cursorMaxWidth) + return -1; + + if (ci->height > subsystem->cursorMaxHeight) + return -1; + + subsystem->cursorHotX = ci->xhot; + subsystem->cursorHotY = ci->yhot; + subsystem->cursorWidth = ci->width; + subsystem->cursorHeight = ci->height; + subsystem->cursorId = ci->cursor_serial; + n = ci->width * ci->height; + pDstPixel = (UINT32*)subsystem->cursorPixels; + + for (int k = 0; k < n; k++) + { + /* XFixesCursorImage.pixels is in *unsigned long*, which may be 8 bytes */ + *pDstPixel++ = (UINT32)ci->pixels[k]; + } + + XFree(ci); + x11_shadow_pointer_alpha_update(subsystem); +#endif + } + else + { + UINT32 mask = 0; + int win_x = 0; + int win_y = 0; + int root_x = 0; + int root_y = 0; + Window root = 0; + Window child = 0; + XLockDisplay(subsystem->display); + + if (!XQueryPointer(subsystem->display, subsystem->root_window, &root, &child, &root_x, + &root_y, &win_x, &win_y, &mask)) + { + XUnlockDisplay(subsystem->display); + return -1; + } + + XUnlockDisplay(subsystem->display); + x = root_x; + y = root_y; + } + + /* Convert to offset based on current surface */ + if (surface) + { + x -= surface->x; + y -= surface->y; + } + + if ((x != (INT64)subsystem->common.pointerX) || (y != (INT64)subsystem->common.pointerY)) + { + subsystem->common.pointerX = WINPR_ASSERTING_INT_CAST(UINT32, x); + subsystem->common.pointerY = WINPR_ASSERTING_INT_CAST(UINT32, y); + x11_shadow_pointer_position_update(subsystem); + } + + return 1; +} + +static int x11_shadow_handle_xevent(x11ShadowSubsystem* subsystem, XEvent* xevent) +{ + if (xevent->type == MotionNotify) + { + } + +#ifdef WITH_XFIXES + else if (xevent->type == subsystem->xfixes_cursor_notify_event) + { + x11_shadow_query_cursor(subsystem, TRUE); + } + +#endif + else + { + } + + return 1; +} + +static void x11_shadow_validate_region(x11ShadowSubsystem* subsystem, int x, int y, int width, + int height) +{ + XRectangle region; + + if (!subsystem->use_xfixes || !subsystem->use_xdamage) + return; + + region.x = WINPR_ASSERTING_INT_CAST(INT16, x); + region.y = WINPR_ASSERTING_INT_CAST(INT16, y); + region.width = WINPR_ASSERTING_INT_CAST(UINT16, width); + region.height = WINPR_ASSERTING_INT_CAST(UINT16, height); +#if defined(WITH_XFIXES) && defined(WITH_XDAMAGE) + XLockDisplay(subsystem->display); + XFixesSetRegion(subsystem->display, subsystem->xdamage_region, ®ion, 1); + XDamageSubtract(subsystem->display, subsystem->xdamage, subsystem->xdamage_region, None); + XUnlockDisplay(subsystem->display); +#endif +} + +static int x11_shadow_blend_cursor(x11ShadowSubsystem* subsystem) +{ + UINT32 nXSrc = 0; + UINT32 nYSrc = 0; + INT64 nXDst = 0; + INT64 nYDst = 0; + UINT32 nWidth = 0; + UINT32 nHeight = 0; + UINT32 nSrcStep = 0; + UINT32 nDstStep = 0; + BYTE* pSrcData = NULL; + BYTE* pDstData = NULL; + BYTE A = 0; + BYTE R = 0; + BYTE G = 0; + BYTE B = 0; + rdpShadowSurface* surface = NULL; + + if (!subsystem) + return -1; + + surface = subsystem->common.server->surface; + nXSrc = 0; + nYSrc = 0; + nWidth = subsystem->cursorWidth; + nHeight = subsystem->cursorHeight; + nXDst = subsystem->common.pointerX - subsystem->cursorHotX; + nYDst = subsystem->common.pointerY - subsystem->cursorHotY; + + if (nXDst >= surface->width) + return 1; + + if (nXDst < 0) + { + nXDst *= -1; + + if (nXDst >= nWidth) + return 1; + + nXSrc = (UINT32)nXDst; + nWidth -= nXDst; + nXDst = 0; + } + + if (nYDst >= surface->height) + return 1; + + if (nYDst < 0) + { + nYDst *= -1; + + if (nYDst >= nHeight) + return 1; + + nYSrc = (UINT32)nYDst; + nHeight -= nYDst; + nYDst = 0; + } + + if ((nXDst + nWidth) > surface->width) + nWidth = (nXDst > surface->width) ? 0 : (UINT32)(surface->width - nXDst); + + if ((nYDst + nHeight) > surface->height) + nHeight = (nYDst > surface->height) ? 0 : (UINT32)(surface->height - nYDst); + + pSrcData = subsystem->cursorPixels; + nSrcStep = subsystem->cursorWidth * 4; + pDstData = surface->data; + nDstStep = surface->scanline; + + for (size_t y = 0; y < nHeight; y++) + { + const BYTE* pSrcPixel = &pSrcData[((nYSrc + y) * nSrcStep) + (4ULL * nXSrc)]; + BYTE* pDstPixel = &pDstData[((WINPR_ASSERTING_INT_CAST(uint32_t, nYDst) + y) * nDstStep) + + (4ULL * WINPR_ASSERTING_INT_CAST(uint32_t, nXDst))]; + + for (size_t x = 0; x < nWidth; x++) + { + B = *pSrcPixel++; + G = *pSrcPixel++; + R = *pSrcPixel++; + A = *pSrcPixel++; + + if (A == 0xFF) + { + pDstPixel[0] = B; + pDstPixel[1] = G; + pDstPixel[2] = R; + } + else + { + pDstPixel[0] = B + (pDstPixel[0] * (0xFF - A) + (0xFF / 2)) / 0xFF; + pDstPixel[1] = G + (pDstPixel[1] * (0xFF - A) + (0xFF / 2)) / 0xFF; + pDstPixel[2] = R + (pDstPixel[2] * (0xFF - A) + (0xFF / 2)) / 0xFF; + } + + pDstPixel[3] = 0xFF; + pDstPixel += 4; + } + } + + return 1; +} + +static BOOL x11_shadow_check_resize(x11ShadowSubsystem* subsystem) +{ + XWindowAttributes attr; + XLockDisplay(subsystem->display); + XGetWindowAttributes(subsystem->display, subsystem->root_window, &attr); + XUnlockDisplay(subsystem->display); + + if (attr.width != (INT64)subsystem->width || attr.height != (INT64)subsystem->height) + { + MONITOR_DEF* virtualScreen = &(subsystem->common.virtualScreen); + + /* Screen size changed. Refresh monitor definitions and trigger screen resize */ + subsystem->common.numMonitors = x11_shadow_enum_monitors(subsystem->common.monitors, 16); + if (!shadow_screen_resize(subsystem->common.server->screen)) + return FALSE; + + WINPR_ASSERT(attr.width > 0); + WINPR_ASSERT(attr.height > 0); + + subsystem->width = (UINT32)attr.width; + subsystem->height = (UINT32)attr.height; + + virtualScreen->left = 0; + virtualScreen->top = 0; + virtualScreen->right = attr.width - 1; + virtualScreen->bottom = attr.height - 1; + virtualScreen->flags = 1; + return TRUE; + } + + return FALSE; +} + +static int x11_shadow_error_handler_for_capture(Display* display, XErrorEvent* event) +{ + char msg[256]; + XGetErrorText(display, event->error_code, (char*)&msg, sizeof(msg)); + WLog_ERR(TAG, "X11 error: %s Error code: %x, request code: %x, minor code: %x", msg, + event->error_code, event->request_code, event->minor_code); + + /* Ignore BAD MATCH error during image capture. Abort in other case */ + if (event->error_code != BadMatch) + { + abort(); + } + + return 0; +} + +static int x11_shadow_screen_grab(x11ShadowSubsystem* subsystem) +{ + int rc = 0; + size_t count = 0; + int status = -1; + int x = 0; + int y = 0; + int width = 0; + int height = 0; + XImage* image = NULL; + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + RECTANGLE_16 invalidRect; + RECTANGLE_16 surfaceRect; + const RECTANGLE_16* extents = NULL; + server = subsystem->common.server; + surface = server->surface; + count = ArrayList_Count(server->clients); + + if (count < 1) + return 1; + + EnterCriticalSection(&surface->lock); + surfaceRect.left = 0; + surfaceRect.top = 0; + + surfaceRect.right = WINPR_ASSERTING_INT_CAST(UINT16, surface->width); + surfaceRect.bottom = WINPR_ASSERTING_INT_CAST(UINT16, surface->height); + LeaveCriticalSection(&surface->lock); + + XLockDisplay(subsystem->display); + /* + * Ignore BadMatch error during image capture. The screen size may be + * changed outside. We will resize to correct resolution at next frame + */ + XSetErrorHandler(x11_shadow_error_handler_for_capture); +#if defined(WITH_XDAMAGE) + if (subsystem->use_xshm) + { + image = subsystem->fb_image; + XCopyArea(subsystem->display, subsystem->root_window, subsystem->fb_pixmap, + subsystem->xshm_gc, 0, 0, subsystem->width, subsystem->height, 0, 0); + + EnterCriticalSection(&surface->lock); + status = shadow_capture_compare_with_format( + surface->data, surface->format, surface->scanline, surface->width, surface->height, + (BYTE*)&(image->data[surface->width * 4ull]), subsystem->format, + WINPR_ASSERTING_INT_CAST(UINT32, image->bytes_per_line), &invalidRect); + LeaveCriticalSection(&surface->lock); + } + else +#endif + { + EnterCriticalSection(&surface->lock); + image = XGetImage(subsystem->display, subsystem->root_window, surface->x, surface->y, + surface->width, surface->height, AllPlanes, ZPixmap); + + if (image) + { + status = shadow_capture_compare_with_format( + surface->data, surface->format, surface->scanline, surface->width, surface->height, + (BYTE*)image->data, subsystem->format, + WINPR_ASSERTING_INT_CAST(UINT32, image->bytes_per_line), &invalidRect); + } + LeaveCriticalSection(&surface->lock); + if (!image) + { + /* + * BadMatch error happened. The size may have been changed again. + * Give up this frame and we will resize again in next frame + */ + goto fail_capture; + } + } + + /* Restore the default error handler */ + XSetErrorHandler(NULL); + XSync(subsystem->display, False); + XUnlockDisplay(subsystem->display); + + if (status) + { + BOOL empty = 0; + EnterCriticalSection(&surface->lock); + region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect); + region16_intersect_rect(&(surface->invalidRegion), &(surface->invalidRegion), &surfaceRect); + empty = region16_is_empty(&(surface->invalidRegion)); + LeaveCriticalSection(&surface->lock); + + if (!empty) + { + BOOL success = 0; + EnterCriticalSection(&surface->lock); + extents = region16_extents(&(surface->invalidRegion)); + x = extents->left; + y = extents->top; + width = extents->right - extents->left; + height = extents->bottom - extents->top; + WINPR_ASSERT(image); + WINPR_ASSERT(image->bytes_per_line >= 0); + WINPR_ASSERT(width >= 0); + WINPR_ASSERT(height >= 0); + success = freerdp_image_copy_no_overlap( + surface->data, surface->format, surface->scanline, + WINPR_ASSERTING_INT_CAST(uint32_t, x), WINPR_ASSERTING_INT_CAST(uint32_t, y), + WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, height), (BYTE*)image->data, subsystem->format, + WINPR_ASSERTING_INT_CAST(uint32_t, image->bytes_per_line), + WINPR_ASSERTING_INT_CAST(UINT32, x), WINPR_ASSERTING_INT_CAST(UINT32, y), NULL, + FREERDP_FLIP_NONE); + LeaveCriticalSection(&surface->lock); + if (!success) + goto fail_capture; + + // x11_shadow_blend_cursor(subsystem); + count = ArrayList_Count(server->clients); + shadow_subsystem_frame_update(&subsystem->common); + + if (count == 1) + { + rdpShadowClient* client = NULL; + client = (rdpShadowClient*)ArrayList_GetItem(server->clients, 0); + + if (client) + subsystem->common.captureFrameRate = + shadow_encoder_preferred_fps(client->encoder); + } + + EnterCriticalSection(&surface->lock); + region16_clear(&(surface->invalidRegion)); + LeaveCriticalSection(&surface->lock); + } + } + + rc = 1; +fail_capture: + if (!subsystem->use_xshm && image) + XDestroyImage(image); + + if (rc != 1) + { + XSetErrorHandler(NULL); + XSync(subsystem->display, False); + XUnlockDisplay(subsystem->display); + } + + return rc; +} + +static int x11_shadow_subsystem_process_message(x11ShadowSubsystem* subsystem, wMessage* message) +{ + switch (message->id) + { + case SHADOW_MSG_IN_REFRESH_REQUEST_ID: + shadow_subsystem_frame_update((rdpShadowSubsystem*)subsystem); + break; + + default: + WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", message->id); + break; + } + + if (message->Free) + message->Free(message); + + return 1; +} + +static DWORD WINAPI x11_shadow_subsystem_thread(LPVOID arg) +{ + x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)arg; + XEvent xevent; + DWORD status = 0; + DWORD nCount = 0; + DWORD dwInterval = 0; + UINT64 frameTime = 0; + HANDLE events[32]; + wMessage message; + wMessagePipe* MsgPipe = NULL; + MsgPipe = subsystem->common.MsgPipe; + nCount = 0; + events[nCount++] = subsystem->common.event; + events[nCount++] = MessageQueue_Event(MsgPipe->In); + subsystem->common.captureFrameRate = 16; + dwInterval = 1000 / subsystem->common.captureFrameRate; + frameTime = GetTickCount64() + dwInterval; + + while (1) + { + const UINT64 cTime = GetTickCount64(); + const DWORD dwTimeout = + (DWORD)((cTime > frameTime) ? 0 : MIN(UINT32_MAX, frameTime - cTime)); + status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout); + + if (WaitForSingleObject(MessageQueue_Event(MsgPipe->In), 0) == WAIT_OBJECT_0) + { + if (MessageQueue_Peek(MsgPipe->In, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + break; + + x11_shadow_subsystem_process_message(subsystem, &message); + } + } + + if (WaitForSingleObject(subsystem->common.event, 0) == WAIT_OBJECT_0) + { + XLockDisplay(subsystem->display); + + if (XEventsQueued(subsystem->display, QueuedAlready)) + { + XNextEvent(subsystem->display, &xevent); + x11_shadow_handle_xevent(subsystem, &xevent); + } + + XUnlockDisplay(subsystem->display); + } + + if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime)) + { + x11_shadow_check_resize(subsystem); + x11_shadow_screen_grab(subsystem); + x11_shadow_query_cursor(subsystem, FALSE); + dwInterval = 1000 / subsystem->common.captureFrameRate; + frameTime += dwInterval; + } + } + + ExitThread(0); + return 0; +} + +static int x11_shadow_subsystem_base_init(x11ShadowSubsystem* subsystem) +{ + if (subsystem->display) + return 1; /* initialize once */ + + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (!getenv("DISPLAY")) + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + setenv("DISPLAY", ":0", 1); + } + + if (!XInitThreads()) + return -1; + + subsystem->display = XOpenDisplay(NULL); + + if (!subsystem->display) + { + WLog_ERR(TAG, "failed to open display: %s", XDisplayName(NULL)); + return -1; + } + + subsystem->xfds = ConnectionNumber(subsystem->display); + subsystem->number = DefaultScreen(subsystem->display); + subsystem->screen = ScreenOfDisplay(subsystem->display, subsystem->number); + subsystem->depth = WINPR_ASSERTING_INT_CAST(UINT32, DefaultDepthOfScreen(subsystem->screen)); + subsystem->width = WINPR_ASSERTING_INT_CAST(UINT32, WidthOfScreen(subsystem->screen)); + subsystem->height = WINPR_ASSERTING_INT_CAST(UINT32, HeightOfScreen(subsystem->screen)); + subsystem->root_window = RootWindow(subsystem->display, subsystem->number); + return 1; +} + +static int x11_shadow_xfixes_init(x11ShadowSubsystem* subsystem) +{ +#ifdef WITH_XFIXES + int xfixes_event = 0; + int xfixes_error = 0; + int major = 0; + int minor = 0; + + if (!XFixesQueryExtension(subsystem->display, &xfixes_event, &xfixes_error)) + return -1; + + if (!XFixesQueryVersion(subsystem->display, &major, &minor)) + return -1; + + subsystem->xfixes_cursor_notify_event = xfixes_event + XFixesCursorNotify; + XFixesSelectCursorInput(subsystem->display, subsystem->root_window, + XFixesDisplayCursorNotifyMask); + return 1; +#else + return -1; +#endif +} + +static int x11_shadow_xinerama_init(x11ShadowSubsystem* subsystem) +{ +#ifdef WITH_XINERAMA + int xinerama_event = 0; + int xinerama_error = 0; + + const int rc = x11_shadow_subsystem_base_init(subsystem); + if (rc < 0) + return rc; + + if (!XineramaQueryExtension(subsystem->display, &xinerama_event, &xinerama_error)) + return -1; + +#if defined(WITH_XDAMAGE) + int major = 0; + int minor = 0; + if (!XDamageQueryVersion(subsystem->display, &major, &minor)) + return -1; +#endif + + if (!XineramaIsActive(subsystem->display)) + return -1; + + return 1; +#else + return -1; +#endif +} + +static int x11_shadow_xdamage_init(x11ShadowSubsystem* subsystem) +{ +#ifdef WITH_XDAMAGE + int major = 0; + int minor = 0; + int damage_event = 0; + int damage_error = 0; + + if (!subsystem->use_xfixes) + return -1; + + if (!XDamageQueryExtension(subsystem->display, &damage_event, &damage_error)) + return -1; + + if (!XDamageQueryVersion(subsystem->display, &major, &minor)) + return -1; + + if (major < 1) + return -1; + + subsystem->xdamage_notify_event = damage_event + XDamageNotify; + subsystem->xdamage = + XDamageCreate(subsystem->display, subsystem->root_window, XDamageReportDeltaRectangles); + + if (!subsystem->xdamage) + return -1; + +#ifdef WITH_XFIXES + subsystem->xdamage_region = XFixesCreateRegion(subsystem->display, NULL, 0); + + if (!subsystem->xdamage_region) + return -1; + +#endif + return 1; +#else + return -1; +#endif +} + +static int x11_shadow_xshm_init(x11ShadowSubsystem* subsystem) +{ + Bool pixmaps = 0; + int major = 0; + int minor = 0; + XGCValues values; + + if (!XShmQueryExtension(subsystem->display)) + return -1; + + if (!XShmQueryVersion(subsystem->display, &major, &minor, &pixmaps)) + return -1; + + if (!pixmaps) + return -1; + + subsystem->fb_shm_info.shmid = -1; + subsystem->fb_shm_info.shmaddr = (char*)-1; + subsystem->fb_shm_info.readOnly = False; + subsystem->fb_image = + XShmCreateImage(subsystem->display, subsystem->visual, subsystem->depth, ZPixmap, NULL, + &(subsystem->fb_shm_info), subsystem->width, subsystem->height); + + if (!subsystem->fb_image) + { + WLog_ERR(TAG, "XShmCreateImage failed"); + return -1; + } + + subsystem->fb_shm_info.shmid = + shmget(IPC_PRIVATE, + 1ull * WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->bytes_per_line) * + WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->height), + IPC_CREAT | 0600); + + if (subsystem->fb_shm_info.shmid == -1) + { + WLog_ERR(TAG, "shmget failed"); + return -1; + } + + subsystem->fb_shm_info.shmaddr = shmat(subsystem->fb_shm_info.shmid, 0, 0); + subsystem->fb_image->data = subsystem->fb_shm_info.shmaddr; + + if (subsystem->fb_shm_info.shmaddr == ((char*)-1)) + { + WLog_ERR(TAG, "shmat failed"); + return -1; + } + + if (!XShmAttach(subsystem->display, &(subsystem->fb_shm_info))) + return -1; + + XSync(subsystem->display, False); + shmctl(subsystem->fb_shm_info.shmid, IPC_RMID, 0); + subsystem->fb_pixmap = XShmCreatePixmap( + subsystem->display, subsystem->root_window, subsystem->fb_image->data, + &(subsystem->fb_shm_info), WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->width), + WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->height), + WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->depth)); + XSync(subsystem->display, False); + + if (!subsystem->fb_pixmap) + return -1; + + values.subwindow_mode = IncludeInferiors; + values.graphics_exposures = False; +#if defined(WITH_XDAMAGE) + subsystem->xshm_gc = XCreateGC(subsystem->display, subsystem->root_window, + GCSubwindowMode | GCGraphicsExposures, &values); + XSetFunction(subsystem->display, subsystem->xshm_gc, GXcopy); +#endif + XSync(subsystem->display, False); + return 1; +} + +UINT32 x11_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors) +{ + Display* display = NULL; + int displayWidth = 0; + int displayHeight = 0; + int numMonitors = 0; + + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (!getenv("DISPLAY")) + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + setenv("DISPLAY", ":0", 1); + } + + display = XOpenDisplay(NULL); + + if (!display) + { + WLog_ERR(TAG, "failed to open display: %s", XDisplayName(NULL)); + return 0; + } + + displayWidth = WidthOfScreen(DefaultScreenOfDisplay(display)); + displayHeight = HeightOfScreen(DefaultScreenOfDisplay(display)); +#ifdef WITH_XINERAMA + { +#if defined(WITH_XDAMAGE) + int major = 0; + int minor = 0; +#endif + int xinerama_event = 0; + int xinerama_error = 0; + XineramaScreenInfo* screens = NULL; + + const Bool xinerama = XineramaQueryExtension(display, &xinerama_event, &xinerama_error); + const Bool damage = +#if defined(WITH_XDAMAGE) + XDamageQueryVersion(display, &major, &minor); +#else + False; +#endif + + if (xinerama && damage && XineramaIsActive(display)) + { + screens = XineramaQueryScreens(display, &numMonitors); + + if (numMonitors > (INT64)maxMonitors) + numMonitors = (int)maxMonitors; + + if (screens && (numMonitors > 0)) + { + for (int index = 0; index < numMonitors; index++) + { + MONITOR_DEF* monitor = &monitors[index]; + const XineramaScreenInfo* screen = &screens[index]; + + monitor->left = screen->x_org; + monitor->top = screen->y_org; + monitor->right = monitor->left + screen->width - 1; + monitor->bottom = monitor->top + screen->height - 1; + monitor->flags = (index == 0) ? 1 : 0; + } + } + + XFree(screens); + } + } +#endif + XCloseDisplay(display); + + if (numMonitors < 1) + { + MONITOR_DEF* monitor = &monitors[0]; + numMonitors = 1; + + monitor->left = 0; + monitor->top = 0; + monitor->right = displayWidth - 1; + monitor->bottom = displayHeight - 1; + monitor->flags = 1; + } + + errno = 0; + return WINPR_ASSERTING_INT_CAST(uint32_t, numMonitors); +} + +static int x11_shadow_subsystem_init(rdpShadowSubsystem* sub) +{ + int pf_count = 0; + int vi_count = 0; + int nextensions = 0; + char** extensions = NULL; + XVisualInfo* vi = NULL; + XVisualInfo* vis = NULL; + XVisualInfo template = { 0 }; + XPixmapFormatValues* pf = NULL; + XPixmapFormatValues* pfs = NULL; + + x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub; + + if (!subsystem) + return -1; + + subsystem->common.numMonitors = x11_shadow_enum_monitors(subsystem->common.monitors, 16); + const int rc = x11_shadow_subsystem_base_init(subsystem); + if (rc < 0) + return rc; + + subsystem->format = (ImageByteOrder(subsystem->display) == LSBFirst) ? PIXEL_FORMAT_BGRA32 + : PIXEL_FORMAT_ARGB32; + + if ((subsystem->depth != 24) && (subsystem->depth != 32)) + { + WLog_ERR(TAG, "unsupported X11 server color depth: %" PRIu32, subsystem->depth); + return -1; + } + + extensions = XListExtensions(subsystem->display, &nextensions); + + if (!extensions || (nextensions < 0)) + return -1; + + for (int i = 0; i < nextensions; i++) + { + if (strcmp(extensions[i], "Composite") == 0) + subsystem->composite = TRUE; + } + + XFreeExtensionList(extensions); + + if (subsystem->composite) + subsystem->use_xdamage = FALSE; + + pfs = XListPixmapFormats(subsystem->display, &pf_count); + + if (!pfs) + { + WLog_ERR(TAG, "XListPixmapFormats failed"); + return -1; + } + + for (int i = 0; i < pf_count; i++) + { + pf = pfs + i; + + if (pf->depth == (INT64)subsystem->depth) + { + subsystem->bpp = WINPR_ASSERTING_INT_CAST(uint32_t, pf->bits_per_pixel); + subsystem->scanline_pad = WINPR_ASSERTING_INT_CAST(uint32_t, pf->scanline_pad); + break; + } + } + + XFree(pfs); + template.class = TrueColor; + template.screen = subsystem->number; + vis = XGetVisualInfo(subsystem->display, VisualClassMask | VisualScreenMask, &template, + &vi_count); + + if (!vis) + { + WLog_ERR(TAG, "XGetVisualInfo failed"); + return -1; + } + + for (int i = 0; i < vi_count; i++) + { + vi = vis + i; + + if (vi->depth == (INT64)subsystem->depth) + { + subsystem->visual = vi->visual; + break; + } + } + + XFree(vis); + XSelectInput(subsystem->display, subsystem->root_window, SubstructureNotifyMask); + subsystem->cursorMaxWidth = 256; + subsystem->cursorMaxHeight = 256; + subsystem->cursorPixels = + winpr_aligned_malloc(4ULL * subsystem->cursorMaxWidth * subsystem->cursorMaxHeight, 16); + + if (!subsystem->cursorPixels) + return -1; + + x11_shadow_query_cursor(subsystem, TRUE); + + if (subsystem->use_xfixes) + { + if (x11_shadow_xfixes_init(subsystem) < 0) + subsystem->use_xfixes = FALSE; + } + + if (subsystem->use_xinerama) + { + if (x11_shadow_xinerama_init(subsystem) < 0) + subsystem->use_xinerama = FALSE; + } + + if (subsystem->use_xshm) + { + if (x11_shadow_xshm_init(subsystem) < 0) + subsystem->use_xshm = FALSE; + } + + if (subsystem->use_xdamage) + { + if (x11_shadow_xdamage_init(subsystem) < 0) + subsystem->use_xdamage = FALSE; + } + + if (!(subsystem->common.event = + CreateFileDescriptorEvent(NULL, FALSE, FALSE, subsystem->xfds, WINPR_FD_READ))) + return -1; + + { + MONITOR_DEF* virtualScreen = &(subsystem->common.virtualScreen); + virtualScreen->left = 0; + virtualScreen->top = 0; + WINPR_ASSERT(subsystem->width <= INT32_MAX); + WINPR_ASSERT(subsystem->height <= INT32_MAX); + virtualScreen->right = (INT32)subsystem->width - 1; + virtualScreen->bottom = (INT32)subsystem->height - 1; + virtualScreen->flags = 1; + WLog_INFO(TAG, + "X11 Extensions: XFixes: %" PRId32 " Xinerama: %" PRId32 " XDamage: %" PRId32 + " XShm: %" PRId32 "", + subsystem->use_xfixes, subsystem->use_xinerama, subsystem->use_xdamage, + subsystem->use_xshm); + } + + return 1; +} + +static int x11_shadow_subsystem_uninit(rdpShadowSubsystem* sub) +{ + x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub; + + if (!subsystem) + return -1; + + if (subsystem->display) + { + XCloseDisplay(subsystem->display); + subsystem->display = NULL; + } + + if (subsystem->common.event) + { + (void)CloseHandle(subsystem->common.event); + subsystem->common.event = NULL; + } + + if (subsystem->cursorPixels) + { + winpr_aligned_free(subsystem->cursorPixels); + subsystem->cursorPixels = NULL; + } + + return 1; +} + +static int x11_shadow_subsystem_start(rdpShadowSubsystem* sub) +{ + x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub; + + if (!subsystem) + return -1; + + if (!(subsystem->thread = + CreateThread(NULL, 0, x11_shadow_subsystem_thread, (void*)subsystem, 0, NULL))) + { + WLog_ERR(TAG, "Failed to create thread"); + return -1; + } + + return 1; +} + +static int x11_shadow_subsystem_stop(rdpShadowSubsystem* sub) +{ + x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub; + + if (!subsystem) + return -1; + + if (subsystem->thread) + { + if (MessageQueue_PostQuit(subsystem->common.MsgPipe->In, 0)) + (void)WaitForSingleObject(subsystem->thread, INFINITE); + + (void)CloseHandle(subsystem->thread); + subsystem->thread = NULL; + } + + return 1; +} + +static rdpShadowSubsystem* x11_shadow_subsystem_new(void) +{ + x11ShadowSubsystem* subsystem = NULL; + subsystem = (x11ShadowSubsystem*)calloc(1, sizeof(x11ShadowSubsystem)); + + if (!subsystem) + return NULL; + +#ifdef WITH_PAM + subsystem->common.Authenticate = x11_shadow_pam_authenticate; +#endif + subsystem->common.SynchronizeEvent = x11_shadow_input_synchronize_event; + subsystem->common.KeyboardEvent = x11_shadow_input_keyboard_event; + subsystem->common.UnicodeKeyboardEvent = x11_shadow_input_unicode_keyboard_event; + subsystem->common.MouseEvent = x11_shadow_input_mouse_event; + subsystem->common.ExtendedMouseEvent = x11_shadow_input_extended_mouse_event; + subsystem->composite = FALSE; + subsystem->use_xshm = FALSE; /* temporarily disabled */ + subsystem->use_xfixes = TRUE; + subsystem->use_xdamage = FALSE; + subsystem->use_xinerama = TRUE; + return (rdpShadowSubsystem*)subsystem; +} + +static void x11_shadow_subsystem_free(rdpShadowSubsystem* subsystem) +{ + if (!subsystem) + return; + + x11_shadow_subsystem_uninit(subsystem); + free(subsystem); +} + +FREERDP_ENTRY_POINT(FREERDP_API const char* ShadowSubsystemName(void)) +{ + return "X11"; +} + +FREERDP_ENTRY_POINT(FREERDP_API int ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints)) +{ + if (!pEntryPoints) + return -1; + + pEntryPoints->New = x11_shadow_subsystem_new; + pEntryPoints->Free = x11_shadow_subsystem_free; + pEntryPoints->Init = x11_shadow_subsystem_init; + pEntryPoints->Uninit = x11_shadow_subsystem_uninit; + pEntryPoints->Start = x11_shadow_subsystem_start; + pEntryPoints->Stop = x11_shadow_subsystem_stop; + pEntryPoints->EnumMonitors = x11_shadow_enum_monitors; + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.h new file mode 100644 index 0000000000000000000000000000000000000000..a744c36187927bf2a4bd3c8c2ae6d7ab678c1607 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/X11/x11_shadow.h @@ -0,0 +1,115 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_X11_H +#define FREERDP_SERVER_SHADOW_X11_H + +#include + +typedef struct x11_shadow_subsystem x11ShadowSubsystem; + +#include +#include +#include +#include +#include + +#include + +#ifdef WITH_XSHM +#include +#endif + +#ifdef WITH_XFIXES +#include +#endif + +#ifdef WITH_XTEST +#include +#endif + +#ifdef WITH_XDAMAGE +#include +#endif + +#ifdef WITH_XINERAMA +#include +#endif + +struct x11_shadow_subsystem +{ + rdpShadowSubsystem common; + + HANDLE thread; + + UINT32 bpp; + int xfds; + UINT32 depth; + UINT32 width; + UINT32 height; + int number; + XImage* image; + Screen* screen; + Visual* visual; + Display* display; + UINT32 scanline_pad; + BOOL composite; + + BOOL use_xshm; + BOOL use_xfixes; + BOOL use_xdamage; + BOOL use_xinerama; + + XImage* fb_image; + Pixmap fb_pixmap; + Window root_window; + XShmSegmentInfo fb_shm_info; + + UINT32 cursorHotX; + UINT32 cursorHotY; + UINT32 cursorWidth; + UINT32 cursorHeight; + UINT64 cursorId; + BYTE* cursorPixels; + UINT32 cursorMaxWidth; + UINT32 cursorMaxHeight; + rdpShadowClient* lastMouseClient; + +#ifdef WITH_XDAMAGE + GC xshm_gc; + Damage xdamage; + int xdamage_notify_event; + XserverRegion xdamage_region; +#endif + +#ifdef WITH_XFIXES + int xfixes_cursor_notify_event; +#endif + UINT32 format; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_X11_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow-cli.1.in b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow-cli.1.in new file mode 100644 index 0000000000000000000000000000000000000000..ddea924241eae19559b0410e5d5fb2c53adb02f5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow-cli.1.in @@ -0,0 +1,93 @@ +.de URL +\\$2 \(laURL: \\$1 \(ra\\$3 +.. +.if \n[.g] .mso www.tmac +.TH @MANPAGE_NAME@ 1 2017-01-12 "@FREERDP_VERSION_FULL@" "FreeRDP" +.SH NAME +@MANPAGE_NAME@ \- A utility for sharing a X display via RDP. +.SH SYNOPSIS +.B @MANPAGE_NAME@ +[\fB/port:\fP\fI\fP] +[\fB/ipc-socket:\fP\fI\fP] +[\fB/monitors:\fP\fI<0,1,2,...>\fP] +[\fB/rect:\fP\fI\fP] +[\fB+auth\fP] +[\fB-may-view\fP] +[\fB-may-interact\fP] +[\fB/sec:\fP\fI\fP] +[\fB-sec-rdp\fP] +[\fB-sec-tls\fP] +[\fB-sec-nla\fP] +[\fB-sec-ext\fP] +[\fB/sam-file:\fP\fI\fP] +[\fB/version\fP] +[\fB/help\fP] +.SH DESCRIPTION +.B @MANPAGE_NAME@ +can be used to share a running X display like with VNC but by using the RDP +instead. It is also possibly to share only parts (rect) of the display. +.SH OPTIONS +.IP /ipc-socket: +If this option is set an ipc socket with the path \fIipc-socket\fP is used +instead of a TCP socket. +.IP /port: +Set the port to use. Default is 3389. +This option is ignored if ipc-socket is used. +.IP /monitors:<1,2,3,...> +Select the monitor(s) to share. +.IP /rect: +Select rectangle within monitor to share. +.IP -auth +Disable authentication. If authentication is enabled PAM is used with the +X11 subsystem. Running as root is not necessary, however if run as user only +the same user that started @MANPAGE_NAME@ can authenticate. +.br +\fBWarning\fP: If authentication is disabled \fIeveryone\fP can connect. +.IP -may-view +Clients may view without prompt. +.IP -may-interact +Clients may interact without prompt. +.IP /sec: +Force a specific protocol security +.IP -sec-rdp +Disable RDP security (default:on) +.IP -sec-tls +Disable TLS protocol security (default:on) +.IP -sec-nla +Disable NLA protocol security (default:on) +.IP +sec-ext +Use NLA extended protocol security (default:off) +.IP /sam-file: +NTLM SAM file for NLA authentication +.IP /version +Print the version and exit. +.IP /help +Print the help and exit. + +.SH USAGE + +#MANPAGE_NAME@ - start the shadow server on port 3389 with NLA security, SAM database at /etc/winpr/SAM +.br +@MANPAGE_NAME@ /sam-file:SAM.db - same as above, but a custom SAM database provided as argument +.br +@MANPAGE_NAME@ -sec-nla - start the shadow server on port 3380 with TLS/NLA security. This allows authenticating against PAM with unix users. Be aware that the password is transmitted plain text like with basic HTTP auth + +.SH EXAMPLES +@MANPAGE_NAME@ /port:12345 + +When run as user within a X session (for example from an xterm) a socket on +12345 is opened and the current display is shared via RDP. + +.SH EXIT STATUS +.TP +.B 0 +Successful program execution. +.TP +.B 1 +Otherwise. + +.SH SEE ALSO +wlog(7) + +.SH AUTHOR +FreeRDP diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow.pc.in b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..805e2af41669cdbfe2d201460a52a4be3e7b5dc6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/freerdp-shadow.pc.in @@ -0,0 +1,15 @@ +prefix=@PKG_CONFIG_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${prefix}/@FREERDP_INCLUDE_DIR@ +libs=-lfreerdp-shadow@FREERDP_API_VERSION@ -lfreerdp-shadow-subsystem@FREERDP_API_VERSION@ + +Name: FreeRDP shadow +Description: FreeRDP: A Remote Desktop Protocol Implementation +URL: http://www.freerdp.com/ +Version: @FREERDP_VERSION@ +Requires: +Requires.private: @WINPR_PKG_CONFIG_FILENAME@ freerdp@FREERDP_API_VERSION@ +Libs: -L${libdir} ${libs} +Libs.private: -ldl -lpthread +Cflags: -I${includedir} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.c new file mode 100644 index 0000000000000000000000000000000000000000..59c3b074fdf5883181930b1d64b28f551dfe079b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.c @@ -0,0 +1,186 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#define TAG SERVER_TAG("shadow") + +int main(int argc, char** argv) +{ + int status = 0; + DWORD dwExitCode = 0; + COMMAND_LINE_ARGUMENT_A shadow_args[] = { + { "log-filters", COMMAND_LINE_VALUE_REQUIRED, ":[,:[,...]]", NULL, + NULL, -1, NULL, "Set logger filters, see wLog(7) for details" }, + { "log-level", COMMAND_LINE_VALUE_REQUIRED, "[OFF|FATAL|ERROR|WARN|INFO|DEBUG|TRACE]", NULL, + NULL, -1, NULL, "Set the default log level, see wLog(7) for details" }, + { "port", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "Server port" }, + { "ipc-socket", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Server IPC socket" }, + { "bind-address", COMMAND_LINE_VALUE_REQUIRED, "[,, ...]", + NULL, NULL, -1, NULL, + "An address to bind to. Use '[]' for IPv6 addresses, e.g. '[::1]' for " + "localhost" }, + { "monitors", COMMAND_LINE_VALUE_OPTIONAL, "<0,1,2...>", NULL, NULL, -1, NULL, + "Select or list monitors" }, + { "max-connections", COMMAND_LINE_VALUE_REQUIRED, "", 0, NULL, -1, NULL, + "maximum connections allowed to server, 0 to deactivate" }, + { "rect", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Select rectangle within monitor to share" }, + { "auth", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Clients must authenticate" }, + { "remote-guard", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "Remote credential guard" }, + { "may-view", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Clients may view without prompt" }, + { "may-interact", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Clients may interact without prompt" }, + { "sec", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "force specific protocol security" }, + { "sec-rdp", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "rdp protocol security" }, + { "sec-tls", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "tls protocol security" }, + { "sec-nla", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "nla protocol security" }, + { "sec-ext", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "nla extended protocol security" }, + { "sam-file", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "NTLM SAM file for NLA authentication" }, + { "keytab", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Kerberos keytab file for NLA authentication" }, + { "ccache", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Kerberos host ccache file for NLA authentication" }, + { "tls-secrets-file", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "file where tls secrets shall be stored" }, + { "nsc", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, "Allow NSC codec" }, + { "rfx", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow RFX surface bits" }, + { "gfx", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX pipeline" }, + { "gfx-progressive", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX progressive codec" }, + { "gfx-rfx", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX RFX codec" }, + { "gfx-planar", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX planar codec" }, + { "gfx-avc420", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX AVC420 codec" }, + { "gfx-avc444", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "Allow GFX AVC444 codec" }, + { "version", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_VERSION, NULL, NULL, NULL, -1, + NULL, "Print version" }, + { "buildconfig", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_BUILDCONFIG, NULL, NULL, NULL, + -1, NULL, "Print the build configuration" }, + { "help", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_HELP, NULL, NULL, NULL, -1, "?", + "Print help" }, + { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } + }; + + shadow_subsystem_set_entry_builtin(NULL); + + rdpShadowServer* server = shadow_server_new(); + + if (!server) + { + status = -1; + WLog_ERR(TAG, "Server new failed"); + goto fail; + } + + rdpSettings* settings = server->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, TRUE)) + goto fail; + + /* By default allow all GFX modes. + * This can be changed with command line flags [+|-]gfx-CODEC + */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 32) || + !freerdp_settings_set_bool(settings, FreeRDP_NSCodec, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_RemoteFxImageCodec, TRUE) || + !freerdp_settings_set_uint32(settings, FreeRDP_RemoteFxRlgrMode, RLGR3) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxH264, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxProgressive, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxProgressiveV2, TRUE)) + goto fail; + + /* TODO: We do not implement relative mouse callbacks, so deactivate it for now */ + if (!freerdp_settings_set_bool(settings, FreeRDP_MouseUseRelativeMove, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_HasRelativeMouseEvent, FALSE)) + goto fail; + + if ((status = shadow_server_parse_command_line(server, argc, argv, shadow_args)) < 0) + { + shadow_server_command_line_status_print(server, argc, argv, status, shadow_args); + goto fail; + } + + if ((status = shadow_server_init(server)) < 0) + { + WLog_ERR(TAG, "Server initialization failed."); + goto fail; + } + + if ((status = shadow_server_start(server)) < 0) + { + WLog_ERR(TAG, "Failed to start server."); + goto fail; + } + +#ifdef _WIN32 + { + MSG msg = { 0 }; + while (GetMessage(&msg, 0, 0, 0)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } +#endif + + (void)WaitForSingleObject(server->thread, INFINITE); + + if (!GetExitCodeThread(server->thread, &dwExitCode)) + status = -1; + else + status = (int)dwExitCode; + +fail: + shadow_server_uninit(server); + shadow_server_free(server); + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.h new file mode 100644 index 0000000000000000000000000000000000000000..33eb80557abb490971f8e8660ce435b88ab94b1a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow.h @@ -0,0 +1,44 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_SHADOW_H +#define FREERDP_SERVER_SHADOW_SHADOW_H + +#include + +#include "shadow_client.h" +#include "shadow_input.h" +#include "shadow_screen.h" +#include "shadow_surface.h" +#include "shadow_encoder.h" +#include "shadow_capture.h" +#include "shadow_channels.h" +#include "shadow_subsystem.h" +#include "shadow_lobby.h" +#include "shadow_mcevent.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_SHADOW_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.c new file mode 100644 index 0000000000000000000000000000000000000000..a95fb03d01d1aad4028ec1adaf6fc3802d8ce278 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.c @@ -0,0 +1,105 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * Copyright 2023 Pascal Nowack + * + * 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 + +#include +#include "shadow.h" + +#include "shadow_audin.h" +#include + +#if defined(CHANNEL_AUDIN_SERVER) +#include +#endif + +#if defined(CHANNEL_AUDIN_SERVER) + +static UINT AudinServerData(audin_server_context* audin, const SNDIN_DATA* data) +{ + rdpShadowClient* client = NULL; + rdpShadowSubsystem* subsystem = NULL; + + WINPR_ASSERT(audin); + WINPR_ASSERT(data); + + client = audin->userdata; + WINPR_ASSERT(client); + WINPR_ASSERT(client->server); + subsystem = client->server->subsystem; + WINPR_ASSERT(subsystem); + + if (!client->mayInteract) + return CHANNEL_RC_OK; + + if (!IFCALLRESULT(TRUE, subsystem->AudinServerReceiveSamples, subsystem, client, + audin_server_get_negotiated_format(client->audin), data->Data)) + return ERROR_INTERNAL_ERROR; + + return CHANNEL_RC_OK; +} + +#endif + +BOOL shadow_client_audin_init(rdpShadowClient* client) +{ + WINPR_ASSERT(client); + +#if defined(CHANNEL_AUDIN_SERVER) + audin_server_context* audin = client->audin = audin_server_context_new(client->vcm); + + if (!audin) + return FALSE; + + audin->userdata = client; + + audin->Data = AudinServerData; + + if (client->subsystem->audinFormats) + { + if (client->subsystem->nAudinFormats > SSIZE_MAX) + goto fail; + + if (!audin_server_set_formats(client->audin, (SSIZE_T)client->subsystem->nAudinFormats, + client->subsystem->audinFormats)) + goto fail; + } + else + { + if (!audin_server_set_formats(client->audin, -1, NULL)) + goto fail; + } + + return TRUE; +fail: + audin_server_context_free(audin); + client->audin = NULL; +#endif + return FALSE; +} + +void shadow_client_audin_uninit(rdpShadowClient* client) +{ + WINPR_ASSERT(client); + +#if defined(CHANNEL_AUDIN_SERVER) + audin_server_context_free(client->audin); + client->audin = NULL; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.h new file mode 100644 index 0000000000000000000000000000000000000000..0499987ec63f7fe80e874b626a86787191e0f113 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_audin.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * 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 FREERDP_SERVER_SHADOW_AUDIN_H +#define FREERDP_SERVER_SHADOW_AUDIN_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + BOOL shadow_client_audin_init(rdpShadowClient* client); + void shadow_client_audin_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_AUDIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.c new file mode 100644 index 0000000000000000000000000000000000000000..bd1790ae69abf29772879dbf8b1de7ddb859eb3e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.c @@ -0,0 +1,341 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#include "shadow_surface.h" + +#include "shadow_capture.h" + +int shadow_capture_align_clip_rect(RECTANGLE_16* rect, const RECTANGLE_16* clip) +{ + int dx = 0; + int dy = 0; + dx = (rect->left % 16); + + if (dx != 0) + { + rect->left -= dx; + rect->right += dx; + } + + dx = (rect->right % 16); + + if (dx != 0) + { + rect->right += (16 - dx); + } + + dy = (rect->top % 16); + + if (dy != 0) + { + rect->top -= dy; + rect->bottom += dy; + } + + dy = (rect->bottom % 16); + + if (dy != 0) + { + rect->bottom += (16 - dy); + } + + if (rect->left < clip->left) + rect->left = clip->left; + + if (rect->top < clip->top) + rect->top = clip->top; + + if (rect->right > clip->right) + rect->right = clip->right; + + if (rect->bottom > clip->bottom) + rect->bottom = clip->bottom; + + return 1; +} + +int shadow_capture_compare(const BYTE* WINPR_RESTRICT pData1, UINT32 nStep1, UINT32 nWidth, + UINT32 nHeight, const BYTE* WINPR_RESTRICT pData2, UINT32 nStep2, + RECTANGLE_16* WINPR_RESTRICT rect) +{ + return shadow_capture_compare_with_format(pData1, PIXEL_FORMAT_BGRX32, nStep1, nWidth, nHeight, + pData2, PIXEL_FORMAT_BGRX32, nStep2, rect); +} + +static BOOL color_equal(UINT32 colorA, UINT32 formatA, UINT32 colorB, UINT32 formatB) +{ + BYTE ar = 0; + BYTE ag = 0; + BYTE ab = 0; + BYTE aa = 0; + BYTE br = 0; + BYTE bg = 0; + BYTE bb = 0; + BYTE ba = 0; + FreeRDPSplitColor(colorA, formatA, &ar, &ag, &ab, &aa, NULL); + FreeRDPSplitColor(colorB, formatB, &br, &bg, &bb, &ba, NULL); + + if (ar != br) + return FALSE; + if (ag != bg) + return FALSE; + if (ab != bb) + return FALSE; + if (aa != ba) + return FALSE; + return TRUE; +} + +static BOOL pixel_equal(const BYTE* WINPR_RESTRICT a, UINT32 formatA, const BYTE* WINPR_RESTRICT b, + UINT32 formatB, size_t count) +{ + const size_t bppA = FreeRDPGetBytesPerPixel(formatA); + const size_t bppB = FreeRDPGetBytesPerPixel(formatB); + + for (size_t x = 0; x < count; x++) + { + const UINT32 colorA = FreeRDPReadColor(&a[bppA * x], formatA); + const UINT32 colorB = FreeRDPReadColor(&b[bppB * x], formatB); + if (!color_equal(colorA, formatA, colorB, formatB)) + return FALSE; + } + + return TRUE; +} + +static BOOL color_equal_no_alpha(UINT32 colorA, UINT32 formatA, UINT32 colorB, UINT32 formatB) +{ + BYTE ar = 0; + BYTE ag = 0; + BYTE ab = 0; + BYTE br = 0; + BYTE bg = 0; + BYTE bb = 0; + FreeRDPSplitColor(colorA, formatA, &ar, &ag, &ab, NULL, NULL); + FreeRDPSplitColor(colorB, formatB, &br, &bg, &bb, NULL, NULL); + + if (ar != br) + return FALSE; + if (ag != bg) + return FALSE; + if (ab != bb) + return FALSE; + return TRUE; +} + +static BOOL pixel_equal_no_alpha(const BYTE* WINPR_RESTRICT a, UINT32 formatA, + const BYTE* WINPR_RESTRICT b, UINT32 formatB, size_t count) +{ + const size_t bppA = FreeRDPGetBytesPerPixel(formatA); + const size_t bppB = FreeRDPGetBytesPerPixel(formatB); + + for (size_t x = 0; x < count; x++) + { + const UINT32 colorA = FreeRDPReadColor(&a[bppA * x], formatA); + const UINT32 colorB = FreeRDPReadColor(&b[bppB * x], formatB); + if (!color_equal_no_alpha(colorA, formatA, colorB, formatB)) + return FALSE; + } + + return TRUE; +} + +static BOOL pixel_equal_same_format(const BYTE* WINPR_RESTRICT a, UINT32 formatA, + const BYTE* WINPR_RESTRICT b, UINT32 formatB, size_t count) +{ + if (formatA != formatB) + return FALSE; + const size_t bppA = FreeRDPGetBytesPerPixel(formatA); + return memcmp(a, b, count * bppA) == 0; +} + +typedef BOOL (*pixel_equal_fn_t)(const BYTE* WINPR_RESTRICT a, UINT32 formatA, + const BYTE* WINPR_RESTRICT b, UINT32 formatB, size_t count); + +static pixel_equal_fn_t get_comparison_fn(DWORD format1, DWORD format2) +{ + + if (format1 == format2) + return pixel_equal_same_format; + + const UINT32 bpp1 = FreeRDPGetBitsPerPixel(format1); + + if (!FreeRDPColorHasAlpha(format1) || !FreeRDPColorHasAlpha(format2)) + { + /* In case we have RGBA32 and RGBX32 or similar assume the alpha data is equal. + * This allows us to use the fast memcmp comparison. */ + if ((bpp1 == 32) && FreeRDPAreColorFormatsEqualNoAlpha(format1, format2)) + { + switch (format1) + { + case PIXEL_FORMAT_ARGB32: + case PIXEL_FORMAT_XRGB32: + case PIXEL_FORMAT_ABGR32: + case PIXEL_FORMAT_XBGR32: + return pixel_equal; + case PIXEL_FORMAT_RGBA32: + case PIXEL_FORMAT_RGBX32: + case PIXEL_FORMAT_BGRA32: + case PIXEL_FORMAT_BGRX32: + return pixel_equal; + default: + break; + } + } + return pixel_equal_no_alpha; + } + else + return pixel_equal_no_alpha; +} + +int shadow_capture_compare_with_format(const BYTE* WINPR_RESTRICT pData1, UINT32 format1, + UINT32 nStep1, UINT32 nWidth, UINT32 nHeight, + const BYTE* WINPR_RESTRICT pData2, UINT32 format2, + UINT32 nStep2, RECTANGLE_16* WINPR_RESTRICT rect) +{ + pixel_equal_fn_t pixel_equal_fn = get_comparison_fn(format1, format2); + BOOL allEqual = TRUE; + UINT32 tw = 0; + const UINT32 nrow = (nHeight + 15) / 16; + const UINT32 ncol = (nWidth + 15) / 16; + UINT32 l = ncol + 1; + UINT32 t = nrow + 1; + UINT32 r = 0; + UINT32 b = 0; + const size_t bppA = FreeRDPGetBytesPerPixel(format1); + const size_t bppB = FreeRDPGetBytesPerPixel(format2); + const RECTANGLE_16 empty = { 0 }; + WINPR_ASSERT(rect); + + *rect = empty; + + for (size_t ty = 0; ty < nrow; ty++) + { + BOOL rowEqual = TRUE; + size_t th = ((ty + 1) == nrow) ? (nHeight % 16) : 16; + + if (!th) + th = 16; + + for (size_t tx = 0; tx < ncol; tx++) + { + BOOL equal = TRUE; + tw = ((tx + 1) == ncol) ? (nWidth % 16) : 16; + + if (!tw) + tw = 16; + + const BYTE* p1 = &pData1[(ty * 16ULL * nStep1) + (tx * 16ull * bppA)]; + const BYTE* p2 = &pData2[(ty * 16ULL * nStep2) + (tx * 16ull * bppB)]; + + for (size_t k = 0; k < th; k++) + { + if (!pixel_equal_fn(p1, format1, p2, format2, tw)) + { + equal = FALSE; + break; + } + + p1 += nStep1; + p2 += nStep2; + } + + if (!equal) + { + rowEqual = FALSE; + if (l > tx) + l = (UINT32)tx; + + if (r < tx) + r = (UINT32)tx; + } + } + + if (!rowEqual) + { + allEqual = FALSE; + + if (t > ty) + t = (UINT32)ty; + + if (b < ty) + b = (UINT32)ty; + } + } + + if (allEqual) + return 0; + + WINPR_ASSERT(l * 16 <= UINT16_MAX); + WINPR_ASSERT(t * 16 <= UINT16_MAX); + WINPR_ASSERT((r + 1) * 16 <= UINT16_MAX); + WINPR_ASSERT((b + 1) * 16 <= UINT16_MAX); + rect->left = (UINT16)l * 16; + rect->top = (UINT16)t * 16; + rect->right = (UINT16)(r + 1) * 16; + rect->bottom = (UINT16)(b + 1) * 16; + + WINPR_ASSERT(nWidth <= UINT16_MAX); + if (rect->right > nWidth) + rect->right = (UINT16)nWidth; + + WINPR_ASSERT(nHeight <= UINT16_MAX); + if (rect->bottom > nHeight) + rect->bottom = (UINT16)nHeight; + + return 1; +} + +rdpShadowCapture* shadow_capture_new(rdpShadowServer* server) +{ + WINPR_ASSERT(server); + + rdpShadowCapture* capture = (rdpShadowCapture*)calloc(1, sizeof(rdpShadowCapture)); + + if (!capture) + return NULL; + + capture->server = server; + + if (!InitializeCriticalSectionAndSpinCount(&(capture->lock), 4000)) + { + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + shadow_capture_free(capture); + WINPR_PRAGMA_DIAG_POP + return NULL; + } + + return capture; +} + +void shadow_capture_free(rdpShadowCapture* capture) +{ + if (!capture) + return; + + DeleteCriticalSection(&(capture->lock)); + free(capture); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.h new file mode 100644 index 0000000000000000000000000000000000000000..31de5505d332faddc94adb26c9ebe92bc669547d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_capture.h @@ -0,0 +1,52 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_CAPTURE_H +#define FREERDP_SERVER_SHADOW_CAPTURE_H + +#include + +#include +#include +#include + +struct rdp_shadow_capture +{ + rdpShadowServer* server; + + int width; + int height; + + CRITICAL_SECTION lock; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_capture_free(rdpShadowCapture* capture); + + WINPR_ATTR_MALLOC(shadow_capture_free, 1) + rdpShadowCapture* shadow_capture_new(rdpShadowServer* server); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_CAPTURE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..1bf3b161fb68eb281689acaf3e84f27ff1da360e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.c @@ -0,0 +1,56 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include "shadow.h" + +#include "shadow_channels.h" + +UINT shadow_client_channels_post_connect(rdpShadowClient* client) +{ + if (WTSVirtualChannelManagerIsChannelJoined(client->vcm, ENCOMSP_SVC_CHANNEL_NAME)) + { + shadow_client_encomsp_init(client); + } + + if (WTSVirtualChannelManagerIsChannelJoined(client->vcm, REMDESK_SVC_CHANNEL_NAME)) + { + shadow_client_remdesk_init(client); + } + + if (WTSVirtualChannelManagerIsChannelJoined(client->vcm, RDPSND_CHANNEL_NAME)) + { + shadow_client_rdpsnd_init(client); + } + + shadow_client_audin_init(client); + + shadow_client_rdpgfx_init(client); + + return CHANNEL_RC_OK; +} + +void shadow_client_channels_free(rdpShadowClient* client) +{ + shadow_client_rdpgfx_uninit(client); + shadow_client_audin_uninit(client); + shadow_client_rdpsnd_uninit(client); + shadow_client_remdesk_uninit(client); + shadow_client_encomsp_uninit(client); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.h new file mode 100644 index 0000000000000000000000000000000000000000..261041e84980bf3360db565f0295e00fadcd94bd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_channels.h @@ -0,0 +1,45 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_CHANNELS_H +#define FREERDP_SERVER_SHADOW_CHANNELS_H + +#include + +#include +#include + +#include "shadow_encomsp.h" +#include "shadow_remdesk.h" +#include "shadow_rdpsnd.h" +#include "shadow_audin.h" +#include "shadow_rdpgfx.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + UINT shadow_client_channels_post_connect(rdpShadowClient* client); + void shadow_client_channels_free(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_CHANNELS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.c new file mode 100644 index 0000000000000000000000000000000000000000..8dbe08519b68fa7b25c60bed6e5e00613163a9b0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.c @@ -0,0 +1,2718 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "shadow.h" + +#define TAG CLIENT_TAG("shadow") + +typedef struct +{ + BOOL gfxOpened; + BOOL gfxSurfaceCreated; +} SHADOW_GFX_STATUS; + +/* See https://github.com/FreeRDP/FreeRDP/issues/10413 + * + * Microsoft ditched support for RFX and multiple rectangles in BitmapUpdate for + * windows 11 24H2. + * + * So send all updates only with a single rectangle. + */ +#define BitmapUpdateProxy(update, context, bitmap) \ + BitmapUpdateProxyEx((update), (context), (bitmap), __FILE__, __LINE__, __func__) +static BOOL BitmapUpdateProxyEx(rdpUpdate* update, rdpContext* context, const BITMAP_UPDATE* bitmap, + const char* file, size_t line, const char* fkt) +{ + WINPR_ASSERT(update); + WINPR_ASSERT(context); + WINPR_ASSERT(bitmap); + + for (UINT32 x = 0; x < bitmap->number; x++) + { + BITMAP_UPDATE cur = { 0 }; + BITMAP_DATA* bmp = &bitmap->rectangles[x]; + cur.rectangles = bmp; + cur.number = 1; + cur.skipCompression = bitmap->skipCompression; + const BOOL rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, &cur); + if (!rc) + { + const DWORD log_level = WLOG_ERROR; + wLog* log = WLog_Get(TAG); + if (WLog_IsLevelActive(log, log_level)) + { + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "BitmapUpdate[%" PRIu32 "] failed", x); + } + return FALSE; + } + } + + return TRUE; +} + +static INLINE BOOL shadow_client_rdpgfx_new_surface(rdpShadowClient* client) +{ + UINT error = CHANNEL_RC_OK; + RDPGFX_CREATE_SURFACE_PDU createSurface; + RDPGFX_MAP_SURFACE_TO_OUTPUT_PDU surfaceToOutput; + RdpgfxServerContext* context = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + context = client->rdpgfx; + WINPR_ASSERT(context); + settings = ((rdpContext*)client)->settings; + WINPR_ASSERT(settings); + + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) <= UINT16_MAX); + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) <= UINT16_MAX); + createSurface.width = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + createSurface.height = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + createSurface.pixelFormat = GFX_PIXEL_FORMAT_XRGB_8888; + createSurface.surfaceId = client->surfaceId; + surfaceToOutput.outputOriginX = 0; + surfaceToOutput.outputOriginY = 0; + surfaceToOutput.surfaceId = client->surfaceId; + surfaceToOutput.reserved = 0; + IFCALLRET(context->CreateSurface, error, context, &createSurface); + + if (error) + { + WLog_ERR(TAG, "CreateSurface failed with error %" PRIu32 "", error); + return FALSE; + } + + IFCALLRET(context->MapSurfaceToOutput, error, context, &surfaceToOutput); + + if (error) + { + WLog_ERR(TAG, "MapSurfaceToOutput failed with error %" PRIu32 "", error); + return FALSE; + } + + return TRUE; +} + +static INLINE BOOL shadow_client_rdpgfx_release_surface(rdpShadowClient* client) +{ + UINT error = CHANNEL_RC_OK; + RDPGFX_DELETE_SURFACE_PDU pdu; + RdpgfxServerContext* context = NULL; + + WINPR_ASSERT(client); + + context = client->rdpgfx; + WINPR_ASSERT(context); + + pdu.surfaceId = client->surfaceId++; + IFCALLRET(context->DeleteSurface, error, context, &pdu); + + if (error) + { + WLog_ERR(TAG, "DeleteSurface failed with error %" PRIu32 "", error); + return FALSE; + } + + return TRUE; +} + +static INLINE BOOL shadow_client_rdpgfx_reset_graphic(rdpShadowClient* client) +{ + UINT error = CHANNEL_RC_OK; + RDPGFX_RESET_GRAPHICS_PDU pdu = { 0 }; + RdpgfxServerContext* context = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->rdpgfx); + + context = client->rdpgfx; + WINPR_ASSERT(context); + + settings = client->context.settings; + WINPR_ASSERT(settings); + + pdu.width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + pdu.height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + pdu.monitorCount = client->subsystem->numMonitors; + pdu.monitorDefArray = client->subsystem->monitors; + IFCALLRET(context->ResetGraphics, error, context, &pdu); + + if (error) + { + WLog_ERR(TAG, "ResetGraphics failed with error %" PRIu32 "", error); + return FALSE; + } + + client->first_frame = TRUE; + return TRUE; +} + +static INLINE void shadow_client_free_queued_message(void* obj) +{ + wMessage* message = (wMessage*)obj; + + WINPR_ASSERT(message); + if (message->Free) + { + message->Free(message); + message->Free = NULL; + } +} + +static void shadow_client_context_free(freerdp_peer* peer, rdpContext* context) +{ + rdpShadowClient* client = (rdpShadowClient*)context; + rdpShadowServer* server = NULL; + + WINPR_UNUSED(peer); + if (!client) + return; + + server = client->server; + if (server && server->clients) + ArrayList_Remove(server->clients, (void*)client); + + shadow_encoder_free(client->encoder); + + /* Clear queued messages and free resource */ + MessageQueue_Free(client->MsgQueue); + WTSCloseServer(client->vcm); + region16_uninit(&(client->invalidRegion)); + DeleteCriticalSection(&(client->lock)); + + client->MsgQueue = NULL; + client->encoder = NULL; + client->vcm = NULL; +} + +static BOOL shadow_client_context_new(freerdp_peer* peer, rdpContext* context) +{ + BOOL NSCodec = 0; + const char bind_address[] = "bind-address,"; + rdpShadowClient* client = (rdpShadowClient*)context; + rdpSettings* settings = NULL; + const rdpSettings* srvSettings = NULL; + rdpShadowServer* server = NULL; + const wObject cb = { NULL, NULL, NULL, shadow_client_free_queued_message, NULL }; + + WINPR_ASSERT(client); + WINPR_ASSERT(peer); + WINPR_ASSERT(peer->context); + + server = (rdpShadowServer*)peer->ContextExtra; + WINPR_ASSERT(server); + + srvSettings = server->settings; + WINPR_ASSERT(srvSettings); + + client->surfaceId = 1; + client->server = server; + client->subsystem = server->subsystem; + WINPR_ASSERT(client->subsystem); + + settings = peer->context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, + freerdp_settings_get_uint32(srvSettings, FreeRDP_ColorDepth))) + return FALSE; + NSCodec = freerdp_settings_get_bool(srvSettings, FreeRDP_NSCodec); + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, NSCodec)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, + freerdp_settings_get_bool(srvSettings, FreeRDP_RemoteFxCodec))) + return FALSE; + if (!freerdp_settings_set_uint32( + settings, FreeRDP_RemoteFxRlgrMode, + freerdp_settings_get_uint32(srvSettings, FreeRDP_RemoteFxRlgrMode))) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheV3Enabled, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_FrameMarkerCommandEnabled, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_SurfaceFrameMarkerEnabled, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool( + settings, FreeRDP_SupportGraphicsPipeline, + freerdp_settings_get_bool(srvSettings, FreeRDP_SupportGraphicsPipeline))) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxH264, + freerdp_settings_get_bool(srvSettings, FreeRDP_GfxH264))) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DrawAllowSkipAlpha, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DrawAllowColorSubsampling, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DrawAllowDynamicColorFidelity, TRUE)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_CompressionLevel, PACKET_COMPR_TYPE_RDP8)) + return FALSE; + + if (server->ipcSocket && (strncmp(bind_address, server->ipcSocket, + strnlen(bind_address, sizeof(bind_address))) != 0)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_LyncRdpMode, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_CompressionEnabled, FALSE)) + return FALSE; + } + + client->inLobby = TRUE; + client->mayView = server->mayView; + client->mayInteract = server->mayInteract; + + if (!InitializeCriticalSectionAndSpinCount(&(client->lock), 4000)) + goto fail; + + region16_init(&(client->invalidRegion)); + client->vcm = WTSOpenServerA((LPSTR)peer->context); + + if (!client->vcm || client->vcm == INVALID_HANDLE_VALUE) + goto fail; + + if (!(client->MsgQueue = MessageQueue_New(&cb))) + goto fail; + + if (!(client->encoder = shadow_encoder_new(client))) + goto fail; + + if (!ArrayList_Append(server->clients, (void*)client)) + goto fail; + + return TRUE; + +fail: + shadow_client_context_free(peer, context); + return FALSE; +} + +static INLINE void shadow_client_mark_invalid(rdpShadowClient* client, UINT32 numRects, + const RECTANGLE_16* rects) +{ + RECTANGLE_16 screenRegion; + rdpSettings* settings = NULL; + + WINPR_ASSERT(client); + WINPR_ASSERT(rects || (numRects == 0)); + + settings = client->context.settings; + WINPR_ASSERT(settings); + + EnterCriticalSection(&(client->lock)); + + /* Mark client invalid region. No rectangle means full screen */ + if (numRects > 0) + { + for (UINT32 index = 0; index < numRects; index++) + { + region16_union_rect(&(client->invalidRegion), &(client->invalidRegion), &rects[index]); + } + } + else + { + screenRegion.left = 0; + screenRegion.top = 0; + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) <= UINT16_MAX); + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) <= UINT16_MAX); + screenRegion.right = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + screenRegion.bottom = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + region16_union_rect(&(client->invalidRegion), &(client->invalidRegion), &screenRegion); + } + + LeaveCriticalSection(&(client->lock)); +} + +/** + * Function description + * Recalculate client desktop size and update to rdpSettings + * + * @return TRUE if width/height changed. + */ +static INLINE BOOL shadow_client_recalc_desktop_size(rdpShadowClient* client) +{ + INT32 width = 0; + INT32 height = 0; + rdpShadowServer* server = NULL; + rdpSettings* settings = NULL; + RECTANGLE_16 viewport = { 0 }; + + WINPR_ASSERT(client); + server = client->server; + settings = client->context.settings; + + WINPR_ASSERT(server); + WINPR_ASSERT(server->surface); + WINPR_ASSERT(settings); + + WINPR_ASSERT(server->surface->width <= UINT16_MAX); + WINPR_ASSERT(server->surface->height <= UINT16_MAX); + viewport.right = (UINT16)server->surface->width; + viewport.bottom = (UINT16)server->surface->height; + + if (server->shareSubRect) + { + rectangles_intersection(&viewport, &(server->subRect), &viewport); + } + + width = viewport.right - viewport.left; + height = viewport.bottom - viewport.top; + + WINPR_ASSERT(width >= 0); + WINPR_ASSERT(width <= UINT16_MAX); + WINPR_ASSERT(height >= 0); + WINPR_ASSERT(height <= UINT16_MAX); + if (freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) != (UINT32)width || + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) != (UINT32)height) + return TRUE; + + return FALSE; +} + +static BOOL shadow_client_capabilities(freerdp_peer* peer) +{ + rdpShadowSubsystem* subsystem = NULL; + rdpShadowClient* client = NULL; + BOOL ret = TRUE; + + WINPR_ASSERT(peer); + + client = (rdpShadowClient*)peer->context; + WINPR_ASSERT(client); + WINPR_ASSERT(client->server); + + subsystem = client->server->subsystem; + WINPR_ASSERT(subsystem); + + IFCALLRET(subsystem->ClientCapabilities, ret, subsystem, client); + + if (!ret) + WLog_WARN(TAG, "subsystem->ClientCapabilities failed"); + + return ret; +} + +static void shadow_reset_desktop_resize(rdpShadowClient* client) +{ + WINPR_ASSERT(client); + client->resizeRequested = FALSE; +} + +static BOOL shadow_send_desktop_resize(rdpShadowClient* client) +{ + BOOL rc = 0; + rdpUpdate* update = NULL; + rdpSettings* settings = NULL; + const freerdp_peer* peer = NULL; + + WINPR_ASSERT(client); + + settings = client->context.settings; + peer = client->context.peer; + WINPR_ASSERT(peer); + WINPR_ASSERT(client->server); + WINPR_ASSERT(client->server->surface); + + const UINT32 resizeWidth = client->server->surface->width; + const UINT32 resizeHeight = client->server->surface->height; + + if (client->resizeRequested) + { + if ((resizeWidth == client->resizeWidth) && (resizeHeight == client->resizeHeight)) + { + const UINT32 w = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + const UINT32 h = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + WLog_WARN(TAG, + "detected previous resize request for resolution %" PRIu32 "x%" PRIu32 + ", still have %" PRIu32 "x%" PRIu32 ", disconnecting peer", + resizeWidth, resizeHeight, w, h); + return FALSE; + } + } + + update = client->context.update; + WINPR_ASSERT(update); + WINPR_ASSERT(update->DesktopResize); + + // Update peer resolution, required so that during disconnect/reconnect the correct resolution + // is sent to the client. + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, resizeWidth)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, resizeHeight)) + return FALSE; + rc = update->DesktopResize(update->context); + WLog_INFO(TAG, "Client %s resize requested (%" PRIu32 "x%" PRIu32 "@%" PRIu32 ")", + peer->hostname, resizeWidth, resizeHeight, + freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth)); + client->resizeRequested = TRUE; + client->resizeWidth = resizeWidth; + client->resizeHeight = resizeHeight; + + return rc; +} + +static BOOL shadow_client_post_connect(freerdp_peer* peer) +{ + int authStatus = 0; + rdpSettings* settings = NULL; + rdpShadowClient* client = NULL; + rdpShadowServer* server = NULL; + rdpShadowSubsystem* subsystem = NULL; + + WINPR_ASSERT(peer); + + client = (rdpShadowClient*)peer->context; + WINPR_ASSERT(client); + + settings = peer->context->settings; + WINPR_ASSERT(settings); + + server = client->server; + WINPR_ASSERT(server); + + subsystem = server->subsystem; + WINPR_ASSERT(subsystem); + + if (freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth) == 24) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, 16)) /* disable 24bpp */ + return FALSE; + } + + const UINT32 MultifragMaxRequestSize = + freerdp_settings_get_uint32(settings, FreeRDP_MultifragMaxRequestSize); + if (MultifragMaxRequestSize < 0x3F0000) + { + BOOL rc = freerdp_settings_set_bool( + settings, FreeRDP_NSCodec, + FALSE); /* NSCodec compressor does not support fragmentation yet */ + if (!rc) + return FALSE; + } + + WLog_INFO(TAG, "Client from %s is activated (%" PRIu32 "x%" PRIu32 "@%" PRIu32 ")", + peer->hostname, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth)); + + if (shadow_client_channels_post_connect(client) != CHANNEL_RC_OK) + return FALSE; + + shadow_client_mark_invalid(client, 0, NULL); + authStatus = -1; + + const char* Username = freerdp_settings_get_string(settings, FreeRDP_Username); + const char* Domain = freerdp_settings_get_string(settings, FreeRDP_Domain); + const char* Password = freerdp_settings_get_string(settings, FreeRDP_Password); + + if (Username && Password) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoLogonEnabled, TRUE)) + return FALSE; + } + + if (server->authentication && !freerdp_settings_get_bool(settings, FreeRDP_NlaSecurity)) + { + if (subsystem->Authenticate) + { + authStatus = subsystem->Authenticate(subsystem, client, Username, Domain, Password); + } + + if (authStatus < 0) + { + WLog_ERR(TAG, "client authentication failure: %d", authStatus); + return FALSE; + } + } + + if (subsystem->ClientConnect) + { + return subsystem->ClientConnect(subsystem, client); + } + + return TRUE; +} + +/* Convert rects in sub rect coordinate to client/surface coordinate */ +static INLINE void shadow_client_convert_rects(rdpShadowClient* client, RECTANGLE_16* dst, + const RECTANGLE_16* src, UINT32 numRects) +{ + WINPR_ASSERT(client); + WINPR_ASSERT(client->server); + WINPR_ASSERT(dst); + WINPR_ASSERT(src || (numRects == 0)); + + if (client->server->shareSubRect) + { + UINT16 offsetX = client->server->subRect.left; + UINT16 offsetY = client->server->subRect.top; + + for (UINT32 i = 0; i < numRects; i++) + { + const RECTANGLE_16* s = &src[i]; + RECTANGLE_16* d = &dst[i]; + + d->left = s->left + offsetX; + d->right = s->right + offsetX; + d->top = s->top + offsetY; + d->bottom = s->bottom + offsetY; + } + } + else + { + if (src != dst) + { + CopyMemory(dst, src, numRects * sizeof(RECTANGLE_16)); + } + } +} + +static BOOL shadow_client_refresh_request(rdpShadowClient* client) +{ + wMessage message = { 0 }; + wMessagePipe* MsgPipe = NULL; + + WINPR_ASSERT(client); + WINPR_ASSERT(client->subsystem); + + MsgPipe = client->subsystem->MsgPipe; + WINPR_ASSERT(MsgPipe); + + message.id = SHADOW_MSG_IN_REFRESH_REQUEST_ID; + message.wParam = NULL; + message.lParam = NULL; + message.context = (void*)client; + message.Free = NULL; + return MessageQueue_Dispatch(MsgPipe->In, &message); +} + +static BOOL shadow_client_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) +{ + rdpShadowClient* client = (rdpShadowClient*)context; + RECTANGLE_16* rects = NULL; + + /* It is invalid if we have area count but no actual area */ + if (count && !areas) + return FALSE; + + if (count) + { + rects = (RECTANGLE_16*)calloc(count, sizeof(RECTANGLE_16)); + + if (!rects) + { + return FALSE; + } + + shadow_client_convert_rects(client, rects, areas, count); + shadow_client_mark_invalid(client, count, rects); + free(rects); + } + else + { + shadow_client_mark_invalid(client, 0, NULL); + } + + return shadow_client_refresh_request(client); +} + +static BOOL shadow_client_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) +{ + rdpShadowClient* client = (rdpShadowClient*)context; + RECTANGLE_16 region; + + WINPR_ASSERT(client); + + client->suppressOutput = allow ? FALSE : TRUE; + + if (allow) + { + if (area) + { + shadow_client_convert_rects(client, ®ion, area, 1); + shadow_client_mark_invalid(client, 1, ®ion); + } + else + { + shadow_client_mark_invalid(client, 0, NULL); + } + } + + return shadow_client_refresh_request(client); +} + +static BOOL shadow_client_activate(freerdp_peer* peer) +{ + rdpSettings* settings = NULL; + rdpShadowClient* client = NULL; + + WINPR_ASSERT(peer); + + client = (rdpShadowClient*)peer->context; + WINPR_ASSERT(client); + + settings = peer->context->settings; + WINPR_ASSERT(settings); + + /* Resize client if necessary */ + if (shadow_client_recalc_desktop_size(client)) + return shadow_send_desktop_resize(client); + + shadow_reset_desktop_resize(client); + client->activated = TRUE; + client->inLobby = client->mayView ? FALSE : TRUE; + + if (shadow_encoder_reset(client->encoder) < 0) + { + WLog_ERR(TAG, "Failed to reset encoder"); + return FALSE; + } + + /* Update full screen in next update */ + return shadow_client_refresh_rect(&client->context, 0, NULL); +} + +static BOOL shadow_client_logon(freerdp_peer* peer, const SEC_WINNT_AUTH_IDENTITY* identity, + BOOL automatic) +{ + BOOL rc = FALSE; + char* user = NULL; + char* domain = NULL; + char* password = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(automatic); + + WINPR_ASSERT(peer); + WINPR_ASSERT(identity); + + WINPR_ASSERT(peer->context); + + settings = peer->context->settings; + WINPR_ASSERT(settings); + + if (identity->Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE) + { + if (identity->User) + user = ConvertWCharNToUtf8Alloc(identity->User, identity->UserLength, NULL); + + if (identity->Domain) + domain = ConvertWCharNToUtf8Alloc(identity->Domain, identity->DomainLength, NULL); + + if (identity->Password) + password = ConvertWCharNToUtf8Alloc(identity->Password, identity->PasswordLength, NULL); + } + else + { + if (identity->User) + user = _strdup((char*)identity->User); + + if (identity->Domain) + domain = _strdup((char*)identity->Domain); + + if (identity->Password) + password = _strdup((char*)identity->Password); + } + + if ((identity->User && !user) || (identity->Domain && !domain) || + (identity->Password && !password)) + goto fail; + + if (user) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Username, user)) + goto fail; + } + + if (domain) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Domain, domain)) + goto fail; + } + if (password) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Password, password)) + goto fail; + } + rc = TRUE; +fail: + free(user); + free(domain); + free(password); + return rc; +} + +static INLINE void shadow_client_common_frame_acknowledge(rdpShadowClient* client, UINT32 frameId) +{ + /* + * Record the last client acknowledged frame id to + * calculate how much frames are in progress. + * Some rdp clients (win7 mstsc) skips frame ACK if it is + * inactive, we should not expect ACK for each frame. + * So it is OK to calculate in-flight frame count according to + * a latest acknowledged frame id. + */ + WINPR_ASSERT(client); + WINPR_ASSERT(client->encoder); + client->encoder->lastAckframeId = frameId; +} + +static BOOL shadow_client_surface_frame_acknowledge(rdpContext* context, UINT32 frameId) +{ + rdpShadowClient* client = (rdpShadowClient*)context; + shadow_client_common_frame_acknowledge(client, frameId); + /* + * Reset queueDepth for legacy none RDPGFX acknowledge + */ + WINPR_ASSERT(client); + WINPR_ASSERT(client->encoder); + client->encoder->queueDepth = QUEUE_DEPTH_UNAVAILABLE; + return TRUE; +} + +static UINT +shadow_client_rdpgfx_frame_acknowledge(RdpgfxServerContext* context, + const RDPGFX_FRAME_ACKNOWLEDGE_PDU* frameAcknowledge) +{ + rdpShadowClient* client = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(frameAcknowledge); + + client = (rdpShadowClient*)context->custom; + shadow_client_common_frame_acknowledge(client, frameAcknowledge->frameId); + + WINPR_ASSERT(client); + WINPR_ASSERT(client->encoder); + client->encoder->queueDepth = frameAcknowledge->queueDepth; + return CHANNEL_RC_OK; +} + +static BOOL shadow_are_caps_filtered(const rdpSettings* settings, UINT32 caps) +{ + const UINT32 capList[] = { RDPGFX_CAPVERSION_8, RDPGFX_CAPVERSION_81, + RDPGFX_CAPVERSION_10, RDPGFX_CAPVERSION_101, + RDPGFX_CAPVERSION_102, RDPGFX_CAPVERSION_103, + RDPGFX_CAPVERSION_104, RDPGFX_CAPVERSION_105, + RDPGFX_CAPVERSION_106, RDPGFX_CAPVERSION_106_ERR, + RDPGFX_CAPVERSION_107 }; + + WINPR_ASSERT(settings); + const UINT32 filter = freerdp_settings_get_uint32(settings, FreeRDP_GfxCapsFilter); + + for (UINT32 x = 0; x < ARRAYSIZE(capList); x++) + { + if (caps == capList[x]) + return (filter & (1 << x)) != 0; + } + + return TRUE; +} + +static UINT shadow_client_send_caps_confirm(RdpgfxServerContext* context, rdpShadowClient* client, + const RDPGFX_CAPS_CONFIRM_PDU* pdu) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(client); + WINPR_ASSERT(pdu); + + WINPR_ASSERT(context->CapsConfirm); + UINT rc = context->CapsConfirm(context, pdu); + client->areGfxCapsReady = (rc == CHANNEL_RC_OK); + return rc; +} + +static BOOL shadow_client_caps_test_version(RdpgfxServerContext* context, rdpShadowClient* client, + BOOL h264, const RDPGFX_CAPSET* capsSets, + UINT32 capsSetCount, UINT32 capsVersion, UINT* rc) +{ + const rdpSettings* srvSettings = NULL; + rdpSettings* clientSettings = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(client); + WINPR_ASSERT(capsSets || (capsSetCount == 0)); + WINPR_ASSERT(rc); + + WINPR_ASSERT(context->rdpcontext); + srvSettings = context->rdpcontext->settings; + WINPR_ASSERT(srvSettings); + + clientSettings = client->context.settings; + WINPR_ASSERT(clientSettings); + + if (shadow_are_caps_filtered(srvSettings, capsVersion)) + return FALSE; + + for (UINT32 index = 0; index < capsSetCount; index++) + { + const RDPGFX_CAPSET* currentCaps = &capsSets[index]; + + if (currentCaps->version == capsVersion) + { + UINT32 flags = 0; + BOOL planar = FALSE; + BOOL rfx = FALSE; + BOOL avc444v2 = FALSE; + BOOL avc444 = FALSE; + BOOL avc420 = FALSE; + BOOL progressive = FALSE; + RDPGFX_CAPSET caps = *currentCaps; + RDPGFX_CAPS_CONFIRM_PDU pdu = { 0 }; + pdu.capsSet = ∩︀ + + flags = pdu.capsSet->flags; + + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxSmallCache, + (flags & RDPGFX_CAPS_FLAG_SMALL_CACHE) ? TRUE : FALSE)) + return FALSE; + + avc444v2 = avc444 = !(flags & RDPGFX_CAPS_FLAG_AVC_DISABLED); + if (!freerdp_settings_get_bool(srvSettings, FreeRDP_GfxAVC444v2) || !h264) + avc444v2 = FALSE; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444v2, avc444v2)) + return FALSE; + if (!freerdp_settings_get_bool(srvSettings, FreeRDP_GfxAVC444) || !h264) + avc444 = FALSE; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444, avc444)) + return FALSE; + if (!freerdp_settings_get_bool(srvSettings, FreeRDP_GfxH264) || !h264) + avc420 = FALSE; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxH264, avc420)) + return FALSE; + + progressive = freerdp_settings_get_bool(srvSettings, FreeRDP_GfxProgressive); + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxProgressive, progressive)) + return FALSE; + progressive = freerdp_settings_get_bool(srvSettings, FreeRDP_GfxProgressiveV2); + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxProgressiveV2, progressive)) + return FALSE; + + rfx = freerdp_settings_get_bool(srvSettings, FreeRDP_RemoteFxCodec); + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_RemoteFxCodec, rfx)) + return FALSE; + + planar = freerdp_settings_get_bool(srvSettings, FreeRDP_GfxPlanar); + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxPlanar, planar)) + return FALSE; + + if (!avc444v2 && !avc444 && !avc420) + pdu.capsSet->flags |= RDPGFX_CAPS_FLAG_AVC_DISABLED; + + *rc = shadow_client_send_caps_confirm(context, client, &pdu); + return TRUE; + } + } + + return FALSE; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT shadow_client_rdpgfx_caps_advertise(RdpgfxServerContext* context, + const RDPGFX_CAPS_ADVERTISE_PDU* capsAdvertise) +{ + UINT rc = ERROR_INTERNAL_ERROR; + const rdpSettings* srvSettings = NULL; + rdpSettings* clientSettings = NULL; + BOOL h264 = FALSE; + + UINT32 flags = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(capsAdvertise); + + rdpShadowClient* client = (rdpShadowClient*)context->custom; + WINPR_ASSERT(client); + WINPR_ASSERT(context->rdpcontext); + + srvSettings = context->rdpcontext->settings; + WINPR_ASSERT(srvSettings); + + clientSettings = client->context.settings; + WINPR_ASSERT(clientSettings); + +#ifdef WITH_GFX_H264 + h264 = + (shadow_encoder_prepare(client->encoder, FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444) >= 0); +#else + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444v2, FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444, FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxH264, FALSE)) + return rc; +#endif + + /* Request full screen update for new gfx channel */ + if (!shadow_client_refresh_rect(&client->context, 0, NULL)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_107, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_106, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_106_ERR, + &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_105, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_104, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_103, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_102, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_101, &rc)) + return rc; + + if (shadow_client_caps_test_version(context, client, h264, capsAdvertise->capsSets, + capsAdvertise->capsSetCount, RDPGFX_CAPVERSION_10, &rc)) + return rc; + + if (!shadow_are_caps_filtered(srvSettings, RDPGFX_CAPVERSION_81)) + { + for (UINT32 index = 0; index < capsAdvertise->capsSetCount; index++) + { + const RDPGFX_CAPSET* currentCaps = &capsAdvertise->capsSets[index]; + + if (currentCaps->version == RDPGFX_CAPVERSION_81) + { + RDPGFX_CAPSET caps = *currentCaps; + RDPGFX_CAPS_CONFIRM_PDU pdu; + pdu.capsSet = ∩︀ + + flags = pdu.capsSet->flags; + + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444v2, FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444, FALSE)) + return rc; + + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxThinClient, + (flags & RDPGFX_CAPS_FLAG_THINCLIENT) ? TRUE + : FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxSmallCache, + (flags & RDPGFX_CAPS_FLAG_SMALL_CACHE) ? TRUE + : FALSE)) + return rc; + +#ifndef WITH_GFX_H264 + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxH264, FALSE)) + return rc; + pdu.capsSet->flags &= ~RDPGFX_CAPS_FLAG_AVC420_ENABLED; +#else + + if (h264) + { + if (!freerdp_settings_set_bool( + clientSettings, FreeRDP_GfxH264, + (flags & RDPGFX_CAPS_FLAG_AVC420_ENABLED) ? TRUE : FALSE)) + return rc; + } + else + { + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxH264, FALSE)) + return rc; + } +#endif + + return shadow_client_send_caps_confirm(context, client, &pdu); + } + } + } + + if (!shadow_are_caps_filtered(srvSettings, RDPGFX_CAPVERSION_8)) + { + for (UINT32 index = 0; index < capsAdvertise->capsSetCount; index++) + { + const RDPGFX_CAPSET* currentCaps = &capsAdvertise->capsSets[index]; + + if (currentCaps->version == RDPGFX_CAPVERSION_8) + { + RDPGFX_CAPSET caps = *currentCaps; + RDPGFX_CAPS_CONFIRM_PDU pdu; + pdu.capsSet = ∩︀ + flags = pdu.capsSet->flags; + + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444v2, FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxAVC444, FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxH264, FALSE)) + return rc; + + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxThinClient, + (flags & RDPGFX_CAPS_FLAG_THINCLIENT) ? TRUE + : FALSE)) + return rc; + if (!freerdp_settings_set_bool(clientSettings, FreeRDP_GfxSmallCache, + (flags & RDPGFX_CAPS_FLAG_SMALL_CACHE) ? TRUE + : FALSE)) + return rc; + + return shadow_client_send_caps_confirm(context, client, &pdu); + } + } + } + + return CHANNEL_RC_UNSUPPORTED_VERSION; +} + +static INLINE UINT32 rdpgfx_estimate_h264_avc420(RDPGFX_AVC420_BITMAP_STREAM* havc420) +{ + /* H264 metadata + H264 stream. See rdpgfx_write_h264_avc420 */ + WINPR_ASSERT(havc420); + return sizeof(UINT32) /* numRegionRects */ + + 10ULL /* regionRects + quantQualityVals */ + * havc420->meta.numRegionRects + + havc420->length; +} + +/** + * Function description + * + * @return TRUE on success + */ +static BOOL shadow_client_send_surface_gfx(rdpShadowClient* client, const BYTE* pSrcData, + UINT32 nSrcStep, UINT32 SrcFormat, UINT16 nXSrc, + UINT16 nYSrc, UINT16 nWidth, UINT16 nHeight) +{ + UINT32 id = 0; + UINT error = CHANNEL_RC_OK; + const rdpContext* context = (const rdpContext*)client; + const rdpSettings* settings = NULL; + rdpShadowEncoder* encoder = NULL; + RDPGFX_SURFACE_COMMAND cmd = { 0 }; + RDPGFX_START_FRAME_PDU cmdstart = { 0 }; + RDPGFX_END_FRAME_PDU cmdend = { 0 }; + SYSTEMTIME sTime = { 0 }; + + if (!context || !pSrcData) + return FALSE; + + settings = context->settings; + encoder = client->encoder; + + if (!settings || !encoder) + return FALSE; + + if (client->first_frame) + { + rfx_context_reset(encoder->rfx, nWidth, nHeight); + client->first_frame = FALSE; + } + + cmdstart.frameId = shadow_encoder_create_frame_id(encoder); + GetSystemTime(&sTime); + cmdstart.timestamp = (UINT32)(sTime.wHour << 22U | sTime.wMinute << 16U | sTime.wSecond << 10U | + sTime.wMilliseconds); + cmdend.frameId = cmdstart.frameId; + cmd.surfaceId = client->surfaceId; + cmd.format = PIXEL_FORMAT_BGRX32; + cmd.left = nXSrc; + cmd.top = nYSrc; + cmd.right = cmd.left + nWidth; + cmd.bottom = cmd.top + nHeight; + cmd.width = nWidth; + cmd.height = nHeight; + + id = freerdp_settings_get_uint32(settings, FreeRDP_RemoteFxCodecId); +#ifdef WITH_GFX_H264 + const BOOL GfxH264 = freerdp_settings_get_bool(settings, FreeRDP_GfxH264); + const BOOL GfxAVC444 = freerdp_settings_get_bool(settings, FreeRDP_GfxAVC444); + const BOOL GfxAVC444v2 = freerdp_settings_get_bool(settings, FreeRDP_GfxAVC444v2); + if (GfxAVC444 || GfxAVC444v2) + { + INT32 rc = 0; + RDPGFX_AVC444_BITMAP_STREAM avc444 = { 0 }; + RECTANGLE_16 regionRect = { 0 }; + BYTE version = GfxAVC444v2 ? 2 : 1; + + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_AVC444) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_AVC444"); + return FALSE; + } + + WINPR_ASSERT(cmd.left <= UINT16_MAX); + WINPR_ASSERT(cmd.top <= UINT16_MAX); + WINPR_ASSERT(cmd.right <= UINT16_MAX); + WINPR_ASSERT(cmd.bottom <= UINT16_MAX); + regionRect.left = (UINT16)cmd.left; + regionRect.top = (UINT16)cmd.top; + regionRect.right = (UINT16)cmd.right; + regionRect.bottom = (UINT16)cmd.bottom; + rc = avc444_compress(encoder->h264, pSrcData, cmd.format, nSrcStep, nWidth, nHeight, + version, ®ionRect, &avc444.LC, &avc444.bitstream[0].data, + &avc444.bitstream[0].length, &avc444.bitstream[1].data, + &avc444.bitstream[1].length, &avc444.bitstream[0].meta, + &avc444.bitstream[1].meta); + if (rc < 0) + { + WLog_ERR(TAG, "avc420_compress failed for avc444"); + return FALSE; + } + + /* rc > 0 means new data */ + if (rc > 0) + { + avc444.cbAvc420EncodedBitstream1 = rdpgfx_estimate_h264_avc420(&avc444.bitstream[0]); + cmd.codecId = GfxAVC444v2 ? RDPGFX_CODECID_AVC444v2 : RDPGFX_CODECID_AVC444; + cmd.extra = (void*)&avc444; + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + } + + free_h264_metablock(&avc444.bitstream[0].meta); + free_h264_metablock(&avc444.bitstream[1].meta); + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + else if (GfxH264) + { + INT32 rc = 0; + RDPGFX_AVC420_BITMAP_STREAM avc420 = { 0 }; + RECTANGLE_16 regionRect; + + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_AVC420) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_AVC420"); + return FALSE; + } + + WINPR_ASSERT(cmd.left <= UINT16_MAX); + WINPR_ASSERT(cmd.top <= UINT16_MAX); + WINPR_ASSERT(cmd.right <= UINT16_MAX); + WINPR_ASSERT(cmd.bottom <= UINT16_MAX); + regionRect.left = (UINT16)cmd.left; + regionRect.top = (UINT16)cmd.top; + regionRect.right = (UINT16)cmd.right; + regionRect.bottom = (UINT16)cmd.bottom; + rc = avc420_compress(encoder->h264, pSrcData, cmd.format, nSrcStep, nWidth, nHeight, + ®ionRect, &avc420.data, &avc420.length, &avc420.meta); + if (rc < 0) + { + WLog_ERR(TAG, "avc420_compress failed"); + return FALSE; + } + + /* rc > 0 means new data */ + if (rc > 0) + { + cmd.codecId = RDPGFX_CODECID_AVC420; + cmd.extra = (void*)&avc420; + + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + } + free_h264_metablock(&avc420.meta); + + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + else +#endif + if (freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec) && (id != 0)) + { + BOOL rc = 0; + wStream* s = NULL; + RFX_RECT rect; + + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_REMOTEFX) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_REMOTEFX"); + return FALSE; + } + + s = Stream_New(NULL, 1024); + WINPR_ASSERT(s); + + WINPR_ASSERT(cmd.left <= UINT16_MAX); + WINPR_ASSERT(cmd.top <= UINT16_MAX); + WINPR_ASSERT(cmd.right <= UINT16_MAX); + WINPR_ASSERT(cmd.bottom <= UINT16_MAX); + rect.x = (UINT16)cmd.left; + rect.y = (UINT16)cmd.top; + rect.width = WINPR_ASSERTING_INT_CAST(UINT16, cmd.right - cmd.left); + rect.height = WINPR_ASSERTING_INT_CAST(UINT16, cmd.bottom - cmd.top); + + rc = rfx_compose_message(encoder->rfx, s, &rect, 1, pSrcData, nWidth, nHeight, nSrcStep); + + if (!rc) + { + WLog_ERR(TAG, "rfx_compose_message failed"); + Stream_Free(s, TRUE); + return FALSE; + } + + /* rc > 0 means new data */ + if (rc > 0) + { + const size_t pos = Stream_GetPosition(s); + WINPR_ASSERT(pos <= UINT32_MAX); + + cmd.codecId = RDPGFX_CODECID_CAVIDEO; + cmd.data = Stream_Buffer(s); + cmd.length = (UINT32)pos; + + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + } + + Stream_Free(s, TRUE); + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + else if (freerdp_settings_get_bool(settings, FreeRDP_GfxProgressive)) + { + INT32 rc = 0; + REGION16 region; + RECTANGLE_16 regionRect; + + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_PROGRESSIVE) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_PROGRESSIVE"); + return FALSE; + } + + WINPR_ASSERT(cmd.left <= UINT16_MAX); + WINPR_ASSERT(cmd.top <= UINT16_MAX); + WINPR_ASSERT(cmd.right <= UINT16_MAX); + WINPR_ASSERT(cmd.bottom <= UINT16_MAX); + regionRect.left = (UINT16)cmd.left; + regionRect.top = (UINT16)cmd.top; + regionRect.right = (UINT16)cmd.right; + regionRect.bottom = (UINT16)cmd.bottom; + region16_init(®ion); + region16_union_rect(®ion, ®ion, ®ionRect); + rc = progressive_compress(encoder->progressive, pSrcData, nSrcStep * nHeight, cmd.format, + nWidth, nHeight, nSrcStep, ®ion, &cmd.data, &cmd.length); + region16_uninit(®ion); + if (rc < 0) + { + WLog_ERR(TAG, "progressive_compress failed"); + return FALSE; + } + + /* rc > 0 means new data */ + if (rc > 0) + { + cmd.codecId = RDPGFX_CODECID_CAPROGRESSIVE; + + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + } + + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + else if (freerdp_settings_get_bool(settings, FreeRDP_GfxPlanar)) + { + BOOL rc = 0; + const UINT32 w = cmd.right - cmd.left; + const UINT32 h = cmd.bottom - cmd.top; + const BYTE* src = + &pSrcData[cmd.top * nSrcStep + cmd.left * FreeRDPGetBytesPerPixel(SrcFormat)]; + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_PLANAR) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_PLANAR"); + return FALSE; + } + + rc = freerdp_bitmap_planar_context_reset(encoder->planar, w, h); + WINPR_ASSERT(rc); + freerdp_planar_topdown_image(encoder->planar, TRUE); + + cmd.data = freerdp_bitmap_compress_planar(encoder->planar, src, SrcFormat, w, h, nSrcStep, + NULL, &cmd.length); + WINPR_ASSERT(cmd.data || (cmd.length == 0)); + + cmd.codecId = RDPGFX_CODECID_PLANAR; + + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + free(cmd.data); + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + else + { + BOOL rc = 0; + const UINT32 w = cmd.right - cmd.left; + const UINT32 h = cmd.bottom - cmd.top; + const UINT32 length = w * 4 * h; + BYTE* data = malloc(length); + + WINPR_ASSERT(data); + + rc = freerdp_image_copy_no_overlap(data, PIXEL_FORMAT_BGRA32, 0, 0, 0, w, h, pSrcData, + SrcFormat, nSrcStep, cmd.left, cmd.top, NULL, 0); + WINPR_ASSERT(rc); + + cmd.data = data; + cmd.length = length; + cmd.codecId = RDPGFX_CODECID_UNCOMPRESSED; + + IFCALLRET(client->rdpgfx->SurfaceFrameCommand, error, client->rdpgfx, &cmd, &cmdstart, + &cmdend); + free(data); + if (error) + { + WLog_ERR(TAG, "SurfaceFrameCommand failed with error %" PRIu32 "", error); + return FALSE; + } + } + return TRUE; +} + +static BOOL stream_surface_bits_supported(const rdpSettings* settings) +{ + const UINT32 supported = + freerdp_settings_get_uint32(settings, FreeRDP_SurfaceCommandsSupported); + return ((supported & SURFCMDS_STREAM_SURFACE_BITS) != 0); +} + +static BOOL set_surface_bits_supported(const rdpSettings* settings) +{ + const UINT32 supported = + freerdp_settings_get_uint32(settings, FreeRDP_SurfaceCommandsSupported); + return ((supported & SURFCMDS_SET_SURFACE_BITS) != 0); +} + +static BOOL is_surface_command_supported(const rdpSettings* settings) +{ + if (stream_surface_bits_supported(settings)) + { + const UINT32 rfxID = freerdp_settings_get_uint32(settings, FreeRDP_RemoteFxCodecId); + const BOOL supported = freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec); + if (supported && (rfxID != 0)) + return TRUE; + } + if (set_surface_bits_supported(settings)) + { + const UINT32 nsID = freerdp_settings_get_uint32(settings, FreeRDP_NSCodecId); + const BOOL supported = freerdp_settings_get_bool(settings, FreeRDP_NSCodec); + if (supported && (nsID != 0)) + return TRUE; + } + return FALSE; +} + +/** + * Function description + * + * @return TRUE on success + */ +static BOOL shadow_client_send_surface_bits(rdpShadowClient* client, BYTE* pSrcData, + UINT32 nSrcStep, UINT16 nXSrc, UINT16 nYSrc, + UINT16 nWidth, UINT16 nHeight) +{ + BOOL ret = TRUE; + BOOL first = 0; + BOOL last = 0; + wStream* s = NULL; + size_t numMessages = 0; + UINT32 frameId = 0; + rdpUpdate* update = NULL; + rdpContext* context = (rdpContext*)client; + rdpSettings* settings = NULL; + rdpShadowEncoder* encoder = NULL; + SURFACE_BITS_COMMAND cmd = { 0 }; + + if (!context || !pSrcData) + return FALSE; + + update = context->update; + settings = context->settings; + encoder = client->encoder; + + if (!update || !settings || !encoder) + return FALSE; + + if (encoder->frameAck) + frameId = shadow_encoder_create_frame_id(encoder); + + // TODO: Check FreeRDP_RemoteFxCodecMode if we should send RFX IMAGE or VIDEO data + const UINT32 nsID = freerdp_settings_get_uint32(settings, FreeRDP_NSCodecId); + const UINT32 rfxID = freerdp_settings_get_uint32(settings, FreeRDP_RemoteFxCodecId); + if (stream_surface_bits_supported(settings) && + freerdp_settings_get_bool(settings, FreeRDP_RemoteFxCodec) && (rfxID != 0)) + { + RFX_RECT rect = { 0 }; + + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_REMOTEFX) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_REMOTEFX"); + return FALSE; + } + + s = encoder->bs; + rect.x = nXSrc; + rect.y = nYSrc; + rect.width = nWidth; + rect.height = nHeight; + + const UINT32 MultifragMaxRequestSize = + freerdp_settings_get_uint32(settings, FreeRDP_MultifragMaxRequestSize); + RFX_MESSAGE_LIST* messages = + rfx_encode_messages(encoder->rfx, &rect, 1, pSrcData, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + nSrcStep, &numMessages, MultifragMaxRequestSize); + if (!messages) + { + WLog_ERR(TAG, "rfx_encode_messages failed"); + return FALSE; + } + + cmd.cmdType = CMDTYPE_STREAM_SURFACE_BITS; + WINPR_ASSERT(rfxID <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)rfxID; + cmd.destLeft = 0; + cmd.destTop = 0; + cmd.destRight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + cmd.destBottom = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + cmd.bmp.bpp = 32; + cmd.bmp.flags = 0; + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) <= UINT16_MAX); + WINPR_ASSERT(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) <= UINT16_MAX); + cmd.bmp.width = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + cmd.bmp.height = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + cmd.skipCompression = TRUE; + + for (size_t i = 0; i < numMessages; i++) + { + Stream_SetPosition(s, 0); + + const RFX_MESSAGE* msg = rfx_message_list_get(messages, i); + if (!rfx_write_message(encoder->rfx, s, msg)) + { + WLog_ERR(TAG, "rfx_write_message failed"); + ret = FALSE; + break; + } + + WINPR_ASSERT(Stream_GetPosition(s) <= UINT32_MAX); + cmd.bmp.bitmapDataLength = (UINT32)Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + first = (i == 0) ? TRUE : FALSE; + last = ((i + 1) == numMessages) ? TRUE : FALSE; + + if (!encoder->frameAck) + IFCALLRET(update->SurfaceBits, ret, update->context, &cmd); + else + IFCALLRET(update->SurfaceFrameBits, ret, update->context, &cmd, first, last, + frameId); + + if (!ret) + { + WLog_ERR(TAG, "Send surface bits(RemoteFxCodec) failed"); + break; + } + } + + rfx_message_list_free(messages); + } + else if (set_surface_bits_supported(settings) && + freerdp_settings_get_bool(settings, FreeRDP_NSCodec) && (nsID != 0)) + { + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_NSCODEC) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_NSCODEC"); + return FALSE; + } + + s = encoder->bs; + Stream_SetPosition(s, 0); + pSrcData = &pSrcData[(nYSrc * nSrcStep) + (nXSrc * 4)]; + nsc_compose_message(encoder->nsc, s, pSrcData, nWidth, nHeight, nSrcStep); + cmd.cmdType = CMDTYPE_SET_SURFACE_BITS; + cmd.bmp.bpp = 32; + WINPR_ASSERT(nsID <= UINT16_MAX); + cmd.bmp.codecID = (UINT16)nsID; + cmd.destLeft = nXSrc; + cmd.destTop = nYSrc; + cmd.destRight = cmd.destLeft + nWidth; + cmd.destBottom = cmd.destTop + nHeight; + cmd.bmp.width = nWidth; + cmd.bmp.height = nHeight; + WINPR_ASSERT(Stream_GetPosition(s) <= UINT32_MAX); + cmd.bmp.bitmapDataLength = (UINT32)Stream_GetPosition(s); + cmd.bmp.bitmapData = Stream_Buffer(s); + first = TRUE; + last = TRUE; + + if (!encoder->frameAck) + IFCALLRET(update->SurfaceBits, ret, update->context, &cmd); + else + IFCALLRET(update->SurfaceFrameBits, ret, update->context, &cmd, first, last, frameId); + + if (!ret) + { + WLog_ERR(TAG, "Send surface bits(NSCodec) failed"); + } + } + + return ret; +} + +/** + * Function description + * + * @return TRUE on success + */ +static BOOL shadow_client_send_bitmap_update(rdpShadowClient* client, BYTE* pSrcData, + UINT32 nSrcStep, UINT16 nXSrc, UINT16 nYSrc, + UINT16 nWidth, UINT16 nHeight) +{ + BOOL ret = TRUE; + BYTE* data = NULL; + BYTE* buffer = NULL; + UINT32 k = 0; + UINT32 yIdx = 0; + UINT32 xIdx = 0; + UINT32 rows = 0; + UINT32 cols = 0; + UINT32 DstSize = 0; + UINT32 SrcFormat = 0; + BITMAP_DATA* bitmap = NULL; + rdpContext* context = (rdpContext*)client; + UINT32 totalBitmapSize = 0; + UINT32 updateSizeEstimate = 0; + BITMAP_DATA* bitmapData = NULL; + BITMAP_UPDATE bitmapUpdate = { 0 }; + + if (!context || !pSrcData) + return FALSE; + + rdpUpdate* update = context->update; + rdpSettings* settings = context->settings; + rdpShadowEncoder* encoder = client->encoder; + + if (!update || !settings || !encoder) + return FALSE; + + const UINT32 maxUpdateSize = + freerdp_settings_get_uint32(settings, FreeRDP_MultifragMaxRequestSize); + if (freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth) < 32) + { + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_INTERLEAVED) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_INTERLEAVED"); + return FALSE; + } + } + else + { + if (shadow_encoder_prepare(encoder, FREERDP_CODEC_PLANAR) < 0) + { + WLog_ERR(TAG, "Failed to prepare encoder FREERDP_CODEC_PLANAR"); + return FALSE; + } + } + + SrcFormat = PIXEL_FORMAT_BGRX32; + + if ((nXSrc % 4) != 0) + { + nWidth += (nXSrc % 4); + nXSrc -= (nXSrc % 4); + } + + if ((nYSrc % 4) != 0) + { + nHeight += (nYSrc % 4); + nYSrc -= (nYSrc % 4); + } + + rows = (nHeight / 64) + ((nHeight % 64) ? 1 : 0); + cols = (nWidth / 64) + ((nWidth % 64) ? 1 : 0); + k = 0; + totalBitmapSize = 0; + bitmapUpdate.number = rows * cols; + + if (!(bitmapData = (BITMAP_DATA*)calloc(bitmapUpdate.number, sizeof(BITMAP_DATA)))) + return FALSE; + + bitmapUpdate.rectangles = bitmapData; + + if ((nWidth % 4) != 0) + { + nWidth += (4 - (nWidth % 4)); + } + + if ((nHeight % 4) != 0) + { + nHeight += (4 - (nHeight % 4)); + } + + for (yIdx = 0; yIdx < rows; yIdx++) + { + for (xIdx = 0; xIdx < cols; xIdx++) + { + bitmap = &bitmapData[k]; + bitmap->width = 64; + bitmap->height = 64; + bitmap->destLeft = nXSrc + (xIdx * 64); + bitmap->destTop = nYSrc + (yIdx * 64); + + if (((INT64)bitmap->destLeft + bitmap->width) > (nXSrc + nWidth)) + bitmap->width = (UINT32)(nXSrc + nWidth) - bitmap->destLeft; + + if (((INT64)bitmap->destTop + bitmap->height) > (nYSrc + nHeight)) + bitmap->height = (UINT32)(nYSrc + nHeight) - bitmap->destTop; + + bitmap->destRight = bitmap->destLeft + bitmap->width - 1; + bitmap->destBottom = bitmap->destTop + bitmap->height - 1; + bitmap->compressed = TRUE; + + if ((bitmap->width < 4) || (bitmap->height < 4)) + continue; + + if (freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth) < 32) + { + UINT32 bitsPerPixel = freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth); + UINT32 bytesPerPixel = (bitsPerPixel + 7) / 8; + DstSize = 64 * 64 * 4; + buffer = encoder->grid[k]; + interleaved_compress(encoder->interleaved, buffer, &DstSize, bitmap->width, + bitmap->height, pSrcData, SrcFormat, nSrcStep, + bitmap->destLeft, bitmap->destTop, NULL, bitsPerPixel); + bitmap->bitmapDataStream = buffer; + bitmap->bitmapLength = DstSize; + bitmap->bitsPerPixel = bitsPerPixel; + bitmap->cbScanWidth = bitmap->width * bytesPerPixel; + bitmap->cbUncompressedSize = bitmap->width * bitmap->height * bytesPerPixel; + } + else + { + UINT32 dstSize = 0; + buffer = encoder->grid[k]; + data = &pSrcData[(bitmap->destTop * nSrcStep) + (bitmap->destLeft * 4)]; + + buffer = + freerdp_bitmap_compress_planar(encoder->planar, data, SrcFormat, bitmap->width, + bitmap->height, nSrcStep, buffer, &dstSize); + bitmap->bitmapDataStream = buffer; + bitmap->bitmapLength = dstSize; + bitmap->bitsPerPixel = 32; + bitmap->cbScanWidth = bitmap->width * 4; + bitmap->cbUncompressedSize = bitmap->width * bitmap->height * 4; + } + + bitmap->cbCompFirstRowSize = 0; + bitmap->cbCompMainBodySize = bitmap->bitmapLength; + totalBitmapSize += bitmap->bitmapLength; + k++; + } + } + + bitmapUpdate.number = k; + updateSizeEstimate = totalBitmapSize + (k * bitmapUpdate.number) + 16; + + if (updateSizeEstimate > maxUpdateSize) + { + UINT32 i = 0; + UINT32 j = 0; + UINT32 updateSize = 0; + UINT32 newUpdateSize = 0; + BITMAP_DATA* fragBitmapData = NULL; + + if (k > 0) + fragBitmapData = (BITMAP_DATA*)calloc(k, sizeof(BITMAP_DATA)); + + if (!fragBitmapData) + { + WLog_ERR(TAG, "Failed to allocate memory for fragBitmapData"); + ret = FALSE; + goto out; + } + + bitmapUpdate.rectangles = fragBitmapData; + i = j = 0; + updateSize = 1024; + + while (i < k) + { + newUpdateSize = updateSize + (bitmapData[i].bitmapLength + 16); + + if (newUpdateSize < maxUpdateSize) + { + CopyMemory(&fragBitmapData[j++], &bitmapData[i++], sizeof(BITMAP_DATA)); + updateSize = newUpdateSize; + } + + if ((newUpdateSize >= maxUpdateSize) || (i + 1) >= k) + { + bitmapUpdate.number = j; + ret = BitmapUpdateProxy(update, context, &bitmapUpdate); + + if (!ret) + break; + + updateSize = 1024; + j = 0; + } + } + + free(fragBitmapData); + } + else + { + ret = BitmapUpdateProxy(update, context, &bitmapUpdate); + } + +out: + free(bitmapData); + return ret; +} + +/** + * Function description + * + * @return TRUE on success (or nothing need to be updated) + */ +static BOOL shadow_client_send_surface_update(rdpShadowClient* client, SHADOW_GFX_STATUS* pStatus) +{ + BOOL ret = TRUE; + INT64 nXSrc = 0; + INT64 nYSrc = 0; + INT64 nWidth = 0; + INT64 nHeight = 0; + rdpContext* context = (rdpContext*)client; + rdpSettings* settings = NULL; + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + REGION16 invalidRegion; + RECTANGLE_16 surfaceRect; + const RECTANGLE_16* extents = NULL; + BYTE* pSrcData = NULL; + UINT32 nSrcStep = 0; + UINT32 SrcFormat = 0; + UINT32 numRects = 0; + const RECTANGLE_16* rects = NULL; + + if (!context || !pStatus) + return FALSE; + + settings = context->settings; + server = client->server; + + if (!settings || !server) + return FALSE; + + surface = client->inLobby ? server->lobby : server->surface; + + if (!surface) + return FALSE; + + EnterCriticalSection(&(client->lock)); + region16_init(&invalidRegion); + region16_copy(&invalidRegion, &(client->invalidRegion)); + region16_clear(&(client->invalidRegion)); + LeaveCriticalSection(&(client->lock)); + + EnterCriticalSection(&surface->lock); + rects = region16_rects(&(surface->invalidRegion), &numRects); + + for (UINT32 index = 0; index < numRects; index++) + region16_union_rect(&invalidRegion, &invalidRegion, &rects[index]); + + surfaceRect.left = 0; + surfaceRect.top = 0; + WINPR_ASSERT(surface->width <= UINT16_MAX); + WINPR_ASSERT(surface->height <= UINT16_MAX); + surfaceRect.right = (UINT16)surface->width; + surfaceRect.bottom = (UINT16)surface->height; + region16_intersect_rect(&invalidRegion, &invalidRegion, &surfaceRect); + + if (server->shareSubRect) + { + region16_intersect_rect(&invalidRegion, &invalidRegion, &(server->subRect)); + } + + if (region16_is_empty(&invalidRegion)) + { + /* No image region need to be updated. Success */ + goto out; + } + + extents = region16_extents(&invalidRegion); + nXSrc = extents->left; + nYSrc = extents->top; + nWidth = extents->right - extents->left; + nHeight = extents->bottom - extents->top; + pSrcData = surface->data; + nSrcStep = surface->scanline; + SrcFormat = surface->format; + + /* Move to new pSrcData / nXSrc / nYSrc according to sub rect */ + if (server->shareSubRect) + { + INT32 subX = 0; + INT32 subY = 0; + subX = server->subRect.left; + subY = server->subRect.top; + nXSrc -= subX; + nYSrc -= subY; + WINPR_ASSERT(nXSrc >= 0); + WINPR_ASSERT(nXSrc <= UINT16_MAX); + WINPR_ASSERT(nYSrc >= 0); + WINPR_ASSERT(nYSrc <= UINT16_MAX); + pSrcData = &pSrcData[((UINT16)subY * nSrcStep) + ((UINT16)subX * 4U)]; + } + + // WLog_INFO(TAG, "shadow_client_send_surface_update: x: %" PRId64 " y: %" PRId64 " width: %" + // PRId64 " height: %" PRId64 " right: %" PRId64 " bottom: %" PRId64, nXSrc, nYSrc, nWidth, + // nHeight, nXSrc + nWidth, nYSrc + nHeight); + + if (freerdp_settings_get_bool(settings, FreeRDP_SupportGraphicsPipeline)) + { + if (pStatus->gfxOpened && client->areGfxCapsReady) + { + /* GFX/h264 always full screen encoded */ + nWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + nHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + /* Create primary surface if have not */ + if (!pStatus->gfxSurfaceCreated) + { + /* Only init surface when we have h264 supported */ + if (!(ret = shadow_client_rdpgfx_reset_graphic(client))) + goto out; + + if (!(ret = shadow_client_rdpgfx_new_surface(client))) + goto out; + + pStatus->gfxSurfaceCreated = TRUE; + } + + WINPR_ASSERT(nWidth >= 0); + WINPR_ASSERT(nWidth <= UINT16_MAX); + WINPR_ASSERT(nHeight >= 0); + WINPR_ASSERT(nHeight <= UINT16_MAX); + ret = shadow_client_send_surface_gfx(client, pSrcData, nSrcStep, SrcFormat, 0, 0, + (UINT16)nWidth, (UINT16)nHeight); + } + else + { + ret = TRUE; + } + } + else if (is_surface_command_supported(settings)) + { + WINPR_ASSERT(nXSrc >= 0); + WINPR_ASSERT(nXSrc <= UINT16_MAX); + WINPR_ASSERT(nYSrc >= 0); + WINPR_ASSERT(nYSrc <= UINT16_MAX); + WINPR_ASSERT(nWidth >= 0); + WINPR_ASSERT(nWidth <= UINT16_MAX); + WINPR_ASSERT(nHeight >= 0); + WINPR_ASSERT(nHeight <= UINT16_MAX); + ret = shadow_client_send_surface_bits(client, pSrcData, nSrcStep, (UINT16)nXSrc, + (UINT16)nYSrc, (UINT16)nWidth, (UINT16)nHeight); + } + else + { + WINPR_ASSERT(nXSrc >= 0); + WINPR_ASSERT(nXSrc <= UINT16_MAX); + WINPR_ASSERT(nYSrc >= 0); + WINPR_ASSERT(nYSrc <= UINT16_MAX); + WINPR_ASSERT(nWidth >= 0); + WINPR_ASSERT(nWidth <= UINT16_MAX); + WINPR_ASSERT(nHeight >= 0); + WINPR_ASSERT(nHeight <= UINT16_MAX); + ret = shadow_client_send_bitmap_update(client, pSrcData, nSrcStep, (UINT16)nXSrc, + (UINT16)nYSrc, (UINT16)nWidth, (UINT16)nHeight); + } + +out: + LeaveCriticalSection(&surface->lock); + region16_uninit(&invalidRegion); + return ret; +} + +/** + * Function description + * Notify client for resize. The new desktop width/height + * should have already been updated in rdpSettings. + * + * @return TRUE on success + */ +static BOOL shadow_client_send_resize(rdpShadowClient* client, SHADOW_GFX_STATUS* pStatus) +{ + rdpContext* context = (rdpContext*)client; + rdpSettings* settings = NULL; + freerdp_peer* peer = NULL; + + if (!context || !pStatus) + return FALSE; + + peer = context->peer; + settings = context->settings; + + if (!peer || !settings) + return FALSE; + + /** + * Unset client activated flag to avoid sending update message during + * resize. DesktopResize will reactive the client and + * shadow_client_activate would be invoked later. + */ + client->activated = FALSE; + + /* Close Gfx surfaces */ + if (pStatus->gfxSurfaceCreated) + { + if (!shadow_client_rdpgfx_release_surface(client)) + return FALSE; + + pStatus->gfxSurfaceCreated = FALSE; + } + + /* Send Resize */ + if (!shadow_send_desktop_resize(client)) + return FALSE; + shadow_reset_desktop_resize(client); + + /* Clear my invalidRegion. shadow_client_activate refreshes fullscreen */ + EnterCriticalSection(&(client->lock)); + region16_clear(&(client->invalidRegion)); + LeaveCriticalSection(&(client->lock)); + return TRUE; +} + +/** + * Function description + * Mark invalid region for client + * + * @return TRUE on success + */ +static BOOL shadow_client_surface_update(rdpShadowClient* client, REGION16* region) +{ + UINT32 numRects = 0; + const RECTANGLE_16* rects = NULL; + rects = region16_rects(region, &numRects); + shadow_client_mark_invalid(client, numRects, rects); + return TRUE; +} + +/** + * Function description + * Only union invalid region from server surface + * + * @return TRUE on success + */ +static INLINE BOOL shadow_client_no_surface_update(rdpShadowClient* client, + SHADOW_GFX_STATUS* pStatus) +{ + rdpShadowServer* server = NULL; + rdpShadowSurface* surface = NULL; + WINPR_UNUSED(pStatus); + WINPR_ASSERT(client); + server = client->server; + WINPR_ASSERT(server); + surface = client->inLobby ? server->lobby : server->surface; + EnterCriticalSection(&surface->lock); + const BOOL rc = shadow_client_surface_update(client, &(surface->invalidRegion)); + LeaveCriticalSection(&surface->lock); + return rc; +} + +static int shadow_client_subsystem_process_message(rdpShadowClient* client, wMessage* message) +{ + rdpContext* context = (rdpContext*)client; + rdpUpdate* update = NULL; + + WINPR_ASSERT(message); + WINPR_ASSERT(context); + update = context->update; + WINPR_ASSERT(update); + + /* FIXME: the pointer updates appear to be broken when used with bulk compression and mstsc */ + + switch (message->id) + { + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: + { + POINTER_POSITION_UPDATE pointerPosition; + const SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg = + (const SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*)message->wParam; + pointerPosition.xPos = msg->xPos; + pointerPosition.yPos = msg->yPos; + + WINPR_ASSERT(client->server); + if (client->server->shareSubRect) + { + pointerPosition.xPos -= client->server->subRect.left; + pointerPosition.yPos -= client->server->subRect.top; + } + + if (client->activated) + { + if ((msg->xPos != client->pointerX) || (msg->yPos != client->pointerY)) + { + WINPR_ASSERT(update->pointer); + IFCALL(update->pointer->PointerPosition, context, &pointerPosition); + client->pointerX = msg->xPos; + client->pointerY = msg->yPos; + } + } + + break; + } + + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: + { + POINTER_NEW_UPDATE pointerNew = { 0 }; + POINTER_COLOR_UPDATE* pointerColor = { 0 }; + POINTER_CACHED_UPDATE pointerCached = { 0 }; + const SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg = + (const SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)message->wParam; + + WINPR_ASSERT(msg); + pointerNew.xorBpp = 24; + pointerColor = &(pointerNew.colorPtrAttr); + pointerColor->cacheIndex = 0; + pointerColor->hotSpotX = WINPR_ASSERTING_INT_CAST(UINT16, msg->xHot); + pointerColor->hotSpotY = WINPR_ASSERTING_INT_CAST(UINT16, msg->yHot); + pointerColor->width = WINPR_ASSERTING_INT_CAST(UINT16, msg->width); + pointerColor->height = WINPR_ASSERTING_INT_CAST(UINT16, msg->height); + pointerColor->lengthAndMask = WINPR_ASSERTING_INT_CAST(UINT16, msg->lengthAndMask); + pointerColor->lengthXorMask = WINPR_ASSERTING_INT_CAST(UINT16, msg->lengthXorMask); + pointerColor->xorMaskData = msg->xorMaskData; + pointerColor->andMaskData = msg->andMaskData; + pointerCached.cacheIndex = pointerColor->cacheIndex; + + if (client->activated) + { + IFCALL(update->pointer->PointerNew, context, &pointerNew); + IFCALL(update->pointer->PointerCached, context, &pointerCached); + } + + break; + } + + case SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES_ID: + { + const SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES* msg = + (const SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES*)message->wParam; + + WINPR_ASSERT(msg); + + if (client->activated && client->rdpsnd && client->rdpsnd->Activated) + { + client->rdpsnd->src_format = msg->audio_format; + IFCALL(client->rdpsnd->SendSamples, client->rdpsnd, msg->buf, msg->nFrames, + msg->wTimestamp); + } + + break; + } + + case SHADOW_MSG_OUT_AUDIO_OUT_VOLUME_ID: + { + const SHADOW_MSG_OUT_AUDIO_OUT_VOLUME* msg = + (const SHADOW_MSG_OUT_AUDIO_OUT_VOLUME*)message->wParam; + + if (client->activated && client->rdpsnd && client->rdpsnd->Activated) + { + IFCALL(client->rdpsnd->SetVolume, client->rdpsnd, msg->left, msg->right); + } + + break; + } + + default: + WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", message->id); + break; + } + + shadow_client_free_queued_message(message); + return 1; +} + +static DWORD WINAPI shadow_client_thread(LPVOID arg) +{ + rdpShadowClient* client = (rdpShadowClient*)arg; + BOOL rc = FALSE; + DWORD status = 0; + wMessage message = { 0 }; + wMessage pointerPositionMsg = { 0 }; + wMessage pointerAlphaMsg = { 0 }; + wMessage audioVolumeMsg = { 0 }; + HANDLE ChannelEvent = 0; + void* UpdateSubscriber = NULL; + HANDLE UpdateEvent = 0; + freerdp_peer* peer = NULL; + rdpContext* context = NULL; + rdpSettings* settings = NULL; + rdpShadowServer* server = NULL; + rdpShadowSubsystem* subsystem = NULL; + wMessageQueue* MsgQueue = NULL; + /* This should only be visited in client thread */ + SHADOW_GFX_STATUS gfxstatus = { 0 }; + rdpUpdate* update = NULL; + + WINPR_ASSERT(client); + + MsgQueue = client->MsgQueue; + WINPR_ASSERT(MsgQueue); + + server = client->server; + WINPR_ASSERT(server); + subsystem = server->subsystem; + context = (rdpContext*)client; + peer = context->peer; + WINPR_ASSERT(peer); + WINPR_ASSERT(peer->context); + + settings = peer->context->settings; + WINPR_ASSERT(settings); + + peer->Capabilities = shadow_client_capabilities; + peer->PostConnect = shadow_client_post_connect; + peer->Activate = shadow_client_activate; + peer->Logon = shadow_client_logon; + shadow_input_register_callbacks(peer->context->input); + + rc = peer->Initialize(peer); + if (!rc) + goto out; + + update = peer->context->update; + WINPR_ASSERT(update); + + update->RefreshRect = shadow_client_refresh_rect; + update->SuppressOutput = shadow_client_suppress_output; + update->SurfaceFrameAcknowledge = shadow_client_surface_frame_acknowledge; + + if ((!client->vcm) || (!subsystem->updateEvent)) + goto out; + + UpdateSubscriber = shadow_multiclient_get_subscriber(subsystem->updateEvent); + + if (!UpdateSubscriber) + goto out; + + UpdateEvent = shadow_multiclient_getevent(UpdateSubscriber); + WINPR_ASSERT(UpdateEvent); + + ChannelEvent = WTSVirtualChannelManagerGetEventHandle(client->vcm); + WINPR_ASSERT(ChannelEvent); + + rc = freerdp_settings_set_bool(settings, FreeRDP_UnicodeInput, TRUE); + WINPR_ASSERT(rc); + rc = freerdp_settings_set_bool(settings, FreeRDP_HasHorizontalWheel, TRUE); + WINPR_ASSERT(rc); + rc = freerdp_settings_set_bool(settings, FreeRDP_HasExtendedMouseEvent, TRUE); + WINPR_ASSERT(rc); + rc = freerdp_settings_set_bool(settings, FreeRDP_SupportMonitorLayoutPdu, TRUE); + WINPR_ASSERT(rc); + while (1) + { + HANDLE events[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD nCount = 0; + events[nCount++] = UpdateEvent; + { + DWORD tmp = peer->GetEventHandles(peer, &events[nCount], 64 - nCount); + + if (tmp == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP transport event handles"); + goto fail; + } + + nCount += tmp; + } + events[nCount++] = ChannelEvent; + events[nCount++] = MessageQueue_Event(MsgQueue); + +#if defined(CHANNEL_RDPGFX_SERVER) + HANDLE gfxevent = rdpgfx_server_get_event_handle(client->rdpgfx); + + if (gfxevent) + events[nCount++] = gfxevent; +#endif + + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (status == WAIT_FAILED) + goto fail; + + if (WaitForSingleObject(UpdateEvent, 0) == WAIT_OBJECT_0) + { + /* The UpdateEvent means to start sending current frame. It is + * triggered from subsystem implementation and it should ensure + * that the screen and primary surface meta data (width, height, + * scanline, invalid region, etc) is not changed until it is reset + * (at shadow_multiclient_consume). As best practice, subsystem + * implementation should invoke shadow_subsystem_frame_update which + * triggers the event and then wait for completion */ + if (client->activated && !client->suppressOutput) + { + /* Send screen update or resize to this client */ + + /* Check resize */ + if (shadow_client_recalc_desktop_size(client)) + { + /* Screen size changed, do resize */ + if (!shadow_client_send_resize(client, &gfxstatus)) + { + WLog_ERR(TAG, "Failed to send resize message"); + break; + } + } + else + { + /* Send frame */ + if (!shadow_client_send_surface_update(client, &gfxstatus)) + { + WLog_ERR(TAG, "Failed to send surface update"); + break; + } + } + } + else + { + /* Our client don't receive graphic updates. Just save the invalid region */ + if (!shadow_client_no_surface_update(client, &gfxstatus)) + { + WLog_ERR(TAG, "Failed to handle surface update"); + break; + } + } + + /* + * The return value of shadow_multiclient_consume is whether or not + * the subscriber really consumes the event. It's not cared currently. + */ + (void)shadow_multiclient_consume(UpdateSubscriber); + } + + WINPR_ASSERT(peer->CheckFileDescriptor); + if (!peer->CheckFileDescriptor(peer)) + { + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + goto fail; + } + + if (client->activated && + WTSVirtualChannelManagerIsChannelJoined(client->vcm, DRDYNVC_SVC_CHANNEL_NAME)) + { + switch (WTSVirtualChannelManagerGetDrdynvcState(client->vcm)) + { + /* Dynamic channel status may have been changed after processing */ + case DRDYNVC_STATE_NONE: + + /* Call this routine to Initialize drdynvc channel */ + if (!WTSVirtualChannelManagerCheckFileDescriptor(client->vcm)) + { + WLog_ERR(TAG, "Failed to initialize drdynvc channel"); + goto fail; + } + + break; + + case DRDYNVC_STATE_READY: +#if defined(CHANNEL_AUDIN_SERVER) + if (client->audin && !IFCALLRESULT(TRUE, client->audin->IsOpen, client->audin)) + { + if (!IFCALLRESULT(FALSE, client->audin->Open, client->audin)) + { + WLog_ERR(TAG, "Failed to initialize audin channel"); + goto fail; + } + } +#endif + + /* Init RDPGFX dynamic channel */ + if (freerdp_settings_get_bool(settings, FreeRDP_SupportGraphicsPipeline) && + client->rdpgfx && !gfxstatus.gfxOpened) + { + client->rdpgfx->FrameAcknowledge = shadow_client_rdpgfx_frame_acknowledge; + client->rdpgfx->CapsAdvertise = shadow_client_rdpgfx_caps_advertise; + + if (!client->rdpgfx->Open(client->rdpgfx)) + { + WLog_WARN(TAG, "Failed to open GraphicsPipeline"); + if (!freerdp_settings_set_bool(settings, + FreeRDP_SupportGraphicsPipeline, FALSE)) + goto fail; + } + else + { + gfxstatus.gfxOpened = TRUE; + WLog_INFO(TAG, "Gfx Pipeline Opened"); + } + } + + break; + + default: + break; + } + } + + if (WaitForSingleObject(ChannelEvent, 0) == WAIT_OBJECT_0) + { + if (!WTSVirtualChannelManagerCheckFileDescriptor(client->vcm)) + { + WLog_ERR(TAG, "WTSVirtualChannelManagerCheckFileDescriptor failure"); + goto fail; + } + } + +#if defined(CHANNEL_RDPGFX_SERVER) + if (gfxevent) + { + if (WaitForSingleObject(gfxevent, 0) == WAIT_OBJECT_0) + { + rdpgfx_server_handle_messages(client->rdpgfx); + } + } +#endif + + if (WaitForSingleObject(MessageQueue_Event(MsgQueue), 0) == WAIT_OBJECT_0) + { + /* Drain messages. Pointer update could be accumulated. */ + pointerPositionMsg.id = 0; + pointerPositionMsg.Free = NULL; + pointerAlphaMsg.id = 0; + pointerAlphaMsg.Free = NULL; + audioVolumeMsg.id = 0; + audioVolumeMsg.Free = NULL; + + while (MessageQueue_Peek(MsgQueue, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + { + break; + } + + switch (message.id) + { + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&pointerPositionMsg); + pointerPositionMsg = message; + break; + + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&pointerAlphaMsg); + pointerAlphaMsg = message; + break; + + case SHADOW_MSG_OUT_AUDIO_OUT_VOLUME_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&audioVolumeMsg); + audioVolumeMsg = message; + break; + + default: + shadow_client_subsystem_process_message(client, &message); + break; + } + } + + if (message.id == WMQ_QUIT) + { + /* Release stored message */ + shadow_client_free_queued_message(&pointerPositionMsg); + shadow_client_free_queued_message(&pointerAlphaMsg); + shadow_client_free_queued_message(&audioVolumeMsg); + goto fail; + } + else + { + /* Process accumulated messages if needed */ + if (pointerPositionMsg.id) + { + shadow_client_subsystem_process_message(client, &pointerPositionMsg); + } + + if (pointerAlphaMsg.id) + { + shadow_client_subsystem_process_message(client, &pointerAlphaMsg); + } + + if (audioVolumeMsg.id) + { + shadow_client_subsystem_process_message(client, &audioVolumeMsg); + } + } + } + } + +fail: + + /* Free channels early because we establish channels in post connect */ +#if defined(CHANNEL_AUDIN_SERVER) + if (client->audin && !IFCALLRESULT(TRUE, client->audin->IsOpen, client->audin)) + { + if (!IFCALLRESULT(FALSE, client->audin->Close, client->audin)) + { + WLog_WARN(TAG, "AUDIN shutdown failure!"); + } + } +#endif + + if (gfxstatus.gfxOpened) + { + if (gfxstatus.gfxSurfaceCreated) + { + if (!shadow_client_rdpgfx_release_surface(client)) + WLog_WARN(TAG, "GFX release surface failure!"); + } + + WINPR_ASSERT(client->rdpgfx); + WINPR_ASSERT(client->rdpgfx->Close); + rc = client->rdpgfx->Close(client->rdpgfx); + WINPR_ASSERT(rc); + } + + shadow_client_channels_free(client); + + if (UpdateSubscriber) + { + shadow_multiclient_release_subscriber(UpdateSubscriber); + UpdateSubscriber = NULL; + } + + if (peer->connected && subsystem->ClientDisconnect) + { + subsystem->ClientDisconnect(subsystem, client); + } + +out: + WINPR_ASSERT(peer->Disconnect); + peer->Disconnect(peer); + freerdp_peer_context_free(peer); + freerdp_peer_free(peer); + ExitThread(0); + return 0; +} + +BOOL shadow_client_accepted(freerdp_listener* listener, freerdp_peer* peer) +{ + rdpShadowClient* client = NULL; + rdpShadowServer* server = NULL; + + if (!listener || !peer) + return FALSE; + + server = (rdpShadowServer*)listener->info; + WINPR_ASSERT(server); + + peer->ContextExtra = (void*)server; + peer->ContextSize = sizeof(rdpShadowClient); + peer->ContextNew = shadow_client_context_new; + peer->ContextFree = shadow_client_context_free; + + if (!freerdp_peer_context_new_ex(peer, server->settings)) + return FALSE; + + client = (rdpShadowClient*)peer->context; + WINPR_ASSERT(client); + + if (!(client->thread = CreateThread(NULL, 0, shadow_client_thread, client, 0, NULL))) + { + freerdp_peer_context_free(peer); + return FALSE; + } + else + { + /* Close the thread handle to make it detached. */ + (void)CloseHandle(client->thread); + client->thread = NULL; + } + + return TRUE; +} + +static void shadow_msg_out_addref(wMessage* message) +{ + SHADOW_MSG_OUT* msg = NULL; + + WINPR_ASSERT(message); + msg = (SHADOW_MSG_OUT*)message->wParam; + WINPR_ASSERT(msg); + + InterlockedIncrement(&(msg->refCount)); +} + +static void shadow_msg_out_release(wMessage* message) +{ + SHADOW_MSG_OUT* msg = NULL; + + WINPR_ASSERT(message); + msg = (SHADOW_MSG_OUT*)message->wParam; + WINPR_ASSERT(msg); + + if (InterlockedDecrement(&(msg->refCount)) <= 0) + { + IFCALL(msg->Free, message->id, msg); + } +} + +static BOOL shadow_client_dispatch_msg(rdpShadowClient* client, wMessage* message) +{ + if (!client || !message) + return FALSE; + + /* Add reference when it is posted */ + shadow_msg_out_addref(message); + + WINPR_ASSERT(client->MsgQueue); + if (MessageQueue_Dispatch(client->MsgQueue, message)) + return TRUE; + else + { + /* Release the reference since post failed */ + shadow_msg_out_release(message); + return FALSE; + } +} + +BOOL shadow_client_post_msg(rdpShadowClient* client, void* context, UINT32 type, + SHADOW_MSG_OUT* msg, void* lParam) +{ + wMessage message = { 0 }; + message.context = context; + message.id = type; + message.wParam = (void*)msg; + message.lParam = lParam; + message.Free = shadow_msg_out_release; + return shadow_client_dispatch_msg(client, &message); +} + +int shadow_client_boardcast_msg(rdpShadowServer* server, void* context, UINT32 type, + SHADOW_MSG_OUT* msg, void* lParam) +{ + wMessage message = { 0 }; + rdpShadowClient* client = NULL; + int count = 0; + + WINPR_ASSERT(server); + WINPR_ASSERT(msg); + + message.context = context; + message.id = type; + message.wParam = (void*)msg; + message.lParam = lParam; + message.Free = shadow_msg_out_release; + /* First add reference as we reference it in this function. + * Therefore it would not be free'ed during post. */ + shadow_msg_out_addref(&message); + + WINPR_ASSERT(server->clients); + ArrayList_Lock(server->clients); + + for (size_t index = 0; index < ArrayList_Count(server->clients); index++) + { + client = (rdpShadowClient*)ArrayList_GetItem(server->clients, index); + + if (shadow_client_dispatch_msg(client, &message)) + { + count++; + } + } + + ArrayList_Unlock(server->clients); + /* Release the reference for this function */ + shadow_msg_out_release(&message); + return count; +} + +int shadow_client_boardcast_quit(rdpShadowServer* server, int nExitCode) +{ + wMessageQueue* queue = NULL; + int count = 0; + + WINPR_ASSERT(server); + WINPR_ASSERT(server->clients); + + ArrayList_Lock(server->clients); + + for (size_t index = 0; index < ArrayList_Count(server->clients); index++) + { + queue = ((rdpShadowClient*)ArrayList_GetItem(server->clients, index))->MsgQueue; + + if (MessageQueue_PostQuit(queue, nExitCode)) + { + count++; + } + } + + ArrayList_Unlock(server->clients); + return count; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.h new file mode 100644 index 0000000000000000000000000000000000000000..0b03ed48cce4cbe37cfe11b6568e20aa48e7a6b8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_client.h @@ -0,0 +1,35 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_CLIENT_H +#define FREERDP_SERVER_SHADOW_CLIENT_H + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + BOOL shadow_client_accepted(freerdp_listener* listener, freerdp_peer* peer); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_CLIENT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.c new file mode 100644 index 0000000000000000000000000000000000000000..b3d596ffb8d3035829e96178b8811d249e2c0773 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.c @@ -0,0 +1,521 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "shadow.h" + +#include "shadow_encoder.h" + +#include +#define TAG CLIENT_TAG("shadow") + +UINT32 shadow_encoder_preferred_fps(rdpShadowEncoder* encoder) +{ + /* Return preferred fps calculated according to the last + * sent frame id and last client-acknowledged frame id. + */ + return encoder->fps; +} + +UINT32 shadow_encoder_inflight_frames(rdpShadowEncoder* encoder) +{ + /* Return in-flight frame count. + * If queueDepth is SUSPEND_FRAME_ACKNOWLEDGEMENT, count = 0 + * Otherwise, calculate count = + * - + * Note: This function is exported so that subsystem could + * implement its own strategy to tune fps. + */ + return (encoder->queueDepth == SUSPEND_FRAME_ACKNOWLEDGEMENT) + ? 0 + : encoder->frameId - encoder->lastAckframeId; +} + +UINT32 shadow_encoder_create_frame_id(rdpShadowEncoder* encoder) +{ + UINT32 frameId = 0; + UINT32 inFlightFrames = shadow_encoder_inflight_frames(encoder); + + /* + * Calculate preferred fps according to how much frames are + * in-progress. Note that it only works when subsystem implementation + * calls shadow_encoder_preferred_fps and takes the suggestion. + */ + if (inFlightFrames > 1) + { + encoder->fps = (100 / (inFlightFrames + 1) * encoder->maxFps) / 100; + } + else + { + encoder->fps += 2; + + if (encoder->fps > encoder->maxFps) + encoder->fps = encoder->maxFps; + } + + if (encoder->fps < 1) + encoder->fps = 1; + + frameId = ++encoder->frameId; + return frameId; +} + +static int shadow_encoder_init_grid(rdpShadowEncoder* encoder) +{ + UINT32 tileSize = 0; + UINT32 tileCount = 0; + encoder->gridWidth = ((encoder->width + (encoder->maxTileWidth - 1)) / encoder->maxTileWidth); + encoder->gridHeight = + ((encoder->height + (encoder->maxTileHeight - 1)) / encoder->maxTileHeight); + tileSize = encoder->maxTileWidth * encoder->maxTileHeight * 4; + tileCount = encoder->gridWidth * encoder->gridHeight; + encoder->gridBuffer = (BYTE*)calloc(tileSize, tileCount); + + if (!encoder->gridBuffer) + return -1; + + encoder->grid = (BYTE**)calloc(tileCount, sizeof(BYTE*)); + + if (!encoder->grid) + return -1; + + for (UINT32 i = 0; i < encoder->gridHeight; i++) + { + for (UINT32 j = 0; j < encoder->gridWidth; j++) + { + const size_t k = (1ULL * i * encoder->gridWidth) + j; + encoder->grid[k] = &(encoder->gridBuffer[k * tileSize]); + } + } + + return 0; +} + +static int shadow_encoder_uninit_grid(rdpShadowEncoder* encoder) +{ + if (encoder->gridBuffer) + { + free(encoder->gridBuffer); + encoder->gridBuffer = NULL; + } + + if (encoder->grid) + { + free((void*)encoder->grid); + encoder->grid = NULL; + } + + encoder->gridWidth = 0; + encoder->gridHeight = 0; + return 0; +} + +static int shadow_encoder_init_rfx(rdpShadowEncoder* encoder) +{ + if (!encoder->rfx) + encoder->rfx = rfx_context_new_ex( + TRUE, freerdp_settings_get_uint32(encoder->server->settings, FreeRDP_ThreadingFlags)); + + if (!encoder->rfx) + goto fail; + + if (!rfx_context_reset(encoder->rfx, encoder->width, encoder->height)) + goto fail; + + rfx_context_set_mode(encoder->rfx, freerdp_settings_get_uint32(encoder->server->settings, + FreeRDP_RemoteFxRlgrMode)); + rfx_context_set_pixel_format(encoder->rfx, PIXEL_FORMAT_BGRX32); + encoder->codecs |= FREERDP_CODEC_REMOTEFX; + return 1; +fail: + rfx_context_free(encoder->rfx); + return -1; +} + +static int shadow_encoder_init_nsc(rdpShadowEncoder* encoder) +{ + rdpContext* context = (rdpContext*)encoder->client; + rdpSettings* settings = context->settings; + + if (!encoder->nsc) + encoder->nsc = nsc_context_new(); + + if (!encoder->nsc) + goto fail; + + if (!nsc_context_reset(encoder->nsc, encoder->width, encoder->height)) + goto fail; + + if (!nsc_context_set_parameters( + encoder->nsc, NSC_COLOR_LOSS_LEVEL, + freerdp_settings_get_uint32(settings, FreeRDP_NSCodecColorLossLevel))) + goto fail; + if (!nsc_context_set_parameters( + encoder->nsc, NSC_ALLOW_SUBSAMPLING, + freerdp_settings_get_bool(settings, FreeRDP_NSCodecAllowSubsampling) ? 1 : 0)) + goto fail; + if (!nsc_context_set_parameters( + encoder->nsc, NSC_DYNAMIC_COLOR_FIDELITY, + !freerdp_settings_get_bool(settings, FreeRDP_NSCodecAllowDynamicColorFidelity))) + goto fail; + if (!nsc_context_set_parameters(encoder->nsc, NSC_COLOR_FORMAT, PIXEL_FORMAT_BGRX32)) + goto fail; + encoder->codecs |= FREERDP_CODEC_NSCODEC; + return 1; +fail: + nsc_context_free(encoder->nsc); + return -1; +} + +static int shadow_encoder_init_planar(rdpShadowEncoder* encoder) +{ + DWORD planarFlags = 0; + rdpContext* context = (rdpContext*)encoder->client; + rdpSettings* settings = context->settings; + + if (freerdp_settings_get_bool(settings, FreeRDP_DrawAllowSkipAlpha)) + planarFlags |= PLANAR_FORMAT_HEADER_NA; + + planarFlags |= PLANAR_FORMAT_HEADER_RLE; + + if (!encoder->planar) + { + encoder->planar = freerdp_bitmap_planar_context_new(planarFlags, encoder->maxTileWidth, + encoder->maxTileHeight); + } + + if (!encoder->planar) + goto fail; + + if (!freerdp_bitmap_planar_context_reset(encoder->planar, encoder->maxTileWidth, + encoder->maxTileHeight)) + goto fail; + + encoder->codecs |= FREERDP_CODEC_PLANAR; + return 1; +fail: + freerdp_bitmap_planar_context_free(encoder->planar); + return -1; +} + +static int shadow_encoder_init_interleaved(rdpShadowEncoder* encoder) +{ + if (!encoder->interleaved) + encoder->interleaved = bitmap_interleaved_context_new(TRUE); + + if (!encoder->interleaved) + goto fail; + + if (!bitmap_interleaved_context_reset(encoder->interleaved)) + goto fail; + + encoder->codecs |= FREERDP_CODEC_INTERLEAVED; + return 1; +fail: + bitmap_interleaved_context_free(encoder->interleaved); + return -1; +} + +static int shadow_encoder_init_h264(rdpShadowEncoder* encoder) +{ + if (!encoder->h264) + encoder->h264 = h264_context_new(TRUE); + + if (!encoder->h264) + goto fail; + + if (!h264_context_reset(encoder->h264, encoder->width, encoder->height)) + goto fail; + + if (!h264_context_set_option(encoder->h264, H264_CONTEXT_OPTION_RATECONTROL, + encoder->server->h264RateControlMode)) + goto fail; + if (!h264_context_set_option(encoder->h264, H264_CONTEXT_OPTION_BITRATE, + encoder->server->h264BitRate)) + goto fail; + if (!h264_context_set_option(encoder->h264, H264_CONTEXT_OPTION_FRAMERATE, + encoder->server->h264FrameRate)) + goto fail; + if (!h264_context_set_option(encoder->h264, H264_CONTEXT_OPTION_QP, encoder->server->h264QP)) + goto fail; + + encoder->codecs |= FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444; + return 1; +fail: + h264_context_free(encoder->h264); + return -1; +} + +static int shadow_encoder_init_progressive(rdpShadowEncoder* encoder) +{ + WINPR_ASSERT(encoder); + if (!encoder->progressive) + encoder->progressive = progressive_context_new(TRUE); + + if (!encoder->progressive) + goto fail; + + if (!progressive_context_reset(encoder->progressive)) + goto fail; + + encoder->codecs |= FREERDP_CODEC_PROGRESSIVE; + return 1; +fail: + progressive_context_free(encoder->progressive); + return -1; +} + +static int shadow_encoder_init(rdpShadowEncoder* encoder) +{ + encoder->width = encoder->server->screen->width; + encoder->height = encoder->server->screen->height; + encoder->maxTileWidth = 64; + encoder->maxTileHeight = 64; + shadow_encoder_init_grid(encoder); + + if (!encoder->bs) + encoder->bs = Stream_New(NULL, 4ULL * encoder->maxTileWidth * encoder->maxTileHeight); + + if (!encoder->bs) + return -1; + + return 1; +} + +static int shadow_encoder_uninit_rfx(rdpShadowEncoder* encoder) +{ + if (encoder->rfx) + { + rfx_context_free(encoder->rfx); + encoder->rfx = NULL; + } + + encoder->codecs &= (UINT32)~FREERDP_CODEC_REMOTEFX; + return 1; +} + +static int shadow_encoder_uninit_nsc(rdpShadowEncoder* encoder) +{ + if (encoder->nsc) + { + nsc_context_free(encoder->nsc); + encoder->nsc = NULL; + } + + encoder->codecs &= (UINT32)~FREERDP_CODEC_NSCODEC; + return 1; +} + +static int shadow_encoder_uninit_planar(rdpShadowEncoder* encoder) +{ + if (encoder->planar) + { + freerdp_bitmap_planar_context_free(encoder->planar); + encoder->planar = NULL; + } + + encoder->codecs &= (UINT32)~FREERDP_CODEC_PLANAR; + return 1; +} + +static int shadow_encoder_uninit_interleaved(rdpShadowEncoder* encoder) +{ + if (encoder->interleaved) + { + bitmap_interleaved_context_free(encoder->interleaved); + encoder->interleaved = NULL; + } + + encoder->codecs &= (UINT32)~FREERDP_CODEC_INTERLEAVED; + return 1; +} + +static int shadow_encoder_uninit_h264(rdpShadowEncoder* encoder) +{ + if (encoder->h264) + { + h264_context_free(encoder->h264); + encoder->h264 = NULL; + } + + encoder->codecs &= (UINT32) ~(FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444); + return 1; +} + +static int shadow_encoder_uninit_progressive(rdpShadowEncoder* encoder) +{ + WINPR_ASSERT(encoder); + if (encoder->progressive) + { + progressive_context_free(encoder->progressive); + encoder->progressive = NULL; + } + + encoder->codecs &= (UINT32)~FREERDP_CODEC_PROGRESSIVE; + return 1; +} + +static int shadow_encoder_uninit(rdpShadowEncoder* encoder) +{ + shadow_encoder_uninit_grid(encoder); + + if (encoder->bs) + { + Stream_Free(encoder->bs, TRUE); + encoder->bs = NULL; + } + + shadow_encoder_uninit_rfx(encoder); + + shadow_encoder_uninit_nsc(encoder); + + shadow_encoder_uninit_planar(encoder); + + shadow_encoder_uninit_interleaved(encoder); + shadow_encoder_uninit_h264(encoder); + + shadow_encoder_uninit_progressive(encoder); + + return 1; +} + +int shadow_encoder_reset(rdpShadowEncoder* encoder) +{ + int status = 0; + UINT32 codecs = encoder->codecs; + rdpContext* context = (rdpContext*)encoder->client; + rdpSettings* settings = context->settings; + status = shadow_encoder_uninit(encoder); + + if (status < 0) + return -1; + + status = shadow_encoder_init(encoder); + + if (status < 0) + return -1; + + status = shadow_encoder_prepare(encoder, codecs); + + if (status < 0) + return -1; + + encoder->fps = 16; + encoder->maxFps = 32; + encoder->frameId = 0; + encoder->lastAckframeId = 0; + encoder->frameAck = freerdp_settings_get_bool(settings, FreeRDP_SurfaceFrameMarkerEnabled); + return 1; +} + +int shadow_encoder_prepare(rdpShadowEncoder* encoder, UINT32 codecs) +{ + int status = 0; + + if ((codecs & FREERDP_CODEC_REMOTEFX) && !(encoder->codecs & FREERDP_CODEC_REMOTEFX)) + { + WLog_DBG(TAG, "initializing RemoteFX encoder"); + status = shadow_encoder_init_rfx(encoder); + + if (status < 0) + return -1; + } + + if ((codecs & FREERDP_CODEC_NSCODEC) && !(encoder->codecs & FREERDP_CODEC_NSCODEC)) + { + WLog_DBG(TAG, "initializing NSCodec encoder"); + status = shadow_encoder_init_nsc(encoder); + + if (status < 0) + return -1; + } + + if ((codecs & FREERDP_CODEC_PLANAR) && !(encoder->codecs & FREERDP_CODEC_PLANAR)) + { + WLog_DBG(TAG, "initializing planar bitmap encoder"); + status = shadow_encoder_init_planar(encoder); + + if (status < 0) + return -1; + } + + if ((codecs & FREERDP_CODEC_INTERLEAVED) && !(encoder->codecs & FREERDP_CODEC_INTERLEAVED)) + { + WLog_DBG(TAG, "initializing interleaved bitmap encoder"); + status = shadow_encoder_init_interleaved(encoder); + + if (status < 0) + return -1; + } + + if ((codecs & (FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444)) && + !(encoder->codecs & (FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444))) + { + WLog_DBG(TAG, "initializing H.264 encoder"); + status = shadow_encoder_init_h264(encoder); + + if (status < 0) + return -1; + } + + if ((codecs & FREERDP_CODEC_PROGRESSIVE) && !(encoder->codecs & FREERDP_CODEC_PROGRESSIVE)) + { + WLog_DBG(TAG, "initializing progressive encoder"); + status = shadow_encoder_init_progressive(encoder); + + if (status < 0) + return -1; + } + + return 1; +} + +rdpShadowEncoder* shadow_encoder_new(rdpShadowClient* client) +{ + rdpShadowEncoder* encoder = NULL; + rdpShadowServer* server = client->server; + encoder = (rdpShadowEncoder*)calloc(1, sizeof(rdpShadowEncoder)); + + if (!encoder) + return NULL; + + encoder->client = client; + encoder->server = server; + encoder->fps = 16; + encoder->maxFps = 32; + + if (shadow_encoder_init(encoder) < 0) + { + shadow_encoder_free(encoder); + return NULL; + } + + return encoder; +} + +void shadow_encoder_free(rdpShadowEncoder* encoder) +{ + if (!encoder) + return; + + shadow_encoder_uninit(encoder); + free(encoder); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.h new file mode 100644 index 0000000000000000000000000000000000000000..dfe00f3ba4373b0847574472f1824e5b4cda8862 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encoder.h @@ -0,0 +1,81 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_ENCODER_H +#define FREERDP_SERVER_SHADOW_ENCODER_H + +#include +#include + +#include +#include + +#include + +struct rdp_shadow_encoder +{ + rdpShadowClient* client; + rdpShadowServer* server; + + UINT32 width; + UINT32 height; + UINT32 codecs; + + BYTE** grid; + UINT32 gridWidth; + UINT32 gridHeight; + BYTE* gridBuffer; + UINT32 maxTileWidth; + UINT32 maxTileHeight; + + wStream* bs; + + RFX_CONTEXT* rfx; + NSC_CONTEXT* nsc; + BITMAP_PLANAR_CONTEXT* planar; + BITMAP_INTERLEAVED_CONTEXT* interleaved; + H264_CONTEXT* h264; + PROGRESSIVE_CONTEXT* progressive; + + UINT32 fps; + UINT32 maxFps; + BOOL frameAck; + UINT32 frameId; + UINT32 lastAckframeId; + UINT32 queueDepth; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + int shadow_encoder_reset(rdpShadowEncoder* encoder); + int shadow_encoder_prepare(rdpShadowEncoder* encoder, UINT32 codecs); + UINT32 shadow_encoder_create_frame_id(rdpShadowEncoder* encoder); + + void shadow_encoder_free(rdpShadowEncoder* encoder); + + WINPR_ATTR_MALLOC(shadow_encoder_free, 1) + rdpShadowEncoder* shadow_encoder_new(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_ENCODER_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.c new file mode 100644 index 0000000000000000000000000000000000000000..8a3a468362bc065f82896191ad495bead16bacbd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.c @@ -0,0 +1,129 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include +#include "shadow.h" + +#include "shadow_encomsp.h" + +#define TAG SERVER_TAG("shadow") + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +encomsp_change_participant_control_level(EncomspServerContext* context, + ENCOMSP_CHANGE_PARTICIPANT_CONTROL_LEVEL_PDU* pdu) +{ + BOOL inLobby = 0; + BOOL mayView = 0; + BOOL mayInteract = 0; + rdpShadowClient* client = (rdpShadowClient*)context->custom; + + WLog_INFO(TAG, + "ChangeParticipantControlLevel: ParticipantId: %" PRIu32 " Flags: 0x%04" PRIX16 "", + pdu->ParticipantId, pdu->Flags); + + mayView = (pdu->Flags & ENCOMSP_MAY_VIEW) ? TRUE : FALSE; + mayInteract = (pdu->Flags & ENCOMSP_MAY_INTERACT) ? TRUE : FALSE; + + if (mayInteract && !mayView) + mayView = TRUE; /* may interact implies may view */ + + if (mayInteract) + { + if (!client->mayInteract) + { + /* request interact + view */ + client->mayInteract = TRUE; + client->mayView = TRUE; + } + } + else if (mayView) + { + if (client->mayInteract) + { + /* release interact */ + client->mayInteract = FALSE; + } + else if (!client->mayView) + { + /* request view */ + client->mayView = TRUE; + } + } + else + { + if (client->mayInteract) + { + /* release interact + view */ + client->mayView = FALSE; + client->mayInteract = FALSE; + } + else if (client->mayView) + { + /* release view */ + client->mayView = FALSE; + client->mayInteract = FALSE; + } + } + + inLobby = client->mayView ? FALSE : TRUE; + + if (inLobby != client->inLobby) + { + shadow_encoder_reset(client->encoder); + client->inLobby = inLobby; + } + + return CHANNEL_RC_OK; +} + +int shadow_client_encomsp_init(rdpShadowClient* client) +{ + EncomspServerContext* encomsp = NULL; + + encomsp = client->encomsp = encomsp_server_context_new(client->vcm); + + encomsp->rdpcontext = &client->context; + + encomsp->custom = (void*)client; + + encomsp->ChangeParticipantControlLevel = encomsp_change_participant_control_level; + + if (client->encomsp) + client->encomsp->Start(client->encomsp); + + return 1; +} + +void shadow_client_encomsp_uninit(rdpShadowClient* client) +{ + if (client->encomsp) + { + client->encomsp->Stop(client->encomsp); + encomsp_server_context_free(client->encomsp); + client->encomsp = NULL; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.h new file mode 100644 index 0000000000000000000000000000000000000000..6562e25aefc53c210612ff3bb9ec771f576e9daf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_encomsp.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_ENCOMSP_H +#define FREERDP_SERVER_SHADOW_ENCOMSP_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + int shadow_client_encomsp_init(rdpShadowClient* client); + void shadow_client_encomsp_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_ENCOMSP_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.c new file mode 100644 index 0000000000000000000000000000000000000000..97268b8aef77a09a7f8c2351bdf01f2acdae8db6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.c @@ -0,0 +1,114 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include "shadow.h" + +static BOOL shadow_input_synchronize_event(rdpInput* input, UINT32 flags) +{ + rdpShadowClient* client = (rdpShadowClient*)input->context; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (!client->mayInteract) + return TRUE; + + return IFCALLRESULT(TRUE, subsystem->SynchronizeEvent, subsystem, client, flags); +} + +static BOOL shadow_input_keyboard_event(rdpInput* input, UINT16 flags, UINT8 code) +{ + rdpShadowClient* client = (rdpShadowClient*)input->context; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (!client->mayInteract) + return TRUE; + + return IFCALLRESULT(TRUE, subsystem->KeyboardEvent, subsystem, client, flags, code); +} + +static BOOL shadow_input_unicode_keyboard_event(rdpInput* input, UINT16 flags, UINT16 code) +{ + rdpShadowClient* client = (rdpShadowClient*)input->context; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (!client->mayInteract) + return TRUE; + + return IFCALLRESULT(TRUE, subsystem->UnicodeKeyboardEvent, subsystem, client, flags, code); +} + +static BOOL shadow_input_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + rdpShadowClient* client = (rdpShadowClient*)input->context; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (client->server->shareSubRect) + { + x += client->server->subRect.left; + y += client->server->subRect.top; + } + + if (!(flags & PTR_FLAGS_WHEEL)) + { + client->pointerX = x; + client->pointerY = y; + + if ((client->pointerX == subsystem->pointerX) && (client->pointerY == subsystem->pointerY)) + { + flags &= ~PTR_FLAGS_MOVE; + + if (!(flags & (PTR_FLAGS_BUTTON1 | PTR_FLAGS_BUTTON2 | PTR_FLAGS_BUTTON3))) + return TRUE; + } + } + + if (!client->mayInteract) + return TRUE; + + return IFCALLRESULT(TRUE, subsystem->MouseEvent, subsystem, client, flags, x, y); +} + +static BOOL shadow_input_extended_mouse_event(rdpInput* input, UINT16 flags, UINT16 x, UINT16 y) +{ + rdpShadowClient* client = (rdpShadowClient*)input->context; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (client->server->shareSubRect) + { + x += client->server->subRect.left; + y += client->server->subRect.top; + } + + client->pointerX = x; + client->pointerY = y; + + if (!client->mayInteract) + return TRUE; + + return IFCALLRESULT(TRUE, subsystem->ExtendedMouseEvent, subsystem, client, flags, x, y); +} + +void shadow_input_register_callbacks(rdpInput* input) +{ + input->SynchronizeEvent = shadow_input_synchronize_event; + input->KeyboardEvent = shadow_input_keyboard_event; + input->UnicodeKeyboardEvent = shadow_input_unicode_keyboard_event; + input->MouseEvent = shadow_input_mouse_event; + input->ExtendedMouseEvent = shadow_input_extended_mouse_event; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.h new file mode 100644 index 0000000000000000000000000000000000000000..8bde31ce4eb4834c55ff8649aafc911900754b83 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_input.h @@ -0,0 +1,35 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_INPUT_H +#define FREERDP_SERVER_SHADOW_INPUT_H + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_input_register_callbacks(rdpInput* input); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_INPUT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.c new file mode 100644 index 0000000000000000000000000000000000000000..032a2eac4ac8e6f63ad725521fd71970f952fca3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.c @@ -0,0 +1,88 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#include "shadow.h" + +#include "shadow_lobby.h" + +BOOL shadow_client_init_lobby(rdpShadowServer* server) +{ + BOOL rc = FALSE; + int width = 0; + int height = 0; + rdtkSurface* surface = NULL; + RECTANGLE_16 invalidRect; + rdpShadowSurface* lobby = server->lobby; + + if (!lobby) + return FALSE; + + rdtkEngine* engine = rdtk_engine_new(); + if (!engine) + return FALSE; + + EnterCriticalSection(&lobby->lock); + surface = + rdtk_surface_new(engine, lobby->data, WINPR_ASSERTING_INT_CAST(uint16_t, lobby->width), + WINPR_ASSERTING_INT_CAST(uint16_t, lobby->height), lobby->scanline); + if (!surface) + goto fail; + + invalidRect.left = 0; + invalidRect.top = 0; + WINPR_ASSERT(lobby->width <= UINT16_MAX); + WINPR_ASSERT(lobby->height <= UINT16_MAX); + invalidRect.right = (UINT16)lobby->width; + invalidRect.bottom = (UINT16)lobby->height; + if (server->shareSubRect) + { + /* If we have shared sub rect setting, only fill shared rect */ + rectangles_intersection(&invalidRect, &(server->subRect), &invalidRect); + } + + width = invalidRect.right - invalidRect.left; + height = invalidRect.bottom - invalidRect.top; + WINPR_ASSERT(width <= UINT16_MAX); + WINPR_ASSERT(width >= 0); + WINPR_ASSERT(height <= UINT16_MAX); + WINPR_ASSERT(height >= 0); + rdtk_surface_fill(surface, invalidRect.left, invalidRect.top, (UINT16)width, (UINT16)height, + 0x3BB9FF); + + rdtk_label_draw(surface, invalidRect.left, invalidRect.top, (UINT16)width, (UINT16)height, NULL, + "Welcome", 0, 0); + // rdtk_button_draw(surface, 16, 64, 128, 32, NULL, "button"); + // rdtk_text_field_draw(surface, 16, 128, 128, 32, NULL, "text field"); + + rdtk_surface_free(surface); + + region16_union_rect(&(lobby->invalidRegion), &(lobby->invalidRegion), &invalidRect); + + rc = TRUE; +fail: + LeaveCriticalSection(&lobby->lock); + rdtk_engine_free(engine); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.h new file mode 100644 index 0000000000000000000000000000000000000000..37ad9cf69895ad91489db0d5456da4593df075d2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_lobby.h @@ -0,0 +1,40 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_LOBBY_H +#define FREERDP_SERVER_SHADOW_LOBBY_H + +#include + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + BOOL shadow_client_init_lobby(rdpShadowServer* server); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_LOBBY_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.c new file mode 100644 index 0000000000000000000000000000000000000000..905f5aa741eaa9c8e38533f9f60106302341a47c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.c @@ -0,0 +1,341 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * 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 + +#include +#include +#include "shadow.h" + +#define TAG SERVER_TAG("shadow.mcevent") + +struct rdp_shadow_multiclient_event +{ + HANDLE event; /* Kickoff event */ + HANDLE barrierEvent; /* Represents that all clients have consumed event */ + HANDLE doneEvent; /* Event handling finished. Server could continue */ + wArrayList* subscribers; + CRITICAL_SECTION lock; + int consuming; + int waiting; + + /* For debug */ + int eventid; +}; + +struct rdp_shadow_multiclient_subscriber +{ + rdpShadowMultiClientEvent* ref; + BOOL pleaseHandle; /* Indicate if server expects my handling in this turn */ +}; + +rdpShadowMultiClientEvent* shadow_multiclient_new(void) +{ + rdpShadowMultiClientEvent* event = + (rdpShadowMultiClientEvent*)calloc(1, sizeof(rdpShadowMultiClientEvent)); + if (!event) + goto out_error; + + event->event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!event->event) + goto out_free; + + event->barrierEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!event->barrierEvent) + goto out_free_event; + + event->doneEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!event->doneEvent) + goto out_free_barrierEvent; + + event->subscribers = ArrayList_New(TRUE); + if (!event->subscribers) + goto out_free_doneEvent; + + if (!InitializeCriticalSectionAndSpinCount(&(event->lock), 4000)) + goto out_free_subscribers; + + event->consuming = 0; + event->waiting = 0; + event->eventid = 0; + (void)SetEvent(event->doneEvent); + return event; + +out_free_subscribers: + ArrayList_Free(event->subscribers); +out_free_doneEvent: + (void)CloseHandle(event->doneEvent); +out_free_barrierEvent: + (void)CloseHandle(event->barrierEvent); +out_free_event: + (void)CloseHandle(event->event); +out_free: + free(event); +out_error: + return (rdpShadowMultiClientEvent*)NULL; +} + +void shadow_multiclient_free(rdpShadowMultiClientEvent* event) +{ + if (!event) + return; + + DeleteCriticalSection(&(event->lock)); + + ArrayList_Free(event->subscribers); + (void)CloseHandle(event->doneEvent); + (void)CloseHandle(event->barrierEvent); + (void)CloseHandle(event->event); + free(event); +} + +static void Publish(rdpShadowMultiClientEvent* event) +{ + wArrayList* subscribers = NULL; + struct rdp_shadow_multiclient_subscriber* subscriber = NULL; + + subscribers = event->subscribers; + + WINPR_ASSERT(event->consuming == 0); + + /* Count subscribing clients */ + ArrayList_Lock(subscribers); + for (size_t i = 0; i < ArrayList_Count(subscribers); i++) + { + subscriber = (struct rdp_shadow_multiclient_subscriber*)ArrayList_GetItem(subscribers, i); + /* Set flag to subscriber: I acknowledge and please handle */ + subscriber->pleaseHandle = TRUE; + event->consuming++; + } + ArrayList_Unlock(subscribers); + + if (event->consuming > 0) + { + event->eventid = (event->eventid & 0xff) + 1; + WLog_VRB(TAG, "Server published event %d. %d clients.\n", event->eventid, event->consuming); + (void)ResetEvent(event->doneEvent); + (void)SetEvent(event->event); + } +} + +static void WaitForSubscribers(rdpShadowMultiClientEvent* event) +{ + if (event->consuming > 0) + { + /* Wait for clients done */ + WLog_VRB(TAG, "Server wait event %d. %d clients.\n", event->eventid, event->consuming); + LeaveCriticalSection(&(event->lock)); + (void)WaitForSingleObject(event->doneEvent, INFINITE); + EnterCriticalSection(&(event->lock)); + WLog_VRB(TAG, "Server quit event %d. %d clients.\n", event->eventid, event->consuming); + } + + /* Last subscriber should have already reset the event */ + WINPR_ASSERT(WaitForSingleObject(event->event, 0) != WAIT_OBJECT_0); +} + +void shadow_multiclient_publish(rdpShadowMultiClientEvent* event) +{ + if (!event) + return; + + EnterCriticalSection(&(event->lock)); + Publish(event); + LeaveCriticalSection(&(event->lock)); +} +void shadow_multiclient_wait(rdpShadowMultiClientEvent* event) +{ + if (!event) + return; + + EnterCriticalSection(&(event->lock)); + WaitForSubscribers(event); + LeaveCriticalSection(&(event->lock)); +} +void shadow_multiclient_publish_and_wait(rdpShadowMultiClientEvent* event) +{ + if (!event) + return; + + EnterCriticalSection(&(event->lock)); + Publish(event); + WaitForSubscribers(event); + LeaveCriticalSection(&(event->lock)); +} + +static BOOL Consume(struct rdp_shadow_multiclient_subscriber* subscriber, BOOL wait) +{ + rdpShadowMultiClientEvent* event = subscriber->ref; + BOOL ret = FALSE; + + if (WaitForSingleObject(event->event, 0) == WAIT_OBJECT_0 && subscriber->pleaseHandle) + { + /* Consume my share. Server is waiting for us */ + event->consuming--; + ret = TRUE; + } + + WINPR_ASSERT(event->consuming >= 0); + + if (event->consuming == 0) + { + /* Last client reset event before notify clients to continue */ + (void)ResetEvent(event->event); + + if (event->waiting > 0) + { + /* Notify other clients to continue */ + (void)SetEvent(event->barrierEvent); + } + else + { + /* Only one client. Notify server directly */ + (void)SetEvent(event->doneEvent); + } + } + else /* (event->consuming > 0) */ + { + if (wait) + { + /* + * This client need to wait. That means the client will + * continue waiting for other clients to finish. + * The last client should reset barrierEvent. + */ + event->waiting++; + LeaveCriticalSection(&(event->lock)); + (void)WaitForSingleObject(event->barrierEvent, INFINITE); + EnterCriticalSection(&(event->lock)); + event->waiting--; + if (event->waiting == 0) + { + /* + * This is last client waiting for barrierEvent. + * We can now discard barrierEvent and notify + * server to continue. + */ + (void)ResetEvent(event->barrierEvent); + (void)SetEvent(event->doneEvent); + } + } + } + + return ret; +} + +void* shadow_multiclient_get_subscriber(rdpShadowMultiClientEvent* event) +{ + struct rdp_shadow_multiclient_subscriber* subscriber = NULL; + + if (!event) + return NULL; + + EnterCriticalSection(&(event->lock)); + + subscriber = (struct rdp_shadow_multiclient_subscriber*)calloc( + 1, sizeof(struct rdp_shadow_multiclient_subscriber)); + if (!subscriber) + goto out_error; + + subscriber->ref = event; + subscriber->pleaseHandle = FALSE; + + if (!ArrayList_Append(event->subscribers, subscriber)) + goto out_free; + + WLog_VRB(TAG, "Get subscriber %p. Wait event %d. %d clients.\n", (void*)subscriber, + event->eventid, event->consuming); + (void)Consume(subscriber, TRUE); + WLog_VRB(TAG, "Get subscriber %p. Quit event %d. %d clients.\n", (void*)subscriber, + event->eventid, event->consuming); + + LeaveCriticalSection(&(event->lock)); + + return subscriber; + +out_free: + free(subscriber); +out_error: + LeaveCriticalSection(&(event->lock)); + return NULL; +} + +/* + * Consume my share and release my register + * If we have update event and pleaseHandle flag + * We need to consume. Anyway we need to clear + * pleaseHandle flag + */ +void shadow_multiclient_release_subscriber(void* subscriber) +{ + struct rdp_shadow_multiclient_subscriber* s = NULL; + rdpShadowMultiClientEvent* event = NULL; + + if (!subscriber) + return; + + s = (struct rdp_shadow_multiclient_subscriber*)subscriber; + event = s->ref; + + EnterCriticalSection(&(event->lock)); + + WLog_VRB(TAG, "Release Subscriber %p. Drop event %d. %d clients.\n", subscriber, event->eventid, + event->consuming); + (void)Consume(s, FALSE); + WLog_VRB(TAG, "Release Subscriber %p. Quit event %d. %d clients.\n", subscriber, event->eventid, + event->consuming); + + ArrayList_Remove(event->subscribers, subscriber); + + LeaveCriticalSection(&(event->lock)); + + free(subscriber); +} + +BOOL shadow_multiclient_consume(void* subscriber) +{ + struct rdp_shadow_multiclient_subscriber* s = NULL; + rdpShadowMultiClientEvent* event = NULL; + BOOL ret = FALSE; + + if (!subscriber) + return ret; + + s = (struct rdp_shadow_multiclient_subscriber*)subscriber; + event = s->ref; + + EnterCriticalSection(&(event->lock)); + + WLog_VRB(TAG, "Subscriber %p wait event %d. %d clients.\n", subscriber, event->eventid, + event->consuming); + ret = Consume(s, TRUE); + WLog_VRB(TAG, "Subscriber %p quit event %d. %d clients.\n", subscriber, event->eventid, + event->consuming); + + LeaveCriticalSection(&(event->lock)); + + return ret; +} + +HANDLE shadow_multiclient_getevent(void* subscriber) +{ + if (!subscriber) + return (HANDLE)NULL; + + return ((struct rdp_shadow_multiclient_subscriber*)subscriber)->ref->event; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.h new file mode 100644 index 0000000000000000000000000000000000000000..c78b9206f3a1b32b1845a54656e436becba3336b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_mcevent.h @@ -0,0 +1,56 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * 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 FREERDP_SERVER_SHADOW_MCEVENT_H +#define FREERDP_SERVER_SHADOW_MCEVENT_H + +#include + +#include +#include +#include + +/* + * This file implemented a model that an event is consumed + * by multiple clients. All clients should wait others before continue + * Server should wait for all clients before continue + */ + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_multiclient_free(rdpShadowMultiClientEvent* event); + + WINPR_ATTR_MALLOC(shadow_multiclient_free, 1) + rdpShadowMultiClientEvent* shadow_multiclient_new(void); + + void shadow_multiclient_publish(rdpShadowMultiClientEvent* event); + void shadow_multiclient_wait(rdpShadowMultiClientEvent* event); + void shadow_multiclient_publish_and_wait(rdpShadowMultiClientEvent* event); + void* shadow_multiclient_get_subscriber(rdpShadowMultiClientEvent* event); + void shadow_multiclient_release_subscriber(void* subscriber); + BOOL shadow_multiclient_consume(void* subscriber); + HANDLE shadow_multiclient_getevent(void* subscriber); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_MCEVENT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.c new file mode 100644 index 0000000000000000000000000000000000000000..781ee20d220c2221b37ab3c82e751d5efe950eef --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.c @@ -0,0 +1,59 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2016 Jiang Zihao + * + * 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 + +#include +#include "shadow.h" + +#include "shadow_rdpgfx.h" + +int shadow_client_rdpgfx_init(rdpShadowClient* client) +{ + WINPR_ASSERT(client); + + if (!freerdp_settings_get_bool(client->context.settings, FreeRDP_SupportGraphicsPipeline)) + return 1; + +#if defined(CHANNEL_RDPGFX_SERVER) + RdpgfxServerContext* rdpgfx = client->rdpgfx = rdpgfx_server_context_new(client->vcm); + if (!rdpgfx) + return 0; + + rdpgfx->rdpcontext = &client->context; + + rdpgfx->custom = client; + + if (!IFCALLRESULT(CHANNEL_RC_OK, rdpgfx->Initialize, rdpgfx, TRUE)) + return -1; +#endif + + return 1; +} + +void shadow_client_rdpgfx_uninit(rdpShadowClient* client) +{ + WINPR_ASSERT(client); + if (client->rdpgfx) + { +#if defined(CHANNEL_RDPGFX_SERVER) + rdpgfx_server_context_free(client->rdpgfx); +#endif + client->rdpgfx = NULL; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.h new file mode 100644 index 0000000000000000000000000000000000000000..ce81376fefb68b4e47ea80533b3d2b00adad1e26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpgfx.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2016 Jiang Zihao + * + * 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 FREERDP_SERVER_SHADOW_RDPGFX_H +#define FREERDP_SERVER_SHADOW_RDPGFX_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + int shadow_client_rdpgfx_init(rdpShadowClient* client); + void shadow_client_rdpgfx_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_RDPGFX_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.c new file mode 100644 index 0000000000000000000000000000000000000000..f69d80d3e80b165da5161f4bec3420ecfddb3e63 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.c @@ -0,0 +1,90 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * 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 + +#include +#include +#include + +#include +#include +#include + +#include "shadow.h" + +#include "shadow_rdpsnd.h" + +#define TAG SERVER_TAG("shadow") + +static void rdpsnd_activated(RdpsndServerContext* context) +{ + for (size_t i = 0; i < context->num_client_formats; i++) + { + for (size_t j = 0; j < context->num_server_formats; j++) + { + if (audio_format_compatible(&context->server_formats[j], &context->client_formats[i])) + { + context->SelectFormat(context, WINPR_ASSERTING_INT_CAST(UINT16, i)); + return; + } + } + } + + WLog_ERR(TAG, "Could not agree on a audio format with the server\n"); +} + +int shadow_client_rdpsnd_init(rdpShadowClient* client) +{ + RdpsndServerContext* rdpsnd = NULL; + rdpsnd = client->rdpsnd = rdpsnd_server_context_new(client->vcm); + + if (!rdpsnd) + { + return 0; + } + + rdpsnd->data = client; + + if (client->subsystem->rdpsndFormats) + { + rdpsnd->server_formats = client->subsystem->rdpsndFormats; + rdpsnd->num_server_formats = client->subsystem->nRdpsndFormats; + } + else + { + rdpsnd->num_server_formats = server_rdpsnd_get_formats(&rdpsnd->server_formats); + } + + if (rdpsnd->num_server_formats > 0) + rdpsnd->src_format = &rdpsnd->server_formats[0]; + + rdpsnd->Activated = rdpsnd_activated; + rdpsnd->Initialize(rdpsnd, TRUE); + return 1; +} + +void shadow_client_rdpsnd_uninit(rdpShadowClient* client) +{ + if (client->rdpsnd) + { + client->rdpsnd->Stop(client->rdpsnd); + rdpsnd_server_context_free(client->rdpsnd); + client->rdpsnd = NULL; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.h new file mode 100644 index 0000000000000000000000000000000000000000..ae34ea3831b816a94c3d5eed021dd5194dbcf628 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_rdpsnd.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * 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 FREERDP_SERVER_SHADOW_RDPSND_H +#define FREERDP_SERVER_SHADOW_RDPSND_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + int shadow_client_rdpsnd_init(rdpShadowClient* client); + void shadow_client_rdpsnd_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_RDPSND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.c new file mode 100644 index 0000000000000000000000000000000000000000..19fb9f36e7c74f7f7ab29cb14216e68e3bb54ee9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.c @@ -0,0 +1,50 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include "shadow.h" + +#include "shadow_remdesk.h" + +int shadow_client_remdesk_init(rdpShadowClient* client) +{ + RemdeskServerContext* remdesk = NULL; + + remdesk = client->remdesk = remdesk_server_context_new(client->vcm); + remdesk->rdpcontext = &client->context; + + remdesk->custom = (void*)client; + + if (client->remdesk) + client->remdesk->Start(client->remdesk); + + return 1; +} + +void shadow_client_remdesk_uninit(rdpShadowClient* client) +{ + if (client->remdesk) + { + client->remdesk->Stop(client->remdesk); + remdesk_server_context_free(client->remdesk); + client->remdesk = NULL; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.h new file mode 100644 index 0000000000000000000000000000000000000000..88fdba04ae1a473fb65c661a00b71a08b6318c0d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_remdesk.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_REMDESK_H +#define FREERDP_SERVER_SHADOW_REMDESK_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + int shadow_client_remdesk_init(rdpShadowClient* client); + void shadow_client_remdesk_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_REMDESK_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.c new file mode 100644 index 0000000000000000000000000000000000000000..f5a44d0ba62427f247750882f9a910c13b6f9e9a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.c @@ -0,0 +1,163 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "shadow_surface.h" + +#include "shadow_screen.h" +#include "shadow_lobby.h" + +rdpShadowScreen* shadow_screen_new(rdpShadowServer* server) +{ + WINPR_ASSERT(server); + WINPR_ASSERT(server->subsystem); + + rdpShadowScreen* screen = (rdpShadowScreen*)calloc(1, sizeof(rdpShadowScreen)); + + if (!screen) + goto fail; + + screen->server = server; + rdpShadowSubsystem* subsystem = server->subsystem; + + if (!InitializeCriticalSectionAndSpinCount(&(screen->lock), 4000)) + goto fail; + + region16_init(&(screen->invalidRegion)); + + WINPR_ASSERT(subsystem->selectedMonitor < ARRAYSIZE(subsystem->monitors)); + const MONITOR_DEF* primary = &(subsystem->monitors[subsystem->selectedMonitor]); + WINPR_ASSERT(primary); + + INT64 x = primary->left; + INT64 y = primary->top; + INT64 width = primary->right - primary->left + 1; + INT64 height = primary->bottom - primary->top + 1; + + WINPR_ASSERT(x >= 0); + WINPR_ASSERT(x <= UINT16_MAX); + WINPR_ASSERT(y >= 0); + WINPR_ASSERT(y <= UINT16_MAX); + WINPR_ASSERT(width >= 0); + WINPR_ASSERT(width <= UINT16_MAX); + WINPR_ASSERT(height >= 0); + WINPR_ASSERT(height <= UINT16_MAX); + + screen->width = (UINT16)width; + screen->height = (UINT16)height; + + screen->primary = + shadow_surface_new(server, (UINT16)x, (UINT16)y, (UINT16)width, (UINT16)height); + + if (!screen->primary) + goto fail; + + server->surface = screen->primary; + + screen->lobby = shadow_surface_new(server, (UINT16)x, (UINT16)y, (UINT16)width, (UINT16)height); + + if (!screen->lobby) + goto fail; + + server->lobby = screen->lobby; + + if (!shadow_client_init_lobby(server)) + goto fail; + + return screen; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + shadow_screen_free(screen); + WINPR_PRAGMA_DIAG_POP + + return NULL; +} + +void shadow_screen_free(rdpShadowScreen* screen) +{ + if (!screen) + return; + + DeleteCriticalSection(&(screen->lock)); + + region16_uninit(&(screen->invalidRegion)); + + if (screen->primary) + { + shadow_surface_free(screen->primary); + screen->primary = NULL; + } + + if (screen->lobby) + { + shadow_surface_free(screen->lobby); + screen->lobby = NULL; + } + + free(screen); +} + +BOOL shadow_screen_resize(rdpShadowScreen* screen) +{ + if (!screen) + return FALSE; + + WINPR_ASSERT(screen->server); + + rdpShadowSubsystem* subsystem = screen->server->subsystem; + WINPR_ASSERT(subsystem); + WINPR_ASSERT(subsystem->monitors); + + MONITOR_DEF* primary = &(subsystem->monitors[subsystem->selectedMonitor]); + WINPR_ASSERT(primary); + + const INT32 x = primary->left; + const INT32 y = primary->top; + const INT32 width = primary->right - primary->left + 1; + const INT32 height = primary->bottom - primary->top + 1; + + WINPR_ASSERT(x >= 0); + WINPR_ASSERT(x <= UINT16_MAX); + WINPR_ASSERT(y >= 0); + WINPR_ASSERT(y <= UINT16_MAX); + WINPR_ASSERT(width >= 0); + WINPR_ASSERT(width <= UINT16_MAX); + WINPR_ASSERT(height >= 0); + WINPR_ASSERT(height <= UINT16_MAX); + + if (shadow_surface_resize(screen->primary, (UINT16)x, (UINT16)y, (UINT16)width, + (UINT16)height) && + shadow_surface_resize(screen->lobby, (UINT16)x, (UINT16)y, (UINT16)width, (UINT16)height)) + { + if (((UINT32)width != screen->width) || ((UINT32)height != screen->height)) + { + /* screen size is changed. Store new size and reinit lobby */ + screen->width = (UINT32)width; + screen->height = (UINT32)height; + shadow_client_init_lobby(screen->server); + } + return TRUE; + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.h new file mode 100644 index 0000000000000000000000000000000000000000..a7bf7894bc2816fb14532bb7dd0114616fc400a1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_screen.h @@ -0,0 +1,55 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_SCREEN_H +#define FREERDP_SERVER_SHADOW_SCREEN_H + +#include + +#include +#include + +struct rdp_shadow_screen +{ + rdpShadowServer* server; + + UINT32 width; + UINT32 height; + + CRITICAL_SECTION lock; + REGION16 invalidRegion; + + rdpShadowSurface* primary; + rdpShadowSurface* lobby; +}; + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_screen_free(rdpShadowScreen* screen); + + WINPR_ATTR_MALLOC(shadow_screen_free, 1) + rdpShadowScreen* shadow_screen_new(rdpShadowServer* server); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_SCREEN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_server.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_server.c new file mode 100644 index 0000000000000000000000000000000000000000..6e7a90dad3e3fe2b32ad7b9cc856427502086b1a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_server.c @@ -0,0 +1,1026 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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 + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#ifndef _WIN32 +#include +#include +#endif + +#include "shadow.h" + +#define TAG SERVER_TAG("shadow") + +static const char bind_address[] = "bind-address,"; + +#define fail_at(arg, rc) fail_at_((arg), (rc), __FILE__, __func__, __LINE__) +static int fail_at_(const COMMAND_LINE_ARGUMENT_A* arg, int rc, const char* file, const char* fkt, + size_t line) +{ + const DWORD level = WLOG_ERROR; + wLog* log = WLog_Get(TAG); + if (WLog_IsLevelActive(log, level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, level, line, file, fkt, + "Command line parsing failed at '%s' value '%s' [%d]", arg->Name, + arg->Value, rc); + return rc; +} + +static int shadow_server_print_command_line_help(int argc, char** argv, + COMMAND_LINE_ARGUMENT_A* largs) +{ + char* str = NULL; + size_t length = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + if ((argc < 1) || !largs || !argv) + return -1; + + char* path = winpr_GetConfigFilePath(TRUE, "SAM"); + printf("Usage: %s [options]\n", argv[0]); + printf("\n"); + printf("Notes: By default NLA security is active.\n"); + printf("\tIn this mode a SAM database is required.\n"); + printf("\tProvide one with /sam-file:\n"); + printf("\telse the default path %s is used.\n", path); + printf("\tIf there is no existing SAM file authentication for all users will fail.\n"); + printf( + "\n\tIf authentication against PAM is desired, start with -sec-nla (requires compiled in " + "support for PAM)\n\n"); + printf("Syntax:\n"); + printf(" /flag (enables flag)\n"); + printf(" /option: (specifies option with value)\n"); + printf(" +toggle -toggle (enables or disables toggle, where '/' is a synonym of '+')\n"); + printf("\n"); + free(path); + + arg = largs; + + do + { + if (arg->Flags & COMMAND_LINE_VALUE_FLAG) + { + printf(" %s", "/"); + printf("%-20s\n", arg->Name); + printf("\t%s\n", arg->Text); + } + else if ((arg->Flags & COMMAND_LINE_VALUE_REQUIRED) || + (arg->Flags & COMMAND_LINE_VALUE_OPTIONAL)) + { + printf(" %s", "/"); + + if (arg->Format) + { + length = (strlen(arg->Name) + strlen(arg->Format) + 2); + str = (char*)malloc(length + 1); + + if (!str) + return -1; + + (void)sprintf_s(str, length + 1, "%s:%s", arg->Name, arg->Format); + (void)printf("%-20s\n", str); + free(str); + } + else + { + printf("%-20s\n", arg->Name); + } + + printf("\t%s\n", arg->Text); + } + else if (arg->Flags & COMMAND_LINE_VALUE_BOOL) + { + length = strlen(arg->Name) + 32; + str = (char*)malloc(length + 1); + + if (!str) + return -1; + + (void)sprintf_s(str, length + 1, "%s (default:%s)", arg->Name, + arg->Default ? "on" : "off"); + (void)printf(" %s", arg->Default ? "-" : "+"); + (void)printf("%-20s\n", str); + free(str); + (void)printf("\t%s\n", arg->Text); + } + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + return 1; +} + +int shadow_server_command_line_status_print(rdpShadowServer* server, int argc, char** argv, + int status, COMMAND_LINE_ARGUMENT_A* cargs) +{ + WINPR_UNUSED(server); + + if (status == COMMAND_LINE_STATUS_PRINT_VERSION) + { + printf("FreeRDP version %s (git %s)\n", FREERDP_VERSION_FULL, FREERDP_GIT_REVISION); + return COMMAND_LINE_STATUS_PRINT_VERSION; + } + else if (status == COMMAND_LINE_STATUS_PRINT_BUILDCONFIG) + { + printf("%s\n", freerdp_get_build_config()); + return COMMAND_LINE_STATUS_PRINT_BUILDCONFIG; + } + else if (status == COMMAND_LINE_STATUS_PRINT) + { + return COMMAND_LINE_STATUS_PRINT; + } + else if (status < 0) + { + if (shadow_server_print_command_line_help(argc, argv, cargs) < 0) + return -1; + + return COMMAND_LINE_STATUS_PRINT_HELP; + } + + return 1; +} + +int shadow_server_parse_command_line(rdpShadowServer* server, int argc, char** argv, + COMMAND_LINE_ARGUMENT_A* cargs) +{ + int status = 0; + DWORD flags = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + rdpSettings* settings = server->settings; + + if ((argc < 2) || !argv || !cargs) + return 1; + + CommandLineClearArgumentsA(cargs); + flags = COMMAND_LINE_SEPARATOR_COLON; + flags |= COMMAND_LINE_SIGIL_SLASH | COMMAND_LINE_SIGIL_PLUS_MINUS; + status = CommandLineParseArgumentsA(argc, argv, cargs, flags, server, NULL, NULL); + + if (status < 0) + return status; + + arg = cargs; + errno = 0; + + do + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "port") + { + long val = strtol(arg->Value, NULL, 0); + + if ((errno != 0) || (val <= 0) || (val > UINT16_MAX)) + return fail_at(arg, COMMAND_LINE_ERROR); + + server->port = (DWORD)val; + } + CommandLineSwitchCase(arg, "ipc-socket") + { + /* /bind-address is incompatible */ + if (server->ipcSocket) + return fail_at(arg, COMMAND_LINE_ERROR); + server->ipcSocket = _strdup(arg->Value); + + if (!server->ipcSocket) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "bind-address") + { + int rc = 0; + size_t len = strlen(arg->Value) + sizeof(bind_address); + /* /ipc-socket is incompatible */ + if (server->ipcSocket) + return fail_at(arg, COMMAND_LINE_ERROR); + server->ipcSocket = calloc(len, sizeof(CHAR)); + + if (!server->ipcSocket) + return fail_at(arg, COMMAND_LINE_ERROR); + + rc = _snprintf(server->ipcSocket, len, "%s%s", bind_address, arg->Value); + if ((rc < 0) || ((size_t)rc != len - 1)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "may-view") + { + server->mayView = arg->Value ? TRUE : FALSE; + } + CommandLineSwitchCase(arg, "may-interact") + { + server->mayInteract = arg->Value ? TRUE : FALSE; + } + CommandLineSwitchCase(arg, "max-connections") + { + errno = 0; + unsigned long val = strtoul(arg->Value, NULL, 0); + + if ((errno != 0) || (val > UINT32_MAX)) + return fail_at(arg, COMMAND_LINE_ERROR); + server->maxClientsConnected = val; + } + CommandLineSwitchCase(arg, "rect") + { + char* p = NULL; + char* tok[4]; + long x = -1; + long y = -1; + long w = -1; + long h = -1; + char* str = _strdup(arg->Value); + + if (!str) + return fail_at(arg, COMMAND_LINE_ERROR); + + tok[0] = p = str; + p = strchr(p + 1, ','); + + if (!p) + { + free(str); + return fail_at(arg, COMMAND_LINE_ERROR); + } + + *p++ = '\0'; + tok[1] = p; + p = strchr(p + 1, ','); + + if (!p) + { + free(str); + return fail_at(arg, COMMAND_LINE_ERROR); + } + + *p++ = '\0'; + tok[2] = p; + p = strchr(p + 1, ','); + + if (!p) + { + free(str); + return fail_at(arg, COMMAND_LINE_ERROR); + } + + *p++ = '\0'; + tok[3] = p; + x = strtol(tok[0], NULL, 0); + + if (errno != 0) + goto fail; + + y = strtol(tok[1], NULL, 0); + + if (errno != 0) + goto fail; + + w = strtol(tok[2], NULL, 0); + + if (errno != 0) + goto fail; + + h = strtol(tok[3], NULL, 0); + + if (errno != 0) + goto fail; + + fail: + free(str); + + if ((x < 0) || (y < 0) || (w < 1) || (h < 1) || (errno != 0)) + return fail_at(arg, COMMAND_LINE_ERROR); + + if ((x > UINT16_MAX) || (y > UINT16_MAX) || (x + w > UINT16_MAX) || + (y + h > UINT16_MAX)) + return fail_at(arg, COMMAND_LINE_ERROR); + server->subRect.left = (UINT16)x; + server->subRect.top = (UINT16)y; + server->subRect.right = (UINT16)(x + w); + server->subRect.bottom = (UINT16)(y + h); + server->shareSubRect = TRUE; + } + CommandLineSwitchCase(arg, "auth") + { + server->authentication = arg->Value ? TRUE : FALSE; + } + CommandLineSwitchCase(arg, "remote-guard") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteCredentialGuard, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sec") + { + if (strcmp("rdp", arg->Value) == 0) /* Standard RDP */ + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_ExtSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_UseRdpSecurityLayer, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + else if (strcmp("tls", arg->Value) == 0) /* TLS */ + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_ExtSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + else if (strcmp("nla", arg->Value) == 0) /* NLA */ + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_ExtSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + else if (strcmp("ext", arg->Value) == 0) /* NLA Extended */ + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_ExtSecurity, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + else + { + WLog_ERR(TAG, "unknown protocol security: %s", arg->Value); + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + } + CommandLineSwitchCase(arg, "sec-rdp") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sec-tls") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sec-nla") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sec-ext") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_ExtSecurity, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sam-file") + { + if (!freerdp_settings_set_string(settings, FreeRDP_NtlmSamFile, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "log-level") + { + wLog* root = WLog_GetRoot(); + + if (!WLog_SetStringLogLevel(root, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "log-filters") + { + if (!WLog_AddStringLogFilters(arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "nsc") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "rfx") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-progressive") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxProgressive, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-rfx") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-planar") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxPlanar, arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-avc420") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxH264, arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-avc444") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, + arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, arg->Value ? TRUE : FALSE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "keytab") + { + if (!freerdp_settings_set_string(settings, FreeRDP_KerberosKeytab, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "ccache") + { + if (!freerdp_settings_set_string(settings, FreeRDP_KerberosCache, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "tls-secrets-file") + { + if (!freerdp_settings_set_string(settings, FreeRDP_TlsSecretsFile, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchDefault(arg) + { + } + CommandLineSwitchEnd(arg) + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + arg = CommandLineFindArgumentA(cargs, "monitors"); + + if (arg && (arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + { + UINT32 numMonitors = 0; + MONITOR_DEF monitors[16] = { 0 }; + numMonitors = shadow_enum_monitors(monitors, 16); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + /* Select monitors */ + long val = strtol(arg->Value, NULL, 0); + + if ((val < 0) || (errno != 0) || ((UINT32)val >= numMonitors)) + status = COMMAND_LINE_STATUS_PRINT; + + server->selectedMonitor = (UINT32)val; + } + else + { + /* List monitors */ + + for (UINT32 index = 0; index < numMonitors; index++) + { + const MONITOR_DEF* monitor = &monitors[index]; + const INT64 width = monitor->right - monitor->left + 1; + const INT64 height = monitor->bottom - monitor->top + 1; + WLog_INFO(TAG, " %s [%d] %" PRId64 "x%" PRId64 "\t+%" PRId32 "+%" PRId32 "", + (monitor->flags == 1) ? "*" : " ", index, width, height, monitor->left, + monitor->top); + } + + status = COMMAND_LINE_STATUS_PRINT; + } + } + + /* If we want to disable authentication we need to ensure that NLA security + * is not activated. Only TLS and RDP security allow anonymous login. + */ + if (!server->authentication) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, FALSE)) + return COMMAND_LINE_ERROR; + } + return status; +} + +static DWORD WINAPI shadow_server_thread(LPVOID arg) +{ + rdpShadowServer* server = (rdpShadowServer*)arg; + BOOL running = TRUE; + DWORD status = 0; + freerdp_listener* listener = server->listener; + shadow_subsystem_start(server->subsystem); + + while (running) + { + HANDLE events[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD nCount = 0; + events[nCount++] = server->StopEvent; + nCount += listener->GetEventHandles(listener, &events[nCount], ARRAYSIZE(events) - nCount); + + if (nCount <= 1) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + switch (status) + { + case WAIT_FAILED: + case WAIT_OBJECT_0: + running = FALSE; + break; + + default: + { + if (!listener->CheckFileDescriptor(listener)) + { + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + running = FALSE; + } + else + { +#ifdef _WIN32 + Sleep(100); /* FIXME: listener event handles */ +#endif + } + } + break; + } + } + + listener->Close(listener); + shadow_subsystem_stop(server->subsystem); + + /* Signal to the clients that server is being stopped and wait for them + * to disconnect. */ + if (shadow_client_boardcast_quit(server, 0)) + { + while (ArrayList_Count(server->clients) > 0) + { + Sleep(100); + } + } + + ExitThread(0); + return 0; +} + +static BOOL open_port(rdpShadowServer* server, char* address) +{ + BOOL status = 0; + char* modaddr = address; + + if (modaddr) + { + if (modaddr[0] == '[') + { + char* end = strchr(address, ']'); + if (!end) + { + WLog_ERR(TAG, "Could not parse bind-address %s", address); + return -1; + } + *end++ = '\0'; + if (strlen(end) > 0) + { + WLog_ERR(TAG, "Excess data after IPv6 address: '%s'", end); + return -1; + } + modaddr++; + } + } + status = server->listener->Open(server->listener, modaddr, (UINT16)server->port); + + if (!status) + { + WLog_ERR(TAG, + "Problem creating TCP listener. (Port already used or insufficient permissions?)"); + } + + return status; +} + +int shadow_server_start(rdpShadowServer* server) +{ + BOOL ipc = 0; + BOOL status = 0; + WSADATA wsaData; + + if (!server) + return -1; + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) + return -1; + +#ifndef _WIN32 + (void)signal(SIGPIPE, SIG_IGN); +#endif + server->screen = shadow_screen_new(server); + + if (!server->screen) + { + WLog_ERR(TAG, "screen_new failed"); + return -1; + } + + server->capture = shadow_capture_new(server); + + if (!server->capture) + { + WLog_ERR(TAG, "capture_new failed"); + return -1; + } + + /* Bind magic: + * + * empty ... bind TCP all + * ... bind local (IPC) + * bind-socket,
... bind TCP to specified interface + */ + ipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket, + strnlen(bind_address, sizeof(bind_address))) != 0); + if (!ipc) + { + size_t count = 0; + + char** ptr = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count); + if (!ptr || (count <= 1)) + { + if (server->ipcSocket == NULL) + { + if (!open_port(server, NULL)) + { + CommandLineParserFree(ptr); + return -1; + } + } + else + { + CommandLineParserFree(ptr); + return -1; + } + } + + WINPR_ASSERT(ptr || (count == 0)); + for (size_t x = 1; x < count; x++) + { + BOOL success = open_port(server, ptr[x]); + if (!success) + { + CommandLineParserFree(ptr); + return -1; + } + } + CommandLineParserFree(ptr); + } + else + { + status = server->listener->OpenLocal(server->listener, server->ipcSocket); + + if (!status) + { + WLog_ERR(TAG, "Problem creating local socket listener. (Port already used or " + "insufficient permissions?)"); + return -1; + } + } + + if (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL))) + { + return -1; + } + + return 0; +} + +int shadow_server_stop(rdpShadowServer* server) +{ + if (!server) + return -1; + + if (server->thread) + { + (void)SetEvent(server->StopEvent); + (void)WaitForSingleObject(server->thread, INFINITE); + (void)CloseHandle(server->thread); + server->thread = NULL; + if (server->listener && server->listener->Close) + server->listener->Close(server->listener); + } + + if (server->screen) + { + shadow_screen_free(server->screen); + server->screen = NULL; + } + + if (server->capture) + { + shadow_capture_free(server->capture); + server->capture = NULL; + } + + return 0; +} + +static int shadow_server_init_config_path(rdpShadowServer* server) +{ + if (!server->ConfigPath) + { + char* configHome = freerdp_settings_get_config_path(); + + if (configHome) + { + if (!winpr_PathFileExists(configHome) && !winpr_PathMakePath(configHome, 0)) + { + WLog_ERR(TAG, "Failed to create directory '%s'", configHome); + free(configHome); + return -1; + } + + server->ConfigPath = configHome; + } + } + + if (!server->ConfigPath) + return -1; /* no usable config path */ + + return 1; +} + +static BOOL shadow_server_create_certificate(rdpShadowServer* server, const char* filepath) +{ + BOOL rc = FALSE; + char* makecert_argv[6] = { "makecert", "-rdp", "-live", "-silent", "-y", "5" }; + + WINPR_STATIC_ASSERT(ARRAYSIZE(makecert_argv) <= INT_MAX); + const size_t makecert_argc = ARRAYSIZE(makecert_argv); + + MAKECERT_CONTEXT* makecert = makecert_context_new(); + + if (!makecert) + goto out_fail; + + if (makecert_context_process(makecert, (int)makecert_argc, makecert_argv) < 0) + goto out_fail; + + if (makecert_context_set_output_file_name(makecert, "shadow") != 1) + goto out_fail; + + WINPR_ASSERT(server); + WINPR_ASSERT(filepath); + if (!winpr_PathFileExists(server->CertificateFile)) + { + if (makecert_context_output_certificate_file(makecert, filepath) != 1) + goto out_fail; + } + + if (!winpr_PathFileExists(server->PrivateKeyFile)) + { + if (makecert_context_output_private_key_file(makecert, filepath) != 1) + goto out_fail; + } + rc = TRUE; +out_fail: + makecert_context_free(makecert); + return rc; +} +static BOOL shadow_server_init_certificate(rdpShadowServer* server) +{ + char* filepath = NULL; + BOOL ret = FALSE; + + WINPR_ASSERT(server); + + if (!winpr_PathFileExists(server->ConfigPath) && !winpr_PathMakePath(server->ConfigPath, 0)) + { + WLog_ERR(TAG, "Failed to create directory '%s'", server->ConfigPath); + return FALSE; + } + + if (!(filepath = GetCombinedPath(server->ConfigPath, "shadow"))) + return FALSE; + + if (!winpr_PathFileExists(filepath) && !winpr_PathMakePath(filepath, 0)) + { + if (!CreateDirectoryA(filepath, 0)) + { + WLog_ERR(TAG, "Failed to create directory '%s'", filepath); + goto out_fail; + } + } + + server->CertificateFile = GetCombinedPath(filepath, "shadow.crt"); + server->PrivateKeyFile = GetCombinedPath(filepath, "shadow.key"); + + if (!server->CertificateFile || !server->PrivateKeyFile) + goto out_fail; + + if ((!winpr_PathFileExists(server->CertificateFile)) || + (!winpr_PathFileExists(server->PrivateKeyFile))) + { + if (!shadow_server_create_certificate(server, filepath)) + goto out_fail; + } + + rdpSettings* settings = server->settings; + WINPR_ASSERT(settings); + + rdpPrivateKey* key = freerdp_key_new_from_file(server->PrivateKeyFile); + if (!key) + goto out_fail; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerRsaKey, key, 1)) + goto out_fail; + + rdpCertificate* cert = freerdp_certificate_new_from_file(server->CertificateFile); + if (!cert) + goto out_fail; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_RdpServerCertificate, cert, 1)) + goto out_fail; + + if (!freerdp_certificate_is_rdp_security_compatible(cert)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_UseRdpSecurityLayer, FALSE)) + goto out_fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_RdpSecurity, FALSE)) + goto out_fail; + } + ret = TRUE; +out_fail: + free(filepath); + return ret; +} + +static BOOL shadow_server_check_peer_restrictions(freerdp_listener* listener) +{ + WINPR_ASSERT(listener); + + rdpShadowServer* server = (rdpShadowServer*)listener->info; + WINPR_ASSERT(server); + + if (server->maxClientsConnected > 0) + { + const size_t count = ArrayList_Count(server->clients); + if (count >= server->maxClientsConnected) + { + WLog_WARN(TAG, "connection limit [%" PRIuz "] reached, discarding client", + server->maxClientsConnected); + return FALSE; + } + } + return TRUE; +} + +int shadow_server_init(rdpShadowServer* server) +{ + int status = 0; + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + + if (!(server->clients = ArrayList_New(TRUE))) + goto fail; + + if (!(server->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail; + + if (!InitializeCriticalSectionAndSpinCount(&(server->lock), 4000)) + goto fail; + + status = shadow_server_init_config_path(server); + + if (status < 0) + goto fail; + + if (!shadow_server_init_certificate(server)) + goto fail; + + server->listener = freerdp_listener_new(); + + if (!server->listener) + goto fail; + + server->listener->info = (void*)server; + server->listener->CheckPeerAcceptRestrictions = shadow_server_check_peer_restrictions; + server->listener->PeerAccepted = shadow_client_accepted; + server->subsystem = shadow_subsystem_new(); + + if (!server->subsystem) + goto fail; + + status = shadow_subsystem_init(server->subsystem, server); + if (status < 0) + goto fail; + + return status; + +fail: + shadow_server_uninit(server); + WLog_ERR(TAG, "Failed to initialize shadow server"); + return -1; +} + +int shadow_server_uninit(rdpShadowServer* server) +{ + if (!server) + return -1; + + shadow_server_stop(server); + shadow_subsystem_uninit(server->subsystem); + shadow_subsystem_free(server->subsystem); + server->subsystem = NULL; + freerdp_listener_free(server->listener); + server->listener = NULL; + free(server->CertificateFile); + server->CertificateFile = NULL; + free(server->PrivateKeyFile); + server->PrivateKeyFile = NULL; + free(server->ConfigPath); + server->ConfigPath = NULL; + DeleteCriticalSection(&(server->lock)); + (void)CloseHandle(server->StopEvent); + server->StopEvent = NULL; + ArrayList_Free(server->clients); + server->clients = NULL; + return 1; +} + +rdpShadowServer* shadow_server_new(void) +{ + rdpShadowServer* server = NULL; + server = (rdpShadowServer*)calloc(1, sizeof(rdpShadowServer)); + + if (!server) + return NULL; + + server->port = 3389; + server->mayView = TRUE; + server->mayInteract = TRUE; + server->h264RateControlMode = H264_RATECONTROL_VBR; + server->h264BitRate = 10000000; + server->h264FrameRate = 30; + server->h264QP = 0; + server->authentication = TRUE; + server->settings = freerdp_settings_new(FREERDP_SETTINGS_SERVER_MODE); + return server; +} + +void shadow_server_free(rdpShadowServer* server) +{ + if (!server) + return; + + free(server->ipcSocket); + server->ipcSocket = NULL; + freerdp_settings_free(server->settings); + server->settings = NULL; + free(server); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.c new file mode 100644 index 0000000000000000000000000000000000000000..bbdb568ef8c4d5b6a0652a72b0ee5355ce5e8896 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.c @@ -0,0 +1,292 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include "shadow.h" + +#include "shadow_subsystem.h" + +static pfnShadowSubsystemEntry pSubsystemEntry = NULL; + +void shadow_subsystem_set_entry(pfnShadowSubsystemEntry pEntry) +{ + pSubsystemEntry = pEntry; +} + +static int shadow_subsystem_load_entry_points(RDP_SHADOW_ENTRY_POINTS* pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + ZeroMemory(pEntryPoints, sizeof(RDP_SHADOW_ENTRY_POINTS)); + + if (!pSubsystemEntry) + return -1; + + if (pSubsystemEntry(pEntryPoints) < 0) + return -1; + + return 1; +} + +rdpShadowSubsystem* shadow_subsystem_new(void) +{ + RDP_SHADOW_ENTRY_POINTS ep; + rdpShadowSubsystem* subsystem = NULL; + + shadow_subsystem_load_entry_points(&ep); + + if (!ep.New) + return NULL; + + subsystem = ep.New(); + + if (!subsystem) + return NULL; + + CopyMemory(&(subsystem->ep), &ep, sizeof(RDP_SHADOW_ENTRY_POINTS)); + + return subsystem; +} + +void shadow_subsystem_free(rdpShadowSubsystem* subsystem) +{ + if (subsystem && subsystem->ep.Free) + subsystem->ep.Free(subsystem); +} + +int shadow_subsystem_init(rdpShadowSubsystem* subsystem, rdpShadowServer* server) +{ + int status = -1; + + if (!subsystem || !subsystem->ep.Init) + return -1; + + subsystem->server = server; + subsystem->selectedMonitor = server->selectedMonitor; + + if (!(subsystem->MsgPipe = MessagePipe_New())) + goto fail; + + if (!(subsystem->updateEvent = shadow_multiclient_new())) + goto fail; + + if ((status = subsystem->ep.Init(subsystem)) >= 0) + return status; + +fail: + if (subsystem->MsgPipe) + { + MessagePipe_Free(subsystem->MsgPipe); + subsystem->MsgPipe = NULL; + } + + if (subsystem->updateEvent) + { + shadow_multiclient_free(subsystem->updateEvent); + subsystem->updateEvent = NULL; + } + + return status; +} + +static void shadow_subsystem_free_queued_message(void* obj) +{ + wMessage* message = (wMessage*)obj; + if (message->Free) + { + message->Free(message); + message->Free = NULL; + } +} + +void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem) +{ + if (!subsystem) + return; + + if (subsystem->ep.Uninit) + subsystem->ep.Uninit(subsystem); + + if (subsystem->MsgPipe) + { + wObject* obj1 = NULL; + wObject* obj2 = NULL; + /* Release resource in messages before free */ + obj1 = MessageQueue_Object(subsystem->MsgPipe->In); + + obj1->fnObjectFree = shadow_subsystem_free_queued_message; + MessageQueue_Clear(subsystem->MsgPipe->In); + + obj2 = MessageQueue_Object(subsystem->MsgPipe->Out); + obj2->fnObjectFree = shadow_subsystem_free_queued_message; + MessageQueue_Clear(subsystem->MsgPipe->Out); + MessagePipe_Free(subsystem->MsgPipe); + subsystem->MsgPipe = NULL; + } + + if (subsystem->updateEvent) + { + shadow_multiclient_free(subsystem->updateEvent); + subsystem->updateEvent = NULL; + } +} + +int shadow_subsystem_start(rdpShadowSubsystem* subsystem) +{ + int status = 0; + + if (!subsystem || !subsystem->ep.Start) + return -1; + + status = subsystem->ep.Start(subsystem); + + return status; +} + +int shadow_subsystem_stop(rdpShadowSubsystem* subsystem) +{ + int status = 0; + + if (!subsystem || !subsystem->ep.Stop) + return -1; + + status = subsystem->ep.Stop(subsystem); + + return status; +} + +UINT32 shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors) +{ + UINT32 numMonitors = 0; + RDP_SHADOW_ENTRY_POINTS ep; + + if (shadow_subsystem_load_entry_points(&ep) < 0) + return 0; + + numMonitors = ep.EnumMonitors(monitors, maxMonitors); + + return numMonitors; +} + +/** + * Common function for subsystem implementation. + * This function convert 32bit ARGB format pixels to xormask data + * and andmask data and fill into SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE + * Caller should free the andMaskData and xorMaskData later. + */ +int shadow_subsystem_pointer_convert_alpha_pointer_data( + const BYTE* WINPR_RESTRICT pixels, BOOL premultiplied, UINT32 width, UINT32 height, + SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* WINPR_RESTRICT pointerColor) +{ + return shadow_subsystem_pointer_convert_alpha_pointer_data_to_format( + pixels, PIXEL_FORMAT_BGRX32, premultiplied, width, height, pointerColor); +} + +int shadow_subsystem_pointer_convert_alpha_pointer_data_to_format( + const BYTE* pixels, UINT32 format, BOOL premultiplied, UINT32 width, UINT32 height, + SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* pointerColor) +{ + UINT32 xorStep = 0; + UINT32 andStep = 0; + UINT32 andBit = 0; + BYTE* andBits = NULL; + UINT32 andPixel = 0; + const size_t bpp = FreeRDPGetBytesPerPixel(format); + + xorStep = (width * 3); + xorStep += (xorStep % 2); + + andStep = ((width + 7) / 8); + andStep += (andStep % 2); + + pointerColor->lengthXorMask = height * xorStep; + pointerColor->xorMaskData = (BYTE*)calloc(1, pointerColor->lengthXorMask); + + if (!pointerColor->xorMaskData) + return -1; + + pointerColor->lengthAndMask = height * andStep; + pointerColor->andMaskData = (BYTE*)calloc(1, pointerColor->lengthAndMask); + + if (!pointerColor->andMaskData) + { + free(pointerColor->xorMaskData); + pointerColor->xorMaskData = NULL; + return -1; + } + + for (size_t y = 0; y < height; y++) + { + const BYTE* pSrc8 = &pixels[(width * bpp) * (height - 1 - y)]; + BYTE* pDst8 = &(pointerColor->xorMaskData[y * xorStep]); + + andBit = 0x80; + andBits = &(pointerColor->andMaskData[andStep * y]); + + for (size_t x = 0; x < width; x++) + { + BYTE B = 0; + BYTE G = 0; + BYTE R = 0; + BYTE A = 0; + + const UINT32 color = FreeRDPReadColor(&pSrc8[x * bpp], format); + FreeRDPSplitColor(color, format, &R, &G, &B, &A, NULL); + + andPixel = 0; + + if (A < 64) + A = 0; /* pixel cannot be partially transparent */ + + if (!A) + { + /* transparent pixel: XOR = black, AND = 1 */ + andPixel = 1; + B = G = R = 0; + } + else + { + if (premultiplied) + { + B = (B * 0xFF) / A; + G = (G * 0xFF) / A; + R = (R * 0xFF) / A; + } + } + + *pDst8++ = B; + *pDst8++ = G; + *pDst8++ = R; + + if (andPixel) + *andBits |= andBit; + if (!(andBit >>= 1)) + { + andBits++; + andBit = 0x80; + } + } + } + + return 1; +} + +void shadow_subsystem_frame_update(rdpShadowSubsystem* subsystem) +{ + shadow_multiclient_publish_and_wait(subsystem->updateEvent); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.h new file mode 100644 index 0000000000000000000000000000000000000000..206dfddb697a26cf4ad17104e3ce97cbbab10880 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem.h @@ -0,0 +1,47 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_SUBSYSTEM_H +#define FREERDP_SERVER_SHADOW_SUBSYSTEM_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_subsystem_free(rdpShadowSubsystem* subsystem); + + WINPR_ATTR_MALLOC(shadow_subsystem_free, 1) + rdpShadowSubsystem* shadow_subsystem_new(void); + + int shadow_subsystem_init(rdpShadowSubsystem* subsystem, rdpShadowServer* server); + void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem); + + int shadow_subsystem_start(rdpShadowSubsystem* subsystem); + int shadow_subsystem_stop(rdpShadowSubsystem* subsystem); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_SUBSYSTEM_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem_builtin.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem_builtin.c new file mode 100644 index 0000000000000000000000000000000000000000..c379735462ada613cc0382a8d74fbd61f74a3965 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_subsystem_builtin.c @@ -0,0 +1,73 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2016 Jiang Zihao + * + * 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 + +#include + +typedef struct +{ + const char* (*name)(void); + pfnShadowSubsystemEntry entry; +} RDP_SHADOW_SUBSYSTEM; + +extern int ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +extern const char* ShadowSubsystemName(void); + +static RDP_SHADOW_SUBSYSTEM g_Subsystems[] = { + + { ShadowSubsystemName, ShadowSubsystemEntry } +}; + +static size_t g_SubsystemCount = ARRAYSIZE(g_Subsystems); + +static pfnShadowSubsystemEntry shadow_subsystem_load_static_entry(const char* name) +{ + if (!name) + { + if (g_SubsystemCount > 0) + { + const RDP_SHADOW_SUBSYSTEM* cur = &g_Subsystems[0]; + WINPR_ASSERT(cur->entry); + + return cur->entry; + } + + return NULL; + } + + for (size_t index = 0; index < g_SubsystemCount; index++) + { + const RDP_SHADOW_SUBSYSTEM* cur = &g_Subsystems[index]; + WINPR_ASSERT(cur->name); + WINPR_ASSERT(cur->entry); + + if (strcmp(name, cur->name()) == 0) + return cur->entry; + } + + return NULL; +} + +void shadow_subsystem_set_entry_builtin(const char* name) +{ + pfnShadowSubsystemEntry entry = shadow_subsystem_load_static_entry(name); + + if (entry) + shadow_subsystem_set_entry(entry); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.c b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.c new file mode 100644 index 0000000000000000000000000000000000000000..16aeccef1dd8ae0154960a68fff6bd3410ac11f6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.c @@ -0,0 +1,104 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include "shadow.h" + +#include "shadow_surface.h" +#define ALIGN_SCREEN_SIZE(size, align) \ + ((((size) % (align)) != 0) ? ((size) + (align) - ((size) % (align))) : (size)) + +rdpShadowSurface* shadow_surface_new(rdpShadowServer* server, UINT16 x, UINT16 y, UINT32 width, + UINT32 height) +{ + rdpShadowSurface* surface = NULL; + surface = (rdpShadowSurface*)calloc(1, sizeof(rdpShadowSurface)); + + if (!surface) + return NULL; + + surface->server = server; + surface->x = x; + surface->y = y; + surface->width = width; + surface->height = height; + surface->scanline = ALIGN_SCREEN_SIZE(surface->width, 32) * 4; + surface->format = PIXEL_FORMAT_BGRX32; + surface->data = (BYTE*)calloc(ALIGN_SCREEN_SIZE(surface->height, 32), surface->scanline); + + if (!surface->data) + { + free(surface); + return NULL; + } + + if (!InitializeCriticalSectionAndSpinCount(&(surface->lock), 4000)) + { + free(surface->data); + free(surface); + return NULL; + } + + region16_init(&(surface->invalidRegion)); + return surface; +} + +void shadow_surface_free(rdpShadowSurface* surface) +{ + if (!surface) + return; + + free(surface->data); + DeleteCriticalSection(&(surface->lock)); + region16_uninit(&(surface->invalidRegion)); + free(surface); +} + +BOOL shadow_surface_resize(rdpShadowSurface* surface, UINT16 x, UINT16 y, UINT32 width, + UINT32 height) +{ + BYTE* buffer = NULL; + UINT32 scanline = ALIGN_SCREEN_SIZE(width, 4) * 4; + + if (!surface) + return FALSE; + + if ((width == surface->width) && (height == surface->height)) + { + /* We don't need to reset frame buffer, just update left top */ + surface->x = x; + surface->y = y; + return TRUE; + } + + buffer = (BYTE*)realloc(surface->data, 1ull * scanline * ALIGN_SCREEN_SIZE(height, 4ull)); + + if (buffer) + { + surface->x = x; + surface->y = y; + surface->width = width; + surface->height = height; + surface->scanline = scanline; + surface->data = buffer; + return TRUE; + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.h b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.h new file mode 100644 index 0000000000000000000000000000000000000000..277df0a2c6498e45c9f2e52f5f19a4d6c260dade --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/server/shadow/shadow_surface.h @@ -0,0 +1,45 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 FREERDP_SERVER_SHADOW_SURFACE_H +#define FREERDP_SERVER_SHADOW_SURFACE_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + void shadow_surface_free(rdpShadowSurface* surface); + + WINPR_ATTR_MALLOC(shadow_surface_free, 1) + rdpShadowSurface* shadow_surface_new(rdpShadowServer* server, UINT16 x, UINT16 y, UINT32 width, + UINT32 height); + + BOOL shadow_surface_resize(rdpShadowSurface* surface, UINT16 x, UINT16 y, UINT32 width, + UINT32 height); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SERVER_SHADOW_SURFACE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/tools/wireshark/rdp-udp.lua b/local-test-freerdp-delta-01/afc-freerdp/tools/wireshark/rdp-udp.lua new file mode 100644 index 0000000000000000000000000000000000000000..5ed50cdcd10618ec5e66304aad86597a91a994fb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/tools/wireshark/rdp-udp.lua @@ -0,0 +1,709 @@ +--[[ + RDP UDP transport dissector for wireshark + + 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. + + Copyright 2021 David Fort +--]] + +local sslDissector = Dissector.get ("tls") +local dtlsDissector = Dissector.get ("dtls") + +local dprint = function(...) + print(table.concat({"Lua:", ...}," ")) +end + +local dprint2 = dprint + +dprint2("loading RDP-UDP with wireshark=", get_version()) + +local rdpudp = Proto("rdpudp", "UDP transport for RDP") + +-- UDP1 fields +local pf_udp_snSourceAck = ProtoField.uint32("rdpudp.snsourceack", "snSourceAck", base.HEX) +local pf_udp_ReceiveWindowSize = ProtoField.uint16("rdpudp.receivewindowsize", "ReceiveWindowSize", base.DEC) +local pf_udp_flags = ProtoField.uint16("rdpudp.flags", "Flags", base.HEX) + +RDPUDP_SYN = 0x0001 +RDPUDP_FIN = 0x0002 +RDPUDP_ACK = 0x0004 +RDPUDP_DATA = 0x0008 +RDPUDP_FEC = 0x0010 +RDPUDP_CN = 0x0020 +RDPUDP_CWR = 0x0040 +RDPUDP_AOA = 0x0100 +RDPUDP_SYNLOSSY = 0x0200 +RDPUDP_ACKDELAYED = 0x0400 +RDPUDP_CORRELATIONID = 0x0800 +RDPUDP_SYNEX = 0x1000 + +local pf_udp_flag_syn = ProtoField.bool("rdpudp.flags.syn", "Syn", base.HEX, nil, RDPUDP_SYN) +local pf_udp_flag_fin = ProtoField.bool("rdpudp.flags.fin", "Fin", base.HEX, nil, RDPUDP_FIN) +local pf_udp_flag_ack = ProtoField.bool("rdpudp.flags.ack", "Ack", base.HEX, nil, RDPUDP_ACK) +local pf_udp_flag_data = ProtoField.bool("rdpudp.flags.data", "Data", base.HEX, nil, RDPUDP_DATA) +local pf_udp_flag_fec = ProtoField.bool("rdpudp.flags.fec", "FECData", base.HEX, nil, RDPUDP_FEC) +local pf_udp_flag_cn = ProtoField.bool("rdpudp.flags.cn", "CN", base.HEX, nil, RDPUDP_CN) +local pf_udp_flag_cwr = ProtoField.bool("rdpudp.flags.cwr", "CWR", base.HEX, nil, RDPUDP_CWR) +local pf_udp_flag_aoa = ProtoField.bool("rdpudp.flags.aoa", "Ack of Acks", base.HEX, nil, RDPUDP_AOA) +local pf_udp_flag_synlossy = ProtoField.bool("rdpudp.flags.synlossy", "Syn lossy", base.HEX, nil, RDPUDP_SYNLOSSY) +local pf_udp_flag_ackdelayed = ProtoField.bool("rdpudp.flags.ackdelayed", "Ack delayed", base.HEX, nil, RDPUDP_ACKDELAYED) +local pf_udp_flag_correlationId = ProtoField.bool("rdpudp.flags.correlationid", "Correlation id", base.HEX, nil, RDPUDP_CORRELATIONID) +local pf_udp_flag_synex = ProtoField.bool("rdpudp.flags.synex", "SynEx", base.HEX, nil, RDPUDP_SYNEX) + +local pf_udp_snInitialSequenceNumber = ProtoField.uint32("rdpudp.initialsequencenumber", "Initial SequenceNumber", base.HEX) +local pf_udp_upstreamMtu = ProtoField.uint16("rdpudp.upstreammtu", "Upstream MTU", base.DEC) +local pf_udp_downstreamMtu = ProtoField.uint16("rdpudp.downstreammtu", "DownStream MTU", base.DEC) + +local pf_udp_correlationId = ProtoField.new("Correlation Id", "rdpudp.correlationid", ftypes.BYTES) + +local pf_udp_synex_flags = ProtoField.uint16("rdpudp.synex.flags", "Flags", base.HEX) +local pf_udp_synex_flag_version = ProtoField.bool("rdpudp.synex.flags.versioninfo", "Version info", base.HEX, nil, 0x0001) +local pf_udp_synex_version = ProtoField.uint16("rdpudp.synex.version", "Version", base.HEX, {[1]="Version 1", [2]="Version 2", [0x101]="Version 3"}) +local pf_udp_synex_cookiehash = ProtoField.new("Cookie Hash", "rdpudp.synex.cookiehash", ftypes.BYTES) + +local pf_udp_ack_vectorsize = ProtoField.uint16("rdpudp.ack.vectorsize", "uAckVectorSize", base.DEC) +local pf_udp_ack_item = ProtoField.uint8("rdpudp.ack.item", "Ack item", base.HEX) +local pf_udp_ack_item_state = ProtoField.uint8("rdpudp.ack.item.state", "VECTOR_ELEMENT_STATE", base.HEX, {[0]="Received", [1]="Reserved 1", [2]="Reserved 2", [3]="Pending"}, 0xc0) +local pf_udp_ack_item_rle = ProtoField.uint8("rdpudp.ack.item.rle", "Run length", base.DEC, nil, 0x3f) + +local pf_udp_fec_coded = ProtoField.uint32("rdpudp.fec.coded", "snCoded", base.HEX) +local pf_udp_fec_sourcestart = ProtoField.uint32("rdpudp.fec.sourcestart", "snSourceStart", base.HEX) +local pf_udp_fec_range = ProtoField.uint8("rdpudp.fec.range", "Range", base.DEC) +local pf_udp_fec_fecindex = ProtoField.uint8("rdpudp.fec.fecindex", "Fec index", base.HEX) + +local pf_udp_resetseqenum = ProtoField.uint32("rdpudp.resetSeqNum", "snResetSeqNum", base.HEX) + +local pf_udp_source_sncoded = ProtoField.uint32("rdpudp.data.sncoded", "snCoded", base.HEX) +local pf_udp_source_snSourceStart = ProtoField.uint32("rdpudp.data.sourceStart", "snSourceStart", base.HEX) + + +-- UDP2 fields +local pf_PacketPrefixByte = ProtoField.new("PacketPrefixByte", "rdpudp2.prefixbyte", ftypes.UINT8, nil, base.HEX) + +local pf_packetType = ProtoField.uint8("rdpudp2.packetType", "PacketType", base.HEX, {[0] = "Data", [8] = "Dummy"}, 0x1e, "type of packet") + +RDPUDP2_ACK = 0x0001 +RDPUDP2_DATA = 0x0004 +RDPUDP2_ACKVEC = 0x0008 +RDPUDP2_AOA = 0x0010 +RDPUDP2_OVERHEAD = 0x0040 +RDPUDP2_DELAYACK = 0x00100 + +local pf_flags = ProtoField.uint16("rdpudp2.flags", "Flags", base.HEX, nil, 0xfff, "flags") +local pf_flag_ack = ProtoField.bool("rdpudp2.flags.ack", "Ack", base.HEX, nil, RDPUDP2_ACK, "packet contains Ack payload") +local pf_flag_data = ProtoField.bool("rdpudp2.flags.data", "Data", base.HEX, nil, RDPUDP2_DATA, "packet contains Data payload") +local pf_flag_ackvec = ProtoField.bool("rdpudp2.flags.ackvec", "AckVec", base.HEX, nil, RDPUDP2_ACKVEC, "packet contains AckVec payload") +local pf_flag_aoa = ProtoField.bool("rdpudp2.flags.ackofacks", "AckOfAcks", base.HEX, nil, RDPUDP2_AOA, "packet contains AckOfAcks payload") +local pf_flag_overhead = ProtoField.bool("rdpudp2.flags.overheadsize", "OverheadSize", base.HEX, nil, RDPUDP2_OVERHEAD, "packet contains OverheadSize payload") +local pf_flag_delayackinfo = ProtoField.bool("rdpudp2.flags.delayackinfo", "DelayedAckInfo", base.HEX, nil, RDPUDP2_DELAYACK, "packet contains DelayedAckInfo payload") + +local pf_logWindow = ProtoField.uint16("rdpudp2.logWindow", "LogWindow", base.DEC, nil, 0xf000, "flags") + +local pf_AckSeq = ProtoField.uint16("rdpudp2.ack.seqnum", "Base Seq", base.HEX) +local pf_AckTs = ProtoField.uint24("rdpudp2.ack.ts", "receivedTS", base.DEC) +local pf_AckSendTimeGap = ProtoField.uint8("rdpudp2.ack.sendTimeGap", "sendTimeGap", base.DEC) +local pf_ndelayedAcks = ProtoField.uint8("rdpudp2.ack.numDelayedAcks", "NumDelayedAcks", base.DEC, nil, 0x0f) +local pf_delayedTimeScale = ProtoField.uint8("rdpudp2.ack.delayedTimeScale", "delayedTimeScale", base.DEC, nil, 0xf0) +local pf_delayedAcks = ProtoField.new("Delayed acks", "rdpudp2.ack.delayedAcks", ftypes.BYTES) +local pf_delayedAck = ProtoField.uint8("rdpudp2.ack.delayedAck", "Delayed ack", base.DEC) + +local pf_OverHeadSize = ProtoField.uint8("rdpudp2.overheadsize", "Overhead size", base.DEC) + +local pf_DelayAckMax = ProtoField.uint8("rdpudp2.delayackinfo.max", "MaxDelayedAcks", base.DEC) +local pf_DelayAckTimeout = ProtoField.uint8("rdpudp2.delayackinfo.timeout", "DelayedAckTimeoutInMs", base.DEC) + +local pf_AckOfAcks = ProtoField.uint16("rdpudp2.ackofacks", "Ack of Acks", base.HEX) + +local pf_DataSeqNumber = ProtoField.uint16("rdpudp2.data.seqnum", "sequence number", base.HEX) +local pf_DataChannelSeqNumber = ProtoField.uint16("rdpudp2.data.channelseqnumber", "Channel sequence number", base.HEX) +local pf_Data = ProtoField.new("Data", "rdpudp2.data", ftypes.BYTES) + +local pf_AckvecBaseSeq = ProtoField.uint16("rdpudp2.ackvec.baseseqnum", "Base sequence number", base.HEX) +local pf_AckvecCodecAckVecSize = ProtoField.uint16("rdpudp2.ackvec.codecackvecsize", "Codec ackvec size", base.DEC, nil, 0x7f) +local pf_AckvecHaveTs = ProtoField.bool("rdpudp2.ackvec.havets", "have timestamp", base.DEC, nil, 0x80) +local pf_AckvecTimeStamp = ProtoField.uint24("rdpudp2.ackvec.timestamp", "Timestamp", base.HEX) +local pf_AckvecCodedAck = ProtoField.uint8("rdpudp2.ackvec.codecAck", "Coded Ack", base.HEX) +local pf_AckvecCodedAckMode = ProtoField.uint8("rdpudp2.ackvec.codecAckMode", "Mode", base.HEX, {[0]="Bitmap", [1]="Run length"}, 0x80) +local pf_AckvecCodedAckRleState = ProtoField.uint8("rdpudp2.ackvec.codecAckRleState", "State", base.HEX, {[0]="lost",[1]="received"}, 0x40) +local pf_AckvecCodedAckRleLen = ProtoField.uint8("rdpudp2.ackvec.codecAckRleLen", "Length", base.DEC, nil, 0x3f) + +rdpudp.fields = { + -- UDP1 + pf_udp_snSourceAck, pf_udp_ReceiveWindowSize, pf_udp_flags, pf_udp_flag_syn, + pf_udp_flag_fin, pf_udp_flag_ack, pf_udp_flag_data, pf_udp_flag_fec, pf_udp_flag_cn, + pf_udp_flag_cwr, pf_udp_flag_aoa, pf_udp_flag_synlossy, pf_udp_flag_ackdelayed, + pf_udp_flag_correlationId, pf_udp_flag_synex, + pf_udp_snInitialSequenceNumber, pf_udp_upstreamMtu, pf_udp_downstreamMtu, + pf_udp_correlationId, + pf_udp_synex_flags, pf_udp_synex_flag_version, pf_udp_synex_version, pf_udp_synex_cookiehash, + pf_udp_ack_vectorsize, pf_udp_ack_item, pf_udp_ack_item_state, pf_udp_ack_item_rle, + pf_udp_fec_coded, pf_udp_fec_sourcestart, pf_udp_fec_range, pf_udp_fec_fecindex, + pf_udp_resetseqenum, + pf_udp_source_sncoded, pf_udp_source_snSourceStart, + + -- UDP2 + pf_PacketPrefixByte, pf_packetType, + pf_flags, pf_flag_ack, pf_flag_data, pf_flag_ackvec, pf_flag_aoa, pf_flag_overhead, pf_flag_delayackinfo, + pf_logWindow, + pf_Ack, pf_AckSeq, pf_AckTs, pf_AckSendTimeGap, pf_ndelayedAcks, pf_delayedTimeScale, pf_delayedAcks, + pf_OverHeadSize, + pf_DelayAckMax, pf_DelayAckTimeout, + pf_AckOfAcks, + pf_DataSeqNumber, pf_Data, pf_DataChannelSeqNumber, + pf_Ackvec, pf_AckvecBaseSeq, pf_AckvecCodecAckVecSize, pf_AckvecHaveTs, pf_AckvecTimeStamp, pf_AckvecCodedAck, pf_AckvecCodedAckMode, + pf_AckvecCodedAckRleState, pf_AckvecCodedAckRleLen +} + +rdpudp.prefs.track_udp2_peer_states = Pref.bool("Track state of UDP2 peers", true, "Keep track of state of UDP2 peers (receiver and sender windows") +rdpudp.prefs.debug_ssl = Pref.bool("SSL debug message", false, "print verbose message of the SSL fragments reassembly") + + + +local field_rdpudp_flags = Field.new("rdpudp.flags") +local field_rdpudp2_packetType = Field.new("rdpudp2.packetType") +local field_rdpudp2_channelSeqNumber = Field.new("rdpudp2.data.channelseqnumber") +local field_rdpudp2_ackvec_base = Field.new("rdpudp2.ackvec.baseseqnum") + +function unwrapPacket(tvbuf) + local len = tvbuf:reported_length_remaining() + local ret = tvbuf:bytes(7, 1) .. tvbuf:bytes(1, 6) .. tvbuf:bytes(0, 1) .. tvbuf:bytes(8, len-8) + --dprint2("input first bytes=", tvbuf:bytes(0, 9):tohex(true, " ")) + --dprint2("output first bytes=", ret:subset(0, 9):tohex(true, " ")) + return ret:tvb("RDP-UDP unwrapped") +end + +function rdpudp.init() + udpComms = {} +end + +function computePacketKey(pktinfo) + local addr_lo = pktinfo.net_src + local addr_hi = pktinfo.net_dst + local port_lo = pktinfo.src_port + local port_hi = pktinfo.dst_port + + if addr_lo > addr_hi then + addr_hi, addr_lo = addr_lo, addr_hi + port_hi, port_lo = port_lo, port_hi + end + + return tostring(addr_lo) .. ":" .. tostring(port_lo) .. " -> " .. tostring(addr_hi) .. ":" .. tostring(port_hi) +end + +function tableItem(pktinfo) + local key = computePacketKey(pktinfo) + local ret = udpComms[key] + if ret == nil then + dprint2(pktinfo.number .. " creating entry for " .. key) + udpComms[key] = { isLossy = false, switchToUdp2 = nil, sslFragments = {}, + serverAddr = nil, clientAddr = nil, + serverState = { receiveLow = nil, receiveHigh = nil, senderLow = nil, senderHigh = nil }, + clientState = { receiveLow = nil, receiveHigh = nil, senderLow = nil, senderHigh = nil } + } + ret = udpComms[key] + end + return ret +end + +function doAlign(v, alignment) + local rest = v % alignment + if rest ~= 0 then + return v + alignment - rest + end + return v +end + +function dissectV1(tvbuf, pktinfo, tree) + --dprint2("dissecting in UDP1 mode") + local pktlen = tvbuf:reported_length_remaining() + + tree:add(pf_udp_snSourceAck, tvbuf:range(0, 4)) + tree:add(pf_udp_ReceiveWindowSize, tvbuf:range(4, 2)) + local flagsRange = tvbuf:range(6, 2) + local flagsItem = tree:add(pf_udp_flags, flagsRange) + -- + flagsItem:add(pf_udp_flag_syn, flagsRange) + flagsItem:add(pf_udp_flag_fin, flagsRange) + flagsItem:add(pf_udp_flag_ack, flagsRange) + flagsItem:add(pf_udp_flag_data, flagsRange) + flagsItem:add(pf_udp_flag_fec, flagsRange) + flagsItem:add(pf_udp_flag_cn, flagsRange) + flagsItem:add(pf_udp_flag_cwr, flagsRange) + flagsItem:add(pf_udp_flag_aoa, flagsRange) + flagsItem:add(pf_udp_flag_synlossy, flagsRange) + flagsItem:add(pf_udp_flag_ackdelayed, flagsRange) + flagsItem:add(pf_udp_flag_correlationId, flagsRange) + flagsItem:add(pf_udp_flag_synex, flagsRange) + + startAt = 8 + local flags = flagsRange:uint() + local haveSyn = bit32.band(flags, RDPUDP_SYN) ~= 0 + local haveAck = bit32.band(flags, RDPUDP_ACK) ~= 0 + local isLossySyn = bit32.band(flags, RDPUDP_SYNLOSSY) ~= 0 + local tableRecord = tableItem(pktinfo) + + + if isLossySyn then + tableRecord.isLossy = true + end + + if haveSyn then + -- dprint2("rdpudp - SYN") + local synItem = tree:add("Syn", tvbuf:range(startAt, 8)) + + synItem:add(pf_udp_snInitialSequenceNumber, tvbuf:range(startAt, 4)) + synItem:add(pf_udp_upstreamMtu, tvbuf:range(startAt+4, 2)) + synItem:add(pf_udp_downstreamMtu, tvbuf:range(startAt+6, 2)) + + startAt = startAt + 8 + end + + if bit32.band(flags, RDPUDP_CORRELATIONID) ~= 0 then + -- dprint2("rdpudp - CorrelationId") + tree:add(pf_udp_correlationId, tvbuf:range(startAt, 16)) + startAt = startAt + 32 + end + + if bit32.band(flags, RDPUDP_SYNEX) ~= 0 then + -- dprint2("rdpudp - SynEx") + local synexItem = tree:add("SynEx") + + local synexFlagsRange = tvbuf:range(startAt, 2) + local synexFlags = synexItem:add(pf_udp_synex_flags, synexFlagsRange); + -- + synexFlags:add(pf_udp_synex_flag_version, synexFlagsRange) + local exflags = synexFlagsRange:uint() + startAt = startAt + 2 + if bit32.band(exflags, 1) ~= 0 then + synexItem:add(pf_udp_synex_version, tvbuf:range(startAt, 2)) + local versionVal = tvbuf:range(startAt, 2):uint() + startAt = startAt + 2 + + if versionVal == 0x101 then + if not haveAck then + synexItem:add(pf_udp_synex_cookiehash, tvbuf:range(startAt, 32)) + startAt = startAt + 32 + else + -- switch to UDP2 + tableRecord.switchToUdp2 = pktinfo.number + end + end + end + + local mask = RDPUDP_SYN + RDPUDP_ACK + if bit32.band(flags, mask) == mask then + tableRecord.serverAddr = tostring(pktinfo.net_src) + tableRecord.clientAddr = tostring(pktinfo.net_dst) + -- dprint2(pktinfo.number .. ": key='" .. computePacketKey(pktinfo) .. + -- "' setting server=" .. tableRecord.serverAddr .. " client=" .. tableRecord.clientAddr) + end + end + + if haveAck and not haveSyn then + -- dprint2("rdpudp - Ack") + local ackItem = tree:add("Ack") + ackItem:add(pf_udp_ack_vectorsize, tvbuf:range(startAt, 2)) + + local i = 0 + uAckVectorSize = tvbuf:range(startAt, 2):uint() + while i < uAckVectorSize do + local ackRange = tvbuf:range(startAt + 2 + i, 1) + local ack = ackItem:add(pf_udp_ack_item, ackRange) + ack:add(pf_udp_ack_item_state, ackRange) + ack:add(pf_udp_ack_item_rle, ackRange) + i = i + 1 + end -- while + + -- aligned on a dword (4 bytes) boundary + -- dprint2("pktinfo=",pktinfo.number," blockSz=",doAlign(2 + uAckVectorSize, 4)) + startAt = startAt + doAlign(2 + uAckVectorSize, 4) + end + + if bit32.band(flags, RDPUDP_FEC) ~= 0 then + -- dprint2("rdpudp - FEC header") + local fecItem = tree:add("FEC", tvbuf:range(startAt, 12)) + fecItem:add(pf_udp_fec_coded, tvbuf:range(startAt, 4)) + fecItem:add(pf_udp_fec_sourcestart, tvbuf:range(startAt+4, 4)) + fecItem:add(pf_udp_fec_range, tvbuf:range(startAt+8, 1)) + fecItem:add(pf_udp_fec_fecindex, tvbuf:range(startAt+9, 1)) + + startAt = startAt + (4 * 3) + end + + if bit32.band(flags, RDPUDP_AOA) ~= 0 then + -- dprint2("rdpudp - AOA") + tree:add(pf_udp_resetseqenum, tvbuf:range(startAt, 4)) + startAt = startAt + 4 + end + + if bit32.band(flags, RDPUDP_DATA) ~= 0 then + -- dprint2("rdpudp - Data") + local dataItem = tree:add("Data") + dataItem:add(pf_udp_source_sncoded, tvbuf:range(startAt, 4)) + dataItem:add(pf_udp_source_snSourceStart, tvbuf:range(startAt+4, 4)) + startAt = startAt + 8 + + local payload = tvbuf:range(startAt) + local subTvb = payload:tvb("payload") + if tableRecord.isLossy then + dtlsDissector:call(subTvb, pktinfo, dataItem) + else + sslDissector:call(subTvb, pktinfo, dataItem) + end + end + + return pktlen +end + +-- given a tvb containing SSL records returns the part of the buffer that has complete +-- SSL records +function getCompleteSslRecordsLen(tvb) + local startAt = 0 + local remLen = tvb:reported_length_remaining() + + while remLen > 5 do + local recordLen = 5 + tvb:range(startAt+3, 2):uint() + if remLen < recordLen then + break + end + startAt = startAt + recordLen + remLen = remLen - recordLen + end -- while + + return startAt; +end + +TLS_OK = 0 +TLS_SHORT = 1 +TLS_NOT_TLS = 2 +TLS_NOT_COMPLETE = 3 +sslResNames = {[0]="TLS_OK", [1]="TLS_SHORT", [2]="TLS_NOT_TLS", [3]="TLS_NOT_COMPLETE"} + +function checkSslRecord(tvb) + local remLen = tvb:reported_length_remaining() + + if remLen <= 5 then + return TLS_SHORT, 0 + end + + local b0 = tvb:range(0, 1):uint() + if b0 < 0x14 or b0 > 0x17 then + -- dprint2("doesn't look like a SSL record, b0=",b0) + return TLS_NOT_TLS, 0 + end + + local recordLen = 5 + tvb:range(3, 2):uint() + if remLen < recordLen then + return TLS_NOT_COMPLETE, recordLen + end + return TLS_OK, recordLen +end + + +function getSslFragments(pktinfo) + local addr0 = pktinfo.net_src + local addr1 = pktinfo.net_dst + local port0 = pktinfo.src_port + local port1 = pktinfo.dst_port + local key = tostring(addr0) .. ":" .. tostring(port0) .. "->" .. tostring(addr1) .. ":" .. tostring(port1) + + local tableRecord = tableItem(pktinfo) + if tableRecord.sslFragments[key] == nil then + tableRecord.sslFragments[key] = {} + end + + return tableRecord.sslFragments[key] +end + +function dissectV2(in_tvbuf, pktinfo, tree) + -- dprint2("dissecting in UDP2 mode") + local pktlen = in_tvbuf:reported_length_remaining() + if pktlen < 7 then + dprint2("packet ", pktinfo.number, " too short, len=", pktlen) + return + end + + local conversation = tableItem(pktinfo) + local sourceState = nil + local targetState = nil + if rdpudp.prefs.track_udp2_peer_states then + if tostring(pktinfo.net_dst) == conversation.serverAddr then + sourceState = conversation.clientState + targetState = conversation.serverState + else + sourceState = conversation.serverState + targetState = conversation.clientState + end + end + + pktinfo.cols.info = "" + local info = "(" + local tvbuf = unwrapPacket(in_tvbuf) + local prefixRange = tvbuf:range(0, 1) + local prefix_tree = tree:add(pf_PacketPrefixByte, prefixRange) + -- + local packetType = prefix_tree:add(pf_packetType, prefixRange) + + local flagsRange = tvbuf:range(1,2) + local flagsTree = tree:add_le(pf_flags, flagsRange) + -- + flagsTree:add_packet_field(pf_flag_ack, flagsRange, ENC_LITTLE_ENDIAN) + flagsTree:add_le(pf_flag_data, flagsRange) + flagsTree:add_le(pf_flag_ackvec, flagsRange) + flagsTree:add_le(pf_flag_aoa, flagsRange) + flagsTree:add_le(pf_flag_overhead, flagsRange) + flagsTree:add_le(pf_flag_delayackinfo, flagsRange) + + tree:add_le(pf_logWindow, flagsRange) + + local flags = tvbuf:range(1,2):le_uint() + + local startAt = 3 + if bit32.band(flags, RDPUDP2_ACK) ~= 0 then + -- dprint2("got ACK payload") + info = info .. "ACK," + local ackTree = tree:add("Ack") + + ackTree:add_le(pf_AckSeq, tvbuf:range(startAt, 2)) + ackTree:add_le(pf_AckTs, tvbuf:range(startAt+2, 3)) + ackTree:add(pf_AckSendTimeGap, tvbuf:range(startAt+5, 1)) + ackTree:add(pf_ndelayedAcks, tvbuf:range(startAt+6, 1)) + ackTree:add(pf_delayedTimeScale, tvbuf:range(startAt+6, 1)) + + local ackSeq = tvbuf:range(startAt, 2):le_uint() + local ackTs = tvbuf:range(startAt+2, 3):le_uint() + local nacks = bit32.band(tvbuf:range(startAt+6, 1):le_uint(), 0xf) + local delayAckTimeScale = bit32.rshift(bit32.band(tvbuf:range(startAt+6, 1):le_uint(), 0xf0), 4) + -- dprint2(pktinfo.number,": nACKs=", nacks, "delayAckTS=", bit32.rshift(delayAckTimeScale, 4)) + + if rdpudp.prefs.track_udp2_peer_states then + targetState.senderLow = ackSeq + end + + startAt = startAt + 7 + if nacks ~= 0 then + local acksItem = ackTree:add(pf_delayedAcks, tvbuf:range(startAt, nacks)) + local i + for i = nacks-1, 0, -1 do + local ackDelay = tvbuf:range(startAt+i, 1):le_uint() * bit32.lshift(1, delayAckTimeScale) + acksItem:add(pf_delayedAck, tvbuf:range(startAt+i, 1), "seq=0x" .. string.format("%0.4x", ackSeq-i-1) .. " ts=" .. ackTs-ackDelay) + end + acksItem:add(pf_delayedAck, tvbuf:range(startAt, nacks), "seq=0x" .. string.format("%0.4x", ackSeq) .. " ts=" .. ackTs):set_generated() + end + startAt = startAt + nacks + end + + if bit32.band(flags, RDPUDP2_OVERHEAD) ~= 0 then + info = info .. "OVERHEAD," + + tree:add_le(pf_OverHeadSize, tvbuf:range(startAt, 1)) + startAt = startAt + 1 + end + + if bit32.band(flags, RDPUDP2_DELAYACK) ~= 0 then + info = info .. "DELAYEDACK," + + local delayAckItem = tree:add("DelayAckInfo", tvbuf:range(startAt, 3)) + delayAckItem:add_le(pf_DelayAckMax, tvbuf:range(startAt, 1)) + delayAckItem:add_le(pf_DelayAckTimeout, tvbuf:range(startAt+1, 2)) + startAt = startAt + 3 + end + + if bit32.band(flags, RDPUDP2_AOA) ~= 0 then + info = info .. "AOA," + tree:add_le(pf_AckOfAcks, tvbuf:range(startAt, 2)) + startAt = startAt + 2 + end + + local dataTree + local isDummy = (field_rdpudp2_packetType()() == 0x8) + if bit32.band(flags, RDPUDP2_DATA) ~= 0 then + if isDummy then + info = info .. "DUMMY," + else + info = info .. "DATA," + end + dataTree = tree:add(isDummy and "Dummy Data" or "Data") + dataTree:add_le(pf_DataSeqNumber, tvbuf:range(startAt, 2)) + startAt = startAt + 2 + end + + if bit32.band(flags, RDPUDP2_ACKVEC) ~= 0 then + -- dprint2("got ACKVEC payload") + info = info .. "ACKVEC," + + local codedAckVecSizeA = tvbuf:range(startAt+2, 1):le_uint() + local codedAckVecSize = bit32.band(codedAckVecSizeA, 0x7f) + local haveTs = bit32.band(codedAckVecSizeA, 0x80) ~= 0 + + local ackVecTree = tree:add("AckVec") + ackVecTree:add_le(pf_AckvecBaseSeq, tvbuf:range(startAt, 2)) + ackVecTree:add(pf_AckvecCodecAckVecSize, tvbuf:range(startAt+2, 1)) + ackVecTree:add(pf_AckvecHaveTs, tvbuf:range(startAt+2, 1)) + startAt = startAt + 3 + if haveTs then + ackVecTree:add_le(pf_AckvecTimeStamp, tvbuf:range(startAt, 4)) + startAt = startAt + 4 + end + local codedAckVector = ackVecTree:add("Vector", tvbuf:range(startAt, codedAckVecSize)) + local seqNumber = field_rdpudp2_ackvec_base()() + for i = 0, codedAckVecSize-1, 1 do + local bRange = tvbuf:range(startAt + i, 1) + local b = bRange:uint() + + local codedAck = codedAckVector:add(pf_AckvecCodedAck, bRange, b) + codedAck:add(pf_AckvecCodedAckMode, bRange) + + local itemString = ""; + if bit32.band(b, 0x80) == 0 then + -- bitmap length mode + itemString = string.format("bitmap(0x%0.2x): ", b) + local mask = 0x1 + for j = 0, 7-1 do + flag = "!" + if bit32.band(b, mask) ~= 0 then + flag = "" + end + + itemString = itemString .. " " .. flag .. string.format("%0.4x", seqNumber) + mask = mask * 2 + seqNumber = seqNumber + 1 + end + else + -- run length mode + codedAck:add(pf_AckvecCodedAckRleState, bRange) + codedAck:add(pf_AckvecCodedAckRleLen, bRange) + + local rleLen = bit32.band(b, 0x3f) + itemString = "rle(len=" .. rleLen .. "): ".. (bit32.band(b, 0x40) and "received" or "lost") .. + string.format(" %0.4x -> %0.4x", seqNumber, seqNumber + rleLen) + seqNumber = seqNumber + rleLen + end + + codedAck:set_text(itemString) + + end + + startAt = startAt + codedAckVecSize + end + + if not isDummy and bit32.band(flags, RDPUDP2_DATA) ~= 0 then + dataTree:add_le(pf_DataChannelSeqNumber, tvbuf:range(startAt, 2)) + local payload = tvbuf:range(startAt + 2) + local subTvb = payload:tvb("payload") + + local channelSeqId = field_rdpudp2_channelSeqNumber()() + local sslFragments = getSslFragments(pktinfo) + local workTvb = nil + + local sslRes, recordLen = checkSslRecord(subTvb) + if rdpudp.prefs.debug_ssl then + dprint2("packet=", pktinfo.number, " channelSeq=", channelSeqId, + " dataLen=", subTvb:reported_length_remaining(), + " sslRes=", sslResNames[sslRes], + " recordLen=", recordLen) + end + if sslRes == TLS_OK then + workTvb = subTvb + elseif sslRes == TLS_SHORT or sslRes == TLS_NOT_COMPLETE then + if rdpudp.prefs.debug_ssl then + dprint2("packet=", pktinfo.number, " recording fragment len=", subTvb:len()) + end + + local frag = ByteArray.new() + frag:append(subTvb:bytes()) + sslFragments[channelSeqId] = frag + + elseif sslRes == TLS_NOT_TLS then + local prevFragment = sslFragments[channelSeqId-1] + if rdpudp.prefs.debug_ssl then + dprint2("packet=",pktinfo.number," picking channelSeq=", channelSeqId-1, " havePrevFragment=", prevFragment ~= nil and "ok" or "no") + end + if prevFragment ~= nil then + -- dprint2("prevLen=",prevFragment:len(), " subTvbLen=",subTvb:len()) + local testBytes = prevFragment .. subTvb:bytes() + local testTvb = ByteArray.tvb(testBytes, "reassembled fragment") + + sslRes, recordLen = checkSslRecord(testTvb) + if rdpudp.prefs.debug_ssl then + dprint2("packet=", pktinfo.number, + " reassembled len=", testTvb:reported_length_remaining(), + " sslRes=", sslResNames[sslRes], + " recordLen=", recordLen) + end + if sslRes == TLS_OK then + workTvb = testTvb + end + end + end + + if workTvb ~= nil then + repeat + if rdpudp.prefs.debug_ssl then + dprint2("treating workTvbLen=", workTvb:reported_length_remaining(), " recordLen=",recordLen) + end + local sslFragment = workTvb:range(0, recordLen):tvb("SSL fragment") + sslDissector:call(sslFragment, pktinfo, dataTree) + + workTvb = workTvb:range(recordLen):tvb() + sslRes, recordLen = checkSslRecord(workTvb) + + if sslRes == TLS_SHORT or sslRes == TLS_NOT_COMPLETE then + if rdpudp.prefs.debug_ssl then + dprint2("packet=", pktinfo.number, " recording fragment len=", subTvb:len()) + end + + local frag = ByteArray.new() + frag:append(workTvb:bytes()) + sslFragments[channelSeqId] = frag + end + + until sslRes ~= TLS_OK or workTvb:reported_length_remaining() == 0 + else + dataTree:add_le(pf_Data, payload) + end + end + + info = string.sub(info, 0, -2) .. ")" + pktinfo.cols.info = info -- .. tostring(pktinfo.cols.info) + if rdpudp.prefs.track_udp2_peer_states then + local stateTrackItem = tree:add("UDP2 state tracking") + stateTrackItem:set_generated() + stateTrackItem:add(tostring(pktinfo.net_dst) == conversation.serverAddr and "Client -> Server" or "Server -> Client") + end + + + return pktlen +end + +function rdpudp.dissector(in_tvbuf, pktinfo, root) + -- dprint2("rdpudp.dissector called") + pktinfo.cols.protocol:set("RDP-UDP") + + local pktlen = in_tvbuf:reported_length_remaining() + local tree = root:add(rdpudp, in_tvbuf:range(0,pktlen)) + + local tableRecord = tableItem(pktinfo) + local doDissectV1 = true + if tableRecord.switchToUdp2 ~= nil and tableRecord.switchToUdp2 < pktinfo.number then + doDissectV1 = false + end + + if doDissectV1 then + return dissectV1(in_tvbuf, pktinfo, tree) + end + + return dissectV2(in_tvbuf, pktinfo, tree) +end + +DissectorTable.get("udp.port"):add(3389, rdpudp) diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/include/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c4857a164eeb0f9696fb98208b70618c5553f3c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/CMakeLists.txt @@ -0,0 +1,21 @@ +# UWAC: Using Wayland As Client +# cmake build script +# +# Copyright 2015 David FORT +# +# 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. + +if(NOT UWAC_FORCE_STATIC_BUILD) + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${UWAC_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h") + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/uwac DESTINATION ${UWAC_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac-tools.h b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac-tools.h new file mode 100644 index 0000000000000000000000000000000000000000..65d26170181c0cf4906df360ac095334ec49f099 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac-tools.h @@ -0,0 +1,43 @@ +/* + * Copyright © 2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef UWAC_TOOLS_H_ +#define UWAC_TOOLS_H_ + +#include +#include + +struct uwac_touch_point +{ + uint32_t id; + wl_fixed_t x, y; +}; +typedef struct uwac_touch_point UwacTouchPoint; + +struct uwac_touch_automata; +typedef struct uwac_touch_automata UwacTouchAutomata; + +UWAC_API void UwacTouchAutomataInit(UwacTouchAutomata* automata); +UWAC_API void UwacTouchAutomataReset(UwacTouchAutomata* automata); +UWAC_API bool UwacTouchAutomataInjectEvent(UwacTouchAutomata* automata, UwacEvent* event); + +#endif /* UWAC_TOOLS_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac.h b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac.h new file mode 100644 index 0000000000000000000000000000000000000000..e1db8de7d3e01c3e772c08ed7a596f0a8ac31cd6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/include/uwac/uwac.h @@ -0,0 +1,668 @@ +/* + * Copyright © 2014-2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef UWAC_H_ +#define UWAC_H_ + +#include +#include + +#if defined(__GNUC__) && (__GNUC__ >= 4) +#define UWAC_API __attribute__((visibility("default"))) +#else +#define UWAC_API +#endif + +typedef struct uwac_position UwacPosition; +typedef struct uwac_size UwacSize; +typedef struct uwac_display UwacDisplay; +typedef struct uwac_output UwacOutput; +typedef struct uwac_window UwacWindow; +typedef struct uwac_seat UwacSeat; +typedef uint32_t UwacSeatId; + +/** @brief error codes */ +typedef enum +{ + UWAC_SUCCESS = 0, + UWAC_ERROR_NOMEMORY, + UWAC_ERROR_UNABLE_TO_CONNECT, + UWAC_ERROR_INVALID_DISPLAY, + UWAC_NOT_ENOUGH_RESOURCES, + UWAC_TIMEDOUT, + UWAC_NOT_FOUND, + UWAC_ERROR_CLOSED, + UWAC_ERROR_INTERNAL, + + UWAC_ERROR_LAST, +} UwacReturnCode; + +/** @brief input modifiers */ +enum +{ + UWAC_MOD_SHIFT_MASK = 0x01, + UWAC_MOD_ALT_MASK = 0x02, + UWAC_MOD_CONTROL_MASK = 0x04, + UWAC_MOD_CAPS_MASK = 0x08, + UWAC_MOD_NUM_MASK = 0x10, +}; + +/** @brief a position */ +struct uwac_position +{ + int x; + int y; +}; + +/** @brief a rectangle size measure */ +struct uwac_size +{ + int width; + int height; +}; + +/** @brief event types */ +enum +{ + UWAC_EVENT_NEW_SEAT = 0, + UWAC_EVENT_REMOVED_SEAT, + UWAC_EVENT_NEW_OUTPUT, + UWAC_EVENT_CONFIGURE, + UWAC_EVENT_POINTER_ENTER, + UWAC_EVENT_POINTER_LEAVE, + UWAC_EVENT_POINTER_MOTION, + UWAC_EVENT_POINTER_BUTTONS, + UWAC_EVENT_POINTER_AXIS, + UWAC_EVENT_KEYBOARD_ENTER, + UWAC_EVENT_KEYBOARD_MODIFIERS, + UWAC_EVENT_KEY, + UWAC_EVENT_TOUCH_FRAME_BEGIN, + UWAC_EVENT_TOUCH_UP, + UWAC_EVENT_TOUCH_DOWN, + UWAC_EVENT_TOUCH_MOTION, + UWAC_EVENT_TOUCH_CANCEL, + UWAC_EVENT_TOUCH_FRAME_END, + UWAC_EVENT_FRAME_DONE, + UWAC_EVENT_CLOSE, + UWAC_EVENT_CLIPBOARD_AVAILABLE, + UWAC_EVENT_CLIPBOARD_SELECT, + UWAC_EVENT_CLIPBOARD_OFFER, + UWAC_EVENT_OUTPUT_GEOMETRY, + UWAC_EVENT_POINTER_AXIS_DISCRETE, + UWAC_EVENT_POINTER_FRAME, + UWAC_EVENT_POINTER_SOURCE +}; + +/** @brief window states */ +enum +{ + UWAC_WINDOW_MAXIMIZED = 0x1, + UWAC_WINDOW_RESIZING = 0x2, + UWAC_WINDOW_FULLSCREEN = 0x4, + UWAC_WINDOW_ACTIVATED = 0x8, +}; + +struct uwac_new_output_event +{ + int type; + UwacOutput* output; +}; +typedef struct uwac_new_output_event UwacOutputNewEvent; + +struct uwac_new_seat_event +{ + int type; + UwacSeat* seat; +}; +typedef struct uwac_new_seat_event UwacSeatNewEvent; + +struct uwac_removed_seat_event +{ + int type; + UwacSeatId id; +}; +typedef struct uwac_removed_seat_event UwacSeatRemovedEvent; + +struct uwac_keyboard_enter_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; +}; +typedef struct uwac_keyboard_enter_event UwacKeyboardEnterLeaveEvent; + +struct uwac_keyboard_modifiers_event +{ + int type; + uint32_t modifiers; +}; +typedef struct uwac_keyboard_modifiers_event UwacKeyboardModifiersEvent; + +struct uwac_pointer_enter_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; + uint32_t x, y; +}; +typedef struct uwac_pointer_enter_event UwacPointerEnterLeaveEvent; + +struct uwac_pointer_motion_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; + uint32_t x, y; +}; +typedef struct uwac_pointer_motion_event UwacPointerMotionEvent; + +struct uwac_pointer_button_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; + uint32_t x, y; + uint32_t button; + enum wl_pointer_button_state state; +}; +typedef struct uwac_pointer_button_event UwacPointerButtonEvent; + +struct uwac_pointer_axis_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; + uint32_t x, y; + uint32_t axis; + wl_fixed_t value; +}; +typedef struct uwac_pointer_axis_event UwacPointerAxisEvent; + +struct uwac_pointer_frame_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; +}; +typedef struct uwac_pointer_frame_event UwacPointerFrameEvent; + +struct uwac_pointer_source_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; + enum wl_pointer_axis_source axis_source; +}; +typedef struct uwac_pointer_source_event UwacPointerSourceEvent; + +struct uwac_touch_frame_event +{ + int type; + UwacWindow* window; + UwacSeat* seat; +}; +typedef struct uwac_touch_frame_event UwacTouchFrameBegin; +typedef struct uwac_touch_frame_event UwacTouchFrameEnd; +typedef struct uwac_touch_frame_event UwacTouchCancel; + +struct uwac_touch_data +{ + int type; + UwacWindow* window; + UwacSeat* seat; + int32_t id; + wl_fixed_t x; + wl_fixed_t y; +}; +typedef struct uwac_touch_data UwacTouchUp; +typedef struct uwac_touch_data UwacTouchDown; +typedef struct uwac_touch_data UwacTouchMotion; + +struct uwac_frame_done_event +{ + int type; + UwacWindow* window; +}; +typedef struct uwac_frame_done_event UwacFrameDoneEvent; + +struct uwac_configure_event +{ + int type; + UwacWindow* window; + int32_t width; + int32_t height; + int states; +}; +typedef struct uwac_configure_event UwacConfigureEvent; + +struct uwac_key_event +{ + int type; + UwacWindow* window; + uint32_t raw_key; + uint32_t sym; + bool pressed; + bool repeated; +}; +typedef struct uwac_key_event UwacKeyEvent; + +struct uwac_close_event +{ + int type; + UwacWindow* window; +}; +typedef struct uwac_close_event UwacCloseEvent; + +struct uwac_clipboard_event +{ + int type; + UwacSeat* seat; + char mime[64]; +}; +typedef struct uwac_clipboard_event UwacClipboardEvent; + +struct uwac_output_geometry_event +{ + int type; + UwacOutput* output; + int x; + int y; + int physical_width; + int physical_height; + int subpixel; + const char* make; + const char* model; + int transform; +}; +typedef struct uwac_output_geometry_event UwacOutputGeometryEvent; + +union uwac_event +{ + int type; + UwacOutputNewEvent output_new; + UwacOutputGeometryEvent output_geometry; + UwacSeatNewEvent seat_new; + UwacSeatRemovedEvent seat_removed; + UwacPointerEnterLeaveEvent mouse_enter_leave; + UwacPointerMotionEvent mouse_motion; + UwacPointerButtonEvent mouse_button; + UwacPointerAxisEvent mouse_axis; + UwacPointerFrameEvent mouse_frame; + UwacPointerSourceEvent mouse_source; + UwacKeyboardEnterLeaveEvent keyboard_enter_leave; + UwacKeyboardModifiersEvent keyboard_modifiers; + UwacClipboardEvent clipboard; + UwacKeyEvent key; + UwacTouchFrameBegin touchFrameBegin; + UwacTouchUp touchUp; + UwacTouchDown touchDown; + UwacTouchMotion touchMotion; + UwacTouchFrameEnd touchFrameEnd; + UwacTouchCancel touchCancel; + UwacFrameDoneEvent frame_done; + UwacConfigureEvent configure; + UwacCloseEvent close; +}; +typedef union uwac_event UwacEvent; + +typedef bool (*UwacErrorHandler)(UwacDisplay* d, UwacReturnCode code, const char* msg, ...); +typedef void (*UwacDataTransferHandler)(UwacSeat* seat, void* context, const char* mime, int fd); +typedef void (*UwacCancelDataTransferHandler)(UwacSeat* seat, void* context); + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * install a handler that will be called when UWAC encounter internal errors. The + * handler is supposed to answer if the execution can continue. I can also be used + * to log things. + * + * @param handler the error handling function to install + */ + UWAC_API void UwacInstallErrorHandler(UwacErrorHandler handler); + + /** + * Opens the corresponding wayland display, using NULL you will open the default + * display. + * + * @param name the name of the display to open + * @return the created UwacDisplay object + */ + UWAC_API UwacDisplay* UwacOpenDisplay(const char* name, UwacReturnCode* err); + + /** + * closes the corresponding UwacDisplay + * + * @param pdisplay a pointer on the display to close + * @return UWAC_SUCCESS if the operation was successful, the corresponding error otherwise + */ + UWAC_API UwacReturnCode UwacCloseDisplay(UwacDisplay** pdisplay); + + /** + * Returns the file descriptor associated with the UwacDisplay, this is useful when + * you want to poll that file descriptor for activity. + * + * @param display an opened UwacDisplay + * @return the corresponding descriptor + */ + UWAC_API int UwacDisplayGetFd(UwacDisplay* display); + + /** + * Returns a human readable form of a Uwac error code + * + * @param error the error number + * @return the associated string + */ + UWAC_API const char* UwacErrorString(UwacReturnCode error); + + /** + * returns the last error that occurred on a display + * + * @param display the display + * @return the last error that have been set for this display + */ + UWAC_API UwacReturnCode UwacDisplayGetLastError(const UwacDisplay* display); + + /** + * retrieves the version of a given interface + * + * @param display the display connection + * @param name the name of the interface + * @param version the output variable for the version + * @return UWAC_SUCCESS if the interface was found, UWAC_NOT_FOUND otherwise + */ + UWAC_API UwacReturnCode UwacDisplayQueryInterfaceVersion(const UwacDisplay* display, + const char* name, uint32_t* version); + + /** + * returns the number SHM formats that have been reported by the compositor + * + * @param display a connected UwacDisplay + * @return the number of SHM formats supported + */ + UWAC_API uint32_t UwacDisplayQueryGetNbShmFormats(UwacDisplay* display); + + /** + * returns the supported ShmFormats + * + * @param display a connected UwacDisplay + * @param formats a pointer on an array of wl_shm_format with enough place for formats_size + *items + * @param formats_size the size of the formats array + * @param filled the number of filled entries in the formats array + * @return UWAC_SUCCESS on success, an error otherwise + */ + UWAC_API UwacReturnCode UwacDisplayQueryShmFormats(const UwacDisplay* display, + enum wl_shm_format* formats, + int formats_size, int* filled); + + /** + * returns the number of registered outputs + * + * @param display the display to query + * @return the number of outputs + */ + UWAC_API uint32_t UwacDisplayGetNbOutputs(const UwacDisplay* display); + + /** + * retrieve a particular UwacOutput object + * + * @param display the display to query + * @param index index of the output + * @return the given UwacOutput, NULL if something failed (so you should query + *UwacDisplayGetLastError() to have the reason) + */ + UWAC_API const UwacOutput* UwacDisplayGetOutput(UwacDisplay* display, int index); + + /** + * retrieve the resolution of a given UwacOutput + * + * @param output the UwacOutput + * @param resolution a pointer on the + * @return UWAC_SUCCESS on success + */ + UWAC_API UwacReturnCode UwacOutputGetResolution(const UwacOutput* output, UwacSize* resolution); + + /** + * retrieve the position of a given UwacOutput + * + * @param output the UwacOutput + * @param pos a pointer on the target position + * @return UWAC_SUCCESS on success + */ + UWAC_API UwacReturnCode UwacOutputGetPosition(const UwacOutput* output, UwacPosition* pos); + + /** + * creates a window using a SHM surface + * + * @param display the display to attach the window to + * @param width the width of the window + * @param height the height of the window + * @param format format to use for the SHM surface + * @return the created UwacWindow, NULL if something failed (use UwacDisplayGetLastError() to + *know more about this) + */ + UWAC_API UwacWindow* UwacCreateWindowShm(UwacDisplay* display, uint32_t width, uint32_t height, + enum wl_shm_format format); + + /** + * destroys the corresponding UwacWindow + * + * @param window a pointer on the UwacWindow to destroy + * @return if the operation completed successfully + */ + UWAC_API UwacReturnCode UwacDestroyWindow(UwacWindow** window); + + /** + * Sets the region that should be considered opaque to the compositor. + * + * @param window the UwacWindow + * @param x The horizontal coordinate in pixels + * @param y The vertical coordinate in pixels + * @param width The width of the region + * @param height The height of the region + * @return UWAC_SUCCESS on success, an error otherwise + */ + UWAC_API UwacReturnCode UwacWindowSetOpaqueRegion(UwacWindow* window, uint32_t x, uint32_t y, + uint32_t width, uint32_t height); + + /** + * Sets the region of the window that can trigger input events + * + * @param window the UwacWindow + * @param x The horizontal coordinate in pixels + * @param y The vertical coordinate in pixels + * @param width The width of the region + * @param height The height of the region + * @return UWAC_SUCCESS on success, an error otherwise + */ + UWAC_API UwacReturnCode UwacWindowSetInputRegion(UwacWindow* window, uint32_t x, uint32_t y, + uint32_t width, uint32_t height); + + /** + * retrieves a pointer on the current window content to draw a frame + * @param window the UwacWindow + * @return a pointer on the current window content + */ + UWAC_API void* UwacWindowGetDrawingBuffer(UwacWindow* window); + + /** + * sets a rectangle as dirty for the next frame of a window + * + * @param window the UwacWindow + * @param x left coordinate + * @param y top coordinate + * @param width the width of the dirty rectangle + * @param height the height of the dirty rectangle + * @return UWAC_SUCCESS on success, an Uwac error otherwise + */ + UWAC_API UwacReturnCode UwacWindowAddDamage(UwacWindow* window, uint32_t x, uint32_t y, + uint32_t width, uint32_t height); + + /** + * returns the geometry of the given UwacWindow buffer + * + * @param window the UwacWindow + * @param geometry the geometry to fill + * @param stride the length of a buffer line in bytes + * @return UWAC_SUCCESS on success, an Uwac error otherwise + */ + UWAC_API UwacReturnCode UwacWindowGetDrawingBufferGeometry(UwacWindow* window, + UwacSize* geometry, size_t* stride); + + /** + * Sends a frame to the compositor with the content of the drawing buffer + * + * @param window the UwacWindow to refresh + * @param copyContentForNextFrame if true the content to display is copied in the next drawing + *buffer + * @return UWAC_SUCCESS if the operation was successful + */ + UWAC_API UwacReturnCode UwacWindowSubmitBuffer(UwacWindow* window, + bool copyContentForNextFrame); + + /** + * returns the geometry of the given UwacWindows + * + * @param window the UwacWindow + * @param geometry the geometry to fill + * @return UWAC_SUCCESS on success, an Uwac error otherwise + */ + UWAC_API UwacReturnCode UwacWindowGetGeometry(UwacWindow* window, UwacSize* geometry); + + /** + * Sets or unset the fact that the window is set fullscreen. After this call the + * application should get prepared to receive a configure event. The output is used + * only when going fullscreen, it is optional and not used when exiting fullscreen. + * + * @param window the UwacWindow + * @param output an optional UwacOutput to put the window fullscreen on + * @param isFullscreen set or unset fullscreen + * @return UWAC_SUCCESS if the operation was a success + */ + UWAC_API UwacReturnCode UwacWindowSetFullscreenState(UwacWindow* window, UwacOutput* output, + bool isFullscreen); + + /** + * When possible (depending on the shell) sets the title of the UwacWindow + * + * @param window the UwacWindow + * @param name title + */ + UWAC_API void UwacWindowSetTitle(UwacWindow* window, const char* name); + + /** + * Sets the app id of the UwacWindow + * + * @param window the UwacWindow + * @param app_id app id + */ + UWAC_API void UwacWindowSetAppId(UwacWindow* window, const char* app_id); + + /** Dispatch the display + * + * @param display The display to dispatch + * @param timeout The maximum time to wait in milliseconds (-1 == infinite). + * @return 1 for success, 0 if display not running, -1 on failure + */ + UWAC_API int UwacDisplayDispatch(UwacDisplay* display, int timeout); + + /** + * Returns if you have some pending events, and you can UwacNextEvent() without blocking + * + * @param display the UwacDisplay + * @return if there's some pending events + */ + UWAC_API bool UwacHasEvent(UwacDisplay* display); + + /** Waits until an event occurs, and when it's there copy the event from the queue to + * event. + * + * @param display the Uwac display + * @param event the event to fill + * @return if the operation completed successfully + */ + UWAC_API UwacReturnCode UwacNextEvent(UwacDisplay* display, UwacEvent* event); + + /** + * returns the name of the given UwacSeat + * + * @param seat the UwacSeat + * @return the name of the seat + */ + UWAC_API const char* UwacSeatGetName(const UwacSeat* seat); + + /** + * returns the id of the given UwacSeat + * + * @param seat the UwacSeat + * @return the id of the seat + */ + UWAC_API UwacSeatId UwacSeatGetId(const UwacSeat* seat); + + /** + * + */ + UWAC_API UwacReturnCode UwacClipboardOfferDestroy(UwacSeat* seat); + UWAC_API UwacReturnCode UwacClipboardOfferCreate(UwacSeat* seat, const char* mime); + UWAC_API UwacReturnCode UwacClipboardOfferAnnounce(UwacSeat* seat, void* context, + UwacDataTransferHandler transfer, + UwacCancelDataTransferHandler cancel); + UWAC_API void* UwacClipboardDataGet(UwacSeat* seat, const char* mime, size_t* size); + + /** + * Inhibits or restores keyboard shortcuts. + * + * @param seat The UwacSeat to inhibit the shortcuts for + * @param inhibit Inhibit or restore keyboard shortcuts + * + * @return UWAC_SUCCESS or an appropriate error code. + */ + UWAC_API UwacReturnCode UwacSeatInhibitShortcuts(UwacSeat* seat, bool inhibit); + + /** + * @brief UwacSeatSetMouseCursor Sets the specified image as the new mouse cursor. + * Special values: If data == NULL && length == 0 + * the cursor is hidden, if data == NULL && length != 0 + * the default system cursor is used. + * + * @param seat The UwacSeat to apply the cursor image to + * @param data A pointer to the image data + * @param length The size of the image data + * @param width The image width in pixel + * @param height The image height in pixel + * @param hot_x The hotspot horizontal offset in pixel + * @param hot_y The hotspot vertical offset in pixel + * + * @return UWAC_SUCCESS if successful, an appropriate error otherwise. + */ + UWAC_API UwacReturnCode UwacSeatSetMouseCursor(UwacSeat* seat, const void* data, size_t length, + size_t width, size_t height, size_t hot_x, + size_t hot_y); + +#ifdef __cplusplus +} +#endif + +#endif /* UWAC_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..03b7ed0a0f0a8dfda540a51e777f31f75fdbc05a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/CMakeLists.txt @@ -0,0 +1,108 @@ +# UWAC: Using Wayland As Client +# +# Copyright 2015 David FORT +# +# 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 "uwac") +set(MODULE_PREFIX "UWAC") + +set(GENERATED_SOURCES "") +macro(generate_protocol_file PROTO) + add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-protocol.c" COMMAND ${CMAKE_COMMAND} -E make_directory + ${CMAKE_CURRENT_BINARY_DIR}/protocols + COMMAND ${WAYLAND_SCANNER} code < ${CMAKE_CURRENT_SOURCE_DIR}/../protocols/${PROTO}.xml > + ${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-protocol.c + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../protocols/${PROTO}.xml + ) + + add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-client-protocol.h" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/protocols + COMMAND ${WAYLAND_SCANNER} client-header < ${CMAKE_CURRENT_SOURCE_DIR}/../protocols/${PROTO}.xml > + ${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-client-protocol.h + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../protocols/${PROTO}.xml + ) + + list(APPEND GENERATED_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-client-protocol.h) + list(APPEND GENERATED_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/protocols/${PROTO}-protocol.c) +endmacro() + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +generate_protocol_file(xdg-shell) +generate_protocol_file(viewporter) +generate_protocol_file(xdg-decoration-unstable-v1) +generate_protocol_file(server-decoration) +generate_protocol_file(ivi-application) +generate_protocol_file(fullscreen-shell-unstable-v1) +generate_protocol_file(keyboard-shortcuts-inhibit-unstable-v1) + +if(FREEBSD) + include_directories(SYSTEM ${EPOLLSHIM_INCLUDE_DIR}) +endif() +include_directories(SYSTEM ${WAYLAND_INCLUDE_DIR}) +include_directories(SYSTEM ${XKBCOMMON_INCLUDE_DIR}) +include_directories("${CMAKE_CURRENT_SOURCE_DIR}/../include") +include_directories("${CMAKE_CURRENT_BINARY_DIR}/../include") +include_directories("${CMAKE_CURRENT_BINARY_DIR}/protocols") + +add_compile_definitions(BUILD_IVI BUILD_FULLSCREEN_SHELL ENABLE_XKBCOMMON) + +set(${MODULE_PREFIX}_SRCS + ${GENERATED_SOURCES} + uwac-display.c + uwac-input.c + uwac-clipboard.c + uwac-os.c + uwac-os.h + uwac-output.c + uwac-priv.h + uwac-tools.c + uwac-utils.c + uwac-window.c +) + +add_library(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +set_target_properties(${MODULE_NAME} PROPERTIES LINKER_LANGUAGE C) +set_target_properties(${MODULE_NAME} PROPERTIES OUTPUT_NAME ${MODULE_NAME}${UWAC_API_VERSION}) +if(WITH_LIBRARY_VERSIONING) + set_target_properties(${MODULE_NAME} PROPERTIES VERSION ${UWAC_VERSION} SOVERSION ${UWAC_API_VERSION}) +endif() + +target_link_libraries( + ${MODULE_NAME} ${${MODULE_PREFIX}_LIBS} PRIVATE ${WAYLAND_LIBS} ${XKBCOMMON_LIBS} ${EPOLLSHIM_LIBS} +) +if(UWAC_HAVE_PIXMAN_REGION) + target_link_libraries(${MODULE_NAME} PRIVATE ${pixman_LINK_LIBRARIES}) +else() + target_link_libraries(${MODULE_NAME} PRIVATE freerdp) +endif() + +target_link_libraries(${MODULE_NAME} PRIVATE m) + +if(NOT UWAC_FORCE_STATIC_BUILD) + target_include_directories(${MODULE_NAME} INTERFACE $) + + install(TARGETS ${MODULE_NAME} COMPONENT libraries EXPORT uwac ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) +endif() + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "uwac") + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + # add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-clipboard.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-clipboard.c new file mode 100644 index 0000000000000000000000000000000000000000..430603bc2ddf65d20f969830b6d5ac8ba3556217 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-clipboard.c @@ -0,0 +1,282 @@ +/* + * Copyright © 2018 Armin Novak + * Copyright © 2018 Thincast Technologies GmbH + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include "uwac-priv.h" +#include "uwac-utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* paste */ +static void data_offer_offer(void* data, struct wl_data_offer* data_offer, + const char* offered_mime_type) +{ + UwacSeat* seat = (UwacSeat*)data; + + assert(seat); + if (!seat->ignore_announcement) + { + UwacClipboardEvent* event = + (UwacClipboardEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_CLIPBOARD_OFFER); + + if (!event) + { + assert(uwacErrorHandler(seat->display, UWAC_ERROR_INTERNAL, + "failed to allocate a clipboard event\n")); + } + else + { + event->seat = seat; + (void)snprintf(event->mime, sizeof(event->mime), "%s", offered_mime_type); + } + } +} + +static const struct wl_data_offer_listener data_offer_listener = { .offer = data_offer_offer }; + +static void data_device_data_offer(void* data, struct wl_data_device* data_device, + struct wl_data_offer* data_offer) +{ + UwacSeat* seat = (UwacSeat*)data; + + assert(seat); + if (!seat->ignore_announcement) + { + UwacClipboardEvent* event = + (UwacClipboardEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_CLIPBOARD_SELECT); + + if (!event) + { + assert(uwacErrorHandler(seat->display, UWAC_ERROR_INTERNAL, + "failed to allocate a close event\n")); + } + else + event->seat = seat; + + wl_data_offer_add_listener(data_offer, &data_offer_listener, data); + seat->offer = data_offer; + } + else + seat->offer = NULL; +} + +static void data_device_selection(void* data, struct wl_data_device* data_device, + struct wl_data_offer* data_offer) +{ +} + +static const struct wl_data_device_listener data_device_listener = { + .data_offer = data_device_data_offer, .selection = data_device_selection +}; + +/* copy */ +static void data_source_target_handler(void* data, struct wl_data_source* data_source, + const char* mime_type) +{ +} + +static void data_source_send_handler(void* data, struct wl_data_source* data_source, + const char* mime_type, int fd) +{ + UwacSeat* seat = (UwacSeat*)data; + seat->transfer_data(seat, seat->data_context, mime_type, fd); +} + +static void data_source_cancelled_handler(void* data, struct wl_data_source* data_source) +{ + UwacSeat* seat = (UwacSeat*)data; + seat->cancel_data(seat, seat->data_context); +} + +static const struct wl_data_source_listener data_source_listener = { + .target = data_source_target_handler, + .send = data_source_send_handler, + .cancelled = data_source_cancelled_handler +}; + +static void UwacRegisterDeviceListener(UwacSeat* s) +{ + wl_data_device_add_listener(s->data_device, &data_device_listener, s); +} + +static UwacReturnCode UwacCreateDataSource(UwacSeat* s) +{ + if (!s) + return UWAC_ERROR_INTERNAL; + + s->data_source = wl_data_device_manager_create_data_source(s->display->data_device_manager); + wl_data_source_add_listener(s->data_source, &data_source_listener, s); + return UWAC_SUCCESS; +} + +UwacReturnCode UwacSeatRegisterClipboard(UwacSeat* s) +{ + UwacClipboardEvent* event = NULL; + + if (!s) + return UWAC_ERROR_INTERNAL; + + if (!s->display->data_device_manager || !s->data_device) + return UWAC_NOT_ENOUGH_RESOURCES; + + UwacRegisterDeviceListener(s); + + UwacReturnCode rc = UwacCreateDataSource(s); + + if (rc != UWAC_SUCCESS) + return rc; + event = (UwacClipboardEvent*)UwacDisplayNewEvent(s->display, UWAC_EVENT_CLIPBOARD_AVAILABLE); + + if (!event) + { + assert(uwacErrorHandler(s->display, UWAC_ERROR_INTERNAL, + "failed to allocate a clipboard event\n")); + return UWAC_ERROR_INTERNAL; + } + + event->seat = s; + return UWAC_SUCCESS; +} + +UwacReturnCode UwacClipboardOfferDestroy(UwacSeat* seat) +{ + if (!seat) + return UWAC_ERROR_INTERNAL; + + if (seat->data_source) + wl_data_source_destroy(seat->data_source); + + return UwacCreateDataSource(seat); +} + +UwacReturnCode UwacClipboardOfferCreate(UwacSeat* seat, const char* mime) +{ + if (!seat || !mime) + return UWAC_ERROR_INTERNAL; + + wl_data_source_offer(seat->data_source, mime); + return UWAC_SUCCESS; +} + +static void callback_done(void* data, struct wl_callback* callback, uint32_t serial) +{ + *(uint32_t*)data = serial; +} + +static const struct wl_callback_listener callback_listener = { .done = callback_done }; + +static uint32_t get_serial(UwacSeat* s) +{ + struct wl_callback* callback = NULL; + uint32_t serial = 0; + callback = wl_display_sync(s->display->display); + wl_callback_add_listener(callback, &callback_listener, &serial); + + while (serial == 0) + { + wl_display_dispatch(s->display->display); + } + + return serial; +} + +UwacReturnCode UwacClipboardOfferAnnounce(UwacSeat* seat, void* context, + UwacDataTransferHandler transfer, + UwacCancelDataTransferHandler cancel) +{ + if (!seat) + return UWAC_ERROR_INTERNAL; + + seat->data_context = context; + seat->transfer_data = transfer; + seat->cancel_data = cancel; + seat->ignore_announcement = true; + wl_data_device_set_selection(seat->data_device, seat->data_source, get_serial(seat)); + wl_display_roundtrip(seat->display->display); + seat->ignore_announcement = false; + return UWAC_SUCCESS; +} + +void* UwacClipboardDataGet(UwacSeat* seat, const char* mime, size_t* size) +{ + ssize_t r = 0; + size_t alloc = 0; + size_t pos = 0; + char* data = NULL; + int pipefd[2] = { 0 }; + + if (!seat || !mime || !size || !seat->offer) + return NULL; + + *size = 0; + if (pipe(pipefd) != 0) + return NULL; + + wl_data_offer_receive(seat->offer, mime, pipefd[1]); + close(pipefd[1]); + wl_display_roundtrip(seat->display->display); + wl_display_flush(seat->display->display); + + do + { + if (alloc >= SIZE_MAX - 1024) + goto fail; + + alloc += 1024; + void* tmp = xrealloc(data, alloc); + if (!tmp) + goto fail; + + data = tmp; + + if (pos > alloc) + goto fail; + + r = read(pipefd[0], &data[pos], alloc - pos); + if (r > 0) + pos += r; + if (r < 0) + goto fail; + } while (r > 0); + + close(pipefd[0]); + + if (alloc > 0) + { + data[pos] = '\0'; + *size = pos + 1; + } + return data; + +fail: + free(data); + close(pipefd[0]); + return NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-display.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-display.c new file mode 100644 index 0000000000000000000000000000000000000000..9bc602aa52ccea4e096526c6c5052d11f0571b35 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-display.c @@ -0,0 +1,796 @@ +/* + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include "uwac-priv.h" +#include "uwac-utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "uwac-os.h" +#include "wayland-cursor.h" + +#define TARGET_COMPOSITOR_INTERFACE 3U +#define TARGET_SHM_INTERFACE 1U +#define TARGET_SHELL_INTERFACE 1U +#define TARGET_DDM_INTERFACE 1U +#define TARGET_SEAT_INTERFACE 5U +#define TARGET_XDG_VERSION 5U /* The version of xdg-shell that we implement */ + +#if !defined(NDEBUG) +static const char* event_names[] = { + "new seat", "removed seat", "new output", "configure", "pointer enter", + "pointer leave", "pointer motion", "pointer buttons", "pointer axis", "keyboard enter", + "key", "touch frame begin", "touch up", "touch down", "touch motion", + "touch cancel", "touch frame end", "frame done", "close", NULL +}; +#endif + +static bool uwac_default_error_handler(UwacDisplay* display, UwacReturnCode code, const char* msg, + ...) +{ + va_list args; + va_start(args, msg); + (void)vfprintf(stderr, "%s", args); + va_end(args); + return false; +} + +UwacErrorHandler uwacErrorHandler = uwac_default_error_handler; + +void UwacInstallErrorHandler(UwacErrorHandler handler) +{ + if (handler) + uwacErrorHandler = handler; + else + uwacErrorHandler = uwac_default_error_handler; +} + +static void cb_shm_format(void* data, struct wl_shm* wl_shm, uint32_t format) +{ + UwacDisplay* d = data; + + if (format == WL_SHM_FORMAT_RGB565) + d->has_rgb565 = true; + + d->shm_formats_nb++; + d->shm_formats = + xrealloc((void*)d->shm_formats, sizeof(enum wl_shm_format) * d->shm_formats_nb); + d->shm_formats[d->shm_formats_nb - 1] = format; +} + +static struct wl_shm_listener shm_listener = { cb_shm_format }; + +static void xdg_shell_ping(void* data, struct xdg_wm_base* xdg_wm_base, uint32_t serial) +{ + xdg_wm_base_pong(xdg_wm_base, serial); +} + +static const struct xdg_wm_base_listener xdg_wm_base_listener = { + xdg_shell_ping, +}; + +#ifdef BUILD_FULLSCREEN_SHELL +static void fullscreen_capability(void* data, + struct zwp_fullscreen_shell_v1* zwp_fullscreen_shell_v1, + uint32_t capability) +{ +} + +static const struct zwp_fullscreen_shell_v1_listener fullscreen_shell_listener = { + fullscreen_capability, +}; +#endif + +static void display_destroy_seat(UwacDisplay* d, uint32_t name) +{ + UwacSeat* seat = NULL; + UwacSeat* tmp = NULL; + wl_list_for_each_safe(seat, tmp, &d->seats, link) + { + if (seat->seat_id == name) + { + UwacSeatDestroy(seat); + } + } +} + +static void UwacSeatRegisterDDM(UwacSeat* seat) +{ + UwacDisplay* d = seat->display; + if (!d->data_device_manager) + return; + + if (!seat->data_device) + seat->data_device = + wl_data_device_manager_get_data_device(d->data_device_manager, seat->seat); +} + +static void UwacRegisterCursor(UwacSeat* seat) +{ + if (!seat || !seat->display || !seat->display->compositor) + return; + + seat->pointer_surface = wl_compositor_create_surface(seat->display->compositor); +} + +static void registry_handle_global(void* data, struct wl_registry* registry, uint32_t id, + const char* interface, uint32_t version) +{ + UwacDisplay* d = data; + UwacGlobal* global = NULL; + global = xzalloc(sizeof *global); + global->name = id; + global->interface = xstrdup(interface); + global->version = version; + wl_list_insert(d->globals.prev, &global->link); + + if (strcmp(interface, "wl_compositor") == 0) + { + d->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, + min(TARGET_COMPOSITOR_INTERFACE, version)); + } + else if (strcmp(interface, "wl_shm") == 0) + { + d->shm = + wl_registry_bind(registry, id, &wl_shm_interface, min(TARGET_SHM_INTERFACE, version)); + wl_shm_add_listener(d->shm, &shm_listener, d); + } + else if (strcmp(interface, "wl_output") == 0) + { + UwacOutput* output = NULL; + UwacOutputNewEvent* ev = NULL; + output = UwacCreateOutput(d, id, version); + + if (!output) + { + assert(uwacErrorHandler(d, UWAC_ERROR_NOMEMORY, "unable to create output\n")); + return; + } + + ev = (UwacOutputNewEvent*)UwacDisplayNewEvent(d, UWAC_EVENT_NEW_OUTPUT); + + if (ev) + ev->output = output; + } + else if (strcmp(interface, "wl_seat") == 0) + { + UwacSeatNewEvent* ev = NULL; + UwacSeat* seat = NULL; + seat = UwacSeatNew(d, id, min(version, TARGET_SEAT_INTERFACE)); + + if (!seat) + { + assert(uwacErrorHandler(d, UWAC_ERROR_NOMEMORY, "unable to create new seat\n")); + return; + } + + UwacSeatRegisterDDM(seat); + UwacSeatRegisterClipboard(seat); + UwacRegisterCursor(seat); + ev = (UwacSeatNewEvent*)UwacDisplayNewEvent(d, UWAC_EVENT_NEW_SEAT); + + if (!ev) + { + assert(uwacErrorHandler(d, UWAC_ERROR_NOMEMORY, "unable to create new seat event\n")); + return; + } + + ev->seat = seat; + } + else if (strcmp(interface, "wl_data_device_manager") == 0) + { + UwacSeat* seat = NULL; + UwacSeat* tmp = NULL; + + d->data_device_manager = wl_registry_bind(registry, id, &wl_data_device_manager_interface, + min(TARGET_DDM_INTERFACE, version)); + + wl_list_for_each_safe(seat, tmp, &d->seats, link) + { + UwacSeatRegisterDDM(seat); + UwacSeatRegisterClipboard(seat); + UwacRegisterCursor(seat); + } + } + else if (strcmp(interface, "wl_shell") == 0) + { + d->shell = wl_registry_bind(registry, id, &wl_shell_interface, + min(TARGET_SHELL_INTERFACE, version)); + } + else if (strcmp(interface, "xdg_wm_base") == 0) + { + d->xdg_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1); + xdg_wm_base_add_listener(d->xdg_base, &xdg_wm_base_listener, d); + } + else if (strcmp(interface, "wp_viewporter") == 0) + { + d->viewporter = wl_registry_bind(registry, id, &wp_viewporter_interface, 1); + } + else if (strcmp(interface, "zwp_keyboard_shortcuts_inhibit_manager_v1") == 0) + { + d->keyboard_inhibit_manager = + wl_registry_bind(registry, id, &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1); + } + else if (strcmp(interface, "zxdg_decoration_manager_v1") == 0) + { + d->deco_manager = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1); + } + else if (strcmp(interface, "org_kde_kwin_server_decoration_manager") == 0) + { + d->kde_deco_manager = + wl_registry_bind(registry, id, &org_kde_kwin_server_decoration_manager_interface, 1); + } +#if BUILD_IVI + else if (strcmp(interface, "ivi_application") == 0) + { + d->ivi_application = wl_registry_bind(registry, id, &ivi_application_interface, 1); + } +#endif +#if BUILD_FULLSCREEN_SHELL + else if (strcmp(interface, "zwp_fullscreen_shell_v1") == 0) + { + d->fullscreen_shell = wl_registry_bind(registry, id, &zwp_fullscreen_shell_v1_interface, 1); + zwp_fullscreen_shell_v1_add_listener(d->fullscreen_shell, &fullscreen_shell_listener, d); + } +#endif +#if 0 + else if (strcmp(interface, "text_cursor_position") == 0) + { + d->text_cursor_position = wl_registry_bind(registry, id, &text_cursor_position_interface, 1); + } + else if (strcmp(interface, "workspace_manager") == 0) + { + //init_workspace_manager(d, id); + } + else if (strcmp(interface, "wl_subcompositor") == 0) + { + d->subcompositor = wl_registry_bind(registry, id, &wl_subcompositor_interface, 1); +#endif +} + +static void registry_handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) +{ + UwacDisplay* d = data; + UwacGlobal* global = NULL; + UwacGlobal* tmp = NULL; + wl_list_for_each_safe(global, tmp, &d->globals, link) + { + if (global->name != name) + continue; + +#if 0 + + if (strcmp(global->interface, "wl_output") == 0) + display_destroy_output(d, name); + +#endif + + if (strcmp(global->interface, "wl_seat") == 0) + { + UwacSeatRemovedEvent* ev = NULL; + display_destroy_seat(d, name); + ev = (UwacSeatRemovedEvent*)UwacDisplayNewEvent(d, UWAC_EVENT_REMOVED_SEAT); + + if (ev) + ev->id = name; + } + + wl_list_remove(&global->link); + free(global->interface); + free(global); + } +} + +static void UwacDestroyGlobal(UwacGlobal* global) +{ + free(global->interface); + wl_list_remove(&global->link); + free(global); +} + +static void* display_bind(UwacDisplay* display, uint32_t name, const struct wl_interface* interface, + uint32_t version) +{ + return wl_registry_bind(display->registry, name, interface, version); +} + +static const struct wl_registry_listener registry_listener = { registry_handle_global, + registry_handle_global_remove }; + +int UwacDisplayWatchFd(UwacDisplay* display, int fd, uint32_t events, UwacTask* task) +{ + struct epoll_event ep; + ep.events = events; + ep.data.ptr = task; + return epoll_ctl(display->epoll_fd, EPOLL_CTL_ADD, fd, &ep); +} + +static void UwacDisplayUnwatchFd(UwacDisplay* display, int fd) +{ + epoll_ctl(display->epoll_fd, EPOLL_CTL_DEL, fd, NULL); +} + +static void display_exit(UwacDisplay* display) +{ + display->running = false; +} + +static void display_dispatch_events(UwacTask* task, uint32_t events) +{ + UwacDisplay* display = container_of(task, UwacDisplay, dispatch_fd_task); + struct epoll_event ep; + int ret = 0; + display->display_fd_events = events; + + if ((events & EPOLLERR) || (events & EPOLLHUP)) + { + display_exit(display); + return; + } + + if (events & EPOLLIN) + { + ret = wl_display_dispatch(display->display); + + if (ret == -1) + { + display_exit(display); + return; + } + } + + if (events & EPOLLOUT) + { + ret = wl_display_flush(display->display); + + if (ret == 0) + { + ep.events = EPOLLIN | EPOLLERR | EPOLLHUP; + ep.data.ptr = &display->dispatch_fd_task; + epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD, display->display_fd, &ep); + } + else if (ret == -1 && errno != EAGAIN) + { + display_exit(display); + return; + } + } +} + +UwacDisplay* UwacOpenDisplay(const char* name, UwacReturnCode* err) +{ + UwacDisplay* ret = NULL; + ret = (UwacDisplay*)xzalloc(sizeof(*ret)); + + if (!ret) + { + *err = UWAC_ERROR_NOMEMORY; + return NULL; + } + + wl_list_init(&ret->globals); + wl_list_init(&ret->seats); + wl_list_init(&ret->outputs); + wl_list_init(&ret->windows); + ret->display = wl_display_connect(name); + + if (ret->display == NULL) + { + char buffer[256] = { 0 }; + (void)fprintf(stderr, "failed to connect to Wayland display %s: %s\n", name, + uwac_strerror(errno, buffer, sizeof(buffer))); + *err = UWAC_ERROR_UNABLE_TO_CONNECT; + goto out_free; + } + + ret->epoll_fd = uwac_os_epoll_create_cloexec(); + + if (ret->epoll_fd < 0) + { + *err = UWAC_NOT_ENOUGH_RESOURCES; + goto out_disconnect; + } + + ret->display_fd = wl_display_get_fd(ret->display); + ret->registry = wl_display_get_registry(ret->display); + + if (!ret->registry) + { + *err = UWAC_ERROR_NOMEMORY; + goto out_close_epoll; + } + + wl_registry_add_listener(ret->registry, ®istry_listener, ret); + + if ((wl_display_roundtrip(ret->display) < 0) || (wl_display_roundtrip(ret->display) < 0)) + { + uwacErrorHandler(ret, UWAC_ERROR_UNABLE_TO_CONNECT, + "Failed to process Wayland connection: %m\n"); + *err = UWAC_ERROR_UNABLE_TO_CONNECT; + goto out_free_registry; + } + + ret->dispatch_fd_task.run = display_dispatch_events; + + if (UwacDisplayWatchFd(ret, ret->display_fd, EPOLLIN | EPOLLERR | EPOLLHUP, + &ret->dispatch_fd_task) < 0) + { + uwacErrorHandler(ret, UWAC_ERROR_INTERNAL, "unable to watch display fd: %m\n"); + *err = UWAC_ERROR_INTERNAL; + goto out_free_registry; + } + + ret->running = true; + ret->last_error = *err = UWAC_SUCCESS; + return ret; +out_free_registry: + wl_registry_destroy(ret->registry); +out_close_epoll: + close(ret->epoll_fd); +out_disconnect: + wl_display_disconnect(ret->display); +out_free: + free(ret); + return NULL; +} + +int UwacDisplayDispatch(UwacDisplay* display, int timeout) +{ + int ret = 0; + int count = 0; + UwacTask* task = NULL; + struct epoll_event ep[16]; + wl_display_dispatch_pending(display->display); + + if (!display->running) + return 0; + + ret = wl_display_flush(display->display); + + if (ret < 0 && errno == EAGAIN) + { + ep[0].events = (EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP); + ep[0].data.ptr = &display->dispatch_fd_task; + epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD, display->display_fd, &ep[0]); + } + else if (ret < 0) + { + return -1; + } + + count = epoll_wait(display->epoll_fd, ep, ARRAY_LENGTH(ep), timeout); + + for (int i = 0; i < count; i++) + { + task = ep[i].data.ptr; + task->run(task, ep[i].events); + } + + return 1; +} + +UwacReturnCode UwacDisplayGetLastError(const UwacDisplay* display) +{ + return display->last_error; +} + +UwacReturnCode UwacCloseDisplay(UwacDisplay** pdisplay) +{ + UwacDisplay* display = NULL; + UwacSeat* seat = NULL; + UwacSeat* tmpSeat = NULL; + UwacWindow* window = NULL; + UwacWindow* tmpWindow = NULL; + UwacOutput* output = NULL; + UwacOutput* tmpOutput = NULL; + UwacGlobal* global = NULL; + UwacGlobal* tmpGlobal = NULL; + assert(pdisplay); + display = *pdisplay; + + if (!display) + return UWAC_ERROR_INVALID_DISPLAY; + + /* destroy windows */ + wl_list_for_each_safe(window, tmpWindow, &display->windows, link) + { + UwacDestroyWindow(&window); + } + /* destroy seats */ + wl_list_for_each_safe(seat, tmpSeat, &display->seats, link) + { + UwacSeatDestroy(seat); + } + /* destroy output */ + wl_list_for_each_safe(output, tmpOutput, &display->outputs, link) + { + UwacDestroyOutput(output); + } + /* destroy globals */ + wl_list_for_each_safe(global, tmpGlobal, &display->globals, link) + { + UwacDestroyGlobal(global); + } + + if (display->compositor) + wl_compositor_destroy(display->compositor); + + if (display->keyboard_inhibit_manager) + zwp_keyboard_shortcuts_inhibit_manager_v1_destroy(display->keyboard_inhibit_manager); + + if (display->deco_manager) + zxdg_decoration_manager_v1_destroy(display->deco_manager); + + if (display->kde_deco_manager) + org_kde_kwin_server_decoration_manager_destroy(display->kde_deco_manager); + +#ifdef BUILD_FULLSCREEN_SHELL + + if (display->fullscreen_shell) + zwp_fullscreen_shell_v1_destroy(display->fullscreen_shell); + +#endif +#ifdef BUILD_IVI + + if (display->ivi_application) + ivi_application_destroy(display->ivi_application); + +#endif + + if (display->xdg_toplevel) + xdg_toplevel_destroy(display->xdg_toplevel); + + if (display->xdg_base) + xdg_wm_base_destroy(display->xdg_base); + + if (display->shell) + wl_shell_destroy(display->shell); + + if (display->shm) + wl_shm_destroy(display->shm); + + if (display->viewporter) + wp_viewporter_destroy(display->viewporter); + + if (display->subcompositor) + wl_subcompositor_destroy(display->subcompositor); + + if (display->data_device_manager) + wl_data_device_manager_destroy(display->data_device_manager); + + free(display->shm_formats); + wl_registry_destroy(display->registry); + close(display->epoll_fd); + wl_display_disconnect(display->display); + + /* cleanup the event queue */ + while (display->push_queue) + { + UwacEventListItem* item = display->push_queue; + display->push_queue = item->tail; + free(item); + } + + free(display); + *pdisplay = NULL; + return UWAC_SUCCESS; +} + +int UwacDisplayGetFd(UwacDisplay* display) +{ + return display->epoll_fd; +} + +static const char* errorStrings[] = { + "success", + "out of memory error", + "unable to connect to wayland display", + "invalid UWAC display", + "not enough resources", + "timed out", + "not found", + "closed connection", + + "internal error", +}; + +const char* UwacErrorString(UwacReturnCode error) +{ + if (error < UWAC_SUCCESS || error >= UWAC_ERROR_LAST) + return "invalid error code"; + + return errorStrings[error]; +} + +UwacReturnCode UwacDisplayQueryInterfaceVersion(const UwacDisplay* display, const char* name, + uint32_t* version) +{ + const UwacGlobal* global = NULL; + const UwacGlobal* tmp = NULL; + + if (!display) + return UWAC_ERROR_INVALID_DISPLAY; + + wl_list_for_each_safe(global, tmp, &display->globals, link) + { + if (strcmp(global->interface, name) == 0) + { + if (version) + *version = global->version; + + return UWAC_SUCCESS; + } + } + return UWAC_NOT_FOUND; +} + +uint32_t UwacDisplayQueryGetNbShmFormats(UwacDisplay* display) +{ + if (!display) + { + return 0; + } + + if (!display->shm) + { + display->last_error = UWAC_NOT_FOUND; + return 0; + } + + display->last_error = UWAC_SUCCESS; + return display->shm_formats_nb; +} + +UwacReturnCode UwacDisplayQueryShmFormats(const UwacDisplay* display, enum wl_shm_format* formats, + int formats_size, int* filled) +{ + if (!display) + return UWAC_ERROR_INVALID_DISPLAY; + + *filled = min((int64_t)display->shm_formats_nb, formats_size); + memcpy(formats, (const void*)display->shm_formats, *filled * sizeof(enum wl_shm_format)); + return UWAC_SUCCESS; +} + +uint32_t UwacDisplayGetNbOutputs(const UwacDisplay* display) +{ + return wl_list_length(&display->outputs); +} + +const UwacOutput* UwacDisplayGetOutput(UwacDisplay* display, int index) +{ + int i = 0; + int display_count = 0; + UwacOutput* ret = NULL; + + if (!display) + return NULL; + + display_count = wl_list_length(&display->outputs); + if (display_count <= index) + return NULL; + + wl_list_for_each(ret, &display->outputs, link) + { + if (i == index) + break; + i++; + } + + if (!ret) + { + display->last_error = UWAC_NOT_FOUND; + return NULL; + } + + display->last_error = UWAC_SUCCESS; + return ret; +} + +UwacReturnCode UwacOutputGetResolution(const UwacOutput* output, UwacSize* resolution) +{ + if ((output->resolution.height <= 0) || (output->resolution.width <= 0)) + return UWAC_ERROR_INTERNAL; + + *resolution = output->resolution; + return UWAC_SUCCESS; +} + +UwacReturnCode UwacOutputGetPosition(const UwacOutput* output, UwacPosition* pos) +{ + *pos = output->position; + return UWAC_SUCCESS; +} + +UwacEvent* UwacDisplayNewEvent(UwacDisplay* display, int type) +{ + UwacEventListItem* ret = NULL; + + if (!display) + { + return 0; + } + + ret = xzalloc(sizeof(UwacEventListItem)); + + if (!ret) + { + assert(uwacErrorHandler(display, UWAC_ERROR_NOMEMORY, "unable to allocate a '%s' event", + event_names[type])); + display->last_error = UWAC_ERROR_NOMEMORY; + return 0; + } + + ret->event.type = type; + ret->tail = display->push_queue; + + if (ret->tail) + ret->tail->head = ret; + else + display->pop_queue = ret; + + display->push_queue = ret; + return &ret->event; +} + +bool UwacHasEvent(UwacDisplay* display) +{ + return display->pop_queue != NULL; +} + +UwacReturnCode UwacNextEvent(UwacDisplay* display, UwacEvent* event) +{ + UwacEventListItem* prevItem = NULL; + int ret = 0; + + if (!display) + return UWAC_ERROR_INVALID_DISPLAY; + + while (!display->pop_queue) + { + ret = UwacDisplayDispatch(display, 1 * 1000); + + if (ret < 0) + return UWAC_ERROR_INTERNAL; + else if (ret == 0) + return UWAC_ERROR_CLOSED; + } + + prevItem = display->pop_queue->head; + *event = display->pop_queue->event; + free(display->pop_queue); + display->pop_queue = prevItem; + + if (prevItem) + prevItem->tail = NULL; + else + display->push_queue = NULL; + + return UWAC_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-input.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-input.c new file mode 100644 index 0000000000000000000000000000000000000000..c579946332d765cb21a858a43c96c3ed20c03d52 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-input.c @@ -0,0 +1,1284 @@ +/* + * Copyright © 2014-2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include "uwac-priv.h" +#include "uwac-utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "uwac-os.h" +#include "wayland-cursor.h" +#include "wayland-client-protocol.h" + +static struct wl_buffer* create_pointer_buffer(UwacSeat* seat, const void* src, size_t size) +{ + struct wl_buffer* buffer = NULL; + struct wl_shm_pool* pool = NULL; + + assert(seat); + + const int fd = uwac_create_anonymous_file(WINPR_ASSERTING_INT_CAST(off_t, size)); + + if (fd < 0) + return buffer; + + void* data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + + if (data == MAP_FAILED) + { + goto error_mmap; + } + memcpy(data, src, size); + + pool = wl_shm_create_pool(seat->display->shm, fd, WINPR_ASSERTING_INT_CAST(int32_t, size)); + + if (!pool) + { + munmap(data, size); + goto error_mmap; + } + + buffer = wl_shm_pool_create_buffer( + pool, 0, WINPR_ASSERTING_INT_CAST(int32_t, seat->pointer_image->width), + WINPR_ASSERTING_INT_CAST(int32_t, seat->pointer_image->height), + WINPR_ASSERTING_INT_CAST(int32_t, seat->pointer_image->width * 4), WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + + if (munmap(data, size) < 0) + { + char buffer[256] = { 0 }; + (void)fprintf(stderr, "%s: munmap(%p, %zu) failed with [%d] %s\n", __func__, data, size, + errno, uwac_strerror(errno, buffer, sizeof(buffer))); + } + +error_mmap: + close(fd); + return buffer; +} + +static void on_buffer_release(void* data, struct wl_buffer* wl_buffer) +{ + (void)data; + wl_buffer_destroy(wl_buffer); +} + +static const struct wl_buffer_listener buffer_release_listener = { on_buffer_release }; + +static UwacReturnCode set_cursor_image(UwacSeat* seat, uint32_t serial) +{ + struct wl_buffer* buffer = NULL; + struct wl_cursor* cursor = NULL; + struct wl_cursor_image* image = NULL; + struct wl_surface* surface = NULL; + int32_t x = 0; + int32_t y = 0; + + if (!seat || !seat->display || !seat->default_cursor || !seat->default_cursor->images) + return UWAC_ERROR_INTERNAL; + + int scale = 1; + if (seat->pointer_focus) + scale = seat->pointer_focus->display->actual_scale; + + switch (seat->pointer_type) + { + case 2: /* Custom pointer */ + image = seat->pointer_image; + buffer = create_pointer_buffer(seat, seat->pointer_data, seat->pointer_size); + if (!buffer) + return UWAC_ERROR_INTERNAL; + if (wl_buffer_add_listener(buffer, &buffer_release_listener, seat) < 0) + return UWAC_ERROR_INTERNAL; + + surface = seat->pointer_surface; + x = WINPR_ASSERTING_INT_CAST(int32_t, image->hotspot_x / scale); + y = WINPR_ASSERTING_INT_CAST(int32_t, image->hotspot_y / scale); + break; + case 1: /* NULL pointer */ + break; + default: /* Default system pointer */ + cursor = seat->default_cursor; + if (!cursor) + return UWAC_ERROR_INTERNAL; + image = cursor->images[0]; + if (!image) + return UWAC_ERROR_INTERNAL; + x = WINPR_ASSERTING_INT_CAST(int32_t, image->hotspot_x); + y = WINPR_ASSERTING_INT_CAST(int32_t, image->hotspot_y); + buffer = wl_cursor_image_get_buffer(image); + if (!buffer) + return UWAC_ERROR_INTERNAL; + surface = seat->pointer_surface; + break; + } + + if (surface && buffer) + { + wl_surface_set_buffer_scale(surface, scale); + wl_surface_attach(surface, buffer, 0, 0); + wl_surface_damage(surface, 0, 0, WINPR_ASSERTING_INT_CAST(int32_t, image->width), + WINPR_ASSERTING_INT_CAST(int32_t, image->height)); + wl_surface_commit(surface); + } + + wl_pointer_set_cursor(seat->pointer, serial, surface, x, y); + + return UWAC_SUCCESS; +} + +static void keyboard_repeat_func(UwacTask* task, uint32_t events) +{ + UwacSeat* input = container_of(task, UwacSeat, repeat_task); + assert(input); + UwacWindow* window = input->keyboard_focus; + uint64_t exp = 0; + + if (read(input->repeat_timer_fd, &exp, sizeof exp) != sizeof exp) + /* If we change the timer between the fd becoming + * readable and getting here, there'll be nothing to + * read and we get EAGAIN. */ + return; + + if (window) + { + UwacKeyEvent* key = NULL; + + key = (UwacKeyEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_KEY); + if (!key) + return; + + key->window = window; + key->sym = input->repeat_sym; + key->raw_key = input->repeat_key; + key->pressed = true; + key->repeated = true; + } +} + +static void keyboard_handle_keymap(void* data, struct wl_keyboard* keyboard, uint32_t format, + int fd, uint32_t size) +{ + UwacSeat* input = data; + struct xkb_keymap* keymap = NULL; + struct xkb_state* state = NULL; + char* map_str = NULL; + int mapFlags = MAP_SHARED; + + if (!data) + { + close(fd); + return; + } + + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) + { + close(fd); + return; + } + + if (input->seat_version >= 7) + mapFlags = MAP_PRIVATE; + + map_str = mmap(NULL, size, PROT_READ, mapFlags, fd, 0); + if (map_str == MAP_FAILED) + { + close(fd); + return; + } + + keymap = xkb_keymap_new_from_string(input->xkb_context, map_str, XKB_KEYMAP_FORMAT_TEXT_V1, 0); + munmap(map_str, size); + close(fd); + + if (!keymap) + { + assert(uwacErrorHandler(input->display, UWAC_ERROR_INTERNAL, "failed to compile keymap\n")); + return; + } + + state = xkb_state_new(keymap); + if (!state) + { + assert( + uwacErrorHandler(input->display, UWAC_ERROR_NOMEMORY, "failed to create XKB state\n")); + xkb_keymap_unref(keymap); + return; + } + + xkb_keymap_unref(input->xkb.keymap); + xkb_state_unref(input->xkb.state); + input->xkb.keymap = keymap; + input->xkb.state = state; + + input->xkb.control_mask = 1 << xkb_keymap_mod_get_index(input->xkb.keymap, "Control"); + input->xkb.alt_mask = 1 << xkb_keymap_mod_get_index(input->xkb.keymap, "Mod1"); + input->xkb.shift_mask = 1 << xkb_keymap_mod_get_index(input->xkb.keymap, "Shift"); + input->xkb.caps_mask = 1 << xkb_keymap_mod_get_index(input->xkb.keymap, "Lock"); + input->xkb.num_mask = 1 << xkb_keymap_mod_get_index(input->xkb.keymap, "Mod2"); +} + +static void keyboard_handle_key(void* data, struct wl_keyboard* keyboard, uint32_t serial, + uint32_t time, uint32_t key, uint32_t state_w); + +static void keyboard_handle_enter(void* data, struct wl_keyboard* keyboard, uint32_t serial, + struct wl_surface* surface, struct wl_array* keys) +{ + UwacSeat* input = (UwacSeat*)data; + assert(input); + + UwacKeyboardEnterLeaveEvent* event = (UwacKeyboardEnterLeaveEvent*)UwacDisplayNewEvent( + input->display, UWAC_EVENT_KEYBOARD_ENTER); + if (!event) + return; + + event->window = input->keyboard_focus = (UwacWindow*)wl_surface_get_user_data(surface); + event->seat = input; + + /* we may have the keys in the `keys` array, but as this function is called only + * when the window gets focus, so there may be keys from other unrelated windows, eg. + * this was leading to problems like passing CTRL+D to freerdp from closing terminal window + * if it was closing very fast and the keys was still pressed by the user while the freerdp + * gets focus + * + * currently just ignore this, as further key presses will be handled correctly anyway + */ +} + +static void keyboard_handle_leave(void* data, struct wl_keyboard* keyboard, uint32_t serial, + struct wl_surface* surface) +{ + struct itimerspec its = { 0 }; + uint32_t* pressedKey = NULL; + size_t i = 0; + + UwacSeat* input = (UwacSeat*)data; + assert(input); + + its.it_interval.tv_sec = 0; + its.it_interval.tv_nsec = 0; + its.it_value.tv_sec = 0; + its.it_value.tv_nsec = 0; + (void)timerfd_settime(input->repeat_timer_fd, 0, &its, NULL); + + UwacPointerEnterLeaveEvent* event = + (UwacPointerEnterLeaveEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_POINTER_LEAVE); + if (!event) + return; + + event->window = input->keyboard_focus; + + /* we are currently losing input focus of the main window: + * check if we currently have some keys pressed and release them as if we enter the window again + * it will be still "virtually" pressed in remote even if in reality the key has been released + */ + for (pressedKey = input->pressed_keys.data, i = 0; i < input->pressed_keys.size; + i += sizeof(uint32_t)) + { + keyboard_handle_key(data, keyboard, serial, 0, *pressedKey, WL_KEYBOARD_KEY_STATE_RELEASED); + pressedKey++; + } +} + +static int update_key_pressed(UwacSeat* seat, uint32_t key) +{ + uint32_t* keyPtr = NULL; + assert(seat); + + /* check if the key is not already pressed */ + wl_array_for_each(keyPtr, &seat->pressed_keys) + { + if (*keyPtr == key) + return 1; + } + + keyPtr = wl_array_add(&seat->pressed_keys, sizeof(uint32_t)); + if (!keyPtr) + return -1; + + *keyPtr = key; + return 0; +} + +static int update_key_released(UwacSeat* seat, uint32_t key) +{ + size_t toMove = 0; + bool found = false; + + assert(seat); + + size_t i = 0; + uint32_t* keyPtr = seat->pressed_keys.data; + for (; i < seat->pressed_keys.size; i++, keyPtr++) + { + if (*keyPtr == key) + { + found = true; + break; + } + } + + if (found) + { + toMove = seat->pressed_keys.size - ((i + 1) * sizeof(uint32_t)); + if (toMove) + memmove(keyPtr, keyPtr + 1, toMove); + + seat->pressed_keys.size -= sizeof(uint32_t); + } + return 1; +} + +static void keyboard_handle_key(void* data, struct wl_keyboard* keyboard, uint32_t serial, + uint32_t time, uint32_t key, uint32_t state_w) +{ + UwacSeat* input = (UwacSeat*)data; + assert(input); + + UwacWindow* window = input->keyboard_focus; + UwacKeyEvent* keyEvent = NULL; + + uint32_t code = 0; + uint32_t num_syms = 0; + enum wl_keyboard_key_state state = state_w; + const xkb_keysym_t* syms = NULL; + xkb_keysym_t sym = 0; + struct itimerspec its; + + if (state_w == WL_KEYBOARD_KEY_STATE_PRESSED) + update_key_pressed(input, key); + else + update_key_released(input, key); + + input->display->serial = serial; + code = key + 8; + if (!window || !input->xkb.state) + return; + + /* We only use input grabs for pointer events for now, so just + * ignore key presses if a grab is active. We expand the key + * event delivery mechanism to route events to widgets to + * properly handle key grabs. In the meantime, this prevents + * key event delivery while a grab is active. */ + /*if (input->grab && input->grab_button == 0) + return;*/ + + num_syms = xkb_state_key_get_syms(input->xkb.state, code, &syms); + + sym = XKB_KEY_NoSymbol; + if (num_syms == 1) + sym = syms[0]; + + if (state == WL_KEYBOARD_KEY_STATE_RELEASED && key == input->repeat_key) + { + its.it_interval.tv_sec = 0; + its.it_interval.tv_nsec = 0; + its.it_value.tv_sec = 0; + its.it_value.tv_nsec = 0; + (void)timerfd_settime(input->repeat_timer_fd, 0, &its, NULL); + } + else if (state == WL_KEYBOARD_KEY_STATE_PRESSED && + xkb_keymap_key_repeats(input->xkb.keymap, code)) + { + input->repeat_sym = sym; + input->repeat_key = key; + input->repeat_time = time; + its.it_interval.tv_sec = input->repeat_rate_sec; + its.it_interval.tv_nsec = input->repeat_rate_nsec; + its.it_value.tv_sec = input->repeat_delay_sec; + its.it_value.tv_nsec = input->repeat_delay_nsec; + (void)timerfd_settime(input->repeat_timer_fd, 0, &its, NULL); + } + + keyEvent = (UwacKeyEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_KEY); + if (!keyEvent) + return; + + keyEvent->window = window; + keyEvent->sym = sym; + keyEvent->raw_key = key; + keyEvent->pressed = (state == WL_KEYBOARD_KEY_STATE_PRESSED); + keyEvent->repeated = false; +} + +static void keyboard_handle_modifiers(void* data, struct wl_keyboard* keyboard, uint32_t serial, + uint32_t mods_depressed, uint32_t mods_latched, + uint32_t mods_locked, uint32_t group) +{ + UwacSeat* input = data; + assert(input); + + UwacKeyboardModifiersEvent* event = NULL; + xkb_mod_mask_t mask = 0; + + /* If we're not using a keymap, then we don't handle PC-style modifiers */ + if (!input->xkb.keymap) + return; + + xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched, mods_locked, 0, 0, group); + mask = xkb_state_serialize_mods(input->xkb.state, XKB_STATE_MODS_DEPRESSED | + XKB_STATE_MODS_LATCHED | + XKB_STATE_MODS_LOCKED); + input->modifiers = 0; + if (mask & input->xkb.control_mask) + input->modifiers |= UWAC_MOD_CONTROL_MASK; + if (mask & input->xkb.alt_mask) + input->modifiers |= UWAC_MOD_ALT_MASK; + if (mask & input->xkb.shift_mask) + input->modifiers |= UWAC_MOD_SHIFT_MASK; + if (mask & input->xkb.caps_mask) + input->modifiers |= UWAC_MOD_CAPS_MASK; + if (mask & input->xkb.num_mask) + input->modifiers |= UWAC_MOD_NUM_MASK; + + event = (UwacKeyboardModifiersEvent*)UwacDisplayNewEvent(input->display, + UWAC_EVENT_KEYBOARD_MODIFIERS); + if (!event) + return; + + event->modifiers = input->modifiers; +} + +static void set_repeat_info(UwacSeat* input, int32_t rate, int32_t delay) +{ + assert(input); + + input->repeat_rate_sec = input->repeat_rate_nsec = 0; + input->repeat_delay_sec = input->repeat_delay_nsec = 0; + + /* a rate of zero disables any repeating, regardless of the delay's + * value */ + if (rate == 0) + return; + + if (rate == 1) + input->repeat_rate_sec = 1; + else + input->repeat_rate_nsec = 1000000000 / rate; + + input->repeat_delay_sec = delay / 1000; + delay -= (input->repeat_delay_sec * 1000); + input->repeat_delay_nsec = delay * 1000 * 1000; +} + +static void keyboard_handle_repeat_info(void* data, struct wl_keyboard* keyboard, int32_t rate, + int32_t delay) +{ + UwacSeat* input = data; + assert(input); + + set_repeat_info(input, rate, delay); +} + +static const struct wl_keyboard_listener keyboard_listener = { + keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, + keyboard_handle_key, keyboard_handle_modifiers, keyboard_handle_repeat_info +}; + +static bool touch_send_start_frame(UwacSeat* seat) +{ + assert(seat); + + UwacTouchFrameBegin* ev = + (UwacTouchFrameBegin*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_FRAME_BEGIN); + if (!ev) + return false; + + seat->touch_frame_started = true; + return true; +} + +static void touch_handle_down(void* data, struct wl_touch* wl_touch, uint32_t serial, uint32_t time, + struct wl_surface* surface, int32_t id, wl_fixed_t x_w, + wl_fixed_t y_w) +{ + UwacSeat* seat = data; + UwacTouchDown* tdata = NULL; + + assert(seat); + assert(seat->display); + + seat->display->serial = serial; + if (!seat->touch_frame_started && !touch_send_start_frame(seat)) + return; + + tdata = (UwacTouchDown*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_DOWN); + if (!tdata) + return; + + tdata->seat = seat; + tdata->id = id; + + double sx = wl_fixed_to_double(x_w); + double sy = wl_fixed_to_double(y_w); + + tdata->x = (wl_fixed_t)lround(sx); + tdata->y = (wl_fixed_t)lround(sy); + +#if 0 + struct widget *widget; + float sx = wl_fixed_to_double(x); + float sy = wl_fixed_to_double(y); + + + input->touch_focus = wl_surface_get_user_data(surface); + if (!input->touch_focus) { + DBG("Failed to find to touch focus for surface %p\n", (void*) surface); + return; + } + + if (surface != input->touch_focus->main_surface->surface) { + DBG("Ignoring input event from subsurface %p\n", (void*) surface); + input->touch_focus = NULL; + return; + } + + if (input->grab) + widget = input->grab; + else + widget = window_find_widget(input->touch_focus, + wl_fixed_to_double(x), + wl_fixed_to_double(y)); + if (widget) { + struct touch_point *tp = xmalloc(sizeof *tp); + if (tp) { + tp->id = id; + tp->widget = widget; + tp->x = sx; + tp->y = sy; + wl_list_insert(&input->touch_point_list, &tp->link); + + if (widget->touch_down_handler) + (*widget->touch_down_handler)(widget, input, + serial, time, id, + sx, sy, + widget->user_data); + } + } +#endif +} + +static void touch_handle_up(void* data, struct wl_touch* wl_touch, uint32_t serial, uint32_t time, + int32_t id) +{ + UwacSeat* seat = data; + UwacTouchUp* tdata = NULL; + + assert(seat); + + if (!seat->touch_frame_started && !touch_send_start_frame(seat)) + return; + + tdata = (UwacTouchUp*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_UP); + if (!tdata) + return; + + tdata->seat = seat; + tdata->id = id; + +#if 0 + struct touch_point *tp, *tmp; + + if (!input->touch_focus) { + DBG("No touch focus found for touch up event!\n"); + return; + } + + wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) { + if (tp->id != id) + continue; + + if (tp->widget->touch_up_handler) + (*tp->widget->touch_up_handler)(tp->widget, input, serial, + time, id, + tp->widget->user_data); + + wl_list_remove(&tp->link); + free(tp); + + return; + } +#endif +} + +static void touch_handle_motion(void* data, struct wl_touch* wl_touch, uint32_t time, int32_t id, + wl_fixed_t x_w, wl_fixed_t y_w) +{ + UwacSeat* seat = data; + assert(seat); + + UwacTouchMotion* tdata = NULL; + + if (!seat->touch_frame_started && !touch_send_start_frame(seat)) + return; + + tdata = (UwacTouchMotion*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_MOTION); + if (!tdata) + return; + + tdata->seat = seat; + tdata->id = id; + + double sx = wl_fixed_to_double(x_w); + double sy = wl_fixed_to_double(y_w); + + tdata->x = (wl_fixed_t)lround(sx); + tdata->y = (wl_fixed_t)lround(sy); + +#if 0 + struct touch_point *tp; + float sx = wl_fixed_to_double(x); + float sy = wl_fixed_to_double(y); + + DBG("touch_handle_motion: %i %i\n", id, wl_list_length(&seat->touch_point_list)); + + if (!seat->touch_focus) { + DBG("No touch focus found for touch motion event!\n"); + return; + } + + wl_list_for_each(tp, &seat->touch_point_list, link) { + if (tp->id != id) + continue; + + tp->x = sx; + tp->y = sy; + if (tp->widget->touch_motion_handler) + (*tp->widget->touch_motion_handler)(tp->widget, seat, time, + id, sx, sy, + tp->widget->user_data); + return; + } +#endif +} + +static void touch_handle_frame(void* data, struct wl_touch* wl_touch) +{ + UwacSeat* seat = data; + assert(seat); + + UwacTouchFrameEnd* ev = + (UwacTouchFrameEnd*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_FRAME_END); + if (!ev) + return; + + ev->seat = seat; + seat->touch_frame_started = false; +} + +static void touch_handle_cancel(void* data, struct wl_touch* wl_touch) +{ + UwacSeat* seat = data; + assert(seat); + + UwacTouchCancel* ev = + (UwacTouchCancel*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_TOUCH_CANCEL); + if (!ev) + return; + + ev->seat = seat; + seat->touch_frame_started = false; + +#if 0 + struct touch_point *tp, *tmp; + + DBG("touch_handle_cancel\n"); + + if (!input->touch_focus) { + DBG("No touch focus found for touch cancel event!\n"); + return; + } + + wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) { + if (tp->widget->touch_cancel_handler) + (*tp->widget->touch_cancel_handler)(tp->widget, input, + tp->widget->user_data); + + wl_list_remove(&tp->link); + free(tp); + } +#endif +} + +static void touch_handle_shape(void* data, struct wl_touch* wl_touch, int32_t id, wl_fixed_t major, + wl_fixed_t minor) +{ + UwacSeat* seat = data; + assert(seat); + + // TODO +} + +static void touch_handle_orientation(void* data, struct wl_touch* wl_touch, int32_t id, + wl_fixed_t orientation) +{ + UwacSeat* seat = data; + assert(seat); + + // TODO +} + +static const struct wl_touch_listener touch_listener = { + touch_handle_down, touch_handle_up, touch_handle_motion, touch_handle_frame, + touch_handle_cancel, touch_handle_shape, touch_handle_orientation +}; + +static void pointer_handle_enter(void* data, struct wl_pointer* pointer, uint32_t serial, + struct wl_surface* surface, wl_fixed_t sx_w, wl_fixed_t sy_w) +{ + UwacSeat* input = data; + UwacWindow* window = NULL; + UwacPointerEnterLeaveEvent* event = NULL; + + assert(input); + + double sx = wl_fixed_to_double(sx_w); + double sy = wl_fixed_to_double(sy_w); + + if (!surface) + { + /* enter event for a window we've just destroyed */ + return; + } + + input->display->serial = serial; + input->display->pointer_focus_serial = serial; + window = wl_surface_get_user_data(surface); + if (window) + window->pointer_enter_serial = serial; + input->pointer_focus = window; + input->sx = sx; + input->sy = sy; + + event = + (UwacPointerEnterLeaveEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_POINTER_ENTER); + if (!event) + return; + + event->seat = input; + event->window = window; + event->x = (uint32_t)lround(sx); + event->y = (uint32_t)lround(sy); + + /* Apply cursor theme */ + set_cursor_image(input, serial); +} + +static void pointer_handle_leave(void* data, struct wl_pointer* pointer, uint32_t serial, + struct wl_surface* surface) +{ + UwacPointerEnterLeaveEvent* event = NULL; + UwacWindow* window = NULL; + UwacSeat* input = data; + assert(input); + + input->display->serial = serial; + + event = + (UwacPointerEnterLeaveEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_POINTER_LEAVE); + if (!event) + return; + + window = wl_surface_get_user_data(surface); + + event->seat = input; + event->window = window; +} + +static void pointer_handle_motion(void* data, struct wl_pointer* pointer, uint32_t time, + wl_fixed_t sx_w, wl_fixed_t sy_w) +{ + UwacPointerMotionEvent* motion_event = NULL; + UwacSeat* input = data; + assert(input); + + UwacWindow* window = input->pointer_focus; + if (!window || !window->display) + return; + + int scale = window->display->actual_scale; + int sx_i = wl_fixed_to_int(sx_w) * scale; + int sy_i = wl_fixed_to_int(sy_w) * scale; + double sx_d = wl_fixed_to_double(sx_w) * scale; + double sy_d = wl_fixed_to_double(sy_w) * scale; + + if ((sx_i < 0) || (sy_i < 0)) + return; + + input->sx = sx_d; + input->sy = sy_d; + + motion_event = + (UwacPointerMotionEvent*)UwacDisplayNewEvent(input->display, UWAC_EVENT_POINTER_MOTION); + if (!motion_event) + return; + + motion_event->seat = input; + motion_event->window = window; + motion_event->x = sx_i; + motion_event->y = sy_i; +} + +static void pointer_handle_button(void* data, struct wl_pointer* pointer, uint32_t serial, + uint32_t time, uint32_t button, uint32_t state_w) +{ + UwacPointerButtonEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + seat->display->serial = serial; + + event = (UwacPointerButtonEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_BUTTONS); + if (!event) + return; + + event->seat = seat; + event->window = window; + event->x = (uint32_t)lround(seat->sx); + event->y = (uint32_t)lround(seat->sy); + event->button = button; + event->state = (enum wl_pointer_button_state)state_w; +} + +static void pointer_handle_axis(void* data, struct wl_pointer* pointer, uint32_t time, + uint32_t axis, wl_fixed_t value) +{ + UwacPointerAxisEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + if (!window) + return; + + event = (UwacPointerAxisEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_AXIS); + if (!event) + return; + + event->seat = seat; + event->window = window; + event->x = (uint32_t)lround(seat->sx); + event->y = (uint32_t)lround(seat->sy); + event->axis = axis; + event->value = value; +} + +static void pointer_frame(void* data, struct wl_pointer* wl_pointer) +{ + UwacPointerFrameEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + if (!window) + return; + + event = (UwacPointerFrameEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_FRAME); + if (!event) + return; + + event->seat = seat; + event->window = window; +} + +static void pointer_axis_source(void* data, struct wl_pointer* wl_pointer, uint32_t axis_source) +{ + UwacPointerSourceEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + if (!window) + return; + + event = (UwacPointerSourceEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_SOURCE); + if (!event) + return; + + event->seat = seat; + event->window = window; + event->axis_source = axis_source; +} + +static void pointer_axis_stop(void* data, struct wl_pointer* wl_pointer, uint32_t time, + uint32_t axis) +{ + UwacSeat* seat = data; + assert(seat); +} + +static void pointer_axis_discrete(void* data, struct wl_pointer* wl_pointer, uint32_t axis, + int32_t discrete) +{ + /*UwacSeat *seat = data;*/ + UwacPointerAxisEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + if (!window) + return; + + event = + (UwacPointerAxisEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_AXIS_DISCRETE); + if (!event) + return; + + event->seat = seat; + event->window = window; + event->x = (uint32_t)lround(seat->sx); + event->y = (uint32_t)lround(seat->sy); + event->axis = axis; + event->value = discrete; +} + +static void pointer_axis_value120(void* data, struct wl_pointer* wl_pointer, uint32_t axis, + int32_t value120) +{ + /*UwacSeat *seat = data;*/ + UwacPointerAxisEvent* event = NULL; + UwacSeat* seat = data; + assert(seat); + + UwacWindow* window = seat->pointer_focus; + + if (!window) + return; + + event = + (UwacPointerAxisEvent*)UwacDisplayNewEvent(seat->display, UWAC_EVENT_POINTER_AXIS_DISCRETE); + if (!event) + return; + + event->seat = seat; + event->window = window; + event->x = (uint32_t)lround(seat->sx); + event->y = (uint32_t)lround(seat->sy); + event->axis = axis; + event->value = value120 / 120; +} + +static const struct wl_pointer_listener pointer_listener = { + pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, + pointer_handle_axis, pointer_frame, pointer_axis_source, pointer_axis_stop, + pointer_axis_discrete, pointer_axis_value120 +}; + +static void seat_handle_capabilities(void* data, struct wl_seat* seat, uint32_t caps) +{ + UwacSeat* input = data; + assert(input); + + if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) + { + input->pointer = wl_seat_get_pointer(seat); + wl_pointer_set_user_data(input->pointer, input); + wl_pointer_add_listener(input->pointer, &pointer_listener, input); + + input->cursor_theme = wl_cursor_theme_load(NULL, 32, input->display->shm); + if (!input->cursor_theme) + { + assert(uwacErrorHandler(input->display, UWAC_ERROR_NOMEMORY, + "unable to get wayland cursor theme\n")); + return; + } + + input->default_cursor = wl_cursor_theme_get_cursor(input->cursor_theme, "left_ptr"); + if (!input->default_cursor) + { + assert(uwacErrorHandler(input->display, UWAC_ERROR_NOMEMORY, + "unable to get wayland cursor left_ptr\n")); + return; + } + } + else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) + { +#ifdef WL_POINTER_RELEASE_SINCE_VERSION + if (input->seat_version >= WL_POINTER_RELEASE_SINCE_VERSION) + wl_pointer_release(input->pointer); + else +#endif + wl_pointer_destroy(input->pointer); + if (input->cursor_theme) + wl_cursor_theme_destroy(input->cursor_theme); + + input->default_cursor = NULL; + input->cursor_theme = NULL; + input->pointer = NULL; + } + + if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) + { + input->keyboard = wl_seat_get_keyboard(seat); + wl_keyboard_set_user_data(input->keyboard, input); + wl_keyboard_add_listener(input->keyboard, &keyboard_listener, input); + } + else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) + { +#ifdef WL_KEYBOARD_RELEASE_SINCE_VERSION + if (input->seat_version >= WL_KEYBOARD_RELEASE_SINCE_VERSION) + wl_keyboard_release(input->keyboard); + else +#endif + wl_keyboard_destroy(input->keyboard); + input->keyboard = NULL; + } + + if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) + { + input->touch = wl_seat_get_touch(seat); + wl_touch_set_user_data(input->touch, input); + wl_touch_add_listener(input->touch, &touch_listener, input); + } + else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) + { +#ifdef WL_TOUCH_RELEASE_SINCE_VERSION + if (input->seat_version >= WL_TOUCH_RELEASE_SINCE_VERSION) + wl_touch_release(input->touch); + else +#endif + wl_touch_destroy(input->touch); + input->touch = NULL; + } +} + +static void seat_handle_name(void* data, struct wl_seat* seat, const char* name) +{ + UwacSeat* input = data; + assert(input); + + if (input->name) + free(input->name); + + input->name = strdup(name); + if (!input->name) + assert(uwacErrorHandler(input->display, UWAC_ERROR_NOMEMORY, + "unable to strdup seat's name\n")); +} + +static const struct wl_seat_listener seat_listener = { seat_handle_capabilities, seat_handle_name }; + +UwacSeat* UwacSeatNew(UwacDisplay* d, uint32_t id, uint32_t version) +{ + UwacSeat* ret = xzalloc(sizeof(UwacSeat)); + if (!ret) + return NULL; + + ret->display = d; + ret->seat_id = id; + ret->seat_version = version; + + wl_array_init(&ret->pressed_keys); + ret->xkb_context = xkb_context_new(0); + if (!ret->xkb_context) + { + (void)fprintf(stderr, "%s: unable to allocate a xkb_context\n", __func__); + goto fail; + } + + ret->seat = wl_registry_bind(d->registry, id, &wl_seat_interface, version); + wl_seat_add_listener(ret->seat, &seat_listener, ret); + wl_seat_set_user_data(ret->seat, ret); + + ret->repeat_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); + if (ret->repeat_timer_fd < 0) + { + (void)fprintf(stderr, "%s: error creating repeat timer\n", __func__); + goto fail; + } + ret->repeat_task.run = keyboard_repeat_func; + if (UwacDisplayWatchFd(d, ret->repeat_timer_fd, EPOLLIN, &ret->repeat_task) < 0) + { + (void)fprintf(stderr, "%s: error polling repeat timer\n", __func__); + goto fail; + } + + wl_list_insert(d->seats.prev, &ret->link); + return ret; + +fail: + UwacSeatDestroy(ret); + return NULL; +} + +void UwacSeatDestroy(UwacSeat* s) +{ + if (!s) + return; + + UwacSeatInhibitShortcuts(s, false); + if (s->seat) + { +#ifdef WL_SEAT_RELEASE_SINCE_VERSION + if (s->seat_version >= WL_SEAT_RELEASE_SINCE_VERSION) + wl_seat_release(s->seat); + else +#endif + wl_seat_destroy(s->seat); + } + s->seat = NULL; + + free(s->name); + wl_array_release(&s->pressed_keys); + + xkb_state_unref(s->xkb.state); + xkb_context_unref(s->xkb_context); + + if (s->pointer) + { +#ifdef WL_POINTER_RELEASE_SINCE_VERSION + if (s->seat_version >= WL_POINTER_RELEASE_SINCE_VERSION) + wl_pointer_release(s->pointer); + else +#endif + wl_pointer_destroy(s->pointer); + } + + if (s->touch) + { +#ifdef WL_TOUCH_RELEASE_SINCE_VERSION + if (s->seat_version >= WL_TOUCH_RELEASE_SINCE_VERSION) + wl_touch_release(s->touch); + else +#endif + wl_touch_destroy(s->touch); + } + + if (s->keyboard) + { +#ifdef WL_KEYBOARD_RELEASE_SINCE_VERSION + if (s->seat_version >= WL_KEYBOARD_RELEASE_SINCE_VERSION) + wl_keyboard_release(s->keyboard); + else +#endif + wl_keyboard_destroy(s->keyboard); + } + + if (s->data_device) + wl_data_device_destroy(s->data_device); + + if (s->data_source) + wl_data_source_destroy(s->data_source); + + if (s->pointer_surface) + wl_surface_destroy(s->pointer_surface); + + free(s->pointer_image); + free(s->pointer_data); + + wl_list_remove(&s->link); + free(s); +} + +const char* UwacSeatGetName(const UwacSeat* seat) +{ + assert(seat); + return seat->name; +} + +UwacSeatId UwacSeatGetId(const UwacSeat* seat) +{ + assert(seat); + return seat->seat_id; +} + +UwacReturnCode UwacSeatInhibitShortcuts(UwacSeat* s, bool inhibit) +{ + if (!s) + return UWAC_ERROR_CLOSED; + + if (s->keyboard_inhibitor) + { + zwp_keyboard_shortcuts_inhibitor_v1_destroy(s->keyboard_inhibitor); + s->keyboard_inhibitor = NULL; + } + if (inhibit && s->display && s->display->keyboard_inhibit_manager) + s->keyboard_inhibitor = zwp_keyboard_shortcuts_inhibit_manager_v1_inhibit_shortcuts( + s->display->keyboard_inhibit_manager, s->keyboard_focus->surface, s->seat); + + if (inhibit && !s->keyboard_inhibitor) + return UWAC_ERROR_INTERNAL; + return UWAC_SUCCESS; +} + +UwacReturnCode UwacSeatSetMouseCursor(UwacSeat* seat, const void* data, size_t length, size_t width, + size_t height, size_t hot_x, size_t hot_y) +{ + if (!seat) + return UWAC_ERROR_CLOSED; + + free(seat->pointer_image); + seat->pointer_image = NULL; + + free(seat->pointer_data); + seat->pointer_data = NULL; + seat->pointer_size = 0; + + /* There is a cursor provided */ + if ((data != NULL) && (length != 0)) + { + seat->pointer_image = xzalloc(sizeof(struct wl_cursor_image)); + if (!seat->pointer_image) + return UWAC_ERROR_NOMEMORY; + seat->pointer_image->width = width; + seat->pointer_image->height = height; + seat->pointer_image->hotspot_x = hot_x; + seat->pointer_image->hotspot_y = hot_y; + + free(seat->pointer_data); + seat->pointer_data = xmalloc(length); + memcpy(seat->pointer_data, data, length); + seat->pointer_size = length; + + seat->pointer_type = 2; + } + /* We want to use the system cursor */ + else if (length != 0) + { + seat->pointer_type = 0; + } + /* Hide the cursor */ + else + { + seat->pointer_type = 1; + } + if (seat && !seat->default_cursor) + return UWAC_SUCCESS; + return set_cursor_image(seat, seat->display->pointer_focus_serial); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.c new file mode 100644 index 0000000000000000000000000000000000000000..449252f504881abef0a591787a100d13dbd9bf3c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.c @@ -0,0 +1,290 @@ +/* + * Copyright © 2012 Collabora, Ltd. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * This file is an adaptation of src/wayland-os.h from the wayland project and + * shared/os-compatiblity.h from the weston project. + * + * Functions have been renamed just to prevent name clashes. + */ + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreserved-id-macro" +#endif + +#define _GNU_SOURCE // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#if defined(__FreeBSD__) || defined(__DragonFly__) +#define USE_SHM +#endif + +/* uClibc and uClibc-ng don't provide O_TMPFILE */ +#if !defined(O_TMPFILE) && !defined(__FreeBSD__) +#define O_TMPFILE (020000000 | O_DIRECTORY) +#endif + +#include +#include +#ifdef USE_SHM +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "uwac-os.h" +#include "uwac-utils.h" + +static int set_cloexec_or_close(int fd) +{ + long flags = 0; + + if (fd == -1) + return -1; + + flags = fcntl(fd, F_GETFD); + + if (flags == -1) + goto err; + + if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) + goto err; + + return fd; +err: + close(fd); + return -1; +} + +int uwac_os_socket_cloexec(int domain, int type, int protocol) +{ + int fd = 0; + fd = socket(domain, type | SOCK_CLOEXEC, protocol); + + if (fd >= 0) + return fd; + + if (errno != EINVAL) + return -1; + + fd = socket(domain, type, protocol); + return set_cloexec_or_close(fd); +} + +int uwac_os_dupfd_cloexec(int fd, long minfd) +{ + int newfd = 0; + newfd = fcntl(fd, F_DUPFD_CLOEXEC, minfd); + + if (newfd >= 0) + return newfd; + + if (errno != EINVAL) + return -1; + + newfd = fcntl(fd, F_DUPFD, minfd); + return set_cloexec_or_close(newfd); +} + +static ssize_t recvmsg_cloexec_fallback(int sockfd, struct msghdr* msg, int flags) +{ + ssize_t len = 0; + struct cmsghdr* cmsg = NULL; + unsigned char* data = NULL; + int* end = NULL; + len = recvmsg(sockfd, msg, flags); + + if (len == -1) + return -1; + + if (!msg->msg_control || msg->msg_controllen == 0) + return len; + + cmsg = CMSG_FIRSTHDR(msg); + + for (; cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) + { + if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) + continue; + + data = CMSG_DATA(cmsg); + end = (int*)(data + cmsg->cmsg_len - CMSG_LEN(0)); + + for (int* fd = (int*)data; fd < end; ++fd) + *fd = set_cloexec_or_close(*fd); + } + + return len; +} + +ssize_t uwac_os_recvmsg_cloexec(int sockfd, struct msghdr* msg, int flags) +{ + ssize_t len = 0; + len = recvmsg(sockfd, msg, flags | MSG_CMSG_CLOEXEC); + + if (len >= 0) + return len; + + if (errno != EINVAL) + return -1; + + return recvmsg_cloexec_fallback(sockfd, msg, flags); +} + +int uwac_os_epoll_create_cloexec(void) +{ + int fd = 0; +#ifdef EPOLL_CLOEXEC + fd = epoll_create1(EPOLL_CLOEXEC); + + if (fd >= 0) + return fd; + + if (errno != EINVAL) + return -1; + +#endif + fd = epoll_create(1); + return set_cloexec_or_close(fd); +} + +static int create_tmpfile_cloexec(char* tmpname) +{ + int fd = 0; +#ifdef USE_SHM + fd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600); +#elif defined(UWAC_HAVE_MKOSTEMP) + fd = mkostemp(tmpname, O_CLOEXEC); + + if (fd >= 0) + unlink(tmpname); + +#else + fd = mkstemp(tmpname); + + if (fd >= 0) + { + fd = set_cloexec_or_close(fd); + unlink(tmpname); + } + +#endif + return fd; +} + +/* + * Create a new, unique, anonymous file of the given size, and + * return the file descriptor for it. The file descriptor is set + * CLOEXEC. The file is immediately suitable for mmap()'ing + * the given size at offset zero. + * + * The file should not have a permanent backing store like a disk, + * but may have if XDG_RUNTIME_DIR is not properly implemented in OS. + * + * The file name is deleted from the file system. + * + * The file is suitable for buffer sharing between processes by + * transmitting the file descriptor over Unix sockets using the + * SCM_RIGHTS methods. + * + * If the C library implements posix_fallocate(), it is used to + * guarantee that disk space is available for the file at the + * given size. If disk space is insufficient, errno is set to ENOSPC. + * If posix_fallocate() is not supported, program may receive + * SIGBUS on accessing mmap()'ed file contents instead. + */ +int uwac_create_anonymous_file(off_t size) +{ + static const char template[] = "/weston-shared-XXXXXX"; + size_t length = 0; + char* name = NULL; + int fd = 0; + int ret = 0; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + const char* path = getenv("XDG_RUNTIME_DIR"); + + if (!path) + { + errno = ENOENT; + return -1; + } + +#ifdef O_TMPFILE + fd = open(path, O_TMPFILE | O_RDWR | O_EXCL, 0600); +#else + /* + * Some platforms (e.g. FreeBSD) won't support O_TMPFILE and can't + * reasonably emulate it at first blush. Opt to make them rely on + * the create_tmpfile_cloexec() path instead. + */ + fd = -1; +#endif + + if (fd < 0) + { + length = strlen(path) + sizeof(template); + name = xmalloc(length); + + if (!name) + return -1; + + (void)snprintf(name, length, "%s%s", path, template); + fd = create_tmpfile_cloexec(name); + free(name); + } + + if (fd < 0) + return -1; + +#ifdef UWAC_HAVE_POSIX_FALLOCATE + ret = posix_fallocate(fd, 0, size); + + if (ret != 0) + { + close(fd); + errno = ret; + return -1; + } + +#else + ret = ftruncate(fd, size); + + if (ret < 0) + { + close(fd); + return -1; + } + +#endif + return fd; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.h b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.h new file mode 100644 index 0000000000000000000000000000000000000000..ef14bf4dab4b068df59ea789359b116ab57f26f2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-os.h @@ -0,0 +1,45 @@ +/* + * Copyright © 2012 Collabora, Ltd. + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * This file is an adaptation of src/wayland-os.h from the wayland project and + * shared/os-compatiblity.h from the weston project. + * + * Functions have been renamed just to prevent name clashes. + */ + +#ifndef UWAC_OS_H +#define UWAC_OS_H + +#include + +int uwac_os_socket_cloexec(int domain, int type, int protocol); + +int uwac_os_dupfd_cloexec(int fd, long minfd); + +ssize_t uwac_os_recvmsg_cloexec(int sockfd, struct msghdr* msg, int flags); + +int uwac_os_epoll_create_cloexec(void); + +int uwac_create_anonymous_file(off_t size); +#endif /* UWAC_OS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-output.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-output.c new file mode 100644 index 0000000000000000000000000000000000000000..079018eb088b5c64ac7d746b9eef290a832d8ed2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-output.c @@ -0,0 +1,183 @@ +/* + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include "uwac-priv.h" +#include "uwac-utils.h" + +#include +#include +#include +#include + +#define TARGET_OUTPUT_INTERFACE 2U + +static bool dupstr(char** dst, const char* src) +{ + assert(dst); + free(*dst); + *dst = NULL; + if (!src) + return true; + *dst = strdup(src); + return *dst != NULL; +} + +static void output_handle_geometry(void* data, struct wl_output* wl_output, int x, int y, + int physical_width, int physical_height, int subpixel, + const char* make, const char* model, int transform) +{ + UwacOutput* output = data; + assert(output); + + output->position.x = x; + output->position.y = y; + output->transform = transform; + + if (!dupstr(&output->make, make)) + { + assert(uwacErrorHandler(output->display, UWAC_ERROR_NOMEMORY, "%s: unable to strdup make\n", + __func__)); + } + + if (!dupstr(&output->model, model)) + { + assert(uwacErrorHandler(output->display, UWAC_ERROR_NOMEMORY, + "%s: unable to strdup model\n", __func__)); + } + + UwacEvent* event = UwacDisplayNewEvent(output->display, UWAC_EVENT_OUTPUT_GEOMETRY); + event->output_geometry.output = output; + event->output_geometry.x = x; + event->output_geometry.y = y; + event->output_geometry.physical_width = physical_width; + event->output_geometry.physical_height = physical_height; + event->output_geometry.subpixel = subpixel; + event->output_geometry.make = output->make; + event->output_geometry.model = output->model; + event->output_geometry.transform = transform; +} + +static void output_handle_done(void* data, struct wl_output* wl_output) +{ + UwacOutput* output = data; + assert(output); + + output->doneReceived = true; +} + +static void output_handle_scale(void* data, struct wl_output* wl_output, int32_t scale) +{ + UwacOutput* output = data; + assert(output); + + output->scale = scale; + if (scale > output->display->actual_scale) + output->display->actual_scale = scale; +} + +static void output_handle_name(void* data, struct wl_output* wl_output, const char* name) +{ + UwacOutput* output = data; + assert(output); + + if (!dupstr(&output->name, name)) + { + assert(uwacErrorHandler(output->display, UWAC_ERROR_NOMEMORY, "%s: unable to strdup make\n", + __func__)); + } +} + +static void output_handle_description(void* data, struct wl_output* wl_output, + const char* description) +{ + UwacOutput* output = data; + assert(output); + + if (!dupstr(&output->description, description)) + { + assert(uwacErrorHandler(output->display, UWAC_ERROR_NOMEMORY, "%s: unable to strdup make\n", + __func__)); + } +} + +static void output_handle_mode(void* data, struct wl_output* wl_output, uint32_t flags, int width, + int height, int refresh) +{ + UwacOutput* output = data; + assert(output); + // UwacDisplay *display = output->display; + + if (output->doneNeeded && output->doneReceived) + { + /* TODO: we should clear the mode list */ + } + + if (flags & WL_OUTPUT_MODE_CURRENT) + { + output->resolution.width = width; + output->resolution.height = height; + /* output->allocation.width = width; + output->allocation.height = height; + if (display->output_configure_handler) + (*display->output_configure_handler)( + output, display->user_data);*/ + } +} + +static const struct wl_output_listener output_listener = { + output_handle_geometry, output_handle_mode, output_handle_done, + output_handle_scale, output_handle_name, output_handle_description +}; + +UwacOutput* UwacCreateOutput(UwacDisplay* d, uint32_t id, uint32_t version) +{ + UwacOutput* o = xzalloc(sizeof *o); + if (!o) + return NULL; + + o->display = d; + o->server_output_id = id; + o->doneNeeded = (version > 1); + o->doneReceived = false; + o->output = wl_registry_bind(d->registry, id, &wl_output_interface, + min(TARGET_OUTPUT_INTERFACE, version)); + wl_output_add_listener(o->output, &output_listener, o); + + wl_list_insert(d->outputs.prev, &o->link); + return o; +} + +int UwacDestroyOutput(UwacOutput* output) +{ + if (!output) + return UWAC_SUCCESS; + + free(output->make); + free(output->model); + free(output->name); + free(output->description); + + wl_output_destroy(output->output); + wl_list_remove(&output->link); + free(output); + + return UWAC_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-priv.h b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-priv.h new file mode 100644 index 0000000000000000000000000000000000000000..5b922d142e801cef993014ade2a189a690340d11 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-priv.h @@ -0,0 +1,291 @@ +/* + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef UWAC_PRIV_H_ +#define UWAC_PRIV_H_ + +#include + +#include +#include +#include "xdg-shell-client-protocol.h" +#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "server-decoration-client-protocol.h" +#include "viewporter-client-protocol.h" + +#ifdef BUILD_IVI +#include "ivi-application-client-protocol.h" +#endif +#ifdef BUILD_FULLSCREEN_SHELL +#include "fullscreen-shell-unstable-v1-client-protocol.h" +#endif + +#ifdef UWAC_HAVE_PIXMAN_REGION +#include +#else +#include +#endif + +#include + +#include + +extern UwacErrorHandler uwacErrorHandler; + +typedef struct uwac_task UwacTask; + +/** @brief task struct + */ +struct uwac_task +{ + void (*run)(UwacTask* task, uint32_t events); + struct wl_list link; +}; + +/** @brief a global registry object + */ +struct uwac_global +{ + uint32_t name; + char* interface; + uint32_t version; + struct wl_list link; +}; +typedef struct uwac_global UwacGlobal; + +struct uwac_event_list_item; +typedef struct uwac_event_list_item UwacEventListItem; + +/** @brief double linked list element + */ +struct uwac_event_list_item +{ + UwacEvent event; + UwacEventListItem *tail, *head; +}; + +/** @brief main connection object to a wayland display + */ +struct uwac_display +{ + struct wl_list globals; + + struct wl_display* display; + struct wl_registry* registry; + struct wl_compositor* compositor; + struct wp_viewporter* viewporter; + struct wl_subcompositor* subcompositor; + struct wl_shell* shell; + struct xdg_toplevel* xdg_toplevel; + struct xdg_wm_base* xdg_base; + struct wl_data_device_manager* devicemanager; + struct zwp_keyboard_shortcuts_inhibit_manager_v1* keyboard_inhibit_manager; + struct zxdg_decoration_manager_v1* deco_manager; + struct org_kde_kwin_server_decoration_manager* kde_deco_manager; +#ifdef BUILD_IVI + struct ivi_application* ivi_application; +#endif +#ifdef BUILD_FULLSCREEN_SHELL + struct zwp_fullscreen_shell_v1* fullscreen_shell; +#endif + + struct wl_shm* shm; + enum wl_shm_format* shm_formats; + uint32_t shm_formats_nb; + bool has_rgb565; + + struct wl_data_device_manager* data_device_manager; + struct text_cursor_position* text_cursor_position; + struct workspace_manager* workspace_manager; + + struct wl_list seats; + + int display_fd; + UwacReturnCode last_error; + uint32_t display_fd_events; + int epoll_fd; + bool running; + UwacTask dispatch_fd_task; + uint32_t serial; + uint32_t pointer_focus_serial; + int actual_scale; + + struct wl_list windows; + + struct wl_list outputs; + + UwacEventListItem *push_queue, *pop_queue; +}; + +/** @brief an output on a wayland display */ +struct uwac_output +{ + UwacDisplay* display; + + bool doneNeeded; + bool doneReceived; + + UwacPosition position; + UwacSize resolution; + int transform; + int scale; + char* make; + char* model; + uint32_t server_output_id; + struct wl_output* output; + + struct wl_list link; + char* name; + char* description; +}; + +/** @brief a seat attached to a wayland display */ +struct uwac_seat +{ + UwacDisplay* display; + char* name; + struct wl_seat* seat; + uint32_t seat_id; + uint32_t seat_version; + struct wl_data_device* data_device; + struct wl_data_source* data_source; + struct wl_pointer* pointer; + struct wl_surface* pointer_surface; + struct wl_cursor_image* pointer_image; + struct wl_cursor_theme* cursor_theme; + struct wl_cursor* default_cursor; + void* pointer_data; + size_t pointer_size; + int pointer_type; + struct wl_keyboard* keyboard; + struct wl_touch* touch; + struct wl_data_offer* offer; + struct xkb_context* xkb_context; + struct zwp_keyboard_shortcuts_inhibitor_v1* keyboard_inhibitor; + + struct + { + struct xkb_keymap* keymap; + struct xkb_state* state; + xkb_mod_mask_t control_mask; + xkb_mod_mask_t alt_mask; + xkb_mod_mask_t shift_mask; + xkb_mod_mask_t caps_mask; + xkb_mod_mask_t num_mask; + } xkb; + uint32_t modifiers; + int32_t repeat_rate_sec, repeat_rate_nsec; + int32_t repeat_delay_sec, repeat_delay_nsec; + uint32_t repeat_sym, repeat_key, repeat_time; + + struct wl_array pressed_keys; + + UwacWindow* pointer_focus; + + UwacWindow* keyboard_focus; + + UwacWindow* touch_focus; + bool touch_frame_started; + + int repeat_timer_fd; + UwacTask repeat_task; + double sx, sy; + struct wl_list link; + + void* data_context; + UwacDataTransferHandler transfer_data; + UwacCancelDataTransferHandler cancel_data; + bool ignore_announcement; +}; + +/** @brief a buffer used for drawing a surface frame */ +struct uwac_buffer +{ + bool used; + bool dirty; +#ifdef UWAC_HAVE_PIXMAN_REGION + pixman_region32_t damage; +#else + REGION16 damage; +#endif + struct wl_buffer* wayland_buffer; + void* data; + size_t size; +}; +typedef struct uwac_buffer UwacBuffer; + +/** @brief a window */ +struct uwac_window +{ + UwacDisplay* display; + int width, height, stride; + int surfaceStates; + enum wl_shm_format format; + + size_t nbuffers; + UwacBuffer* buffers; + + struct wl_region* opaque_region; + struct wl_region* input_region; + ssize_t drawingBufferIdx; + ssize_t pendingBufferIdx; + struct wl_surface* surface; + struct wp_viewport* viewport; + struct wl_shell_surface* shell_surface; + struct xdg_surface* xdg_surface; + struct xdg_toplevel* xdg_toplevel; + struct zxdg_toplevel_decoration_v1* deco; + struct org_kde_kwin_server_decoration* kde_deco; +#ifdef BUILD_IVI + struct ivi_surface* ivi_surface; +#endif + struct wl_list link; + + uint32_t pointer_enter_serial; + uint32_t pointer_cursor_serial; + int pointer_current_cursor; +}; + +/**@brief data to pass to wl_buffer release listener */ +struct uwac_buffer_release_data +{ + UwacWindow* window; + size_t bufferIdx; +}; +typedef struct uwac_buffer_release_data UwacBufferReleaseData; + +/* in uwa-display.c */ +UwacEvent* UwacDisplayNewEvent(UwacDisplay* d, int type); +int UwacDisplayWatchFd(UwacDisplay* display, int fd, uint32_t events, UwacTask* task); + +/* in uwac-input.c */ +UwacSeat* UwacSeatNew(UwacDisplay* d, uint32_t id, uint32_t version); +void UwacSeatDestroy(UwacSeat* s); + +/* in uwac-output.c */ +UwacOutput* UwacCreateOutput(UwacDisplay* d, uint32_t id, uint32_t version); +int UwacDestroyOutput(UwacOutput* output); + +UwacReturnCode UwacSeatRegisterClipboard(UwacSeat* s); + +#endif /* UWAC_PRIV_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-tools.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-tools.c new file mode 100644 index 0000000000000000000000000000000000000000..760970e6789d582e15568eaef9952a74035b6deb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-tools.c @@ -0,0 +1,106 @@ +/* + * Copyright © 2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include +#include +#include + +struct uwac_touch_automata +{ + struct wl_array tp; +}; + +void UwacTouchAutomataInit(UwacTouchAutomata* automata) +{ + wl_array_init(&automata->tp); +} + +void UwacTouchAutomataReset(UwacTouchAutomata* automata) +{ + automata->tp.size = 0; +} + +bool UwacTouchAutomataInjectEvent(UwacTouchAutomata* automata, UwacEvent* event) +{ + + UwacTouchPoint* tp = NULL; + + switch (event->type) + { + case UWAC_EVENT_TOUCH_FRAME_BEGIN: + break; + + case UWAC_EVENT_TOUCH_UP: + { + UwacTouchUp* touchUp = &event->touchUp; + size_t toMove = automata->tp.size - sizeof(UwacTouchPoint); + + wl_array_for_each(tp, &automata->tp) + { + if ((int64_t)tp->id == touchUp->id) + { + if (toMove) + memmove(tp, tp + 1, toMove); + return true; + } + + toMove -= sizeof(UwacTouchPoint); + } + break; + } + + case UWAC_EVENT_TOUCH_DOWN: + { + UwacTouchDown* touchDown = &event->touchDown; + + wl_array_for_each(tp, &automata->tp) + { + if ((int64_t)tp->id == touchDown->id) + { + tp->x = touchDown->x; + tp->y = touchDown->y; + return true; + } + } + + tp = wl_array_add(&automata->tp, sizeof(UwacTouchPoint)); + if (!tp) + return false; + + if (touchDown->id < 0) + return false; + + tp->id = (uint32_t)touchDown->id; + tp->x = touchDown->x; + tp->y = touchDown->y; + break; + } + + case UWAC_EVENT_TOUCH_FRAME_END: + break; + + default: + break; + } + + return true; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.c new file mode 100644 index 0000000000000000000000000000000000000000..79d419bec7c6a82d0d6ff2539248d338d91c9f15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.c @@ -0,0 +1,68 @@ +/* + * Copyright © 2012 Collabora, Ltd. + * Copyright © 2008 Kristian Høgsberg + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include + +#include +#include +#include +#include + +#include "uwac-utils.h" + +/* + * This part is an adaptation of client/window.c from the weston project. + */ + +static void* fail_on_null(void* p) +{ + if (p == NULL) + { + (void)fprintf(stderr, "out of memory\n"); + // NOLINTNEXTLINE(concurrency-mt-unsafe) + exit(EXIT_FAILURE); + } + + return p; +} + +void* xmalloc(size_t s) +{ + return fail_on_null(malloc(s)); +} + +void* xzalloc(size_t s) +{ + return fail_on_null(zalloc(s)); +} + +char* xstrdup(const char* s) +{ + return fail_on_null(strdup(s)); +} + +void* xrealloc(void* p, size_t s) +{ + return fail_on_null(realloc(p, s)); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.h b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.h new file mode 100644 index 0000000000000000000000000000000000000000..34cfbe1ad797246bdd8649c4a6d105761e18f0ef --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-utils.h @@ -0,0 +1,62 @@ +/* + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#ifndef UWAC_UTILS_H_ +#define UWAC_UTILS_H_ + +#include +#include + +#include + +#define min(a, b) (a) < (b) ? (a) : (b) + +#define container_of(ptr, type, member) (type*)((char*)(ptr)-offsetof(type, member)) + +#define ARRAY_LENGTH(a) (sizeof(a) / sizeof(a)[0]) + +void* xmalloc(size_t s); + +static inline void* zalloc(size_t size) +{ + return calloc(1, size); +} + +void* xzalloc(size_t s); + +char* xstrdup(const char* s); + +void* xrealloc(void* p, size_t s); + +static inline char* uwac_strerror(int dw, char* dmsg, size_t size) +{ +#ifdef __STDC_LIB_EXT1__ + (void)strerror_s(dw, dmsg, size); +#elif defined(UWAC_HAVE_STRERROR_R) + (void)strerror_r(dw, dmsg, size); +#else + (void)_snprintf(dmsg, size, "%s", strerror(dw)); +#endif + return dmsg; +} + +#endif /* UWAC_UTILS_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-window.c b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-window.c new file mode 100644 index 0000000000000000000000000000000000000000..69784702d5146bd9dcfed854ee8d1f1ddec4b00a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/libuwac/uwac-window.c @@ -0,0 +1,921 @@ +/* + * Copyright © 2014 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "uwac-priv.h" +#include "uwac-utils.h" +#include "uwac-os.h" + +#include + +#include + +#define UWAC_INITIAL_BUFFERS 3ull + +static int bppFromShmFormat(enum wl_shm_format format) +{ + switch (format) + { + case WL_SHM_FORMAT_ARGB8888: + case WL_SHM_FORMAT_XRGB8888: + default: + return 4; + } +} + +static void buffer_release(void* data, struct wl_buffer* buffer) +{ + UwacBufferReleaseData* releaseData = data; + UwacBuffer* uwacBuffer = &releaseData->window->buffers[releaseData->bufferIdx]; + uwacBuffer->used = false; +} + +static const struct wl_buffer_listener buffer_listener = { buffer_release }; + +static void UwacWindowDestroyBuffers(UwacWindow* w) +{ + for (size_t i = 0; i < w->nbuffers; i++) + { + UwacBuffer* buffer = &w->buffers[i]; +#ifdef UWAC_HAVE_PIXMAN_REGION + pixman_region32_fini(&buffer->damage); +#else + region16_uninit(&buffer->damage); +#endif + UwacBufferReleaseData* releaseData = + (UwacBufferReleaseData*)wl_buffer_get_user_data(buffer->wayland_buffer); + wl_buffer_destroy(buffer->wayland_buffer); + free(releaseData); + munmap(buffer->data, buffer->size); + } + + w->nbuffers = 0; + free(w->buffers); + w->buffers = NULL; +} + +static int UwacWindowShmAllocBuffers(UwacWindow* w, uint64_t nbuffers, uint64_t allocSize, + uint32_t width, uint32_t height, enum wl_shm_format format); + +static void xdg_handle_toplevel_configure(void* data, struct xdg_toplevel* xdg_toplevel, + int32_t width, int32_t height, struct wl_array* states) +{ + UwacWindow* window = (UwacWindow*)data; + int scale = window->display->actual_scale; + int32_t actual_width = width; + int32_t actual_height = height; + width *= scale; + height *= scale; + UwacConfigureEvent* event = NULL; + int ret = 0; + int surfaceState = 0; + enum xdg_toplevel_state* state = NULL; + surfaceState = 0; + wl_array_for_each(state, states) + { + switch (*state) + { + case XDG_TOPLEVEL_STATE_MAXIMIZED: + surfaceState |= UWAC_WINDOW_MAXIMIZED; + break; + + case XDG_TOPLEVEL_STATE_FULLSCREEN: + surfaceState |= UWAC_WINDOW_FULLSCREEN; + break; + + case XDG_TOPLEVEL_STATE_ACTIVATED: + surfaceState |= UWAC_WINDOW_ACTIVATED; + break; + + case XDG_TOPLEVEL_STATE_RESIZING: + surfaceState |= UWAC_WINDOW_RESIZING; + break; + + default: + break; + } + } + window->surfaceStates = surfaceState; + event = (UwacConfigureEvent*)UwacDisplayNewEvent(window->display, UWAC_EVENT_CONFIGURE); + + if (!event) + { + assert(uwacErrorHandler(window->display, UWAC_ERROR_NOMEMORY, + "failed to allocate a configure event\n")); + return; + } + + event->window = window; + event->states = surfaceState; + + if ((width > 0 && height > 0) && (width != window->width || height != window->height)) + { + event->width = width; + event->height = height; + UwacWindowDestroyBuffers(window); + window->width = width; + window->stride = width * bppFromShmFormat(window->format); + window->height = height; + ret = + UwacWindowShmAllocBuffers(window, UWAC_INITIAL_BUFFERS, 1ull * window->stride * height, + width, height, window->format); + + if (ret != UWAC_SUCCESS) + { + assert( + uwacErrorHandler(window->display, ret, "failed to reallocate a wayland buffers\n")); + window->drawingBufferIdx = window->pendingBufferIdx = -1; + return; + } + + window->drawingBufferIdx = 0; + if (window->pendingBufferIdx != -1) + window->pendingBufferIdx = window->drawingBufferIdx; + + if (window->viewport) + { + wp_viewport_set_source(window->viewport, wl_fixed_from_int(0), wl_fixed_from_int(0), + wl_fixed_from_int(actual_width), + wl_fixed_from_int(actual_height)); + wp_viewport_set_destination(window->viewport, actual_width, actual_height); + } + } + else + { + event->width = window->width; + event->height = window->height; + } +} + +static void xdg_handle_toplevel_close(void* data, struct xdg_toplevel* xdg_toplevel) +{ + UwacCloseEvent* event = NULL; + UwacWindow* window = (UwacWindow*)data; + event = (UwacCloseEvent*)UwacDisplayNewEvent(window->display, UWAC_EVENT_CLOSE); + + if (!event) + { + assert(uwacErrorHandler(window->display, UWAC_ERROR_INTERNAL, + "failed to allocate a close event\n")); + return; + } + + event->window = window; +} + +static const struct xdg_toplevel_listener xdg_toplevel_listener = { + xdg_handle_toplevel_configure, + xdg_handle_toplevel_close, +}; + +static void xdg_handle_surface_configure(void* data, struct xdg_surface* xdg_surface, + uint32_t serial) +{ + xdg_surface_ack_configure(xdg_surface, serial); +} + +static const struct xdg_surface_listener xdg_surface_listener = { + .configure = xdg_handle_surface_configure, +}; + +#if BUILD_IVI + +static void ivi_handle_configure(void* data, struct ivi_surface* surface, int32_t width, + int32_t height) +{ + UwacWindow* window = (UwacWindow*)data; + UwacConfigureEvent* event = NULL; + int ret = 0; + event = (UwacConfigureEvent*)UwacDisplayNewEvent(window->display, UWAC_EVENT_CONFIGURE); + + if (!event) + { + assert(uwacErrorHandler(window->display, UWAC_ERROR_NOMEMORY, + "failed to allocate a configure event\n")); + return; + } + + event->window = window; + event->states = 0; + + if (width && height) + { + event->width = width; + event->height = height; + UwacWindowDestroyBuffers(window); + window->width = width; + window->stride = width * bppFromShmFormat(window->format); + window->height = height; + ret = + UwacWindowShmAllocBuffers(window, UWAC_INITIAL_BUFFERS, 1ull * window->stride * height, + width, height, window->format); + + if (ret != UWAC_SUCCESS) + { + assert( + uwacErrorHandler(window->display, ret, "failed to reallocate a wayland buffers\n")); + window->drawingBufferIdx = window->pendingBufferIdx = -1; + return; + } + + window->drawingBufferIdx = 0; + if (window->pendingBufferIdx != -1) + window->pendingBufferIdx = window->drawingBufferIdx; + } + else + { + event->width = window->width; + event->height = window->height; + } +} + +static const struct ivi_surface_listener ivi_surface_listener = { + ivi_handle_configure, +}; +#endif + +static void shell_ping(void* data, struct wl_shell_surface* surface, uint32_t serial) +{ + wl_shell_surface_pong(surface, serial); +} + +static void shell_configure(void* data, struct wl_shell_surface* surface, uint32_t edges, + int32_t width, int32_t height) +{ + UwacWindow* window = (UwacWindow*)data; + UwacConfigureEvent* event = NULL; + int ret = 0; + event = (UwacConfigureEvent*)UwacDisplayNewEvent(window->display, UWAC_EVENT_CONFIGURE); + + if (!event) + { + assert(uwacErrorHandler(window->display, UWAC_ERROR_NOMEMORY, + "failed to allocate a configure event\n")); + return; + } + + event->window = window; + event->states = 0; + + if (width && height) + { + event->width = width; + event->height = height; + UwacWindowDestroyBuffers(window); + window->width = width; + window->stride = width * bppFromShmFormat(window->format); + window->height = height; + ret = + UwacWindowShmAllocBuffers(window, UWAC_INITIAL_BUFFERS, 1ull * window->stride * height, + width, height, window->format); + + if (ret != UWAC_SUCCESS) + { + assert( + uwacErrorHandler(window->display, ret, "failed to reallocate a wayland buffers\n")); + window->drawingBufferIdx = window->pendingBufferIdx = -1; + return; + } + + window->drawingBufferIdx = 0; + if (window->pendingBufferIdx != -1) + window->pendingBufferIdx = window->drawingBufferIdx; + } + else + { + event->width = window->width; + event->height = window->height; + } +} + +static void shell_popup_done(void* data, struct wl_shell_surface* surface) +{ +} + +static const struct wl_shell_surface_listener shell_listener = { shell_ping, shell_configure, + shell_popup_done }; + +int UwacWindowShmAllocBuffers(UwacWindow* w, uint64_t nbuffers, uint64_t allocSize, uint32_t width, + uint32_t height, enum wl_shm_format format) +{ + int ret = UWAC_SUCCESS; + int fd = 0; + void* data = NULL; + struct wl_shm_pool* pool = NULL; + + if ((width > INT32_MAX) || (height > INT32_MAX)) + return UWAC_ERROR_NOMEMORY; + + const int64_t pagesize = sysconf(_SC_PAGESIZE); + if (pagesize <= 0) + return UWAC_ERROR_NOMEMORY; + + /* round up to a multiple of PAGESIZE to page align data for each buffer */ + const uint64_t test = (1ull * allocSize + (size_t)pagesize - 1ull) & ~((size_t)pagesize - 1); + if (test > INT64_MAX) + return UWAC_ERROR_NOMEMORY; + + allocSize = test; + + UwacBuffer* newBuffers = + xrealloc(w->buffers, (0ull + w->nbuffers + nbuffers) * sizeof(UwacBuffer)); + + if (!newBuffers) + return UWAC_ERROR_NOMEMORY; + + w->buffers = newBuffers; + memset(w->buffers + w->nbuffers, 0, sizeof(UwacBuffer) * nbuffers); + + const size_t allocbuffersize = 1ull * allocSize * nbuffers; + if (allocbuffersize > INT32_MAX) + return UWAC_ERROR_NOMEMORY; + + fd = uwac_create_anonymous_file(WINPR_ASSERTING_INT_CAST(off_t, allocbuffersize)); + + if (fd < 0) + { + return UWAC_ERROR_INTERNAL; + } + + data = mmap(NULL, allocbuffersize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + + if (data == MAP_FAILED) + { + ret = UWAC_ERROR_NOMEMORY; + goto error_mmap; + } + + pool = wl_shm_create_pool(w->display->shm, fd, (int32_t)allocbuffersize); + + if (!pool) + { + munmap(data, allocbuffersize); + ret = UWAC_ERROR_NOMEMORY; + goto error_mmap; + } + + for (uint64_t i = 0; i < nbuffers; i++) + { + const size_t idx = (size_t)i; + const size_t bufferIdx = w->nbuffers + idx; + UwacBuffer* buffer = &w->buffers[bufferIdx]; + +#ifdef UWAC_HAVE_PIXMAN_REGION + pixman_region32_init(&buffer->damage); +#else + region16_init(&buffer->damage); +#endif + const size_t offset = allocSize * idx; + if (offset > INT32_MAX) + goto error_mmap; + + buffer->data = &((char*)data)[allocSize * idx]; + buffer->size = allocSize; + buffer->wayland_buffer = wl_shm_pool_create_buffer(pool, (int32_t)offset, (int32_t)width, + (int32_t)height, w->stride, format); + UwacBufferReleaseData* listener_data = xmalloc(sizeof(UwacBufferReleaseData)); + listener_data->window = w; + listener_data->bufferIdx = bufferIdx; + wl_buffer_add_listener(buffer->wayland_buffer, &buffer_listener, listener_data); + } + + wl_shm_pool_destroy(pool); + w->nbuffers += nbuffers; +error_mmap: + close(fd); + return ret; +} + +static UwacBuffer* UwacWindowFindFreeBuffer(UwacWindow* w, ssize_t* index) +{ + int ret = 0; + + if (index) + *index = -1; + + size_t i = 0; + for (; i < w->nbuffers; i++) + { + if (!w->buffers[i].used) + { + w->buffers[i].used = true; + if (index) + *index = WINPR_ASSERTING_INT_CAST(ssize_t, i); + return &w->buffers[i]; + } + } + + ret = UwacWindowShmAllocBuffers(w, 2, 1ull * w->stride * w->height, w->width, w->height, + w->format); + + if (ret != UWAC_SUCCESS) + { + w->display->last_error = ret; + return NULL; + } + + w->buffers[i].used = true; + if (index) + *index = WINPR_ASSERTING_INT_CAST(ssize_t, i); + return &w->buffers[i]; +} + +static UwacReturnCode UwacWindowSetDecorations(UwacWindow* w) +{ + if (!w || !w->display) + return UWAC_ERROR_INTERNAL; + + if (w->display->deco_manager) + { + w->deco = zxdg_decoration_manager_v1_get_toplevel_decoration(w->display->deco_manager, + w->xdg_toplevel); + if (!w->deco) + { + uwacErrorHandler(w->display, UWAC_NOT_FOUND, + "Current window manager does not allow decorating with SSD"); + } + else + zxdg_toplevel_decoration_v1_set_mode(w->deco, + ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + } + else if (w->display->kde_deco_manager) + { + w->kde_deco = + org_kde_kwin_server_decoration_manager_create(w->display->kde_deco_manager, w->surface); + if (!w->kde_deco) + { + uwacErrorHandler(w->display, UWAC_NOT_FOUND, + "Current window manager does not allow decorating with SSD"); + } + else + org_kde_kwin_server_decoration_request_mode(w->kde_deco, + ORG_KDE_KWIN_SERVER_DECORATION_MODE_SERVER); + } + return UWAC_SUCCESS; +} + +UwacWindow* UwacCreateWindowShm(UwacDisplay* display, uint32_t width, uint32_t height, + enum wl_shm_format format) +{ + UwacWindow* w = NULL; + int ret = 0; + + if (!display) + { + return NULL; + } + + w = xzalloc(sizeof(*w)); + + if (!w) + { + display->last_error = UWAC_ERROR_NOMEMORY; + return NULL; + } + + w->display = display; + w->format = format; + w->width = WINPR_ASSERTING_INT_CAST(int32_t, width); + w->height = WINPR_ASSERTING_INT_CAST(int32_t, height); + w->stride = WINPR_ASSERTING_INT_CAST(int32_t, width* bppFromShmFormat(format)); + const size_t allocSize = 1ULL * w->stride * height; + ret = UwacWindowShmAllocBuffers(w, UWAC_INITIAL_BUFFERS, allocSize, width, height, format); + + if (ret != UWAC_SUCCESS) + { + display->last_error = ret; + goto out_error_free; + } + + w->buffers[0].used = true; + w->drawingBufferIdx = 0; + w->pendingBufferIdx = -1; + w->surface = wl_compositor_create_surface(display->compositor); + + if (!w->surface) + { + display->last_error = UWAC_ERROR_NOMEMORY; + goto out_error_surface; + } + + wl_surface_set_user_data(w->surface, w); + +#if BUILD_IVI + uint32_t ivi_surface_id = 1; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + char* env = getenv("IVI_SURFACE_ID"); + if (env) + { + unsigned long val = 0; + char* endp = NULL; + + errno = 0; + val = strtoul(env, &endp, 10); + + if (!errno && val != 0 && val != UINT32_MAX) + ivi_surface_id = val; + } + + if (display->ivi_application) + { + w->ivi_surface = + ivi_application_surface_create(display->ivi_application, ivi_surface_id, w->surface); + assert(w->ivi_surface); + ivi_surface_add_listener(w->ivi_surface, &ivi_surface_listener, w); + } + else +#endif +#if BUILD_FULLSCREEN_SHELL + if (display->fullscreen_shell) + { + zwp_fullscreen_shell_v1_present_surface(display->fullscreen_shell, w->surface, + ZWP_FULLSCREEN_SHELL_V1_PRESENT_METHOD_CENTER, + NULL); + } + else +#endif + if (display->xdg_base) + { + w->xdg_surface = xdg_wm_base_get_xdg_surface(display->xdg_base, w->surface); + + if (!w->xdg_surface) + { + display->last_error = UWAC_ERROR_NOMEMORY; + goto out_error_shell; + } + + xdg_surface_add_listener(w->xdg_surface, &xdg_surface_listener, w); + + w->xdg_toplevel = xdg_surface_get_toplevel(w->xdg_surface); + if (!w->xdg_toplevel) + { + display->last_error = UWAC_ERROR_NOMEMORY; + goto out_error_shell; + } + + assert(w->xdg_surface); + xdg_toplevel_add_listener(w->xdg_toplevel, &xdg_toplevel_listener, w); + wl_surface_commit(w->surface); + wl_display_roundtrip(w->display->display); + } + else + { + w->shell_surface = wl_shell_get_shell_surface(display->shell, w->surface); + assert(w->shell_surface); + wl_shell_surface_add_listener(w->shell_surface, &shell_listener, w); + wl_shell_surface_set_toplevel(w->shell_surface); + } + + if (display->viewporter) + { + w->viewport = wp_viewporter_get_viewport(display->viewporter, w->surface); + if (display->actual_scale != 1) + wl_surface_set_buffer_scale(w->surface, display->actual_scale); + } + + wl_list_insert(display->windows.prev, &w->link); + display->last_error = UWAC_SUCCESS; + UwacWindowSetDecorations(w); + return w; +out_error_shell: + wl_surface_destroy(w->surface); +out_error_surface: + UwacWindowDestroyBuffers(w); +out_error_free: + free(w); + return NULL; +} + +UwacReturnCode UwacDestroyWindow(UwacWindow** pwindow) +{ + UwacWindow* w = NULL; + assert(pwindow); + w = *pwindow; + UwacWindowDestroyBuffers(w); + + if (w->deco) + zxdg_toplevel_decoration_v1_destroy(w->deco); + + if (w->kde_deco) + org_kde_kwin_server_decoration_destroy(w->kde_deco); + + if (w->xdg_surface) + xdg_surface_destroy(w->xdg_surface); + +#if BUILD_IVI + + if (w->ivi_surface) + ivi_surface_destroy(w->ivi_surface); + +#endif + + if (w->opaque_region) + wl_region_destroy(w->opaque_region); + + if (w->input_region) + wl_region_destroy(w->input_region); + + if (w->viewport) + wp_viewport_destroy(w->viewport); + + wl_surface_destroy(w->surface); + wl_list_remove(&w->link); + free(w); + *pwindow = NULL; + return UWAC_SUCCESS; +} + +UwacReturnCode UwacWindowSetOpaqueRegion(UwacWindow* window, uint32_t x, uint32_t y, uint32_t width, + uint32_t height) +{ + assert(window); + + if (window->opaque_region) + wl_region_destroy(window->opaque_region); + + window->opaque_region = wl_compositor_create_region(window->display->compositor); + + if (!window->opaque_region) + return UWAC_ERROR_NOMEMORY; + + wl_region_add(window->opaque_region, WINPR_ASSERTING_INT_CAST(int32_t, x), + WINPR_ASSERTING_INT_CAST(int32_t, y), WINPR_ASSERTING_INT_CAST(int32_t, width), + WINPR_ASSERTING_INT_CAST(int32_t, height)); + wl_surface_set_opaque_region(window->surface, window->opaque_region); + return UWAC_SUCCESS; +} + +UwacReturnCode UwacWindowSetInputRegion(UwacWindow* window, uint32_t x, uint32_t y, uint32_t width, + uint32_t height) +{ + assert(window); + + if (window->input_region) + wl_region_destroy(window->input_region); + + window->input_region = wl_compositor_create_region(window->display->compositor); + + if (!window->input_region) + return UWAC_ERROR_NOMEMORY; + + wl_region_add(window->input_region, WINPR_ASSERTING_INT_CAST(int32_t, x), + WINPR_ASSERTING_INT_CAST(int32_t, y), WINPR_ASSERTING_INT_CAST(int32_t, width), + WINPR_ASSERTING_INT_CAST(int32_t, height)); + wl_surface_set_input_region(window->surface, window->input_region); + return UWAC_SUCCESS; +} + +void* UwacWindowGetDrawingBuffer(UwacWindow* window) +{ + UwacBuffer* buffer = NULL; + + if (window->drawingBufferIdx < 0) + return NULL; + + buffer = &window->buffers[window->drawingBufferIdx]; + if (!buffer) + return NULL; + + return buffer->data; +} + +static void frame_done_cb(void* data, struct wl_callback* callback, uint32_t time); + +static const struct wl_callback_listener frame_listener = { frame_done_cb }; + +#ifdef UWAC_HAVE_PIXMAN_REGION +static void damage_surface(UwacWindow* window, UwacBuffer* buffer, int scale) +{ + int nrects = 0; + const pixman_box32_t* box = pixman_region32_rectangles(&buffer->damage, &nrects); + + for (int i = 0; i < nrects; i++, box++) + { + const int x = ((int)floor(box->x1 / scale)) - 1; + const int y = ((int)floor(box->y1 / scale)) - 1; + const int w = ((int)ceil((box->x2 - box->x1) / scale)) + 2; + const int h = ((int)ceil((box->y2 - box->y1) / scale)) + 2; + wl_surface_damage(window->surface, x, y, w, h); + } + + pixman_region32_clear(&buffer->damage); +} +#else +static void damage_surface(UwacWindow* window, UwacBuffer* buffer, int scale) +{ + uint32_t nrects = 0; + const RECTANGLE_16* boxes = region16_rects(&buffer->damage, &nrects); + + for (UINT32 i = 0; i < nrects; i++) + { + const RECTANGLE_16* box = &boxes[i]; + const double dx = floor(1.0 * box->left / scale); + const double dy = floor(1.0 * box->top / scale); + const double dw = ceil(1.0 * (box->right - box->left) / scale); + const double dh = ceil(1.0 * (box->bottom - box->top) / scale); + const int x = ((int)dx) - 1; + const int y = ((int)dy) - 1; + const int w = ((int)dw) + 2; + const int h = ((int)dh) + 2; + wl_surface_damage(window->surface, x, y, w, h); + } + + region16_clear(&buffer->damage); +} +#endif + +static void UwacSubmitBufferPtr(UwacWindow* window, UwacBuffer* buffer) +{ + wl_surface_attach(window->surface, buffer->wayland_buffer, 0, 0); + + int scale = window->display->actual_scale; + damage_surface(window, buffer, scale); + + struct wl_callback* frame_callback = wl_surface_frame(window->surface); + wl_callback_add_listener(frame_callback, &frame_listener, window); + wl_surface_commit(window->surface); + buffer->dirty = false; +} + +static void frame_done_cb(void* data, struct wl_callback* callback, uint32_t time) +{ + UwacWindow* window = (UwacWindow*)data; + UwacFrameDoneEvent* event = NULL; + + wl_callback_destroy(callback); + window->pendingBufferIdx = -1; + event = (UwacFrameDoneEvent*)UwacDisplayNewEvent(window->display, UWAC_EVENT_FRAME_DONE); + + if (event) + event->window = window; +} + +#ifdef UWAC_HAVE_PIXMAN_REGION +UwacReturnCode UwacWindowAddDamage(UwacWindow* window, uint32_t x, uint32_t y, uint32_t width, + uint32_t height) +{ + UwacBuffer* buf = NULL; + + if (window->drawingBufferIdx < 0) + return UWAC_ERROR_INTERNAL; + + buf = &window->buffers[window->drawingBufferIdx]; + if (!pixman_region32_union_rect(&buf->damage, &buf->damage, x, y, width, height)) + return UWAC_ERROR_INTERNAL; + + buf->dirty = true; + return UWAC_SUCCESS; +} +#else +UwacReturnCode UwacWindowAddDamage(UwacWindow* window, uint32_t x, uint32_t y, uint32_t width, + uint32_t height) +{ + RECTANGLE_16 box; + UwacBuffer* buf = NULL; + + box.left = x; + box.top = y; + box.right = x + width; + box.bottom = y + height; + + if (window->drawingBufferIdx < 0) + return UWAC_ERROR_INTERNAL; + + buf = &window->buffers[window->drawingBufferIdx]; + if (!buf) + return UWAC_ERROR_INTERNAL; + + if (!region16_union_rect(&buf->damage, &buf->damage, &box)) + return UWAC_ERROR_INTERNAL; + + buf->dirty = true; + return UWAC_SUCCESS; +} +#endif + +UwacReturnCode UwacWindowGetDrawingBufferGeometry(UwacWindow* window, UwacSize* geometry, + size_t* stride) +{ + if (!window || (window->drawingBufferIdx < 0)) + return UWAC_ERROR_INTERNAL; + + if (geometry) + { + geometry->width = window->width; + geometry->height = window->height; + } + + if (stride) + *stride = window->stride; + + return UWAC_SUCCESS; +} + +UwacReturnCode UwacWindowSubmitBuffer(UwacWindow* window, bool copyContentForNextFrame) +{ + UwacBuffer* currentDrawingBuffer = NULL; + UwacBuffer* nextDrawingBuffer = NULL; + UwacBuffer* pendingBuffer = NULL; + + if (window->drawingBufferIdx < 0) + return UWAC_ERROR_INTERNAL; + + currentDrawingBuffer = &window->buffers[window->drawingBufferIdx]; + + if ((window->pendingBufferIdx >= 0) || !currentDrawingBuffer->dirty) + return UWAC_SUCCESS; + + window->pendingBufferIdx = window->drawingBufferIdx; + nextDrawingBuffer = UwacWindowFindFreeBuffer(window, &window->drawingBufferIdx); + pendingBuffer = &window->buffers[window->pendingBufferIdx]; + + if ((!nextDrawingBuffer) || (window->drawingBufferIdx < 0)) + return UWAC_ERROR_NOMEMORY; + + if (copyContentForNextFrame) + memcpy(nextDrawingBuffer->data, pendingBuffer->data, + 1ull * window->stride * window->height); + + UwacSubmitBufferPtr(window, pendingBuffer); + return UWAC_SUCCESS; +} + +UwacReturnCode UwacWindowGetGeometry(UwacWindow* window, UwacSize* geometry) +{ + assert(window); + assert(geometry); + geometry->width = window->width; + geometry->height = window->height; + return UWAC_SUCCESS; +} + +UwacReturnCode UwacWindowSetFullscreenState(UwacWindow* window, UwacOutput* output, + bool isFullscreen) +{ + if (window->xdg_toplevel) + { + if (isFullscreen) + { + xdg_toplevel_set_fullscreen(window->xdg_toplevel, output ? output->output : NULL); + } + else + { + xdg_toplevel_unset_fullscreen(window->xdg_toplevel); + } + } + else if (window->shell_surface) + { + if (isFullscreen) + { + wl_shell_surface_set_fullscreen(window->shell_surface, + WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT, 0, + output ? output->output : NULL); + } + else + { + wl_shell_surface_set_toplevel(window->shell_surface); + } + } + + return UWAC_SUCCESS; +} + +void UwacWindowSetTitle(UwacWindow* window, const char* name) +{ + if (window->xdg_toplevel) + xdg_toplevel_set_title(window->xdg_toplevel, name); + else if (window->shell_surface) + wl_shell_surface_set_title(window->shell_surface, name); +} + +void UwacWindowSetAppId(UwacWindow* window, const char* app_id) +{ + if (window->xdg_toplevel) + xdg_toplevel_set_app_id(window->xdg_toplevel, app_id); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/fullscreen-shell-unstable-v1.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/fullscreen-shell-unstable-v1.xml new file mode 100644 index 0000000000000000000000000000000000000000..7d141ee3cbe59910df607eef43e737e2e24021ac --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/fullscreen-shell-unstable-v1.xml @@ -0,0 +1,220 @@ + + + + + + Displays a single surface per output. + + This interface provides a mechanism for a single client to display + simple full-screen surfaces. While there technically may be multiple + clients bound to this interface, only one of those clients should be + shown at a time. + + To present a surface, the client uses either the present_surface or + present_surface_for_mode requests. Presenting a surface takes effect + on the next wl_surface.commit. See the individual requests for + details about scaling and mode switches. + + The client can have at most one surface per output at any time. + Requesting a surface to be presented on an output that already has a + surface replaces the previously presented surface. Presenting a null + surface removes its content and effectively disables the output. + Exactly what happens when an output is "disabled" is + compositor-specific. The same surface may be presented on multiple + outputs simultaneously. + + Once a surface is presented on an output, it stays on that output + until either the client removes it or the compositor destroys the + output. This way, the client can update the output's contents by + simply attaching a new buffer. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + Release the binding from the wl_fullscreen_shell interface. + + This destroys the server-side object and frees this binding. If + the client binds to wl_fullscreen_shell multiple times, it may wish + to free some of those bindings. + + + + + + Various capabilities that can be advertised by the compositor. They + are advertised one-at-a-time when the wl_fullscreen_shell interface is + bound. See the wl_fullscreen_shell.capability event for more details. + + ARBITRARY_MODES: + This is a hint to the client that indicates that the compositor is + capable of setting practically any mode on its outputs. If this + capability is provided, wl_fullscreen_shell.present_surface_for_mode + will almost never fail and clients should feel free to set whatever + mode they like. If the compositor does not advertise this, it may + still support some modes that are not advertised through wl_global.mode + but it is less likely. + + CURSOR_PLANE: + This is a hint to the client that indicates that the compositor can + handle a cursor surface from the client without actually compositing. + This may be because of a hardware cursor plane or some other mechanism. + If the compositor does not advertise this capability then setting + wl_pointer.cursor may degrade performance or be ignored entirely. If + CURSOR_PLANE is not advertised, it is recommended that the client draw + its own cursor and set wl_pointer.cursor(NULL). + + + + + + + + Advertises a single capability of the compositor. + + When the wl_fullscreen_shell interface is bound, this event is emitted + once for each capability advertised. Valid capabilities are given by + the wl_fullscreen_shell.capability enum. If clients want to take + advantage of any of these capabilities, they should use a + wl_display.sync request immediately after binding to ensure that they + receive all the capability events. + + + + + + + Hints to indicate to the compositor how to deal with a conflict + between the dimensions of the surface and the dimensions of the + output. The compositor is free to ignore this parameter. + + + + + + + + + + + Present a surface on the given output. + + If the output is null, the compositor will present the surface on + whatever display (or displays) it thinks best. In particular, this + may replace any or all surfaces currently presented so it should + not be used in combination with placing surfaces on specific + outputs. + + The method parameter is a hint to the compositor for how the surface + is to be presented. In particular, it tells the compositor how to + handle a size mismatch between the presented surface and the + output. The compositor is free to ignore this parameter. + + The "zoom", "zoom_crop", and "stretch" methods imply a scaling + operation on the surface. This will override any kind of output + scaling, so the buffer_scale property of the surface is effectively + ignored. + + + + + + + + + Presents a surface on the given output for a particular mode. + + If the current size of the output differs from that of the surface, + the compositor will attempt to change the size of the output to + match the surface. The result of the mode-switch operation will be + returned via the provided wl_fullscreen_shell_mode_feedback object. + + If the current output mode matches the one requested or if the + compositor successfully switches the mode to match the surface, + then the mode_successful event will be sent and the output will + contain the contents of the given surface. If the compositor + cannot match the output size to the surface size, the mode_failed + will be sent and the output will contain the contents of the + previously presented surface (if any). If another surface is + presented on the given output before either of these has a chance + to happen, the present_cancelled event will be sent. + + Due to race conditions and other issues unknown to the client, no + mode-switch operation is guaranteed to succeed. However, if the + mode is one advertised by wl_output.mode or if the compositor + advertises the ARBITRARY_MODES capability, then the client should + expect that the mode-switch operation will usually succeed. + + If the size of the presented surface changes, the resulting output + is undefined. The compositor may attempt to change the output mode + to compensate. However, there is no guarantee that a suitable mode + will be found and the client has no way to be notified of success + or failure. + + The framerate parameter specifies the desired framerate for the + output in mHz. The compositor is free to ignore this parameter. A + value of 0 indicates that the client has no preference. + + If the value of wl_output.scale differs from wl_surface.buffer_scale, + then the compositor may choose a mode that matches either the buffer + size or the surface size. In either case, the surface will fill the + output. + + + + + + + + + + These errors can be emitted in response to wl_fullscreen_shell requests. + + + + + + + + + This event indicates that the attempted mode switch operation was + successful. A surface of the size requested in the mode switch + will fill the output without scaling. + + Upon receiving this event, the client should destroy the + wl_fullscreen_shell_mode_feedback object. + + + + + + This event indicates that the attempted mode switch operation + failed. This may be because the requested output mode is not + possible or it may mean that the compositor does not want to allow it. + + Upon receiving this event, the client should destroy the + wl_fullscreen_shell_mode_feedback object. + + + + + + This event indicates that the attempted mode switch operation was + cancelled. Most likely this is because the client requested a + second mode switch before the first one completed. + + Upon receiving this event, the client should destroy the + wl_fullscreen_shell_mode_feedback object. + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/ivi-application.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/ivi-application.xml new file mode 100644 index 0000000000000000000000000000000000000000..54a203e905c93a565d80bfc7c731ad09a7ad6a4e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/ivi-application.xml @@ -0,0 +1,100 @@ + + + + + Copyright (C) 2013 DENSO CORPORATION + Copyright (c) 2013 BMW Car IT GmbH + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + + + + This removes link from ivi_id to wl_surface and destroys ivi_surface. + The ID, ivi_id, is free and can be used for surface_create again. + + + + + + The configure event asks the client to resize its surface. + + The size is a hint, in the sense that the client is free to + ignore it if it doesn't resize, pick a smaller size (to + satisfy aspect ratio or resize in steps of NxM pixels). + + The client is free to dismiss all but the last configure + event it received. + + The width and height arguments specify the size of the window + in surface local coordinates. + + + + + + + + + This interface is exposed as a global singleton. + This interface is implemented by servers that provide IVI-style user interfaces. + It allows clients to associate a ivi_surface with wl_surface. + + + + + + + + + + This request gives the wl_surface the role of an IVI Surface. Creating more than + one ivi_surface for a wl_surface is not allowed. Note, that this still allows the + following example: + + 1. create a wl_surface + 2. create ivi_surface for the wl_surface + 3. destroy the ivi_surface + 4. create ivi_surface for the wl_surface (with the same or another ivi_id as before) + + surface_create will create a interface:ivi_surface with numeric ID; ivi_id in + ivi compositor. These ivi_ids are defined as unique in the system to identify + it inside of ivi compositor. The ivi compositor implements business logic how to + set properties of the surface with ivi_id according to status of the system. + E.g. a unique ID for Car Navigation application is used for implementing special + logic of the application about where it shall be located. + The server regards following cases as protocol errors and disconnects the client. + - wl_surface already has an nother role. + - ivi_id is already assigned to an another wl_surface. + + If client destroys ivi_surface or wl_surface which is assigned to the ivi_surface, + ivi_id which is assigned to the ivi_surface is free for reuse. + + + + + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/keyboard-shortcuts-inhibit-unstable-v1.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/keyboard-shortcuts-inhibit-unstable-v1.xml new file mode 100644 index 0000000000000000000000000000000000000000..27748764d835daeceb5ff76882783a45878638e5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/keyboard-shortcuts-inhibit-unstable-v1.xml @@ -0,0 +1,143 @@ + + + + + Copyright © 2017 Red Hat Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol specifies a way for a client to request the compositor + to ignore its own keyboard shortcuts for a given seat, so that all + key events from that seat get forwarded to a surface. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible + changes may be added together with the corresponding interface + version bump. + Backward incompatible changes are done by bumping the version + number in the protocol and interface names and resetting the + interface version. Once the protocol is to be declared stable, + the 'z' prefix and the version number in the protocol and + interface names are removed and the interface version number is + reset. + + + + + A global interface used for inhibiting the compositor keyboard shortcuts. + + + + + Destroy the keyboard shortcuts inhibitor manager. + + + + + + Create a new keyboard shortcuts inhibitor object associated with + the given surface for the given seat. + + If shortcuts are already inhibited for the specified seat and surface, + a protocol error "already_inhibited" is raised by the compositor. + + + + + + + + + + + + + + A keyboard shortcuts inhibitor instructs the compositor to ignore + its own keyboard shortcuts when the associated surface has keyboard + focus. As a result, when the surface has keyboard focus on the given + seat, it will receive all key events originating from the specified + seat, even those which would normally be caught by the compositor for + its own shortcuts. + + The Wayland compositor is however under no obligation to disable + all of its shortcuts, and may keep some special key combo for its own + use, including but not limited to one allowing the user to forcibly + restore normal keyboard events routing in the case of an unwilling + client. The compositor may also use the same key combo to reactivate + an existing shortcut inhibitor that was previously deactivated on + user request. + + When the compositor restores its own keyboard shortcuts, an + "inactive" event is emitted to notify the client that the keyboard + shortcuts inhibitor is not effectively active for the surface and + seat any more, and the client should not expect to receive all + keyboard events. + + When the keyboard shortcuts inhibitor is inactive, the client has + no way to forcibly reactivate the keyboard shortcuts inhibitor. + + The user can chose to re-enable a previously deactivated keyboard + shortcuts inhibitor using any mechanism the compositor may offer, + in which case the compositor will send an "active" event to notify + the client. + + If the surface is destroyed, unmapped, or loses the seat's keyboard + focus, the keyboard shortcuts inhibitor becomes irrelevant and the + compositor will restore its own keyboard shortcuts but no "inactive" + event is emitted in this case. + + + + + Remove the keyboard shortcuts inhibitor from the associated wl_surface. + + + + + + This event indicates that the shortcut inhibitor is active. + + The compositor sends this event every time compositor shortcuts + are inhibited on behalf of the surface. When active, the client + may receive input events normally reserved by the compositor + (see zwp_keyboard_shortcuts_inhibitor_v1). + + This occurs typically when the initial request "inhibit_shortcuts" + first becomes active or when the user instructs the compositor to + re-enable and existing shortcuts inhibitor using any mechanism + offered by the compositor. + + + + + + This event indicates that the shortcuts inhibitor is inactive, + normal shortcuts processing is restored by the compositor. + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/server-decoration.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/server-decoration.xml new file mode 100644 index 0000000000000000000000000000000000000000..7ea135a12b1da7bcecd7817929770686bcd00aa5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/server-decoration.xml @@ -0,0 +1,96 @@ + + + . + ]]> + + + This interface allows to coordinate whether the server should create + a server-side window decoration around a wl_surface representing a + shell surface (wl_shell_surface or similar). By announcing support + for this interface the server indicates that it supports server + side decorations. + + Use in conjunction with zxdg_decoration_manager_v1 is undefined. + + + + When a client creates a server-side decoration object it indicates + that it supports the protocol. The client is supposed to tell the + server whether it wants server-side decorations or will provide + client-side decorations. + + If the client does not create a server-side decoration object for + a surface the server interprets this as lack of support for this + protocol and considers it as client-side decorated. Nevertheless a + client-side decorated surface should use this protocol to indicate + to the server that it does not want a server-side deco. + + + + + + + + + + + + + This event is emitted directly after binding the interface. It contains + the default mode for the decoration. When a new server decoration object + is created this new object will be in the default mode until the first + request_mode is requested. + + The server may change the default mode at any time. + + + + + + + + + + + + + + + + + + + + + This event is emitted directly after the decoration is created and + represents the base decoration policy by the server. E.g. a server + which wants all surfaces to be client-side decorated will send Client, + a server which wants server-side decoration will send Server. + + The client can request a different mode through the decoration request. + The server will acknowledge this by another event with the same mode. So + even if a server prefers server-side decoration it's possible to force a + client-side decoration. + + The server may emit this event at any time. In this case the client can + again request a different mode. It's the responsibility of the server to + prevent a feedback loop. + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/viewporter.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/viewporter.xml new file mode 100644 index 0000000000000000000000000000000000000000..d1048d1f3327603af92ceaa446843f8fc354f819 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/viewporter.xml @@ -0,0 +1,180 @@ + + + + + Copyright © 2013-2016 Collabora, Ltd. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + The global interface exposing surface cropping and scaling + capabilities is used to instantiate an interface extension for a + wl_surface object. This extended interface will then allow + cropping and scaling the surface contents, effectively + disconnecting the direct relationship between the buffer and the + surface size. + + + + + Informs the server that the client will not be using this + protocol object anymore. This does not affect any other objects, + wp_viewport objects included. + + + + + + + + + + Instantiate an interface extension for the given wl_surface to + crop and scale its content. If the given wl_surface already has + a wp_viewport object associated, the viewport_exists + protocol error is raised. + + + + + + + + + An additional interface to a wl_surface object, which allows the + client to specify the cropping and scaling of the surface + contents. + + This interface works with two concepts: the source rectangle (src_x, + src_y, src_width, src_height), and the destination size (dst_width, + dst_height). The contents of the source rectangle are scaled to the + destination size, and content outside the source rectangle is ignored. + This state is double-buffered, and is applied on the next + wl_surface.commit. + + The two parts of crop and scale state are independent: the source + rectangle, and the destination size. Initially both are unset, that + is, no scaling is applied. The whole of the current wl_buffer is + used as the source, and the surface size is as defined in + wl_surface.attach. + + If the destination size is set, it causes the surface size to become + dst_width, dst_height. The source (rectangle) is scaled to exactly + this size. This overrides whatever the attached wl_buffer size is, + unless the wl_buffer is NULL. If the wl_buffer is NULL, the surface + has no content and therefore no size. Otherwise, the size is always + at least 1x1 in surface local coordinates. + + If the source rectangle is set, it defines what area of the wl_buffer is + taken as the source. If the source rectangle is set and the destination + size is not set, then src_width and src_height must be integers, and the + surface size becomes the source rectangle size. This results in cropping + without scaling. If src_width or src_height are not integers and + destination size is not set, the bad_size protocol error is raised when + the surface state is applied. + + The coordinate transformations from buffer pixel coordinates up to + the surface-local coordinates happen in the following order: + 1. buffer_transform (wl_surface.set_buffer_transform) + 2. buffer_scale (wl_surface.set_buffer_scale) + 3. crop and scale (wp_viewport.set*) + This means, that the source rectangle coordinates of crop and scale + are given in the coordinates after the buffer transform and scale, + i.e. in the coordinates that would be the surface-local coordinates + if the crop and scale was not applied. + + If src_x or src_y are negative, the bad_value protocol error is raised. + Otherwise, if the source rectangle is partially or completely outside of + the non-NULL wl_buffer, then the out_of_buffer protocol error is raised + when the surface state is applied. A NULL wl_buffer does not raise the + out_of_buffer error. + + If the wl_surface associated with the wp_viewport is destroyed, + all wp_viewport requests except 'destroy' raise the protocol error + no_surface. + + If the wp_viewport object is destroyed, the crop and scale + state is removed from the wl_surface. The change will be applied + on the next wl_surface.commit. + + + + + The associated wl_surface's crop and scale state is removed. + The change is applied on the next wl_surface.commit. + + + + + + + + + + + + + Set the source rectangle of the associated wl_surface. See + wp_viewport for the description, and relation to the wl_buffer + size. + + If all of x, y, width and height are -1.0, the source rectangle is + unset instead. Any other set of values where width or height are zero + or negative, or x or y are negative, raise the bad_value protocol + error. + + The crop and scale state is double-buffered state, and will be + applied on the next wl_surface.commit. + + + + + + + + + + Set the destination size of the associated wl_surface. See + wp_viewport for the description, and relation to the wl_buffer + size. + + If width is -1 and height is -1, the destination size is unset + instead. Any other pair of values for width and height that + contains zero or negative values raises the bad_value protocol + error. + + The crop and scale state is double-buffered state, and will be + applied on the next wl_surface.commit. + + + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-decoration-unstable-v1.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-decoration-unstable-v1.xml new file mode 100644 index 0000000000000000000000000000000000000000..378e8ff4bbf7ca78f12f481a0a6f01bb4b661dc4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-decoration-unstable-v1.xml @@ -0,0 +1,156 @@ + + + + Copyright © 2018 Simon Ser + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + This interface allows a compositor to announce support for server-side + decorations. + + A window decoration is a set of window controls as deemed appropriate by + the party managing them, such as user interface components used to move, + resize and change a window's state. + + A client can use this protocol to request being decorated by a supporting + compositor. + + If compositor and client do not negotiate the use of a server-side + decoration using this protocol, clients continue to self-decorate as they + see fit. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + Destroy the decoration manager. This doesn't destroy objects created + with the manager. + + + + + + Create a new decoration object associated with the given toplevel. + + Creating an xdg_toplevel_decoration from an xdg_toplevel which has a + buffer attached or committed is a client error, and any attempts by a + client to attach or manipulate a buffer prior to the first + xdg_toplevel_decoration.configure event must also be treated as + errors. + + + + + + + + + The decoration object allows the compositor to toggle server-side window + decorations for a toplevel surface. The client can request to switch to + another mode. + + The xdg_toplevel_decoration object must be destroyed before its + xdg_toplevel. + + + + + + + + + + + Switch back to a mode without any server-side decorations at the next + commit. + + + + + + These values describe window decoration modes. + + + + + + + + Set the toplevel surface decoration mode. This informs the compositor + that the client prefers the provided decoration mode. + + After requesting a decoration mode, the compositor will respond by + emitting a xdg_surface.configure event. The client should then update + its content, drawing it without decorations if the received mode is + server-side decorations. The client must also acknowledge the configure + when committing the new content (see xdg_surface.ack_configure). + + The compositor can decide not to use the client's mode and enforce a + different mode instead. + + Clients whose decoration mode depend on the xdg_toplevel state may send + a set_mode request in response to a xdg_surface.configure event and wait + for the next xdg_surface.configure event to prevent unwanted state. + Such clients are responsible for preventing configure loops and must + make sure not to send multiple successive set_mode requests with the + same decoration mode. + + + + + + + Unset the toplevel surface decoration mode. This informs the compositor + that the client doesn't prefer a particular decoration mode. + + This request has the same semantics as set_mode. + + + + + + The configure event asks the client to change its decoration mode. The + configured state should not be applied immediately. Clients must send an + ack_configure in response to this event. See xdg_surface.configure and + xdg_surface.ack_configure for details. + + A configure event can be sent at any time. The specified mode must be + obeyed by the client. + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-shell.xml b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-shell.xml new file mode 100644 index 0000000000000000000000000000000000000000..e259a1fba6e1f73de9efe26efa9117f568d6100f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/protocols/xdg-shell.xml @@ -0,0 +1,1144 @@ + + + + + Copyright © 2008-2013 Kristian Høgsberg + Copyright © 2013 Rafael Antognolli + Copyright © 2013 Jasper St. Pierre + Copyright © 2010-2013 Intel Corporation + Copyright © 2015-2017 Samsung Electronics Co., Ltd + Copyright © 2015-2017 Red Hat Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + The xdg_wm_base interface is exposed as a global object enabling clients + to turn their wl_surfaces into windows in a desktop environment. It + defines the basic functionality needed for clients and the compositor to + create windows that can be dragged, resized, maximized, etc, as well as + creating transient windows such as popup menus. + + + + + + + + + + + + + + Destroy this xdg_wm_base object. + + Destroying a bound xdg_wm_base object while there are surfaces + still alive created by this xdg_wm_base object instance is illegal + and will result in a protocol error. + + + + + + Create a positioner object. A positioner object is used to position + surfaces relative to some parent surface. See the interface description + and xdg_surface.get_popup for details. + + + + + + + This creates an xdg_surface for the given surface. While xdg_surface + itself is not a role, the corresponding surface may only be assigned + a role extending xdg_surface, such as xdg_toplevel or xdg_popup. + + This creates an xdg_surface for the given surface. An xdg_surface is + used as basis to define a role to a given surface, such as xdg_toplevel + or xdg_popup. It also manages functionality shared between xdg_surface + based surface roles. + + See the documentation of xdg_surface for more details about what an + xdg_surface is and how it is used. + + + + + + + + A client must respond to a ping event with a pong request or + the client may be deemed unresponsive. See xdg_wm_base.ping. + + + + + + + The ping event asks the client if it's still alive. Pass the + serial specified in the event back to the compositor by sending + a "pong" request back with the specified serial. See xdg_wm_base.ping. + + Compositors can use this to determine if the client is still + alive. It's unspecified what will happen if the client doesn't + respond to the ping request, or in what timeframe. Clients should + try to respond in a reasonable amount of time. + + A compositor is free to ping in any way it wants, but a client must + always respond to any xdg_wm_base object it created. + + + + + + + + The xdg_positioner provides a collection of rules for the placement of a + child surface relative to a parent surface. Rules can be defined to ensure + the child surface remains within the visible area's borders, and to + specify how the child surface changes its position, such as sliding along + an axis, or flipping around a rectangle. These positioner-created rules are + constrained by the requirement that a child surface must intersect with or + be at least partially adjacent to its parent surface. + + See the various requests for details about possible rules. + + At the time of the request, the compositor makes a copy of the rules + specified by the xdg_positioner. Thus, after the request is complete the + xdg_positioner object can be destroyed or reused; further changes to the + object will have no effect on previous usages. + + For an xdg_positioner object to be considered complete, it must have a + non-zero size set by set_size, and a non-zero anchor rectangle set by + set_anchor_rect. Passing an incomplete xdg_positioner object when + positioning a surface raises an error. + + + + + + + + + Notify the compositor that the xdg_positioner will no longer be used. + + + + + + Set the size of the surface that is to be positioned with the positioner + object. The size is in surface-local coordinates and corresponds to the + window geometry. See xdg_surface.set_window_geometry. + + If a zero or negative size is set the invalid_input error is raised. + + + + + + + + Specify the anchor rectangle within the parent surface that the child + surface will be placed relative to. The rectangle is relative to the + window geometry as defined by xdg_surface.set_window_geometry of the + parent surface. + + When the xdg_positioner object is used to position a child surface, the + anchor rectangle may not extend outside the window geometry of the + positioned child's parent surface. + + If a negative size is set the invalid_input error is raised. + + + + + + + + + + + + + + + + + + + + + + Defines the anchor point for the anchor rectangle. The specified anchor + is used derive an anchor point that the child surface will be + positioned relative to. If a corner anchor is set (e.g. 'top_left' or + 'bottom_right'), the anchor point will be at the specified corner; + otherwise, the derived anchor point will be centered on the specified + edge, or in the center of the anchor rectangle if no edge is specified. + + + + + + + + + + + + + + + + + + + Defines in what direction a surface should be positioned, relative to + the anchor point of the parent surface. If a corner gravity is + specified (e.g. 'bottom_right' or 'top_left'), then the child surface + will be placed towards the specified gravity; otherwise, the child + surface will be centered over the anchor point on any axis that had no + gravity specified. + + + + + + + The constraint adjustment value define ways the compositor will adjust + the position of the surface, if the unadjusted position would result + in the surface being partly constrained. + + Whether a surface is considered 'constrained' is left to the compositor + to determine. For example, the surface may be partly outside the + compositor's defined 'work area', thus necessitating the child surface's + position be adjusted until it is entirely inside the work area. + + The adjustments can be combined, according to a defined precedence: 1) + Flip, 2) Slide, 3) Resize. + + + + Don't alter the surface position even if it is constrained on some + axis, for example partially outside the edge of an output. + + + + + Slide the surface along the x axis until it is no longer constrained. + + First try to slide towards the direction of the gravity on the x axis + until either the edge in the opposite direction of the gravity is + unconstrained or the edge in the direction of the gravity is + constrained. + + Then try to slide towards the opposite direction of the gravity on the + x axis until either the edge in the direction of the gravity is + unconstrained or the edge in the opposite direction of the gravity is + constrained. + + + + + Slide the surface along the y axis until it is no longer constrained. + + First try to slide towards the direction of the gravity on the y axis + until either the edge in the opposite direction of the gravity is + unconstrained or the edge in the direction of the gravity is + constrained. + + Then try to slide towards the opposite direction of the gravity on the + y axis until either the edge in the direction of the gravity is + unconstrained or the edge in the opposite direction of the gravity is + constrained. + + + + + Invert the anchor and gravity on the x axis if the surface is + constrained on the x axis. For example, if the left edge of the + surface is constrained, the gravity is 'left' and the anchor is + 'left', change the gravity to 'right' and the anchor to 'right'. + + If the adjusted position also ends up being constrained, the resulting + position of the flip_x adjustment will be the one before the + adjustment. + + + + + Invert the anchor and gravity on the y axis if the surface is + constrained on the y axis. For example, if the bottom edge of the + surface is constrained, the gravity is 'bottom' and the anchor is + 'bottom', change the gravity to 'top' and the anchor to 'top'. + + The adjusted position is calculated given the original anchor + rectangle and offset, but with the new flipped anchor and gravity + values. + + If the adjusted position also ends up being constrained, the resulting + position of the flip_y adjustment will be the one before the + adjustment. + + + + + Resize the surface horizontally so that it is completely + unconstrained. + + + + + Resize the surface vertically so that it is completely unconstrained. + + + + + + + Specify how the window should be positioned if the originally intended + position caused the surface to be constrained, meaning at least + partially outside positioning boundaries set by the compositor. The + adjustment is set by constructing a bitmask describing the adjustment to + be made when the surface is constrained on that axis. + + If no bit for one axis is set, the compositor will assume that the child + surface should not change its position on that axis when constrained. + + If more than one bit for one axis is set, the order of how adjustments + are applied is specified in the corresponding adjustment descriptions. + + The default adjustment is none. + + + + + + + Specify the surface position offset relative to the position of the + anchor on the anchor rectangle and the anchor on the surface. For + example if the anchor of the anchor rectangle is at (x, y), the surface + has the gravity bottom|right, and the offset is (ox, oy), the calculated + surface position will be (x + ox, y + oy). The offset position of the + surface is the one used for constraint testing. See + set_constraint_adjustment. + + An example use case is placing a popup menu on top of a user interface + element, while aligning the user interface element of the parent surface + with some user interface element placed somewhere in the popup surface. + + + + + + + + + An interface that may be implemented by a wl_surface, for + implementations that provide a desktop-style user interface. + + It provides a base set of functionality required to construct user + interface elements requiring management by the compositor, such as + toplevel windows, menus, etc. The types of functionality are split into + xdg_surface roles. + + Creating an xdg_surface does not set the role for a wl_surface. In order + to map an xdg_surface, the client must create a role-specific object + using, e.g., get_toplevel, get_popup. The wl_surface for any given + xdg_surface can have at most one role, and may not be assigned any role + not based on xdg_surface. + + A role must be assigned before any other requests are made to the + xdg_surface object. + + The client must call wl_surface.commit on the corresponding wl_surface + for the xdg_surface state to take effect. + + Creating an xdg_surface from a wl_surface which has a buffer attached or + committed is a client error, and any attempts by a client to attach or + manipulate a buffer prior to the first xdg_surface.configure call must + also be treated as errors. + + Mapping an xdg_surface-based role surface is defined as making it + possible for the surface to be shown by the compositor. Note that + a mapped surface is not guaranteed to be visible once it is mapped. + + For an xdg_surface to be mapped by the compositor, the following + conditions must be met: + (1) the client has assigned an xdg_surface-based role to the surface + (2) the client has set and committed the xdg_surface state and the + role-dependent state to the surface + (3) the client has committed a buffer to the surface + + A newly-unmapped surface is considered to have met condition (1) out + of the 3 required conditions for mapping a surface if its role surface + has not been destroyed. + + + + + + + + + + + Destroy the xdg_surface object. An xdg_surface must only be destroyed + after its role object has been destroyed. + + + + + + This creates an xdg_toplevel object for the given xdg_surface and gives + the associated wl_surface the xdg_toplevel role. + + See the documentation of xdg_toplevel for more details about what an + xdg_toplevel is and how it is used. + + + + + + + This creates an xdg_popup object for the given xdg_surface and gives + the associated wl_surface the xdg_popup role. + + If null is passed as a parent, a parent surface must be specified using + some other protocol, before committing the initial state. + + See the documentation of xdg_popup for more details about what an + xdg_popup is and how it is used. + + + + + + + + + The window geometry of a surface is its "visible bounds" from the + user's perspective. Client-side decorations often have invisible + portions like drop-shadows which should be ignored for the + purposes of aligning, placing and constraining windows. + + The window geometry is double buffered, and will be applied at the + time wl_surface.commit of the corresponding wl_surface is called. + + When maintaining a position, the compositor should treat the (x, y) + coordinate of the window geometry as the top left corner of the window. + A client changing the (x, y) window geometry coordinate should in + general not alter the position of the window. + + Once the window geometry of the surface is set, it is not possible to + unset it, and it will remain the same until set_window_geometry is + called again, even if a new subsurface or buffer is attached. + + If never set, the value is the full bounds of the surface, + including any subsurfaces. This updates dynamically on every + commit. This unset is meant for extremely simple clients. + + The arguments are given in the surface-local coordinate space of + the wl_surface associated with this xdg_surface. + + The width and height must be greater than zero. Setting an invalid size + will raise an error. When applied, the effective window geometry will be + the set window geometry clamped to the bounding rectangle of the + combined geometry of the surface of the xdg_surface and the associated + subsurfaces. + + + + + + + + + + When a configure event is received, if a client commits the + surface in response to the configure event, then the client + must make an ack_configure request sometime before the commit + request, passing along the serial of the configure event. + + For instance, for toplevel surfaces the compositor might use this + information to move a surface to the top left only when the client has + drawn itself for the maximized or fullscreen state. + + If the client receives multiple configure events before it + can respond to one, it only has to ack the last configure event. + + A client is not required to commit immediately after sending + an ack_configure request - it may even ack_configure several times + before its next surface commit. + + A client may send multiple ack_configure requests before committing, but + only the last request sent before a commit indicates which configure + event the client really is responding to. + + + + + + + The configure event marks the end of a configure sequence. A configure + sequence is a set of one or more events configuring the state of the + xdg_surface, including the final xdg_surface.configure event. + + Where applicable, xdg_surface surface roles will during a configure + sequence extend this event as a latched state sent as events before the + xdg_surface.configure event. Such events should be considered to make up + a set of atomically applied configuration states, where the + xdg_surface.configure commits the accumulated state. + + Clients should arrange their surface for the new states, and then send + an ack_configure request with the serial sent in this configure event at + some point before committing the new surface. + + If the client receives multiple configure events before it can respond + to one, it is free to discard all but the last event it received. + + + + + + + + This interface defines an xdg_surface role which allows a surface to, + among other things, set window-like properties such as maximize, + fullscreen, and minimize, set application-specific metadata like title and + id, and well as trigger user interactive operations such as interactive + resize and move. + + Unmapping an xdg_toplevel means that the surface cannot be shown + by the compositor until it is explicitly mapped again. + All active operations (e.g., move, resize) are canceled and all + attributes (e.g. title, state, stacking, ...) are discarded for + an xdg_toplevel surface when it is unmapped. + + Attaching a null buffer to a toplevel unmaps the surface. + + + + + This request destroys the role surface and unmaps the surface; + see "Unmapping" behavior in interface section for details. + + + + + + Set the "parent" of this surface. This surface should be stacked + above the parent surface and all other ancestor surfaces. + + Parent windows should be set on dialogs, toolboxes, or other + "auxiliary" surfaces, so that the parent is raised when the dialog + is raised. + + Setting a null parent for a child window removes any parent-child + relationship for the child. Setting a null parent for a window which + currently has no parent is a no-op. + + If the parent is unmapped then its children are managed as + though the parent of the now-unmapped parent has become the + parent of this surface. If no parent exists for the now-unmapped + parent then the children are managed as though they have no + parent surface. + + + + + + + Set a short title for the surface. + + This string may be used to identify the surface in a task bar, + window list, or other user interface elements provided by the + compositor. + + The string must be encoded in UTF-8. + + + + + + + Set an application identifier for the surface. + + The app ID identifies the general class of applications to which + the surface belongs. The compositor can use this to group multiple + surfaces together, or to determine how to launch a new application. + + For D-Bus activatable applications, the app ID is used as the D-Bus + service name. + + The compositor shell will try to group application surfaces together + by their app ID. As a best practice, it is suggested to select app + ID's that match the basename of the application's .desktop file. + For example, "org.freedesktop.FooViewer" where the .desktop file is + "org.freedesktop.FooViewer.desktop". + + See the desktop-entry specification [0] for more details on + application identifiers and how they relate to well-known D-Bus + names and .desktop files. + + [0] http://standards.freedesktop.org/desktop-entry-spec/ + + + + + + + Clients implementing client-side decorations might want to show + a context menu when right-clicking on the decorations, giving the + user a menu that they can use to maximize or minimize the window. + + This request asks the compositor to pop up such a window menu at + the given position, relative to the local surface coordinates of + the parent surface. There are no guarantees as to what menu items + the window menu contains. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. + + + + + + + + + + Start an interactive, user-driven move of the surface. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. The passed + serial is used to determine the type of interactive move (touch, + pointer, etc). + + The server may ignore move requests depending on the state of + the surface (e.g. fullscreen or maximized), or if the passed serial + is no longer valid. + + If triggered, the surface will lose the focus of the device + (wl_pointer, wl_touch, etc) used for the move. It is up to the + compositor to visually indicate that the move is taking place, such as + updating a pointer cursor, during the move. There is no guarantee + that the device focus will return when the move is completed. + + + + + + + + These values are used to indicate which edge of a surface + is being dragged in a resize operation. + + + + + + + + + + + + + + + Start a user-driven, interactive resize of the surface. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. The passed + serial is used to determine the type of interactive resize (touch, + pointer, etc). + + The server may ignore resize requests depending on the state of + the surface (e.g. fullscreen or maximized). + + If triggered, the client will receive configure events with the + "resize" state enum value and the expected sizes. See the "resize" + enum value for more details about what is required. The client + must also acknowledge configure events using "ack_configure". After + the resize is completed, the client will receive another "configure" + event without the resize state. + + If triggered, the surface also will lose the focus of the device + (wl_pointer, wl_touch, etc) used for the resize. It is up to the + compositor to visually indicate that the resize is taking place, + such as updating a pointer cursor, during the resize. There is no + guarantee that the device focus will return when the resize is + completed. + + The edges parameter specifies how the surface should be resized, + and is one of the values of the resize_edge enum. The compositor + may use this information to update the surface position for + example when dragging the top left corner. The compositor may also + use this information to adapt its behavior, e.g. choose an + appropriate cursor image. + + + + + + + + + The different state values used on the surface. This is designed for + state values like maximized, fullscreen. It is paired with the + configure event to ensure that both the client and the compositor + setting the state can be synchronized. + + States set in this way are double-buffered. They will get applied on + the next commit. + + + + The surface is maximized. The window geometry specified in the configure + event must be obeyed by the client. + + The client should draw without shadow or other + decoration outside of the window geometry. + + + + + The surface is fullscreen. The window geometry specified in the + configure event is a maximum; the client cannot resize beyond it. For + a surface to cover the whole fullscreened area, the geometry + dimensions must be obeyed by the client. For more details, see + xdg_toplevel.set_fullscreen. + + + + + The surface is being resized. The window geometry specified in the + configure event is a maximum; the client cannot resize beyond it. + Clients that have aspect ratio or cell sizing configuration can use + a smaller size, however. + + + + + Client window decorations should be painted as if the window is + active. Do not assume this means that the window actually has + keyboard or pointer focus. + + + + + The window is currently in a tiled layout and the left edge is + considered to be adjacent to another part of the tiling grid. + + + + + The window is currently in a tiled layout and the right edge is + considered to be adjacent to another part of the tiling grid. + + + + + The window is currently in a tiled layout and the top edge is + considered to be adjacent to another part of the tiling grid. + + + + + The window is currently in a tiled layout and the bottom edge is + considered to be adjacent to another part of the tiling grid. + + + + + + + Set a maximum size for the window. + + The client can specify a maximum size so that the compositor does + not try to configure the window beyond this size. + + The width and height arguments are in window geometry coordinates. + See xdg_surface.set_window_geometry. + + Values set in this way are double-buffered. They will get applied + on the next commit. + + The compositor can use this information to allow or disallow + different states like maximize or fullscreen and draw accurate + animations. + + Similarly, a tiling window manager may use this information to + place and resize client windows in a more effective way. + + The client should not rely on the compositor to obey the maximum + size. The compositor may decide to ignore the values set by the + client and request a larger size. + + If never set, or a value of zero in the request, means that the + client has no expected maximum size in the given dimension. + As a result, a client wishing to reset the maximum size + to an unspecified state can use zero for width and height in the + request. + + Requesting a maximum size to be smaller than the minimum size of + a surface is illegal and will result in a protocol error. + + The width and height must be greater than or equal to zero. Using + strictly negative values for width and height will result in a + protocol error. + + + + + + + + Set a minimum size for the window. + + The client can specify a minimum size so that the compositor does + not try to configure the window below this size. + + The width and height arguments are in window geometry coordinates. + See xdg_surface.set_window_geometry. + + Values set in this way are double-buffered. They will get applied + on the next commit. + + The compositor can use this information to allow or disallow + different states like maximize or fullscreen and draw accurate + animations. + + Similarly, a tiling window manager may use this information to + place and resize client windows in a more effective way. + + The client should not rely on the compositor to obey the minimum + size. The compositor may decide to ignore the values set by the + client and request a smaller size. + + If never set, or a value of zero in the request, means that the + client has no expected minimum size in the given dimension. + As a result, a client wishing to reset the minimum size + to an unspecified state can use zero for width and height in the + request. + + Requesting a minimum size to be larger than the maximum size of + a surface is illegal and will result in a protocol error. + + The width and height must be greater than or equal to zero. Using + strictly negative values for width and height will result in a + protocol error. + + + + + + + + Maximize the surface. + + After requesting that the surface should be maximized, the compositor + will respond by emitting a configure event. Whether this configure + actually sets the window maximized is subject to compositor policies. + The client must then update its content, drawing in the configured + state. The client must also acknowledge the configure when committing + the new content (see ack_configure). + + It is up to the compositor to decide how and where to maximize the + surface, for example which output and what region of the screen should + be used. + + If the surface was already maximized, the compositor will still emit + a configure event with the "maximized" state. + + If the surface is in a fullscreen state, this request has no direct + effect. It may alter the state the surface is returned to when + unmaximized unless overridden by the compositor. + + + + + + Unmaximize the surface. + + After requesting that the surface should be unmaximized, the compositor + will respond by emitting a configure event. Whether this actually + un-maximizes the window is subject to compositor policies. + If available and applicable, the compositor will include the window + geometry dimensions the window had prior to being maximized in the + configure event. The client must then update its content, drawing it in + the configured state. The client must also acknowledge the configure + when committing the new content (see ack_configure). + + It is up to the compositor to position the surface after it was + unmaximized; usually the position the surface had before maximizing, if + applicable. + + If the surface was already not maximized, the compositor will still + emit a configure event without the "maximized" state. + + If the surface is in a fullscreen state, this request has no direct + effect. It may alter the state the surface is returned to when + unmaximized unless overridden by the compositor. + + + + + + Make the surface fullscreen. + + After requesting that the surface should be fullscreened, the + compositor will respond by emitting a configure event. Whether the + client is actually put into a fullscreen state is subject to compositor + policies. The client must also acknowledge the configure when + committing the new content (see ack_configure). + + The output passed by the request indicates the client's preference as + to which display it should be set fullscreen on. If this value is NULL, + it's up to the compositor to choose which display will be used to map + this surface. + + If the surface doesn't cover the whole output, the compositor will + position the surface in the center of the output and compensate with + with border fill covering the rest of the output. The content of the + border fill is undefined, but should be assumed to be in some way that + attempts to blend into the surrounding area (e.g. solid black). + + If the fullscreened surface is not opaque, the compositor must make + sure that other screen content not part of the same surface tree (made + up of subsurfaces, popups or similarly coupled surfaces) are not + visible below the fullscreened surface. + + + + + + + Make the surface no longer fullscreen. + + After requesting that the surface should be unfullscreened, the + compositor will respond by emitting a configure event. + Whether this actually removes the fullscreen state of the client is + subject to compositor policies. + + Making a surface unfullscreen sets states for the surface based on the following: + * the state(s) it may have had before becoming fullscreen + * any state(s) decided by the compositor + * any state(s) requested by the client while the surface was fullscreen + + The compositor may include the previous window geometry dimensions in + the configure event, if applicable. + + The client must also acknowledge the configure when committing the new + content (see ack_configure). + + + + + + Request that the compositor minimize your surface. There is no + way to know if the surface is currently minimized, nor is there + any way to unset minimization on this surface. + + If you are looking to throttle redrawing when minimized, please + instead use the wl_surface.frame event for this, as this will + also work with live previews on windows in Alt-Tab, Expose or + similar compositor features. + + + + + + This configure event asks the client to resize its toplevel surface or + to change its state. The configured state should not be applied + immediately. See xdg_surface.configure for details. + + The width and height arguments specify a hint to the window + about how its surface should be resized in window geometry + coordinates. See set_window_geometry. + + If the width or height arguments are zero, it means the client + should decide its own window dimension. This may happen when the + compositor needs to configure the state of the surface but doesn't + have any information about any previous or expected dimension. + + The states listed in the event specify how the width/height + arguments should be interpreted, and possibly how it should be + drawn. + + Clients must send an ack_configure in response to this event. See + xdg_surface.configure and xdg_surface.ack_configure for details. + + + + + + + + + The close event is sent by the compositor when the user + wants the surface to be closed. This should be equivalent to + the user clicking the close button in client-side decorations, + if your application has any. + + This is only a request that the user intends to close the + window. The client may choose to ignore this request, or show + a dialog to ask the user to save their data, etc. + + + + + + + A popup surface is a short-lived, temporary surface. It can be used to + implement for example menus, popovers, tooltips and other similar user + interface concepts. + + A popup can be made to take an explicit grab. See xdg_popup.grab for + details. + + When the popup is dismissed, a popup_done event will be sent out, and at + the same time the surface will be unmapped. See the xdg_popup.popup_done + event for details. + + Explicitly destroying the xdg_popup object will also dismiss the popup and + unmap the surface. Clients that want to dismiss the popup when another + surface of their own is clicked should dismiss the popup using the destroy + request. + + A newly created xdg_popup will be stacked on top of all previously created + xdg_popup surfaces associated with the same xdg_toplevel. + + The parent of an xdg_popup must be mapped (see the xdg_surface + description) before the xdg_popup itself. + + The x and y arguments passed when creating the popup object specify + where the top left of the popup should be placed, relative to the + local surface coordinates of the parent surface. See + xdg_surface.get_popup. An xdg_popup must intersect with or be at least + partially adjacent to its parent surface. + + The client must call wl_surface.commit on the corresponding wl_surface + for the xdg_popup state to take effect. + + + + + + + + + This destroys the popup. Explicitly destroying the xdg_popup + object will also dismiss the popup, and unmap the surface. + + If this xdg_popup is not the "topmost" popup, a protocol error + will be sent. + + + + + + This request makes the created popup take an explicit grab. An explicit + grab will be dismissed when the user dismisses the popup, or when the + client destroys the xdg_popup. This can be done by the user clicking + outside the surface, using the keyboard, or even locking the screen + through closing the lid or a timeout. + + If the compositor denies the grab, the popup will be immediately + dismissed. + + This request must be used in response to some sort of user action like a + button press, key press, or touch down event. The serial number of the + event should be passed as 'serial'. + + The parent of a grabbing popup must either be an xdg_toplevel surface or + another xdg_popup with an explicit grab. If the parent is another + xdg_popup it means that the popups are nested, with this popup now being + the topmost popup. + + Nested popups must be destroyed in the reverse order they were created + in, e.g. the only popup you are allowed to destroy at all times is the + topmost one. + + When compositors choose to dismiss a popup, they may dismiss every + nested grabbing popup as well. When a compositor dismisses popups, it + will follow the same dismissing order as required from the client. + + The parent of a grabbing popup must either be another xdg_popup with an + active explicit grab, or an xdg_popup or xdg_toplevel, if there are no + explicit grabs already taken. + + If the topmost grabbing popup is destroyed, the grab will be returned to + the parent of the popup, if that parent previously had an explicit grab. + + If the parent is a grabbing popup which has already been dismissed, this + popup will be immediately dismissed. If the parent is a popup that did + not take an explicit grab, an error will be raised. + + During a popup grab, the client owning the grab will receive pointer + and touch events for all their surfaces as normal (similar to an + "owner-events" grab in X11 parlance), while the top most grabbing popup + will always have keyboard focus. + + + + + + + + This event asks the popup surface to configure itself given the + configuration. The configured state should not be applied immediately. + See xdg_surface.configure for details. + + The x and y arguments represent the position the popup was placed at + given the xdg_positioner rule, relative to the upper left corner of the + window geometry of the parent surface. + + + + + + + + + + The popup_done event is sent out when a popup is dismissed by the + compositor. The client should destroy the xdg_popup object at this + point. + + + + + diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1850cec5eccdf4adca20eb2bcbcc22a44147e75e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/CMakeLists.txt @@ -0,0 +1,45 @@ +set(UWAC_INCLUDE_DIR "include/uwac${UWAC_VERSION_MAJOR}") + +if(NOT UWAC_FORCE_STATIC_BUILD) + # cmake package + export(PACKAGE uwac) + + setfreerdpcmakeinstalldir(UWAC_CMAKE_INSTALL_DIR "uwac${UWAC_VERSION_MAJOR}") + + configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/uwacConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/uwacConfig.cmake + INSTALL_DESTINATION ${UWAC_CMAKE_INSTALL_DIR} PATH_VARS UWAC_INCLUDE_DIR + ) + + write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/uwacConfigVersion.cmake VERSION ${UWAC_VERSION} COMPATIBILITY SameMajorVersion + ) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/uwacConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/uwacConfigVersion.cmake + DESTINATION ${UWAC_CMAKE_INSTALL_DIR} + ) + + install(EXPORT uwac DESTINATION ${UWAC_CMAKE_INSTALL_DIR}) +endif() + +set(UWAC_BUILD_CONFIG_LIST "") +get_cmake_property(res VARIABLES) +foreach(var ${res}) + if(var MATCHES "^WITH_*|^BUILD_TESTING*|^UWAC_HAVE_*") + list(APPEND UWAC_BUILD_CONFIG_LIST "${var}=${${var}}") + endif() +endforeach() + +string(REPLACE ";" " " UWAC_BUILD_CONFIG "${UWAC_BUILD_CONFIG_LIST}") +cleaning_configure_file(version.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/uwac/version.h) +cleaning_configure_file(buildflags.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/uwac/buildflags.h) +cleaning_configure_file(build-config.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/uwac/build-config.h) +cleaning_configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/../include/uwac/config.h) + +if(NOT UWAC_FORCE_STATIC_BUILD) + include(pkg-config-install-prefix) + cleaning_configure_file(uwac.pc.in ${CMAKE_CURRENT_BINARY_DIR}/uwac${UWAC_VERSION_MAJOR}.pc @ONLY) + + set(UWAC_INSTALL_INCLUDE_DIR ${UWAC_INCLUDE_DIR}/uwac) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/uwac${UWAC_VERSION_MAJOR}.pc DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR}) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/build-config.h.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/build-config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..a2c103e99fb78dbed442f6bc2e3002f4efe656aa --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/build-config.h.in @@ -0,0 +1,22 @@ +#ifndef UWAC_BUILD_CONFIG_H +#define UWAC_BUILD_CONFIG_H + +#define UWAC_DATA_PATH "${WINPR_DATA_PATH}" +#define UWAC_KEYMAP_PATH "${WINPR_KEYMAP_PATH}" +#define UWAC_PLUGIN_PATH "${WINPR_PLUGIN_PATH}" + +#define UWAC_INSTALL_PREFIX "${WINPR_INSTALL_PREFIX}" + +#define UWAC_LIBRARY_PATH "${WINPR_LIBRARY_PATH}" + +#define UWAC_ADDIN_PATH "${WINPR_ADDIN_PATH}" + +#define UWAC_SHARED_LIBRARY_SUFFIX "${CMAKE_SHARED_LIBRARY_SUFFIX}" +#define UWAC_SHARED_LIBRARY_PREFIX "${CMAKE_SHARED_LIBRARY_PREFIX}" + +#define UWAC_VENDOR_STRING "${VENDOR}" +#define UWAC_PRODUCT_STRING "${PRODUCT}" + +#define UWAC_PROXY_PLUGINDIR "${WINPR_PROXY_PLUGINDIR}" + +#endif /* UWAC_BUILD_CONFIG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/buildflags.h.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/buildflags.h.in new file mode 100644 index 0000000000000000000000000000000000000000..30ca2085086f77b92dc60a7acb25fea99d56af47 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/buildflags.h.in @@ -0,0 +1,11 @@ +#ifndef UWAC_BUILD_FLAGS_H +#define UWAC_BUILD_FLAGS_H + +#define UWAC_CFLAGS "${CURRENT_C_FLAGS}" +#define UWAC_COMPILER_ID "${CMAKE_C_COMPILER_ID}" +#define UWAC_COMPILER_VERSION "${CMAKE_C_COMPILER_VERSION}" +#define UWAC_TARGET_ARCH "${TARGET_ARCH}" +#define UWAC_BUILD_CONFIG "${UWAC_BUILD_CONFIG}" +#define UWAC_BUILD_TYPE "${CURRENT_BUILD_CONFIG}" + +#endif /* UWAC_BUILD_FLAGS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/config.h.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..bd2d84e3687763dc7302ec00ecff3f7c6f716909 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/config.h.in @@ -0,0 +1,12 @@ +#ifndef UWAC_CONFIG_H +#define UWAC_CONFIG_H + +/* Include files */ +#cmakedefine UWAC_HAVE_TM_GMTOFF +#cmakedefine UWAC_HAVE_POLL_H +#cmakedefine UWAC_HAVE_SYSLOG_H +#cmakedefine UWAC_HAVE_JOURNALD_H +#cmakedefine UWAC_HAVE_PIXMAN_REGION +#cmakedefine UWAC_HAVE_STRERROR_R + +#endif /* UWAC_CONFIG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwac.pc.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwac.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..c0abdee19c28bd3c775efa65384c4bb7c80910e0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwac.pc.in @@ -0,0 +1,15 @@ +prefix=@PKG_CONFIG_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${prefix}/@UWAC_INCLUDE_DIR@ +libs=-luwac@UWAC_VERSION_MAJOR@ + +Name: uwac@UWAC_API_VERSION@ +Description: uwac: using wayland as a client +URL: http://www.freerdp.com/ +Version: @UWAC_VERSION@ +Requires: +Requires.private: wayland-client xkbcommon freerdp@FREERDP_VERSION_MAJOR@ +Libs: -L${libdir} ${libs} +Libs.private: +Cflags: -I${includedir} diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwacConfig.cmake.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwacConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..2433842e9c8f0d2f7373a464118068181c33106e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/uwacConfig.cmake.in @@ -0,0 +1,9 @@ +@PACKAGE_INIT@ + +set(UWAC_VERSION_MAJOR "@UWAC_VERSION_MAJOR@") +set(UWAC_VERSION_MINOR "@UWAC_VERSION_MINOR@") +set(UWAC_VERSION_REVISION "@UWAC_VERSION_REVISION@") + +set_and_check(UWAC_INCLUDE_DIR "@PACKAGE_UWAC_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/uwac.cmake") diff --git a/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/version.h.in b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/version.h.in new file mode 100644 index 0000000000000000000000000000000000000000..1b941b6a03bf225993ef886d7aa2423a5858fc49 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/uwac/templates/version.h.in @@ -0,0 +1,32 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Version includes + * + * Copyright 2021 Thincast Technologies GmbH + * Copyright 2021 Armin Novak + * + * 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 UWAC_VERSION_H +#define UWAC_VERSION_H + +#define UWAC_VERSION_MAJOR ${UWAC_VERSION_MAJOR} +#define UWAC_VERSION_MINOR ${UWAC_VERSION_MINOR} +#define UWAC_VERSION_REVISION ${UWAC_VERSION_REVISION} +#define UWAC_VERSION_SUFFIX "${UWAC_VERSION_SUFFIX}" +#define UWAC_API_VERSION "${UWAC_API_VERSION}" +#define UWAC_VERSION "${UWAC_VERSION}" +#define UWAC_VERSION_FULL "${UWAC_VERSION_FULL}" +#define UWAC_GIT_REVISION "${GIT_REVISION}" + +#endif /* UWAC_VERSION_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4d6ec252b0a62a4724ecdc3411b91226030b043a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/CMakeLists.txt @@ -0,0 +1,44 @@ +# WinPR: Windows Portable Runtime +# winpr cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/build-config.h.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/build-config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..4a9bfbba1f1e4a6383783c5fdc99414879f0ed4d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/build-config.h.in @@ -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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/buildflags.h.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/buildflags.h.in new file mode 100644 index 0000000000000000000000000000000000000000..a94567fd5354191c92133219e0d088218a1a7132 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/buildflags.h.in @@ -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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/config.h.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..ce419556a2de750519ae3cb80a5b7a6c4cb4448f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/config.h.in @@ -0,0 +1,50 @@ +#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_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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/version.h.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/version.h.in new file mode 100644 index 0000000000000000000000000000000000000000..8b8c0abaf84db1ce1448b9916f21c30a59a4e986 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/config/version.h.in @@ -0,0 +1,32 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Version includes + * + * Copyright 2013 Thincast Technologies GmbH + * Copyright 2013 Bernhard Miklautz + * + * 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_ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/asn1.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/asn1.h new file mode 100644 index 0000000000000000000000000000000000000000..75556eb3def9b854a2c07e35ef1f427a29f95fe1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/asn1.h @@ -0,0 +1,212 @@ +/** + * WinPR: Windows Portable Runtime + * ASN1 encoder / decoder + * + * Copyright 2022 David Fort + * + * 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 +#include +#include + +#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; + +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_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert-api.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert-api.h new file mode 100644 index 0000000000000000000000000000000000000000..a2f71d02ec025a0aa1412124b2ea7d09954f433d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert-api.h @@ -0,0 +1,97 @@ +/** + * WinPR: Windows Portable Runtime + * Runtime ASSERT macros + * + * Copyright 2021 Armin Novak + * 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 +#include + +#include +#include + +#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 diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert.h new file mode 100644 index 0000000000000000000000000000000000000000..8aaca9276faa9579ada0077cf45c247ccd3b2cca --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/assert.h @@ -0,0 +1,34 @@ +/** + * WinPR: Windows Portable Runtime + * Compatibility header for runtime ASSERT macros + * + * Copyright 2024 Armin Novak + * 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 +#include + +#include +#include +#include +#include + +#include +#include +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bcrypt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bcrypt.h new file mode 100644 index 0000000000000000000000000000000000000000..06ed40952c202f8c49d89d7e2a1b4e18d2db0cd4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bcrypt.h @@ -0,0 +1,166 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API: Next Generation + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#else + +#include +#include + +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[] = u"RSA"; +static const WCHAR BCRYPT_RSA_SIGN_ALGORITHM[] = u"RSA_SIGN"; +static const WCHAR BCRYPT_DH_ALGORITHM[] = u"DH"; +static const WCHAR BCRYPT_DSA_ALGORITHM[] = u"DSA"; +static const WCHAR BCRYPT_RC2_ALGORITHM[] = u"RC2"; +static const WCHAR BCRYPT_RC4_ALGORITHM[] = u"RC4"; +static const WCHAR BCRYPT_AES_ALGORITHM[] = u"AES"; +static const WCHAR BCRYPT_DES_ALGORITHM[] = u"DES"; +static const WCHAR BCRYPT_DESX_ALGORITHM[] = u"DESX"; +static const WCHAR BCRYPT_3DES_ALGORITHM[] = u"3DES"; +static const WCHAR BCRYPT_3DES_112_ALGORITHM[] = u"3DES_112"; +static const WCHAR BCRYPT_MD2_ALGORITHM[] = u"MD2"; +static const WCHAR BCRYPT_MD4_ALGORITHM[] = u"MD4"; +static const WCHAR BCRYPT_MD5_ALGORITHM[] = u"MD5"; +static const WCHAR BCRYPT_SHA1_ALGORITHM[] = u"SHA1"; +static const WCHAR BCRYPT_SHA256_ALGORITHM[] = u"SHA256"; +static const WCHAR BCRYPT_SHA384_ALGORITHM[] = u"SHA384"; +static const WCHAR BCRYPT_SHA512_ALGORITHM[] = u"SHA512"; +static const WCHAR BCRYPT_AES_GMAC_ALGORITHM[] = u"AES-GMAC"; +static const WCHAR BCRYPT_AES_CMAC_ALGORITHM[] = u"AES-CMAC"; +static const WCHAR BCRYPT_ECDSA_P256_ALGORITHM[] = u"ECDSA_P256"; +static const WCHAR BCRYPT_ECDSA_P384_ALGORITHM[] = u"ECDSA_P384"; +static const WCHAR BCRYPT_ECDSA_P521_ALGORITHM[] = u"ECDSA_P521"; +static const WCHAR BCRYPT_ECDH_P256_ALGORITHM[] = u"ECDSA_P256"; +static const WCHAR BCRYPT_ECDH_P384_ALGORITHM[] = u"ECDSA_P384"; +static const WCHAR BCRYPT_ECDH_P521_ALGORITHM[] = u"ECDSA_P521"; +static const WCHAR BCRYPT_RNG_ALGORITHM[] = u"RNG"; +static const WCHAR BCRYPT_RNG_FIPS186_DSA_ALGORITHM[] = u"FIPS186DSARNG"; +static const WCHAR BCRYPT_RNG_DUAL_EC_ALGORITHM[] = u"DUALECRNG"; + +static const WCHAR BCRYPT_ECDSA_ALGORITHM[] = u"ECDSA"; +static const WCHAR BCRYPT_ECDH_ALGORITHM[] = u"ECDH"; +static const WCHAR BCRYPT_XTS_AES_ALGORITHM[] = u"XTS-AES"; + +static const WCHAR MS_PRIMITIVE_PROVIDER[] = u"Microsoft Primitive Provider"; +static const WCHAR MS_PLATFORM_CRYPTO_PROVIDER[] = u"Microsoft Platform Crypto Provider"; + +#define BCRYPT_ALG_HANDLE_HMAC_FLAG 0x00000008 +#define BCRYPT_PROV_DISPATCH 0x00000001 + +static const WCHAR BCRYPT_OBJECT_LENGTH[] = u"ObjectLength"; +static const WCHAR BCRYPT_ALGORITHM_NAME[] = u"AlgorithmName"; +static const WCHAR BCRYPT_PROVIDER_HANDLE[] = u"ProviderHandle"; +static const WCHAR BCRYPT_CHAINING_MODE[] = u"ChainingMode"; +static const WCHAR BCRYPT_BLOCK_LENGTH[] = u"BlockLength"; +static const WCHAR BCRYPT_KEY_LENGTH[] = u"KeyLength"; +static const WCHAR BCRYPT_KEY_OBJECT_LENGTH[] = u"KeyObjectLength"; +static const WCHAR BCRYPT_KEY_STRENGTH[] = u"KeyStrength"; +static const WCHAR BCRYPT_KEY_LENGTHS[] = u"KeyLengths"; +static const WCHAR BCRYPT_BLOCK_SIZE_LIST[] = u"BlockSizeList"; +static const WCHAR BCRYPT_EFFECTIVE_KEY_LENGTH[] = u"EffectiveKeyLength"; +static const WCHAR BCRYPT_HASH_LENGTH[] = u"HashDigestLength"; +static const WCHAR BCRYPT_HASH_OID_LIST[] = u"HashOIDList"; +static const WCHAR BCRYPT_PADDING_SCHEMES[] = u"PaddingSchemes"; +static const WCHAR BCRYPT_SIGNATURE_LENGTH[] = u"SignatureLength"; +static const WCHAR BCRYPT_HASH_BLOCK_LENGTH[] = u"HashBlockLength"; +static const WCHAR BCRYPT_AUTH_TAG_LENGTH[] = u"AuthTagLength"; +static const WCHAR BCRYPT_PRIMITIVE_TYPE[] = u"PrimitiveType"; +static const WCHAR BCRYPT_IS_KEYED_HASH[] = u"IsKeyedHash"; +static const WCHAR BCRYPT_KEY_DATA_BLOB[] = u"KeyDataBlob"; + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bitstream.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bitstream.h new file mode 100644 index 0000000000000000000000000000000000000000..4a8327eee605346c71dc51bf741035bbaf5a8a8f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/bitstream.h @@ -0,0 +1,186 @@ +/* + * WinPR: Windows Portable Runtime + * BitStream Utils + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include + +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; + if (((UINT32)(_bs->pointer - _bs->buffer) + 4) < (_bs->capacity)) + (_bs->prefetch) |= ((UINT32) * (_bs->pointer + 4) << 24); + if (((UINT32)(_bs->pointer - _bs->buffer) + 5) < (_bs->capacity)) + (_bs->prefetch) |= ((UINT32) * (_bs->pointer + 5) << 16); + if (((UINT32)(_bs->pointer - _bs->buffer) + 6) < (_bs->capacity)) + (_bs->prefetch) |= ((UINT32) * (_bs->pointer + 6) << 8); + if (((UINT32)(_bs->pointer - _bs->buffer) + 7) < (_bs->capacity)) + (_bs->prefetch) |= ((UINT32) * (_bs->pointer + 7) << 0); + } + + static INLINE void BitStream_Fetch(wBitStream* _bs) + { + WINPR_ASSERT(_bs); + (_bs->accumulator) = 0; + if (((UINT32)(_bs->pointer - _bs->buffer) + 0) < (_bs->capacity)) + (_bs->accumulator) |= ((UINT32) * (_bs->pointer + 0) << 24); + if (((UINT32)(_bs->pointer - _bs->buffer) + 1) < (_bs->capacity)) + (_bs->accumulator) |= ((UINT32) * (_bs->pointer + 1) << 16); + if (((UINT32)(_bs->pointer - _bs->buffer) + 2) < (_bs->capacity)) + (_bs->accumulator) |= ((UINT32) * (_bs->pointer + 2) << 8); + if (((UINT32)(_bs->pointer - _bs->buffer) + 3) < (_bs->capacity)) + (_bs->accumulator) |= ((UINT32) * (_bs->pointer + 3) << 0); + BitStream_Prefetch(_bs); + } + + static INLINE void BitStream_Flush(wBitStream* _bs) + { + WINPR_ASSERT(_bs); + if (((UINT32)(_bs->pointer - _bs->buffer) + 0) < (_bs->capacity)) + *(_bs->pointer + 0) = (BYTE)((UINT32)_bs->accumulator >> 24); + if (((UINT32)(_bs->pointer - _bs->buffer) + 1) < (_bs->capacity)) + *(_bs->pointer + 1) = (BYTE)((UINT32)_bs->accumulator >> 16); + if (((UINT32)(_bs->pointer - _bs->buffer) + 2) < (_bs->capacity)) + *(_bs->pointer + 2) = (BYTE)((UINT32)_bs->accumulator >> 8); + if (((UINT32)(_bs->pointer - _bs->buffer) + 3) < (_bs->capacity)) + *(_bs->pointer + 3) = (BYTE)((UINT32)_bs->accumulator >> 0); + } + + 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_API wBitStream* BitStream_New(void); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_UTILS_BITSTREAM_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cast.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cast.h new file mode 100644 index 0000000000000000000000000000000000000000..5d7b2ce41d134da49d861a5394735f74c1085001 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cast.h @@ -0,0 +1,122 @@ +/** + * WinPR: Windows Portable Runtime + * Cast macros + * + * Copyright 2024 Armin Novak + * 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 + +#include + +/** + * @brief C++ safe cast macro + * @since version 3.10.1 + */ +#ifdef __cplusplus +#define WINPR_CXX_COMPAT_CAST(t, val) static_cast(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, var) \ + __extension__({ \ + 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 diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/clipboard.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/clipboard.h new file mode 100644 index 0000000000000000000000000000000000000000..5a6a8ce43d0f7294a26dbe1e2ac0d200edbb2387 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/clipboard.h @@ -0,0 +1,109 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cmdline.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cmdline.h new file mode 100644 index 0000000000000000000000000000000000000000..1421f60a6f88d80456f6ef8ed72940deaf1fc632 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cmdline.h @@ -0,0 +1,196 @@ +/** + * WinPR: Windows Portable Runtime + * Command-Line Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +/* 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 NULL + * + * @since version 3.10.0 + */ + WINPR_API void CommandLineParserFree(char** ptr); + + WINPR_ATTR_MALLOC(CommandLineParserFree, 1) + WINPR_API char** CommandLineParseCommaSeparatedValues(const char* list, size_t* count); + + WINPR_ATTR_MALLOC(CommandLineParserFree, 1) + WINPR_API char** CommandLineParseCommaSeparatedValuesEx(const char* name, const char* list, + size_t* count); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* CommandLineToCommaSeparatedValues(int argc, char* argv[]); + + WINPR_ATTR_MALLOC(free, 1) + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/collections.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/collections.h new file mode 100644 index 0000000000000000000000000000000000000000..aa396651f2e59aacbdaed14bd72cb1f75134c051 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/collections.h @@ -0,0 +1,888 @@ +/** + * WinPR: Windows Portable Runtime + * Collections + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#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 + * + * @var fnObjectNew A new function that creates a clone of the input + * @var fnObjectInit A function initializing an object, but not allocating it + * @var fnObjectUninit A function to deinitialize an object, but not free it + * @var fnObjectFree A function freeing an object + * @var fnObjectEquals A function to compare two objects + */ + typedef struct + { + OBJECT_NEW_FN fnObjectNew; + OBJECT_INIT_FN fnObjectInit; + OBJECT_UNINIT_FN fnObjectUninit; + OBJECT_FREE_FN fnObjectFree; + OBJECT_EQUALS_FN fnObjectEquals; + } 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 NULL + * @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 NULL + * @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 NULL + * + * @return the number of objects queued + */ + WINPR_API size_t Queue_Count(wQueue* queue); + + /** @brief Mutex-Lock a queue + * + * @param queue A pointer to a queue, must not be \b NULL + */ + WINPR_API void Queue_Lock(wQueue* queue); + + /** @brief Mutex-Unlock a queue + * + * @param queue A pointer to a queue, must not be \b NULL + */ + 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 NULL + */ + WINPR_API HANDLE Queue_Event(wQueue* queue); + + /** @brief Mutex-Lock a queue + * + * @param queue A pointer to a queue, must not be \b NULL + * + * @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 NULL + */ + 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 NULL + * @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 NULL 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 NULL 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 NULL + */ + WINPR_API void Queue_Free(wQueue* queue); + + /** @brief Creates a new queue + * + * @return A newly allocated queue or \b NULL in case of failure + */ + WINPR_ATTR_MALLOC(Queue_Free, 1) + 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_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_API WINPR_DEPRECATED(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_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 NULL + * + * @return a \b wObject used to initialize the key object, \b NULL 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 NULL + * + * @return a \b wObject used to initialize the value object, \b NULL 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 NULL + * + * @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 NULL + */ + WINPR_API void ListDictionary_Lock(wListDictionary* listDictionary); + /** @brief mutex-unlock a dictionary + * + * @param listDictionary A dictionary to query, must not be \b NULL + */ + WINPR_API void ListDictionary_Unlock(wListDictionary* listDictionary); + + /** @brief mutex-lock a dictionary + * + * @param listDictionary A dictionary to query, must not be \b NULL + * @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 NULL. 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 NULL + * @param key The key identifying the entry + * + * @return a pointer to the value stored or \b NULL 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 NULL + * @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 NULL + * + * @return a pointer to the value stored or \b NULL 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 NULL + */ + 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 NULL + */ + 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 NULL + * @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 NULL + * @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 NULL + */ + 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 NULL + * @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 NULL 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 NULL + * @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 NULL + */ + 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 NULL in case of failure + */ + WINPR_ATTR_MALLOC(ListDictionary_Free, 1) + WINPR_API wListDictionary* ListDictionary_New(BOOL synchronized); + + /* System.Collections.Generic.LinkedList */ + + 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 NULL + * + * @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 NULL + * + * @return A pointer to the element or \b NULL 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 NULL + * + * @return A pointer to the element or \b NULL 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 NULL + * @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 NULL + * + */ + 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 NULL + * @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 NULL + * @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 NULL + * @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 NULL + * + */ + 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 NULL + * + */ + 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 NULL + * + */ + 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 NULL + * + * @return A pointer to the current entry or \b NULL + */ + 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 NULL + * + * @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 NULL + */ + WINPR_API void LinkedList_Free(wLinkedList* list); + + /** @brief Allocate a linked list + * + * @return A pointer to the newly allocated linked list or \b NULL in case of failure + */ + WINPR_ATTR_MALLOC(LinkedList_Free, 1) + 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 NULL + * + * @return A pointer to the wObject or \b NULL in case of failure + */ + WINPR_API wObject* LinkedList_Object(wLinkedList* list); + + /* System.Collections.Generic.KeyValuePair */ + + /* 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 NULL + * + * @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 NULL + * + * @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 NULL + * + * @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 NULL + * + * @return a \b HANDLE or \b NULL 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 NULL + * @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 NULL + * @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 NULL + * + */ + WINPR_API void CountdownEvent_Reset(wCountdownEvent* countdown, size_t count); + + /** @brief Free a CountdownEvent + * + * @param countdown A pointer to a CountdownEvent, may be \b NULL + */ + 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 NULL in case of failure + */ + WINPR_ATTR_MALLOC(CountdownEvent_Free, 1) + 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_API WINPR_DEPRECATED(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_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_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_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); + WINPR_API size_t MessageQueue_Size(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 NULL if not used. + * + * \return A pointer to a newly allocated MessageQueue or NULL. + */ + WINPR_ATTR_MALLOC(MessageQueue_Free, 1) + 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_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(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), NULL }, 0, \ + { \ + NULL \ + } \ + } + + 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_API wPubSub* PubSub_New(BOOL synchronized); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_COLLECTIONS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/comm.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..c5532248c8fe49bdc229a85cfe0966613fe290f4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/comm.h @@ -0,0 +1,505 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 +#include +#include +#include + +#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_API HANDLE CommCreateFileA(LPCSTR lpFileName, 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; + } _SERIAL_IOCTL_NAME; + + /** + * FIXME: got a proper function name and place + */ + WINPR_API const char* _comm_serial_ioctl_name(ULONG number); + + /** + * FIXME: got a proper function name and place + */ + WINPR_API void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID); + + /** + * FIXME: got a proper function name and place + * + * permissive mode is disabled by default. + */ + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cred.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cred.h new file mode 100644 index 0000000000000000000000000000000000000000..0c7ce8fee78b9701320a9a10c62905dd399bb60f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/cred.h @@ -0,0 +1,62 @@ +/** + * WinPR: Windows Portable Runtime + * Windows credentials + * + * Copyright 2022 David Fort + * + * 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 + +#ifdef _WIN32 +#include +#else + +#define CERT_HASH_LENGTH 20 + +typedef enum +{ + CertCredential, + 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; + +#if 0 /* shall we implement these ? */ +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 + +#endif /* 0 */ + +#endif /* _WIN32 */ + +#endif /* WINPR_CRED_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crt.h new file mode 100644 index 0000000000000000000000000000000000000000..825461580c4eebdf42016b7c88ab0efc84a88dfc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crt.h @@ -0,0 +1,240 @@ +/** + * WinPR: Windows Portable Runtime + * C Run-Time Library Routines + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include +#include + +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER + +#ifndef _WIN32 + +#include + +#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_API void* winpr_aligned_malloc(size_t size, size_t alignment); + + WINPR_ATTR_MALLOC(winpr_aligned_free, 1) + WINPR_API void* winpr_aligned_calloc(size_t count, size_t size, size_t alignment); + + WINPR_ATTR_MALLOC(winpr_aligned_free, 1) + WINPR_API void* winpr_aligned_realloc(void* memblock, size_t size, size_t alignment); + + WINPR_ATTR_MALLOC(winpr_aligned_free, 1) + 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_API void* winpr_aligned_offset_malloc(size_t size, size_t alignment, size_t offset); + + WINPR_ATTR_MALLOC(winpr_aligned_free, 1) + 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_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(NULL, count, size, alignment) +#endif /* defined(_WIN32) && (!defined(__MINGW32__) || defined(_UCRT)) */ + +WINPR_PRAGMA_DIAG_POP + +#endif /* WINPR_CRT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crypto.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..df38fedb708accaea2a6733fe4332aaef5735dcd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/crypto.h @@ -0,0 +1,26 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#endif /* WINPR_CRYPTO_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/custom-crypto.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/custom-crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..d74f4e536f34a5ca63651caf5afef3cb1031569d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/custom-crypto.h @@ -0,0 +1,320 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +/** + * 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_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_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_API WINPR_RC4_CTX* winpr_RC4_New_Allow_FIPS(const void* key, size_t keylen); + + WINPR_ATTR_MALLOC(winpr_RC4_Free, 1) + 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); + + WINPR_ATTR_MALLOC(winpr_Cipher_Free, 1) + WINPR_API WINPR_DEPRECATED_VAR("[since 3.10.0] use winpr_Cipher_NewEx", + WINPR_CIPHER_CTX* winpr_Cipher_New(WINPR_CIPHER_TYPE cipher, + WINPR_CRYPTO_OPERATION op, + const void* key, + const void* iv)); + + /** @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 NULL + * + * @since version 3.10.0 + */ + WINPR_ATTR_MALLOC(winpr_Cipher_Free, 1) + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/debug.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..334a57fb3d8ac9ab4d6a1a1b7712119a57d06a01 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/debug.h @@ -0,0 +1,51 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2014 Armin Novak + * 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 +#include +#include + + 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_API void* winpr_backtrace(DWORD size); + + WINPR_ATTR_MALLOC(free, 1) + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/dsparse.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/dsparse.h new file mode 100644 index 0000000000000000000000000000000000000000..63b2b54e7e0d4f035d3c766da7fa50c7b8ada7e6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/dsparse.h @@ -0,0 +1,127 @@ +/** + * WinPR: Windows Portable Runtime + * Active Directory Domain Services Parsing Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +#else + +#include +#include +#include +#include + +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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/endian.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/endian.h new file mode 100644 index 0000000000000000000000000000000000000000..ba0b7651310a909b3c29987e87128ba928be1a63 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/endian.h @@ -0,0 +1,428 @@ +/* + * WinPR: Windows Portable Runtime + * Endianness Macros + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2024 Armin Novak + * 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 +#include +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/environment.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/environment.h new file mode 100644 index 0000000000000000000000000000000000000000..cd5c1e66efd5fb6e0c0e46d2b33d41b76f1c6523 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/environment.h @@ -0,0 +1,151 @@ +/** + * WinPR: Windows Portable Runtime + * Process Environment Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Thincast Technologies GmbH + * Copyright 2013 DI (FH) Martin Haimberger + * + * 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 +#include + +#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_API LPCH GetEnvironmentStrings(VOID); + + WINPR_ATTR_MALLOC(FreeEnvironmentStringsW, 1) + 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_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_API char** EnvironmentBlockToEnvpA(LPCH lpszEnvironmentBlock); + + WINPR_API DWORD GetEnvironmentVariableX(const char* lpName, char* lpBuffer, DWORD nSize); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetEnvAlloc(LPCSTR lpName); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_ENVIRONMENT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/error.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/error.h new file mode 100644 index 0000000000000000000000000000000000000000..ad50f5a7fed32df7f57b5198cdb9ade3ec4963ed --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/error.h @@ -0,0 +1,3107 @@ +/** + * WinPR: Windows Portable Runtime + * Error Handling Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_ERROR_H +#define WINPR_ERROR_H + +#include +#include + +#ifdef _WIN32 + +#include + +/* mingw is possibly missing some definitions */ +#ifndef RPC_S_PROXY_ACCESS_DENIED +#define RPC_S_PROXY_ACCESS_DENIED 0x000006C1 +#endif + +#ifndef RPC_S_COOKIE_AUTH_FAILED +#define RPC_S_COOKIE_AUTH_FAILED 0x00000729 +#endif + +#ifndef ERROR_OPERATION_IN_PROGRESS +#define ERROR_OPERATION_IN_PROGRESS 0x00000149 +#endif + +#else + +#ifndef NO_ERROR +#define NO_ERROR 0 +#endif + +#define E_UNEXPECTED -2147418113l // 0x8000FFFFL +#define E_ACCESSDENIED -2147024891l // 0x80070005L +#define E_HANDLE -2147024890l // 0x80070006L +#define E_OUTOFMEMORY -2147024882l // 0x8007000EL + +#define E_INVALIDARG -2147024809l // 0x80070057L +#define E_NOTIMPL -2147467263l // 0x80004001L +#define E_NOINTERFACE -2147467262l // 0x80004002L +#define E_POINTER -2147467261l // 0x80004003L +#define E_ABORT -2147467260l // 0x80004004L +#define E_FAIL -2147467259l // 0x80004005L + +#define CO_E_INIT_TLS -2147467258l // 0x80004006l +#define CO_E_INIT_SHARED_ALLOCATOR -2147467257l // 0x80004007l +#define CO_E_INIT_MEMORY_ALLOCATOR -2147467256l // 0x80004008l +#define CO_E_INIT_CLASS_CACHE -2147467255l // 0x80004009l +#define CO_E_INIT_RPC_CHANNEL -2147467254l // 0x8000400Al +#define CO_E_INIT_TLS_SET_CHANNEL_CONTROL -2147467253l // 0x8000400Bl +#define CO_E_INIT_TLS_CHANNEL_CONTROL -2147467252l // 0x8000400Cl +#define CO_E_INIT_UNACCEPTED_USER_ALLOCATOR -2147467251l // 0x8000400Dl +#define CO_E_INIT_SCM_MUTEX_EXISTS -2147467250l // 0x8000400El +#define CO_E_INIT_SCM_FILE_MAPPING_EXISTS -2147467249l // 0x8000400Fl +#define CO_E_INIT_SCM_MAP_VIEW_OF_FILE -2147467248l // 0x80004010l +#define CO_E_INIT_SCM_EXEC_FAILURE -2147467247l // 0x80004011l +#define CO_E_INIT_ONLY_SINGLE_THREADED -2147467246l // 0x80004012l +#define CO_E_CANT_REMOTE -2147467245l // 0x80004013l +#define CO_E_BAD_SERVER_NAME -2147467244l // 0x80004014l +#define CO_E_WRONG_SERVER_IDENTITY -2147467243l // 0x80004015l +#define CO_E_OLE1DDE_DISABLED -2147467242l // 0x80004016l +#define CO_E_RUNAS_SYNTAX -2147467241l // 0x80004017l +#define CO_E_CREATEPROCESS_FAILURE -2147467240l // 0x80004018l +#define CO_E_RUNAS_CREATEPROCESS_FAILURE -2147467239l // 0x80004019l +#define CO_E_RUNAS_LOGON_FAILURE -2147467238l // 0x8000401Al +#define CO_E_LAUNCH_PERMSSION_DENIED -2147467237l // 0x8000401Bl +#define CO_E_START_SERVICE_FAILURE -2147467236l // 0x8000401Cl +#define CO_E_REMOTE_COMMUNICATION_FAILURE -2147467235l // 0x8000401Dl +#define CO_E_SERVER_START_TIMEOUT -2147467234l // 0x8000401El +#define CO_E_CLSREG_INCONSISTENT -2147467233l // 0x8000401Fl +#define CO_E_IIDREG_INCONSISTENT -2147467232l // 0x80004020l +#define CO_E_NOT_SUPPORTED -2147467231l // 0x80004021l +#define CO_E_RELOAD_DLL -2147467230l // 0x80004022l +#define CO_E_MSI_ERROR -2147467229l // 0x80004023l +#define CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT -2147467228l // 0x80004024l +#define CO_E_SERVER_PAUSED -2147467227l // 0x80004025l +#define CO_E_SERVER_NOT_PAUSED -2147467226l // 0x80004026l +#define CO_E_CLASS_DISABLED -2147467225l // 0x80004027l +#define CO_E_CLRNOTAVAILABLE -2147467224l // 0x80004028l +#define CO_E_ASYNC_WORK_REJECTED -2147467223l // 0x80004029l +#define CO_E_SERVER_INIT_TIMEOUT -2147467222l // 0x8000402Al +#define CO_E_NO_SECCTX_IN_ACTIVATE -2147467221l // 0x8000402Bl +#define CO_E_TRACKER_CONFIG -2147467216l // 0x80004030l +#define CO_E_THREADPOOL_CONFIG -2147467215l // 0x80004031l +#define CO_E_SXS_CONFIG -2147467214l // 0x80004032l +#define CO_E_MALFORMED_SPN -2147467213l // 0x80004033l + +#define FACILITY_WINDOWSUPDATE 36 +#define FACILITY_WINDOWS_CE 24 +#define FACILITY_WINDOWS 8 +#define FACILITY_URT 19 +#define FACILITY_UMI 22 +#define FACILITY_SXS 23 +#define FACILITY_STORAGE 3 +#define FACILITY_STATE_MANAGEMENT 34 +#define FACILITY_SSPI 9 +#define FACILITY_SCARD 16 +#define FACILITY_SETUPAPI 15 +#define FACILITY_SECURITY 9 +#define FACILITY_RPC 1 +#define FACILITY_WIN32 7 +#define FACILITY_CONTROL 10 +#define FACILITY_NULL 0 +#define FACILITY_METADIRECTORY 35 +#define FACILITY_MSMQ 14 +#define FACILITY_MEDIASERVER 13 +#define FACILITY_INTERNET 12 +#define FACILITY_ITF 4 +#define FACILITY_HTTP 25 +#define FACILITY_DPLAY 21 +#define FACILITY_DISPATCH 2 +#define FACILITY_DIRECTORYSERVICE 37 +#define FACILITY_CONFIGURATION 33 +#define FACILITY_COMPLUS 17 +#define FACILITY_CERT 11 +#define FACILITY_BACKGROUNDCOPY 32 +#define FACILITY_ACS 20 +#define FACILITY_AAF 18 + +#define FACILITY_NT_BIT 0x10000000 + +#define SEVERITY_SUCCESS 0 +#define SEVERITY_ERROR 1 + +#define HRESULT_CODE(hr) ((hr)&0xFFFF) +#define HRESULT_FACILITY(hr) (((hr) >> 16) & 0x1FFF) + +#define HRESULT_FROM_NT(x) (((x) | FACILITY_NT_BIT)) + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#define ERROR_CAST(t, val) WINPR_CXX_COMPAT_CAST(t, val) + +static INLINE HRESULT HRESULT_FROM_WIN32(unsigned long x) +{ + HRESULT hx = ERROR_CAST(HRESULT, x); + if (hx <= 0) + return hx; + return ERROR_CAST(HRESULT, (((x)&0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000)); +} + +WINPR_PRAGMA_DIAG_POP + +#define HRESULT_SEVERITY(hr) (((hr) >> 31) & 0x1) + +#define SUCCEEDED(hr) (((hr)) >= 0) +#define FAILED(hr) (((hr)) < 0) +#define IS_ERROR(Status) ((ERROR_CAST(unsigned long, Status)) >> 31 == SEVERITY_ERROR) + +#define MAKE_HRESULT(sev, fac, code) \ + ((HRESULT)((ERROR_CAST(unsigned long, sev) << 31) | (ERROR_CAST(unsigned long, fac) << 16) | \ + (ERROR_CAST(unsigned long, code)))) + +#define SCODE_CODE(sc) ((sc)&0xFFFF) +#define SCODE_FACILITY(sc) (((sc) >> 16) & 0x1FFF) +#define SCODE_SEVERITY(sc) (((sc) >> 31) & 0x1) + +#define MAKE_SCODE(sev, fac, code) \ + ((SCODE)((ERROR_CAST(unsigned long, sev) << 31) | (ERROR_CAST(unsigned long, fac) << 16) | \ + (ERROR_CAST(unsigned long, code)))) + +#define S_OK (0L) +#define S_FALSE (1L) + +/* System Error Codes (0-499) */ + +#define ERROR_SUCCESS 0x00000000 +#define ERROR_INVALID_FUNCTION 0x00000001 +#define ERROR_FILE_NOT_FOUND 0x00000002 +#define ERROR_PATH_NOT_FOUND 0x00000003 +#define ERROR_TOO_MANY_OPEN_FILES 0x00000004 +#define ERROR_ACCESS_DENIED 0x00000005 +#define ERROR_INVALID_HANDLE 0x00000006 +#define ERROR_ARENA_TRASHED 0x00000007 +#define ERROR_NOT_ENOUGH_MEMORY 0x00000008 +#define ERROR_INVALID_BLOCK 0x00000009 +#define ERROR_BAD_ENVIRONMENT 0x0000000A +#define ERROR_BAD_FORMAT 0x0000000B +#define ERROR_INVALID_ACCESS 0x0000000C +#define ERROR_INVALID_DATA 0x0000000D +#define ERROR_OUTOFMEMORY 0x0000000E +#define ERROR_INVALID_DRIVE 0x0000000F +#define ERROR_CURRENT_DIRECTORY 0x00000010 +#define ERROR_NOT_SAME_DEVICE 0x00000011 +#define ERROR_NO_MORE_FILES 0x00000012 +#define ERROR_WRITE_PROTECT 0x00000013 +#define ERROR_BAD_UNIT 0x00000014 +#define ERROR_NOT_READY 0x00000015 +#define ERROR_BAD_COMMAND 0x00000016 +#define ERROR_CRC 0x00000017 +#define ERROR_BAD_LENGTH 0x00000018 +#define ERROR_SEEK 0x00000019 +#define ERROR_NOT_DOS_DISK 0x0000001A +#define ERROR_SECTOR_NOT_FOUND 0x0000001B +#define ERROR_OUT_OF_PAPER 0x0000001C +#define ERROR_WRITE_FAULT 0x0000001D +#define ERROR_READ_FAULT 0x0000001E +#define ERROR_GEN_FAILURE 0x0000001F +#define ERROR_SHARING_VIOLATION 0x00000020 +#define ERROR_LOCK_VIOLATION 0x00000021 +#define ERROR_WRONG_DISK 0x00000022 +#define ERROR_SHARING_BUFFER_EXCEEDED 0x00000024 +#define ERROR_HANDLE_EOF 0x00000026 +#define ERROR_HANDLE_DISK_FULL 0x00000027 +#define ERROR_NOT_SUPPORTED 0x00000032 +#define ERROR_REM_NOT_LIST 0x00000033 +#define ERROR_DUP_NAME 0x00000034 +#define ERROR_BAD_NETPATH 0x00000035 +#define ERROR_NETWORK_BUSY 0x00000036 +#define ERROR_DEV_NOT_EXIST 0x00000037 +#define ERROR_TOO_MANY_CMDS 0x00000038 +#define ERROR_ADAP_HDW_ERR 0x00000039 +#define ERROR_BAD_NET_RESP 0x0000003A +#define ERROR_UNEXP_NET_ERR 0x0000003B +#define ERROR_BAD_REM_ADAP 0x0000003C +#define ERROR_PRINTQ_FULL 0x0000003D +#define ERROR_NO_SPOOL_SPACE 0x0000003E +#define ERROR_PRINT_CANCELLED 0x0000003F +#define ERROR_NETNAME_DELETED 0x00000040 +#define ERROR_NETWORK_ACCESS_DENIED 0x00000041 +#define ERROR_BAD_DEV_TYPE 0x00000042 +#define ERROR_BAD_NET_NAME 0x00000043 +#define ERROR_TOO_MANY_NAMES 0x00000044 +#define ERROR_TOO_MANY_SESS 0x00000045 +#define ERROR_SHARING_PAUSED 0x00000046 +#define ERROR_REQ_NOT_ACCEP 0x00000047 +#define ERROR_REDIR_PAUSED 0x00000048 +#define ERROR_FILE_EXISTS 0x00000050 +#define ERROR_CANNOT_MAKE 0x00000052 +#define ERROR_FAIL_I24 0x00000053 +#define ERROR_OUT_OF_STRUCTURES 0x00000054 +#define ERROR_ALREADY_ASSIGNED 0x00000055 +#define ERROR_INVALID_PASSWORD 0x00000056 +#define ERROR_INVALID_PARAMETER 0x00000057 +#define ERROR_NET_WRITE_FAULT 0x00000058 +#define ERROR_NO_PROC_SLOTS 0x00000059 +#define ERROR_TOO_MANY_SEMAPHORES 0x00000064 +#define ERROR_EXCL_SEM_ALREADY_OWNED 0x00000065 +#define ERROR_SEM_IS_SET 0x00000066 +#define ERROR_TOO_MANY_SEM_REQUESTS 0x00000067 +#define ERROR_INVALID_AT_INTERRUPT_TIME 0x00000068 +#define ERROR_SEM_OWNER_DIED 0x00000069 +#define ERROR_SEM_USER_LIMIT 0x0000006A +#define ERROR_DISK_CHANGE 0x0000006B +#define ERROR_DRIVE_LOCKED 0x0000006C +#define ERROR_BROKEN_PIPE 0x0000006D +#define ERROR_OPEN_FAILED 0x0000006E +#define ERROR_BUFFER_OVERFLOW 0x0000006F +#define ERROR_DISK_FULL 0x00000070 +#define ERROR_NO_MORE_SEARCH_HANDLES 0x00000071 +#define ERROR_INVALID_TARGET_HANDLE 0x00000072 +#define ERROR_INVALID_CATEGORY 0x00000075 +#define ERROR_INVALID_VERIFY_SWITCH 0x00000076 +#define ERROR_BAD_DRIVER_LEVEL 0x00000077 +#define ERROR_CALL_NOT_IMPLEMENTED 0x00000078 +#define ERROR_SEM_TIMEOUT 0x00000079 +#define ERROR_INSUFFICIENT_BUFFER 0x0000007A +#define ERROR_INVALID_NAME 0x0000007B +#define ERROR_INVALID_LEVEL 0x0000007C +#define ERROR_NO_VOLUME_LABEL 0x0000007D +#define ERROR_MOD_NOT_FOUND 0x0000007E +#define ERROR_PROC_NOT_FOUND 0x0000007F +#define ERROR_WAIT_NO_CHILDREN 0x00000080 +#define ERROR_CHILD_NOT_COMPLETE 0x00000081 +#define ERROR_DIRECT_ACCESS_HANDLE 0x00000082 +#define ERROR_NEGATIVE_SEEK 0x00000083 +#define ERROR_SEEK_ON_DEVICE 0x00000084 +#define ERROR_IS_JOIN_TARGET 0x00000085 +#define ERROR_IS_JOINED 0x00000086 +#define ERROR_IS_SUBSTED 0x00000087 +#define ERROR_NOT_JOINED 0x00000088 +#define ERROR_NOT_SUBSTED 0x00000089 +#define ERROR_JOIN_TO_JOIN 0x0000008A +#define ERROR_SUBST_TO_SUBST 0x0000008B +#define ERROR_JOIN_TO_SUBST 0x0000008C +#define ERROR_SUBST_TO_JOIN 0x0000008D +#define ERROR_BUSY_DRIVE 0x0000008E +#define ERROR_SAME_DRIVE 0x0000008F +#define ERROR_DIR_NOT_ROOT 0x00000090 +#define ERROR_DIR_NOT_EMPTY 0x00000091 +#define ERROR_IS_SUBST_PATH 0x00000092 +#define ERROR_IS_JOIN_PATH 0x00000093 +#define ERROR_PATH_BUSY 0x00000094 +#define ERROR_IS_SUBST_TARGET 0x00000095 +#define ERROR_SYSTEM_TRACE 0x00000096 +#define ERROR_INVALID_EVENT_COUNT 0x00000097 +#define ERROR_TOO_MANY_MUXWAITERS 0x00000098 +#define ERROR_INVALID_LIST_FORMAT 0x00000099 +#define ERROR_LABEL_TOO_LONG 0x0000009A +#define ERROR_TOO_MANY_TCBS 0x0000009B +#define ERROR_SIGNAL_REFUSED 0x0000009C +#define ERROR_DISCARDED 0x0000009D +#define ERROR_NOT_LOCKED 0x0000009E +#define ERROR_BAD_THREADID_ADDR 0x0000009F +#define ERROR_BAD_ARGUMENTS 0x000000A0 +#define ERROR_BAD_PATHNAME 0x000000A1 +#define ERROR_SIGNAL_PENDING 0x000000A2 +#define ERROR_MAX_THRDS_REACHED 0x000000A4 +#define ERROR_LOCK_FAILED 0x000000A7 +#define ERROR_BUSY 0x000000AA +#define ERROR_DEVICE_SUPPORT_IN_PROGRESS 0x000000AB +#define ERROR_CANCEL_VIOLATION 0x000000AD +#define ERROR_ATOMIC_LOCKS_NOT_SUPPORTED 0x000000AE +#define ERROR_INVALID_SEGMENT_NUMBER 0x000000B4 +#define ERROR_INVALID_ORDINAL 0x000000B6 +#define ERROR_ALREADY_EXISTS 0x000000B7 +#define ERROR_INVALID_FLAG_NUMBER 0x000000BA +#define ERROR_SEM_NOT_FOUND 0x000000BB +#define ERROR_INVALID_STARTING_CODESEG 0x000000BC +#define ERROR_INVALID_STACKSEG 0x000000BD +#define ERROR_INVALID_MODULETYPE 0x000000BE +#define ERROR_INVALID_EXE_SIGNATURE 0x000000BF +#define ERROR_EXE_MARKED_INVALID 0x000000C0 +#define ERROR_BAD_EXE_FORMAT 0x000000C1 +#define ERROR_ITERATED_DATA_EXCEEDS_64k 0x000000C2 +#define ERROR_INVALID_MINALLOCSIZE 0x000000C3 +#define ERROR_DYNLINK_FROM_INVALID_RING 0x000000C4 +#define ERROR_IOPL_NOT_ENABLED 0x000000C5 +#define ERROR_INVALID_SEGDPL 0x000000C6 +#define ERROR_AUTODATASEG_EXCEEDS_64k 0x000000C7 +#define ERROR_RING2SEG_MUST_BE_MOVABLE 0x000000C8 +#define ERROR_RELOC_CHAIN_XEEDS_SEGLIM 0x000000C9 +#define ERROR_INFLOOP_IN_RELOC_CHAIN 0x000000CA +#define ERROR_ENVVAR_NOT_FOUND 0x000000CB +#define ERROR_NO_SIGNAL_SENT 0x000000CD +#define ERROR_FILENAME_EXCED_RANGE 0x000000CE +#define ERROR_RING2_STACK_IN_USE 0x000000CF +#define ERROR_META_EXPANSION_TOO_LONG 0x000000D0 +#define ERROR_INVALID_SIGNAL_NUMBER 0x000000D1 +#define ERROR_THREAD_1_INACTIVE 0x000000D2 +#define ERROR_LOCKED 0x000000D4 +#define ERROR_TOO_MANY_MODULES 0x000000D6 +#define ERROR_NESTING_NOT_ALLOWED 0x000000D7 +#define ERROR_EXE_MACHINE_TYPE_MISMATCH 0x000000D8 +#define ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY 0x000000D9 +#define ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY 0x000000DA +#define ERROR_FILE_CHECKED_OUT 0x000000DC +#define ERROR_CHECKOUT_REQUIRED 0x000000DD +#define ERROR_BAD_FILE_TYPE 0x000000DE +#define ERROR_FILE_TOO_LARGE 0x000000DF +#define ERROR_FORMS_AUTH_REQUIRED 0x000000E0 +#define ERROR_VIRUS_INFECTED 0x000000E1 +#define ERROR_VIRUS_DELETED 0x000000E2 +#define ERROR_PIPE_LOCAL 0x000000E5 +#define ERROR_BAD_PIPE 0x000000E6 +#define ERROR_PIPE_BUSY 0x000000E7 +#define ERROR_NO_DATA 0x000000E8 +#define ERROR_PIPE_NOT_CONNECTED 0x000000E9 +#define ERROR_MORE_DATA 0x000000EA +#define ERROR_VC_DISCONNECTED 0x000000F0 +#define ERROR_INVALID_EA_NAME 0x000000FE +#define ERROR_EA_LIST_INCONSISTENT 0x000000FF +#define WAIT_TIMEOUT 0x00000102 +#define ERROR_NO_MORE_ITEMS 0x00000103 +#define ERROR_CANNOT_COPY 0x0000010A +#define ERROR_DIRECTORY 0x0000010B +#define ERROR_EAS_DIDNT_FIT 0x00000113 +#define ERROR_EA_FILE_CORRUPT 0x00000114 +#define ERROR_EA_TABLE_FULL 0x00000115 +#define ERROR_INVALID_EA_HANDLE 0x00000116 +#define ERROR_EAS_NOT_SUPPORTED 0x0000011A +#define ERROR_NOT_OWNER 0x00000120 +#define ERROR_TOO_MANY_POSTS 0x0000012A +#define ERROR_PARTIAL_COPY 0x0000012B +#define ERROR_OPLOCK_NOT_GRANTED 0x0000012C +#define ERROR_INVALID_OPLOCK_PROTOCOL 0x0000012D +#define ERROR_DISK_TOO_FRAGMENTED 0x0000012E +#define ERROR_DELETE_PENDING 0x0000012F +#define ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING 0x00000130 +#define ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME 0x00000131 +#define ERROR_SECURITY_STREAM_IS_INCONSISTENT 0x00000132 +#define ERROR_INVALID_LOCK_RANGE 0x00000133 +#define ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT 0x00000134 +#define ERROR_NOTIFICATION_GUID_ALREADY_DEFINED 0x00000135 +#define ERROR_INVALID_EXCEPTION_HANDLER 0x00000136 +#define ERROR_DUPLICATE_PRIVILEGES 0x00000137 +#define ERROR_NO_RANGES_PROCESSED 0x00000138 +#define ERROR_NOT_ALLOWED_ON_SYSTEM_FILE 0x00000139 +#define ERROR_DISK_RESOURCES_EXHAUSTED 0x0000013A +#define ERROR_INVALID_TOKEN 0x0000013B +#define ERROR_DEVICE_FEATURE_NOT_SUPPORTED 0x0000013C +#define ERROR_MR_MID_NOT_FOUND 0x0000013D +#define ERROR_SCOPE_NOT_FOUND 0x0000013E +#define ERROR_UNDEFINED_SCOPE 0x0000013F +#define ERROR_INVALID_CAP 0x00000140 +#define ERROR_DEVICE_UNREACHABLE 0x00000141 +#define ERROR_DEVICE_NO_RESOURCES 0x00000142 +#define ERROR_DATA_CHECKSUM_ERROR 0x00000143 +#define ERROR_INTERMIXED_KERNEL_EA_OPERATION 0x00000144 +#define ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED 0x00000146 +#define ERROR_OFFSET_ALIGNMENT_VIOLATION 0x00000147 +#define ERROR_INVALID_FIELD_IN_PARAMETER_LIST 0x00000148 +#define ERROR_OPERATION_IN_PROGRESS 0x00000149 +#define ERROR_BAD_DEVICE_PATH 0x0000014A +#define ERROR_TOO_MANY_DESCRIPTORS 0x0000014B +#define ERROR_SCRUB_DATA_DISABLED 0x0000014C +#define ERROR_NOT_REDUNDANT_STORAGE 0x0000014D +#define ERROR_RESIDENT_FILE_NOT_SUPPORTED 0x0000014E +#define ERROR_COMPRESSED_FILE_NOT_SUPPORTED 0x0000014F +#define ERROR_DIRECTORY_NOT_SUPPORTED 0x00000150 +#define ERROR_NOT_READ_FROM_COPY 0x00000151 +#define ERROR_FAIL_NOACTION_REBOOT 0x0000015E +#define ERROR_FAIL_SHUTDOWN 0x0000015F +#define ERROR_FAIL_RESTART 0x00000160 +#define ERROR_MAX_SESSIONS_REACHED 0x00000161 +#define ERROR_THREAD_MODE_ALREADY_BACKGROUND 0x00000190 +#define ERROR_THREAD_MODE_NOT_BACKGROUND 0x00000191 +#define ERROR_PROCESS_MODE_ALREADY_BACKGROUND 0x00000192 +#define ERROR_PROCESS_MODE_NOT_BACKGROUND 0x00000193 +#define ERROR_INVALID_ADDRESS 0x000001E7 + +/* System Error Codes (500-999) */ + +#define ERROR_USER_PROFILE_LOAD 0x000001F4 +#define ERROR_ARITHMETIC_OVERFLOW 0x00000216 +#define ERROR_PIPE_CONNECTED 0x00000217 +#define ERROR_PIPE_LISTENING 0x00000218 +#define ERROR_VERIFIER_STOP 0x00000219 +#define ERROR_ABIOS_ERROR 0x0000021A +#define ERROR_WX86_WARNING 0x0000021B +#define ERROR_WX86_ERROR 0x0000021C +#define ERROR_TIMER_NOT_CANCELED 0x0000021D +#define ERROR_UNWIND 0x0000021E +#define ERROR_BAD_STACK 0x0000021F +#define ERROR_INVALID_UNWIND_TARGET 0x00000220 +#define ERROR_INVALID_PORT_ATTRIBUTES 0x00000221 +#define ERROR_PORT_MESSAGE_TOO_LONG 0x00000222 +#define ERROR_INVALID_QUOTA_LOWER 0x00000223 +#define ERROR_DEVICE_ALREADY_ATTACHED 0x00000224 +#define ERROR_INSTRUCTION_MISALIGNMENT 0x00000225 +#define ERROR_PROFILING_NOT_STARTED 0x00000226 +#define ERROR_PROFILING_NOT_STOPPED 0x00000227 +#define ERROR_COULD_NOT_INTERPRET 0x00000228 +#define ERROR_PROFILING_AT_LIMIT 0x00000229 +#define ERROR_CANT_WAIT 0x0000022A +#define ERROR_CANT_TERMINATE_SELF 0x0000022B +#define ERROR_UNEXPECTED_MM_CREATE_ERR 0x0000022C +#define ERROR_UNEXPECTED_MM_MAP_ERROR 0x0000022D +#define ERROR_UNEXPECTED_MM_EXTEND_ERR 0x0000022E +#define ERROR_BAD_FUNCTION_TABLE 0x0000022F +#define ERROR_NO_GUID_TRANSLATION 0x00000230 +#define ERROR_INVALID_LDT_SIZE 0x00000231 +#define ERROR_INVALID_LDT_OFFSET 0x00000233 +#define ERROR_INVALID_LDT_DESCRIPTOR 0x00000234 +#define ERROR_TOO_MANY_THREADS 0x00000235 +#define ERROR_THREAD_NOT_IN_PROCESS 0x00000236 +#define ERROR_PAGEFILE_QUOTA_EXCEEDED 0x00000237 +#define ERROR_LOGON_SERVER_CONFLICT 0x00000238 +#define ERROR_SYNCHRONIZATION_REQUIRED 0x00000239 +#define ERROR_NET_OPEN_FAILED 0x0000023A +#define ERROR_IO_PRIVILEGE_FAILED 0x0000023B +#define ERROR_CONTROL_C_EXIT 0x0000023C +#define ERROR_MISSING_SYSTEMFILE 0x0000023D +#define ERROR_UNHANDLED_EXCEPTION 0x0000023E +#define ERROR_APP_INIT_FAILURE 0x0000023F +#define ERROR_PAGEFILE_CREATE_FAILED 0x00000240 +#define ERROR_INVALID_IMAGE_HASH 0x00000241 +#define ERROR_NO_PAGEFILE 0x00000242 +#define ERROR_ILLEGAL_FLOAT_CONTEXT 0x00000243 +#define ERROR_NO_EVENT_PAIR 0x00000244 +#define ERROR_DOMAIN_CTRLR_CONFIG_ERROR 0x00000245 +#define ERROR_ILLEGAL_CHARACTER 0x00000246 +#define ERROR_UNDEFINED_CHARACTER 0x00000247 +#define ERROR_FLOPPY_VOLUME 0x00000248 +#define ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT 0x00000249 +#define ERROR_BACKUP_CONTROLLER 0x0000024A +#define ERROR_MUTANT_LIMIT_EXCEEDED 0x0000024B +#define ERROR_FS_DRIVER_REQUIRED 0x0000024C +#define ERROR_CANNOT_LOAD_REGISTRY_FILE 0x0000024D +#define ERROR_DEBUG_ATTACH_FAILED 0x0000024E +#define ERROR_SYSTEM_PROCESS_TERMINATED 0x0000024F +#define ERROR_DATA_NOT_ACCEPTED 0x00000250 +#define ERROR_VDM_HARD_ERROR 0x00000251 +#define ERROR_DRIVER_CANCEL_TIMEOUT 0x00000252 +#define ERROR_REPLY_MESSAGE_MISMATCH 0x00000253 +#define ERROR_LOST_WRITEBEHIND_DATA 0x00000254 +#define ERROR_CLIENT_SERVER_PARAMETERS_INVALID 0x00000255 +#define ERROR_NOT_TINY_STREAM 0x00000256 +#define ERROR_STACK_OVERFLOW_READ 0x00000257 +#define ERROR_CONVERT_TO_LARGE 0x00000258 +#define ERROR_FOUND_OUT_OF_SCOPE 0x00000259 +#define ERROR_ALLOCATE_BUCKET 0x0000025A +#define ERROR_MARSHALL_OVERFLOW 0x0000025B +#define ERROR_INVALID_VARIANT 0x0000025C +#define ERROR_BAD_COMPRESSION_BUFFER 0x0000025D +#define ERROR_AUDIT_FAILED 0x0000025E +#define ERROR_TIMER_RESOLUTION_NOT_SET 0x0000025F +#define ERROR_INSUFFICIENT_LOGON_INFO 0x00000260 +#define ERROR_BAD_DLL_ENTRYPOINT 0x00000261 +#define ERROR_BAD_SERVICE_ENTRYPOINT 0x00000262 +#define ERROR_IP_ADDRESS_CONFLICT1 0x00000263 +#define ERROR_IP_ADDRESS_CONFLICT2 0x00000264 +#define ERROR_REGISTRY_QUOTA_LIMIT 0x00000265 +#define ERROR_NO_CALLBACK_ACTIVE 0x00000266 +#define ERROR_PWD_TOO_SHORT 0x00000267 +#define ERROR_PWD_TOO_RECENT 0x00000268 +#define ERROR_PWD_HISTORY_CONFLICT 0x00000269 +#define ERROR_UNSUPPORTED_COMPRESSION 0x0000026A +#define ERROR_INVALID_HW_PROFILE 0x0000026B +#define ERROR_INVALID_PLUGPLAY_DEVICE_PATH 0x0000026C +#define ERROR_QUOTA_LIST_INCONSISTENT 0x0000026D +#define ERROR_EVALUATION_EXPIRATION 0x0000026E +#define ERROR_ILLEGAL_DLL_RELOCATION 0x0000026F +#define ERROR_DLL_INIT_FAILED_LOGOFF 0x00000270 +#define ERROR_VALIDATE_CONTINUE 0x00000271 +#define ERROR_NO_MORE_MATCHES 0x00000272 +#define ERROR_RANGE_LIST_CONFLICT 0x00000273 +#define ERROR_SERVER_SID_MISMATCH 0x00000274 +#define ERROR_CANT_ENABLE_DENY_ONLY 0x00000275 +#define ERROR_FLOAT_MULTIPLE_FAULTS 0x00000276 +#define ERROR_FLOAT_MULTIPLE_TRAPS 0x00000277 +#define ERROR_NOINTERFACE 0x00000278 +#define ERROR_DRIVER_FAILED_SLEEP 0x00000279 +#define ERROR_CORRUPT_SYSTEM_FILE 0x0000027A +#define ERROR_COMMITMENT_MINIMUM 0x0000027B +#define ERROR_PNP_RESTART_ENUMERATION 0x0000027C +#define ERROR_SYSTEM_IMAGE_BAD_SIGNATURE 0x0000027D +#define ERROR_PNP_REBOOT_REQUIRED 0x0000027E +#define ERROR_INSUFFICIENT_POWER 0x0000027F +#define ERROR_MULTIPLE_FAULT_VIOLATION 0x00000280 +#define ERROR_SYSTEM_SHUTDOWN 0x00000281 +#define ERROR_PORT_NOT_SET 0x00000282 +#define ERROR_DS_VERSION_CHECK_FAILURE 0x00000283 +#define ERROR_RANGE_NOT_FOUND 0x00000284 +#define ERROR_NOT_SAFE_MODE_DRIVER 0x00000286 +#define ERROR_FAILED_DRIVER_ENTRY 0x00000287 +#define ERROR_DEVICE_ENUMERATION_ERROR 0x00000288 +#define ERROR_MOUNT_POINT_NOT_RESOLVED 0x00000289 +#define ERROR_INVALID_DEVICE_OBJECT_PARAMETER 0x0000028A +/* The following is not a typo. It's the same spelling as in the Microsoft headers */ +#define ERROR_MCA_OCCURED 0x0000028B +#define ERROR_DRIVER_DATABASE_ERROR 0x0000028C +#define ERROR_SYSTEM_HIVE_TOO_LARGE 0x0000028D +#define ERROR_DRIVER_FAILED_PRIOR_UNLOAD 0x0000028E +#define ERROR_VOLSNAP_PREPARE_HIBERNATE 0x0000028F +#define ERROR_HIBERNATION_FAILURE 0x00000290 +#define ERROR_PWD_TOO_LONG 0x00000291 +#define ERROR_FILE_SYSTEM_LIMITATION 0x00000299 +#define ERROR_ASSERTION_FAILURE 0x0000029C +#define ERROR_ACPI_ERROR 0x0000029D +#define ERROR_WOW_ASSERTION 0x0000029E +#define ERROR_PNP_BAD_MPS_TABLE 0x0000029F +#define ERROR_PNP_TRANSLATION_FAILED 0x000002A0 +#define ERROR_PNP_IRQ_TRANSLATION_FAILED 0x000002A1 +#define ERROR_PNP_INVALID_ID 0x000002A2 +#define ERROR_WAKE_SYSTEM_DEBUGGER 0x000002A3 +#define ERROR_HANDLES_CLOSED 0x000002A4 +#define ERROR_EXTRANEOUS_INFORMATION 0x000002A5 +#define ERROR_RXACT_COMMIT_NECESSARY 0x000002A6 +#define ERROR_MEDIA_CHECK 0x000002A7 +#define ERROR_GUID_SUBSTITUTION_MADE 0x000002A8 +#define ERROR_STOPPED_ON_SYMLINK 0x000002A9 +#define ERROR_LONGJUMP 0x000002AA +#define ERROR_PLUGPLAY_QUERY_VETOED 0x000002AB +#define ERROR_UNWIND_CONSOLIDATE 0x000002AC +#define ERROR_REGISTRY_HIVE_RECOVERED 0x000002AD +#define ERROR_DLL_MIGHT_BE_INSECURE 0x000002AE +#define ERROR_DLL_MIGHT_BE_INCOMPATIBLE 0x000002AF +#define ERROR_DBG_EXCEPTION_NOT_HANDLED 0x000002B0 +#define ERROR_DBG_REPLY_LATER 0x000002B1 +#define ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE 0x000002B2 +#define ERROR_DBG_TERMINATE_THREAD 0x000002B3 +#define ERROR_DBG_TERMINATE_PROCESS 0x000002B4 +#define ERROR_DBG_CONTROL_C 0x000002B5 +#define ERROR_DBG_PRINTEXCEPTION_C 0x000002B6 +#define ERROR_DBG_RIPEXCEPTION 0x000002B7 +#define ERROR_DBG_CONTROL_BREAK 0x000002B8 +#define ERROR_DBG_COMMAND_EXCEPTION 0x000002B9 +#define ERROR_OBJECT_NAME_EXISTS 0x000002BA +#define ERROR_THREAD_WAS_SUSPENDED 0x000002BB +#define ERROR_IMAGE_NOT_AT_BASE 0x000002BC +#define ERROR_RXACT_STATE_CREATED 0x000002BD +#define ERROR_SEGMENT_NOTIFICATION 0x000002BE +#define ERROR_BAD_CURRENT_DIRECTORY 0x000002BF +#define ERROR_FT_READ_RECOVERY_FROM_BACKUP 0x000002C0 +#define ERROR_FT_WRITE_RECOVERY 0x000002C1 +#define ERROR_IMAGE_MACHINE_TYPE_MISMATCH 0x000002C2 +#define ERROR_RECEIVE_PARTIAL 0x000002C3 +#define ERROR_RECEIVE_EXPEDITED 0x000002C4 +#define ERROR_RECEIVE_PARTIAL_EXPEDITED 0x000002C5 +#define ERROR_EVENT_DONE 0x000002C6 +#define ERROR_EVENT_PENDING 0x000002C7 +#define ERROR_CHECKING_FILE_SYSTEM 0x000002C8 +#define ERROR_FATAL_APP_EXIT 0x000002C9 +#define ERROR_PREDEFINED_HANDLE 0x000002CA +#define ERROR_WAS_UNLOCKED 0x000002CB +#define ERROR_SERVICE_NOTIFICATION 0x000002CC +#define ERROR_WAS_LOCKED 0x000002CD +#define ERROR_LOG_HARD_ERROR 0x000002CE +#define ERROR_ALREADY_WIN32 0x000002CF +#define ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE 0x000002D0 +#define ERROR_NO_YIELD_PERFORMED 0x000002D1 +#define ERROR_TIMER_RESUME_IGNORED 0x000002D2 +#define ERROR_ARBITRATION_UNHANDLED 0x000002D3 +#define ERROR_CARDBUS_NOT_SUPPORTED 0x000002D4 +#define ERROR_MP_PROCESSOR_MISMATCH 0x000002D5 +#define ERROR_HIBERNATED 0x000002D6 +#define ERROR_RESUME_HIBERNATION 0x000002D7 +#define ERROR_FIRMWARE_UPDATED 0x000002D8 +#define ERROR_DRIVERS_LEAKING_LOCKED_PAGES 0x000002D9 +#define ERROR_WAKE_SYSTEM 0x000002DA +#define ERROR_WAIT_1 0x000002DB +#define ERROR_WAIT_2 0x000002DC +#define ERROR_WAIT_3 0x000002DD +#define ERROR_WAIT_63 0x000002DE +#define ERROR_ABANDONED_WAIT_0 0x000002DF +#define ERROR_ABANDONED_WAIT_63 0x000002E0 +#define ERROR_USER_APC 0x000002E1 +#define ERROR_KERNEL_APC 0x000002E2 +#define ERROR_ALERTED 0x000002E3 +#define ERROR_ELEVATION_REQUIRED 0x000002E4 +#define ERROR_REPARSE 0x000002E5 +#define ERROR_OPLOCK_BREAK_IN_PROGRESS 0x000002E6 +#define ERROR_VOLUME_MOUNTED 0x000002E7 +#define ERROR_RXACT_COMMITTED 0x000002E8 +#define ERROR_NOTIFY_CLEANUP 0x000002E9 +#define ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED 0x000002EA +#define ERROR_PAGE_FAULT_TRANSITION 0x000002EB +#define ERROR_PAGE_FAULT_DEMAND_ZERO 0x000002EC +#define ERROR_PAGE_FAULT_COPY_ON_WRITE 0x000002ED +#define ERROR_PAGE_FAULT_GUARD_PAGE 0x000002EE +#define ERROR_PAGE_FAULT_PAGING_FILE 0x000002EF +#define ERROR_CACHE_PAGE_LOCKED 0x000002F0 +#define ERROR_CRASH_DUMP 0x000002F1 +#define ERROR_BUFFER_ALL_ZEROS 0x000002F2 +#define ERROR_REPARSE_OBJECT 0x000002F3 +#define ERROR_RESOURCE_REQUIREMENTS_CHANGED 0x000002F4 +#define ERROR_TRANSLATION_COMPLETE 0x000002F5 +#define ERROR_NOTHING_TO_TERMINATE 0x000002F6 +#define ERROR_PROCESS_NOT_IN_JOB 0x000002F7 +#define ERROR_PROCESS_IN_JOB 0x000002F8 +#define ERROR_VOLSNAP_HIBERNATE_READY 0x000002F9 +#define ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY 0x000002FA +#define ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED 0x000002FB +#define ERROR_INTERRUPT_STILL_CONNECTED 0x000002FC +#define ERROR_WAIT_FOR_OPLOCK 0x000002FD +#define ERROR_DBG_EXCEPTION_HANDLED 0x000002FE +#define ERROR_DBG_CONTINUE 0x000002FF +#define ERROR_CALLBACK_POP_STACK 0x00000300 +#define ERROR_COMPRESSION_DISABLED 0x00000301 +#define ERROR_CANTFETCHBACKWARDS 0x00000302 +#define ERROR_CANTSCROLLBACKWARDS 0x00000303 +#define ERROR_ROWSNOTRELEASED 0x00000304 +#define ERROR_BAD_ACCESSOR_FLAGS 0x00000305 +#define ERROR_ERRORS_ENCOUNTERED 0x00000306 +#define ERROR_NOT_CAPABLE 0x00000307 +#define ERROR_REQUEST_OUT_OF_SEQUENCE 0x00000308 +#define ERROR_VERSION_PARSE_ERROR 0x00000309 +#define ERROR_BADSTARTPOSITION 0x0000030A +#define ERROR_MEMORY_HARDWARE 0x0000030B +#define ERROR_DISK_REPAIR_DISABLED 0x0000030C +#define ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE 0x0000030D +#define ERROR_SYSTEM_POWERSTATE_TRANSITION 0x0000030E +#define ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION 0x0000030F +#define ERROR_MCA_EXCEPTION 0x00000310 +#define ERROR_ACCESS_AUDIT_BY_POLICY 0x00000311 +#define ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY 0x00000312 +#define ERROR_ABANDON_HIBERFILE 0x00000313 +#define ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED 0x00000314 +#define ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR 0x00000315 +#define ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR 0x00000316 +#define ERROR_BAD_MCFG_TABLE 0x00000317 +#define ERROR_DISK_REPAIR_REDIRECTED 0x00000318 +#define ERROR_DISK_REPAIR_UNSUCCESSFUL 0x00000319 +#define ERROR_CORRUPT_LOG_OVERFULL 0x0000031A +#define ERROR_CORRUPT_LOG_CORRUPTED 0x0000031B +#define ERROR_CORRUPT_LOG_UNAVAILABLE 0x0000031C +#define ERROR_CORRUPT_LOG_DELETED_FULL 0x0000031D +#define ERROR_CORRUPT_LOG_CLEARED 0x0000031E +#define ERROR_ORPHAN_NAME_EXHAUSTED 0x0000031F +#define ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE 0x00000320 +#define ERROR_CANNOT_GRANT_REQUESTED_OPLOCK 0x00000321 +#define ERROR_CANNOT_BREAK_OPLOCK 0x00000322 +#define ERROR_OPLOCK_HANDLE_CLOSED 0x00000323 +#define ERROR_NO_ACE_CONDITION 0x00000324 +#define ERROR_INVALID_ACE_CONDITION 0x00000325 +#define ERROR_FILE_HANDLE_REVOKED 0x00000326 +#define ERROR_IMAGE_AT_DIFFERENT_BASE 0x00000327 +#define ERROR_EA_ACCESS_DENIED 0x000003E2 +#define ERROR_OPERATION_ABORTED 0x000003E3 +#define ERROR_IO_INCOMPLETE 0x000003E4 +#define ERROR_IO_PENDING 0x000003E5 +#define ERROR_NOACCESS 0x000003E6 +#define ERROR_SWAPERROR 0x000003E7 + +/* System Error Codes (1000-1299) */ + +#define ERROR_STACK_OVERFLOW 0x000003E9 +#define ERROR_INVALID_MESSAGE 0x000003EA +#define ERROR_CAN_NOT_COMPLETE 0x000003EB +#define ERROR_INVALID_FLAGS 0x000003EC +#define ERROR_UNRECOGNIZED_VOLUME 0x000003ED +#define ERROR_FILE_INVALID 0x000003EE +#define ERROR_FULLSCREEN_MODE 0x000003EF +#define ERROR_NO_TOKEN 0x000003F0 +#define ERROR_BADDB 0x000003F1 +#define ERROR_BADKEY 0x000003F2 +#define ERROR_CANTOPEN 0x000003F3 +#define ERROR_CANTREAD 0x000003F4 +#define ERROR_CANTWRITE 0x000003F5 +#define ERROR_REGISTRY_RECOVERED 0x000003F6 +#define ERROR_REGISTRY_CORRUPT 0x000003F7 +#define ERROR_REGISTRY_IO_FAILED 0x000003F8 +#define ERROR_NOT_REGISTRY_FILE 0x000003F9 +#define ERROR_KEY_DELETED 0x000003FA +#define ERROR_NO_LOG_SPACE 0x000003FB +#define ERROR_KEY_HAS_CHILDREN 0x000003FC +#define ERROR_CHILD_MUST_BE_VOLATILE 0x000003FD +#define ERROR_NOTIFY_ENUM_DIR 0x000003FE +#define ERROR_DEPENDENT_SERVICES_RUNNING 0x0000041B +#define ERROR_INVALID_SERVICE_CONTROL 0x0000041C +#define ERROR_SERVICE_REQUEST_TIMEOUT 0x0000041D +#define ERROR_SERVICE_NO_THREAD 0x0000041E +#define ERROR_SERVICE_DATABASE_LOCKED 0x0000041F +#define ERROR_SERVICE_ALREADY_RUNNING 0x00000420 +#define ERROR_INVALID_SERVICE_ACCOUNT 0x00000421 +#define ERROR_SERVICE_DISABLED 0x00000422 +#define ERROR_CIRCULAR_DEPENDENCY 0x00000423 +#define ERROR_SERVICE_DOES_NOT_EXIST 0x00000424 +#define ERROR_SERVICE_CANNOT_ACCEPT_CTRL 0x00000425 +#define ERROR_SERVICE_NOT_ACTIVE 0x00000426 +#define ERROR_FAILED_SERVICE_CONTROLLER_CONNECT 0x00000427 +#define ERROR_EXCEPTION_IN_SERVICE 0x00000428 +#define ERROR_DATABASE_DOES_NOT_EXIST 0x00000429 +#define ERROR_SERVICE_SPECIFIC_ERROR 0x0000042A +#define ERROR_PROCESS_ABORTED 0x0000042B +#define ERROR_SERVICE_DEPENDENCY_FAIL 0x0000042C +#define ERROR_SERVICE_LOGON_FAILED 0x0000042D +#define ERROR_SERVICE_START_HANG 0x0000042E +#define ERROR_INVALID_SERVICE_LOCK 0x0000042F +#define ERROR_SERVICE_MARKED_FOR_DELETE 0x00000430 +#define ERROR_SERVICE_EXISTS 0x00000431 +#define ERROR_ALREADY_RUNNING_LKG 0x00000432 +#define ERROR_SERVICE_DEPENDENCY_DELETED 0x00000433 +#define ERROR_BOOT_ALREADY_ACCEPTED 0x00000434 +#define ERROR_SERVICE_NEVER_STARTED 0x00000435 +#define ERROR_DUPLICATE_SERVICE_NAME 0x00000436 +#define ERROR_DIFFERENT_SERVICE_ACCOUNT 0x00000437 +#define ERROR_CANNOT_DETECT_DRIVER_FAILURE 0x00000438 +#define ERROR_CANNOT_DETECT_PROCESS_ABORT 0x00000439 +#define ERROR_NO_RECOVERY_PROGRAM 0x0000043A +#define ERROR_SERVICE_NOT_IN_EXE 0x0000043B +#define ERROR_NOT_SAFEBOOT_SERVICE 0x0000043C +#define ERROR_END_OF_MEDIA 0x0000044C +#define ERROR_FILEMARK_DETECTED 0x0000044D +#define ERROR_BEGINNING_OF_MEDIA 0x0000044E +#define ERROR_SETMARK_DETECTED 0x0000044F +#define ERROR_NO_DATA_DETECTED 0x00000450 +#define ERROR_PARTITION_FAILURE 0x00000451 +#define ERROR_INVALID_BLOCK_LENGTH 0x00000452 +#define ERROR_DEVICE_NOT_PARTITIONED 0x00000453 +#define ERROR_UNABLE_TO_LOCK_MEDIA 0x00000454 +#define ERROR_UNABLE_TO_UNLOAD_MEDIA 0x00000455 +#define ERROR_MEDIA_CHANGED 0x00000456 +#define ERROR_BUS_RESET 0x00000457 +#define ERROR_NO_MEDIA_IN_DRIVE 0x00000458 +#define ERROR_NO_UNICODE_TRANSLATION 0x00000459 +#define ERROR_DLL_INIT_FAILED 0x0000045A +#define ERROR_SHUTDOWN_IN_PROGRESS 0x0000045B +#define ERROR_NO_SHUTDOWN_IN_PROGRESS 0x0000045C +#define ERROR_IO_DEVICE 0x0000045D +#define ERROR_SERIAL_NO_DEVICE 0x0000045E +#define ERROR_IRQ_BUSY 0x0000045F +#define ERROR_MORE_WRITES 0x00000460 +#define ERROR_COUNTER_TIMEOUT 0x00000461 +#define ERROR_FLOPPY_ID_MARK_NOT_FOUND 0x00000462 +#define ERROR_FLOPPY_WRONG_CYLINDER 0x00000463 +#define ERROR_FLOPPY_UNKNOWN_ERROR 0x00000464 +#define ERROR_FLOPPY_BAD_REGISTERS 0x00000465 +#define ERROR_DISK_RECALIBRATE_FAILED 0x00000466 +#define ERROR_DISK_OPERATION_FAILED 0x00000467 +#define ERROR_DISK_RESET_FAILED 0x00000468 +#define ERROR_EOM_OVERFLOW 0x00000469 +#define ERROR_NOT_ENOUGH_SERVER_MEMORY 0x0000046A +#define ERROR_POSSIBLE_DEADLOCK 0x0000046B +#define ERROR_MAPPED_ALIGNMENT 0x0000046C +#define ERROR_SET_POWER_STATE_VETOED 0x00000474 +#define ERROR_SET_POWER_STATE_FAILED 0x00000475 +#define ERROR_TOO_MANY_LINKS 0x00000476 +#define ERROR_OLD_WIN_VERSION 0x0000047E +#define ERROR_APP_WRONG_OS 0x0000047F +#define ERROR_SINGLE_INSTANCE_APP 0x00000480 +#define ERROR_RMODE_APP 0x00000481 +#define ERROR_INVALID_DLL 0x00000482 +#define ERROR_NO_ASSOCIATION 0x00000483 +#define ERROR_DDE_FAIL 0x00000484 +#define ERROR_DLL_NOT_FOUND 0x00000485 +#define ERROR_NO_MORE_USER_HANDLES 0x00000486 +#define ERROR_MESSAGE_SYNC_ONLY 0x00000487 +#define ERROR_SOURCE_ELEMENT_EMPTY 0x00000488 +#define ERROR_DESTINATION_ELEMENT_FULL 0x00000489 +#define ERROR_ILLEGAL_ELEMENT_ADDRESS 0x0000048A +#define ERROR_MAGAZINE_NOT_PRESENT 0x0000048B +#define ERROR_DEVICE_REINITIALIZATION_NEEDED 0x0000048C +#define ERROR_DEVICE_REQUIRES_CLEANING 0x0000048D +#define ERROR_DEVICE_DOOR_OPEN 0x0000048E +#define ERROR_DEVICE_NOT_CONNECTED 0x0000048F +#define ERROR_NOT_FOUND 0x00000490 +#define ERROR_NO_MATCH 0x00000491 +#define ERROR_SET_NOT_FOUND 0x00000492 +#define ERROR_POINT_NOT_FOUND 0x00000493 +#define ERROR_NO_TRACKING_SERVICE 0x00000494 +#define ERROR_NO_VOLUME_ID 0x00000495 +#define ERROR_UNABLE_TO_REMOVE_REPLACED 0x00000497 +#define ERROR_UNABLE_TO_MOVE_REPLACEMENT 0x00000498 +#define ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 0x00000499 +#define ERROR_JOURNAL_DELETE_IN_PROGRESS 0x0000049A +#define ERROR_JOURNAL_NOT_ACTIVE 0x0000049B +#define ERROR_POTENTIAL_FILE_FOUND 0x0000049C +#define ERROR_JOURNAL_ENTRY_DELETED 0x0000049D +#define ERROR_SHUTDOWN_IS_SCHEDULED 0x000004A6 +#define ERROR_SHUTDOWN_USERS_LOGGED_ON 0x000004A7 +#define ERROR_BAD_DEVICE 0x000004B0 +#define ERROR_CONNECTION_UNAVAIL 0x000004B1 +#define ERROR_DEVICE_ALREADY_REMEMBERED 0x000004B2 +#define ERROR_NO_NET_OR_BAD_PATH 0x000004B3 +#define ERROR_BAD_PROVIDER 0x000004B4 +#define ERROR_CANNOT_OPEN_PROFILE 0x000004B5 +#define ERROR_BAD_PROFILE 0x000004B6 +#define ERROR_NOT_CONTAINER 0x000004B7 +#define ERROR_EXTENDED_ERROR 0x000004B8 +#define ERROR_INVALID_GROUPNAME 0x000004B9 +#define ERROR_INVALID_COMPUTERNAME 0x000004BA +#define ERROR_INVALID_EVENTNAME 0x000004BB +#define ERROR_INVALID_DOMAINNAME 0x000004BC +#define ERROR_INVALID_SERVICENAME 0x000004BD +#define ERROR_INVALID_NETNAME 0x000004BE +#define ERROR_INVALID_SHARENAME 0x000004BF +#define ERROR_INVALID_PASSWORDNAME 0x000004C0 +#define ERROR_INVALID_MESSAGENAME 0x000004C1 +#define ERROR_INVALID_MESSAGEDEST 0x000004C2 +#define ERROR_SESSION_CREDENTIAL_CONFLICT 0x000004C3 +#define ERROR_REMOTE_SESSION_LIMIT_EXCEEDED 0x000004C4 +#define ERROR_DUP_DOMAINNAME 0x000004C5 +#define ERROR_NO_NETWORK 0x000004C6 +#define ERROR_CANCELLED 0x000004C7 +#define ERROR_USER_MAPPED_FILE 0x000004C8 +#define ERROR_CONNECTION_REFUSED 0x000004C9 +#define ERROR_GRACEFUL_DISCONNECT 0x000004CA +#define ERROR_ADDRESS_ALREADY_ASSOCIATED 0x000004CB +#define ERROR_ADDRESS_NOT_ASSOCIATED 0x000004CC +#define ERROR_CONNECTION_INVALID 0x000004CD +#define ERROR_CONNECTION_ACTIVE 0x000004CE +#define ERROR_NETWORK_UNREACHABLE 0x000004CF +#define ERROR_HOST_UNREACHABLE 0x000004D0 +#define ERROR_PROTOCOL_UNREACHABLE 0x000004D1 +#define ERROR_PORT_UNREACHABLE 0x000004D2 +#define ERROR_REQUEST_ABORTED 0x000004D3 +#define ERROR_CONNECTION_ABORTED 0x000004D4 +#define ERROR_RETRY 0x000004D5 +#define ERROR_CONNECTION_COUNT_LIMIT 0x000004D6 +#define ERROR_LOGIN_TIME_RESTRICTION 0x000004D7 +#define ERROR_LOGIN_WKSTA_RESTRICTION 0x000004D8 +#define ERROR_INCORRECT_ADDRESS 0x000004D9 +#define ERROR_ALREADY_REGISTERED 0x000004DA +#define ERROR_SERVICE_NOT_FOUND 0x000004DB +#define ERROR_NOT_AUTHENTICATED 0x000004DC +#define ERROR_NOT_LOGGED_ON 0x000004DD +#define ERROR_CONTINUE 0x000004DE +#define ERROR_ALREADY_INITIALIZED 0x000004DF +#define ERROR_NO_MORE_DEVICES 0x000004E0 +#define ERROR_NO_SUCH_SITE 0x000004E1 +#define ERROR_DOMAIN_CONTROLLER_EXISTS 0x000004E2 +#define ERROR_ONLY_IF_CONNECTED 0x000004E3 +#define ERROR_OVERRIDE_NOCHANGES 0x000004E4 +#define ERROR_BAD_USER_PROFILE 0x000004E5 +#define ERROR_NOT_SUPPORTED_ON_SBS 0x000004E6 +#define ERROR_SERVER_SHUTDOWN_IN_PROGRESS 0x000004E7 +#define ERROR_HOST_DOWN 0x000004E8 +#define ERROR_NON_ACCOUNT_SID 0x000004E9 +#define ERROR_NON_DOMAIN_SID 0x000004EA +#define ERROR_APPHELP_BLOCK 0x000004EB +#define ERROR_ACCESS_DISABLED_BY_POLICY 0x000004EC +#define ERROR_REG_NAT_CONSUMPTION 0x000004ED +#define ERROR_CSCSHARE_OFFLINE 0x000004EE +#define ERROR_PKINIT_FAILURE 0x000004EF +#define ERROR_SMARTCARD_SUBSYSTEM_FAILURE 0x000004F0 +#define ERROR_DOWNGRADE_DETECTED 0x000004F1 +#define ERROR_MACHINE_LOCKED 0x000004F7 +#define ERROR_CALLBACK_SUPPLIED_INVALID_DATA 0x000004F9 +#define ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED 0x000004FA +#define ERROR_DRIVER_BLOCKED 0x000004FB +#define ERROR_INVALID_IMPORT_OF_NON_DLL 0x000004FC +#define ERROR_ACCESS_DISABLED_WEBBLADE 0x000004FD +#define ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER 0x000004FE +#define ERROR_RECOVERY_FAILURE 0x000004FF +#define ERROR_ALREADY_FIBER 0x00000500 +#define ERROR_ALREADY_THREAD 0x00000501 +#define ERROR_STACK_BUFFER_OVERRUN 0x00000502 +#define ERROR_PARAMETER_QUOTA_EXCEEDED 0x00000503 +#define ERROR_DEBUGGER_INACTIVE 0x00000504 +#define ERROR_DELAY_LOAD_FAILED 0x00000505 +#define ERROR_VDM_DISALLOWED 0x00000506 +#define ERROR_UNIDENTIFIED_ERROR 0x00000507 +#define ERROR_INVALID_CRUNTIME_PARAMETER 0x00000508 +#define ERROR_BEYOND_VDL 0x00000509 +#define ERROR_INCOMPATIBLE_SERVICE_SID_TYPE 0x0000050A +#define ERROR_DRIVER_PROCESS_TERMINATED 0x0000050B +#define ERROR_IMPLEMENTATION_LIMIT 0x0000050C +#define ERROR_PROCESS_IS_PROTECTED 0x0000050D +#define ERROR_SERVICE_NOTIFY_CLIENT_LAGGING 0x0000050E +#define ERROR_DISK_QUOTA_EXCEEDED 0x0000050F +#define ERROR_CONTENT_BLOCKED 0x00000510 +#define ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE 0x00000511 +#define ERROR_APP_HANG 0x00000512 +#define ERROR_INVALID_LABEL 0x00000513 + +/* System Error Codes (1300-1699) */ +#define ERROR_NOT_ALL_ASSIGNED 0x00000514 +#define ERROR_SOME_NOT_MAPPED 0x00000515 +#define ERROR_NO_QUOTAS_FOR_ACCOUNT 0x00000516 +#define ERROR_LOCAL_USER_SESSION_KEY 0x00000517 +#define ERROR_NULL_LM_PASSWORD 0x00000518 +#define ERROR_UNKNOWN_REVISION 0x00000519 +#define ERROR_REVISION_MISMATCH 0x0000051A +#define ERROR_INVALID_OWNER 0x0000051B +#define ERROR_INVALID_PRIMARY_GROUP 0x0000051C +#define ERROR_NO_IMPERSONATION_TOKEN 0x0000051D +#define ERROR_CANT_DISABLE_MANDATORY 0x0000051E +#define ERROR_NO_LOGON_SERVERS 0x0000051F +#define ERROR_NO_SUCH_LOGON_SESSION 0x00000520 +#define ERROR_NO_SUCH_PRIVILEGE 0x00000521 +#define ERROR_PRIVILEGE_NOT_HELD 0x00000522 +#define ERROR_INVALID_ACCOUNT_NAME 0x00000523 +#define ERROR_USER_EXISTS 0x00000524 +#define ERROR_NO_SUCH_USER 0x00000525 +#define ERROR_GROUP_EXISTS 0x00000526 +#define ERROR_NO_SUCH_GROUP 0x00000527 +#define ERROR_MEMBER_IN_GROUP 0x00000528 +#define ERROR_MEMBER_NOT_IN_GROUP 0x00000529 +#define ERROR_LAST_ADMIN 0x0000052A +#define ERROR_WRONG_PASSWORD 0x0000052B +#define ERROR_ILL_FORMED_PASSWORD 0x0000052C +#define ERROR_PASSWORD_RESTRICTION 0x0000052D +#define ERROR_LOGON_FAILURE 0x0000052E +#define ERROR_ACCOUNT_RESTRICTION 0x0000052F +#define ERROR_INVALID_LOGON_HOURS 0x00000530 +#define ERROR_INVALID_WORKSTATION 0x00000531 +#define ERROR_PASSWORD_EXPIRED 0x00000532 +#define ERROR_ACCOUNT_DISABLED 0x00000533 +#define ERROR_NONE_MAPPED 0x00000534 +#define ERROR_TOO_MANY_LUIDS_REQUESTED 0x00000535 +#define ERROR_LUIDS_EXHAUSTED 0x00000536 +#define ERROR_INVALID_SUB_AUTHORITY 0x00000537 +#define ERROR_INVALID_ACL 0x00000538 +#define ERROR_INVALID_SID 0x00000539 +#define ERROR_INVALID_SECURITY_DESCR 0x0000053A +#define ERROR_BAD_INHERITANCE_ACL 0x0000053C +#define ERROR_SERVER_DISABLED 0x0000053D +#define ERROR_SERVER_NOT_DISABLED 0x0000053E +#define ERROR_INVALID_ID_AUTHORITY 0x0000053F +#define ERROR_ALLOTTED_SPACE_EXCEEDED 0x00000540 +#define ERROR_INVALID_GROUP_ATTRIBUTES 0x00000541 +#define ERROR_BAD_IMPERSONATION_LEVEL 0x00000542 +#define ERROR_CANT_OPEN_ANONYMOUS 0x00000543 +#define ERROR_BAD_VALIDATION_CLASS 0x00000544 +#define ERROR_BAD_TOKEN_TYPE 0x00000545 +#define ERROR_NO_SECURITY_ON_OBJECT 0x00000546 +#define ERROR_CANT_ACCESS_DOMAIN_INFO 0x00000547 +#define ERROR_INVALID_SERVER_STATE 0x00000548 +#define ERROR_INVALID_DOMAIN_STATE 0x00000549 +#define ERROR_INVALID_DOMAIN_ROLE 0x0000054A +#define ERROR_NO_SUCH_DOMAIN 0x0000054B +#define ERROR_DOMAIN_EXISTS 0x0000054C +#define ERROR_DOMAIN_LIMIT_EXCEEDED 0x0000054D +#define ERROR_INTERNAL_DB_CORRUPTION 0x0000054E +#define ERROR_INTERNAL_ERROR 0x0000054F +#define ERROR_GENERIC_NOT_MAPPED 0x00000550 +#define ERROR_BAD_DESCRIPTOR_FORMAT 0x00000551 +#define ERROR_NOT_LOGON_PROCESS 0x00000552 +#define ERROR_LOGON_SESSION_EXISTS 0x00000553 +#define ERROR_NO_SUCH_PACKAGE 0x00000554 +#define ERROR_BAD_LOGON_SESSION_STATE 0x00000555 +#define ERROR_LOGON_SESSION_COLLISION 0x00000556 +#define ERROR_INVALID_LOGON_TYPE 0x00000557 +#define ERROR_CANNOT_IMPERSONATE 0x00000558 +#define ERROR_RXACT_INVALID_STATE 0x00000559 +#define ERROR_RXACT_COMMIT_FAILURE 0x0000055A +#define ERROR_SPECIAL_ACCOUNT 0x0000055B +#define ERROR_SPECIAL_GROUP 0x0000055C +#define ERROR_SPECIAL_USER 0x0000055D +#define ERROR_MEMBERS_PRIMARY_GROUP 0x0000055E +#define ERROR_TOKEN_ALREADY_IN_USE 0x0000055F +#define ERROR_NO_SUCH_ALIAS 0x00000560 +#define ERROR_MEMBER_NOT_IN_ALIAS 0x00000561 +#define ERROR_MEMBER_IN_ALIAS 0x00000562 +#define ERROR_ALIAS_EXISTS 0x00000563 +#define ERROR_LOGON_NOT_GRANTED 0x00000564 +#define ERROR_TOO_MANY_SECRETS 0x00000565 +#define ERROR_SECRET_TOO_LONG 0x00000566 +#define ERROR_INTERNAL_DB_ERROR 0x00000567 +#define ERROR_TOO_MANY_CONTEXT_IDS 0x00000568 +#define ERROR_LOGON_TYPE_NOT_GRANTED 0x00000569 +#define ERROR_NT_CROSS_ENCRYPTION_REQUIRED 0x0000056A +#define ERROR_NO_SUCH_MEMBER 0x0000056B +#define ERROR_INVALID_MEMBER 0x0000056C +#define ERROR_TOO_MANY_SIDS 0x0000056D +#define ERROR_LM_CROSS_ENCRYPTION_REQUIRED 0x0000056E +#define ERROR_NO_INHERITANCE 0x0000056F +#define ERROR_FILE_CORRUPT 0x00000570 +#define ERROR_DISK_CORRUPT 0x00000571 +#define ERROR_NO_USER_SESSION_KEY 0x00000572 +#define ERROR_LICENSE_QUOTA_EXCEEDED 0x00000573 +#define ERROR_WRONG_TARGET_NAME 0x00000574 +#define ERROR_MUTUAL_AUTH_FAILED 0x00000575 +#define ERROR_TIME_SKEW 0x00000576 +#define ERROR_CURRENT_DOMAIN_NOT_ALLOWED 0x00000577 +#define ERROR_INVALID_WINDOW_HANDLE 0x00000578 +#define ERROR_INVALID_MENU_HANDLE 0x00000579 +#define ERROR_INVALID_CURSOR_HANDLE 0x0000057A +#define ERROR_INVALID_ACCEL_HANDLE 0x0000057B +#define ERROR_INVALID_HOOK_HANDLE 0x0000057C +#define ERROR_INVALID_DWP_HANDLE 0x0000057D +#define ERROR_TLW_WITH_WSCHILD 0x0000057E +#define ERROR_CANNOT_FIND_WND_CLASS 0x0000057F +#define ERROR_WINDOW_OF_OTHER_THREAD 0x00000580 +#define ERROR_HOTKEY_ALREADY_REGISTERED 0x00000581 +#define ERROR_CLASS_ALREADY_EXISTS 0x00000582 +#define ERROR_CLASS_DOES_NOT_EXIST 0x00000583 +#define ERROR_CLASS_HAS_WINDOWS 0x00000584 +#define ERROR_INVALID_INDEX 0x00000585 +#define ERROR_INVALID_ICON_HANDLE 0x00000586 +#define ERROR_PRIVATE_DIALOG_INDEX 0x00000587 +#define ERROR_LISTBOX_ID_NOT_FOUND 0x00000588 +#define ERROR_NO_WILDCARD_CHARACTERS 0x00000589 +#define ERROR_CLIPBOARD_NOT_OPEN 0x0000058A +#define ERROR_HOTKEY_NOT_REGISTERED 0x0000058B +#define ERROR_WINDOW_NOT_DIALOG 0x0000058C +#define ERROR_CONTROL_ID_NOT_FOUND 0x0000058D +#define ERROR_INVALID_COMBOBOX_MESSAGE 0x0000058E +#define ERROR_WINDOW_NOT_COMBOBOX 0x0000058F +#define ERROR_INVALID_EDIT_HEIGHT 0x00000590 +#define ERROR_DC_NOT_FOUND 0x00000591 +#define ERROR_INVALID_HOOK_FILTER 0x00000592 +#define ERROR_INVALID_FILTER_PROC 0x00000593 +#define ERROR_HOOK_NEEDS_HMOD 0x00000594 +#define ERROR_GLOBAL_ONLY_HOOK 0x00000595 +#define ERROR_JOURNAL_HOOK_SET 0x00000596 +#define ERROR_HOOK_NOT_INSTALLED 0x00000597 +#define ERROR_INVALID_LB_MESSAGE 0x00000598 +#define ERROR_SETCOUNT_ON_BAD_LB 0x00000599 +#define ERROR_LB_WITHOUT_TABSTOPS 0x0000059A +#define ERROR_DESTROY_OBJECT_OF_OTHER_THREAD 0x0000059B +#define ERROR_CHILD_WINDOW_MENU 0x0000059C +#define ERROR_NO_SYSTEM_MENU 0x0000059D +#define ERROR_INVALID_MSGBOX_STYLE 0x0000059E +#define ERROR_INVALID_SPI_VALUE 0x0000059F +#define ERROR_SCREEN_ALREADY_LOCKED 0x000005A0 +#define ERROR_HWNDS_HAVE_DIFF_PARENT 0x000005A1 +#define ERROR_NOT_CHILD_WINDOW 0x000005A2 +#define ERROR_INVALID_GW_COMMAND 0x000005A3 +#define ERROR_INVALID_THREAD_ID 0x000005A4 +#define ERROR_NON_MDICHILD_WINDOW 0x000005A5 +#define ERROR_POPUP_ALREADY_ACTIVE 0x000005A6 +#define ERROR_NO_SCROLLBARS 0x000005A7 +#define ERROR_INVALID_SCROLLBAR_RANGE 0x000005A8 +#define ERROR_INVALID_SHOWWIN_COMMAND 0x000005A9 +#define ERROR_NO_SYSTEM_RESOURCES 0x000005AA +#define ERROR_NONPAGED_SYSTEM_RESOURCES 0x000005AB +#define ERROR_PAGED_SYSTEM_RESOURCES 0x000005AC +#define ERROR_WORKING_SET_QUOTA 0x000005AD +#define ERROR_PAGEFILE_QUOTA 0x000005AE +#define ERROR_COMMITMENT_LIMIT 0x000005AF +#define ERROR_MENU_ITEM_NOT_FOUND 0x000005B0 +#define ERROR_INVALID_KEYBOARD_HANDLE 0x000005B1 +#define ERROR_HOOK_TYPE_NOT_ALLOWED 0x000005B2 +#define ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION 0x000005B3 +#define ERROR_TIMEOUT 0x000005B4 +#define ERROR_INVALID_MONITOR_HANDLE 0x000005B5 +#define ERROR_INCORRECT_SIZE 0x000005B6 +#define ERROR_SYMLINK_CLASS_DISABLED 0x000005B7 +#define ERROR_SYMLINK_NOT_SUPPORTED 0x000005B8 +#define ERROR_XML_PARSE_ERROR 0x000005B9 +#define ERROR_XMLDSIG_ERROR 0x000005BA +#define ERROR_RESTART_APPLICATION 0x000005BB +#define ERROR_WRONG_COMPARTMENT 0x000005BC +#define ERROR_AUTHIP_FAILURE 0x000005BD +#define ERROR_NO_NVRAM_RESOURCES 0x000005BE +#define ERROR_NOT_GUI_PROCESS 0x000005BF +#define ERROR_EVENTLOG_FILE_CORRUPT 0x000005DC +#define ERROR_EVENTLOG_CANT_START 0x000005DD +#define ERROR_LOG_FILE_FULL 0x000005DE +#define ERROR_EVENTLOG_FILE_CHANGED 0x000005DF +#define ERROR_INVALID_TASK_NAME 0x0000060E +#define ERROR_INVALID_TASK_INDEX 0x0000060F +#define ERROR_THREAD_ALREADY_IN_TASK 0x00000610 +#define ERROR_INSTALL_SERVICE_FAILURE 0x00000641 +#define ERROR_INSTALL_USEREXIT 0x00000642 +#define ERROR_INSTALL_FAILURE 0x00000643 +#define ERROR_INSTALL_SUSPEND 0x00000644 +#define ERROR_UNKNOWN_PRODUCT 0x00000645 +#define ERROR_UNKNOWN_FEATURE 0x00000646 +#define ERROR_UNKNOWN_COMPONENT 0x00000647 +#define ERROR_UNKNOWN_PROPERTY 0x00000648 +#define ERROR_INVALID_HANDLE_STATE 0x00000649 +#define ERROR_BAD_CONFIGURATION 0x0000064A +#define ERROR_INDEX_ABSENT 0x0000064B +#define ERROR_INSTALL_SOURCE_ABSENT 0x0000064C +#define ERROR_INSTALL_PACKAGE_VERSION 0x0000064D +#define ERROR_PRODUCT_UNINSTALLED 0x0000064E +#define ERROR_BAD_QUERY_SYNTAX 0x0000064F +#define ERROR_INVALID_FIELD 0x00000650 +#define ERROR_DEVICE_REMOVED 0x00000651 +#define ERROR_INSTALL_ALREADY_RUNNING 0x00000652 +#define ERROR_INSTALL_PACKAGE_OPEN_FAILED 0x00000653 +#define ERROR_INSTALL_PACKAGE_INVALID 0x00000654 +#define ERROR_INSTALL_UI_FAILURE 0x00000655 +#define ERROR_INSTALL_LOG_FAILURE 0x00000656 +#define ERROR_INSTALL_LANGUAGE_UNSUPPORTED 0x00000657 +#define ERROR_INSTALL_TRANSFORM_FAILURE 0x00000658 +#define ERROR_INSTALL_PACKAGE_REJECTED 0x00000659 +#define ERROR_FUNCTION_NOT_CALLED 0x0000065A +#define ERROR_FUNCTION_FAILED 0x0000065B +#define ERROR_INVALID_TABLE 0x0000065C +#define ERROR_DATATYPE_MISMATCH 0x0000065D +#define ERROR_UNSUPPORTED_TYPE 0x0000065E +#define ERROR_CREATE_FAILED 0x0000065F +#define ERROR_INSTALL_TEMP_UNWRITABLE 0x00000660 +#define ERROR_INSTALL_PLATFORM_UNSUPPORTED 0x00000661 +#define ERROR_INSTALL_NOTUSED 0x00000662 +#define ERROR_PATCH_PACKAGE_OPEN_FAILED 0x00000663 +#define ERROR_PATCH_PACKAGE_INVALID 0x00000664 +#define ERROR_PATCH_PACKAGE_UNSUPPORTED 0x00000665 +#define ERROR_PRODUCT_VERSION 0x00000666 +#define ERROR_INVALID_COMMAND_LINE 0x00000667 +#define ERROR_INSTALL_REMOTE_DISALLOWED 0x00000668 +#define ERROR_SUCCESS_REBOOT_INITIATED 0x00000669 +#define ERROR_PATCH_TARGET_NOT_FOUND 0x0000066A +#define ERROR_PATCH_PACKAGE_REJECTED 0x0000066B +#define ERROR_INSTALL_TRANSFORM_REJECTED 0x0000066C +#define ERROR_INSTALL_REMOTE_PROHIBITED 0x0000066D +#define ERROR_PATCH_REMOVAL_UNSUPPORTED 0x0000066E +#define ERROR_UNKNOWN_PATCH 0x0000066F +#define ERROR_PATCH_NO_SEQUENCE 0x00000670 +#define ERROR_PATCH_REMOVAL_DISALLOWED 0x00000671 +#define ERROR_INVALID_PATCH_XML 0x00000672 +#define ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT 0x00000673 +#define ERROR_INSTALL_SERVICE_SAFEBOOT 0x00000674 +#define ERROR_FAIL_FAST_EXCEPTION 0x00000675 +#define ERROR_INSTALL_REJECTED 0x00000676 + +/* System Error Codes (1700-3999) */ + +#define RPC_S_INVALID_STRING_BINDING 0x000006A4 +#define RPC_S_WRONG_KIND_OF_BINDING 0x000006A5 +#define RPC_S_INVALID_BINDING 0x000006A6 +#define RPC_S_PROTSEQ_NOT_SUPPORTED 0x000006A7 +#define RPC_S_INVALID_RPC_PROTSEQ 0x000006A8 +#define RPC_S_INVALID_STRING_UUID 0x000006A9 +#define RPC_S_INVALID_ENDPOINT_FORMAT 0x000006AA +#define RPC_S_INVALID_NET_ADDR 0x000006AB +#define RPC_S_NO_ENDPOINT_FOUND 0x000006AC +#define RPC_S_INVALID_TIMEOUT 0x000006AD +#define RPC_S_OBJECT_NOT_FOUND 0x000006AE +#define RPC_S_ALREADY_REGISTERED 0x000006AF +#define RPC_S_TYPE_ALREADY_REGISTERED 0x000006B0 +#define RPC_S_ALREADY_LISTENING 0x000006B1 +#define RPC_S_NO_PROTSEQS_REGISTERED 0x000006B2 +#define RPC_S_NOT_LISTENING 0x000006B3 +#define RPC_S_UNKNOWN_MGR_TYPE 0x000006B4 +#define RPC_S_UNKNOWN_IF 0x000006B5 +#define RPC_S_NO_BINDINGS 0x000006B6 +#define RPC_S_NO_PROTSEQS 0x000006B7 +#define RPC_S_CANT_CREATE_ENDPOINT 0x000006B8 +#define RPC_S_OUT_OF_RESOURCES 0x000006B9 +#define RPC_S_SERVER_UNAVAILABLE 0x000006BA +#define RPC_S_SERVER_TOO_BUSY 0x000006BB +#define RPC_S_INVALID_NETWORK_OPTIONS 0x000006BC +#define RPC_S_NO_CALL_ACTIVE 0x000006BD +#define RPC_S_CALL_FAILED 0x000006BE +#define RPC_S_CALL_FAILED_DNE 0x000006BF +#define RPC_S_PROTOCOL_ERROR 0x000006C0 +#define RPC_S_PROXY_ACCESS_DENIED 0x000006C1 +#define RPC_S_UNSUPPORTED_TRANS_SYN 0x000006C2 +#define RPC_S_UNSUPPORTED_TYPE 0x000006C4 +#define RPC_S_INVALID_TAG 0x000006C5 +#define RPC_S_INVALID_BOUND 0x000006C6 +#define RPC_S_NO_ENTRY_NAME 0x000006C7 +#define RPC_S_INVALID_NAME_SYNTAX 0x000006C8 +#define RPC_S_UNSUPPORTED_NAME_SYNTAX 0x000006C9 +#define RPC_S_UUID_NO_ADDRESS 0x000006CB +#define RPC_S_DUPLICATE_ENDPOINT 0x000006CC +#define RPC_S_UNKNOWN_AUTHN_TYPE 0x000006CD +#define RPC_S_MAX_CALLS_TOO_SMALL 0x000006CE +#define RPC_S_STRING_TOO_LONG 0x000006CF +#define RPC_S_PROTSEQ_NOT_FOUND 0x000006D0 +#define RPC_S_PROCNUM_OUT_OF_RANGE 0x000006D1 +#define RPC_S_BINDING_HAS_NO_AUTH 0x000006D2 +#define RPC_S_UNKNOWN_AUTHN_SERVICE 0x000006D3 +#define RPC_S_UNKNOWN_AUTHN_LEVEL 0x000006D4 +#define RPC_S_INVALID_AUTH_IDENTITY 0x000006D5 +#define RPC_S_UNKNOWN_AUTHZ_SERVICE 0x000006D6 +#define EPT_S_INVALID_ENTRY 0x000006D7 +#define EPT_S_CANT_PERFORM_OP 0x000006D8 +#define EPT_S_NOT_REGISTERED 0x000006D9 +#define RPC_S_NOTHING_TO_EXPORT 0x000006DA +#define RPC_S_INCOMPLETE_NAME 0x000006DB +#define RPC_S_INVALID_VERS_OPTION 0x000006DC +#define RPC_S_NO_MORE_MEMBERS 0x000006DD +#define RPC_S_NOT_ALL_OBJS_UNEXPORTED 0x000006DE +#define RPC_S_INTERFACE_NOT_FOUND 0x000006DF +#define RPC_S_ENTRY_ALREADY_EXISTS 0x000006E0 +#define RPC_S_ENTRY_NOT_FOUND 0x000006E1 +#define RPC_S_NAME_SERVICE_UNAVAILABLE 0x000006E2 +#define RPC_S_INVALID_NAF_ID 0x000006E3 +#define RPC_S_CANNOT_SUPPORT 0x000006E4 +#define RPC_S_NO_CONTEXT_AVAILABLE 0x000006E5 +#define RPC_S_INTERNAL_ERROR 0x000006E6 +#define RPC_S_ZERO_DIVIDE 0x000006E7 +#define RPC_S_ADDRESS_ERROR 0x000006E8 +#define RPC_S_FP_DIV_ZERO 0x000006E9 +#define RPC_S_FP_UNDERFLOW 0x000006EA +#define RPC_S_FP_OVERFLOW 0x000006EB +#define RPC_X_NO_MORE_ENTRIES 0x000006EC +#define RPC_X_SS_CHAR_TRANS_OPEN_FAIL 0x000006ED +#define RPC_X_SS_CHAR_TRANS_SHORT_FILE 0x000006EE +#define RPC_X_SS_IN_NULL_CONTEXT 0x000006EF +#define RPC_X_SS_CONTEXT_DAMAGED 0x000006F1 +#define RPC_X_SS_HANDLES_MISMATCH 0x000006F2 +#define RPC_X_SS_CANNOT_GET_CALL_HANDLE 0x000006F3 +#define RPC_X_NULL_REF_POINTER 0x000006F4 +#define RPC_X_ENUM_VALUE_OUT_OF_RANGE 0x000006F5 +#define RPC_X_BYTE_COUNT_TOO_SMALL 0x000006F6 +#define RPC_X_BAD_STUB_DATA 0x000006F7 +#define ERROR_INVALID_USER_BUFFER 0x000006F8 +#define ERROR_UNRECOGNIZED_MEDIA 0x000006F9 +#define ERROR_NO_TRUST_LSA_SECRET 0x000006FA +#define ERROR_NO_TRUST_SAM_ACCOUNT 0x000006FB +#define ERROR_TRUSTED_DOMAIN_FAILURE 0x000006FC +#define ERROR_TRUSTED_RELATIONSHIP_FAILURE 0x000006FD +#define ERROR_TRUST_FAILURE 0x000006FE +#define RPC_S_CALL_IN_PROGRESS 0x000006FF +#define ERROR_NETLOGON_NOT_STARTED 0x00000700 +#define ERROR_ACCOUNT_EXPIRED 0x00000701 +#define ERROR_REDIRECTOR_HAS_OPEN_HANDLES 0x00000702 +#define ERROR_PRINTER_DRIVER_ALREADY_INSTALLED 0x00000703 +#define ERROR_UNKNOWN_PORT 0x00000704 +#define ERROR_UNKNOWN_PRINTER_DRIVER 0x00000705 +#define ERROR_UNKNOWN_PRINTPROCESSOR 0x00000706 +#define ERROR_INVALID_SEPARATOR_FILE 0x00000707 +#define ERROR_INVALID_PRIORITY 0x00000708 +#define ERROR_INVALID_PRINTER_NAME 0x00000709 +#define ERROR_PRINTER_ALREADY_EXISTS 0x0000070A +#define ERROR_INVALID_PRINTER_COMMAND 0x0000070B +#define ERROR_INVALID_DATATYPE 0x0000070C +#define ERROR_INVALID_ENVIRONMENT 0x0000070D +#define RPC_S_NO_MORE_BINDINGS 0x0000070E +#define ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT 0x0000070F +#define ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT 0x00000710 +#define ERROR_NOLOGON_SERVER_TRUST_ACCOUNT 0x00000711 +#define ERROR_DOMAIN_TRUST_INCONSISTENT 0x00000712 +#define ERROR_SERVER_HAS_OPEN_HANDLES 0x00000713 +#define ERROR_RESOURCE_DATA_NOT_FOUND 0x00000714 +#define ERROR_RESOURCE_TYPE_NOT_FOUND 0x00000715 +#define ERROR_RESOURCE_NAME_NOT_FOUND 0x00000716 +#define ERROR_RESOURCE_LANG_NOT_FOUND 0x00000717 +#define ERROR_NOT_ENOUGH_QUOTA 0x00000718 +#define RPC_S_NO_INTERFACES 0x00000719 +#define RPC_S_CALL_CANCELLED 0x0000071A +#define RPC_S_BINDING_INCOMPLETE 0x0000071B +#define RPC_S_COMM_FAILURE 0x0000071C +#define RPC_S_UNSUPPORTED_AUTHN_LEVEL 0x0000071D +#define RPC_S_NO_PRINC_NAME 0x0000071E +#define RPC_S_NOT_RPC_ERROR 0x0000071F +#define RPC_S_UUID_LOCAL_ONLY 0x00000720 +#define RPC_S_SEC_PKG_ERROR 0x00000721 +#define RPC_S_NOT_CANCELLED 0x00000722 +#define RPC_X_INVALID_ES_ACTION 0x00000723 +#define RPC_X_WRONG_ES_VERSION 0x00000724 +#define RPC_X_WRONG_STUB_VERSION 0x00000725 +#define RPC_X_INVALID_PIPE_OBJECT 0x00000726 +#define RPC_X_WRONG_PIPE_ORDER 0x00000727 +#define RPC_X_WRONG_PIPE_VERSION 0x00000728 +#define RPC_S_COOKIE_AUTH_FAILED 0x00000729 +#define RPC_S_GROUP_MEMBER_NOT_FOUND 0x0000076A +#define EPT_S_CANT_CREATE 0x0000076B +#define RPC_S_INVALID_OBJECT 0x0000076C +#define ERROR_INVALID_TIME 0x0000076D +#define ERROR_INVALID_FORM_NAME 0x0000076E +#define ERROR_INVALID_FORM_SIZE 0x0000076F +#define ERROR_ALREADY_WAITING 0x00000770 +#define ERROR_PRINTER_DELETED 0x00000771 +#define ERROR_INVALID_PRINTER_STATE 0x00000772 +#define ERROR_PASSWORD_MUST_CHANGE 0x00000773 +#define ERROR_DOMAIN_CONTROLLER_NOT_FOUND 0x00000774 +#define ERROR_ACCOUNT_LOCKED_OUT 0x00000775 +#define OR_INVALID_OXID 0x00000776 +#define OR_INVALID_OID 0x00000777 +#define OR_INVALID_SET 0x00000778 +#define RPC_S_SEND_INCOMPLETE 0x00000779 +#define RPC_S_INVALID_ASYNC_HANDLE 0x0000077A +#define RPC_S_INVALID_ASYNC_CALL 0x0000077B +#define RPC_X_PIPE_CLOSED 0x0000077C +#define RPC_X_PIPE_DISCIPLINE_ERROR 0x0000077D +#define RPC_X_PIPE_EMPTY 0x0000077E +#define ERROR_NO_SITENAME 0x0000077F +#define ERROR_CANT_ACCESS_FILE 0x00000780 +#define ERROR_CANT_RESOLVE_FILENAME 0x00000781 +#define RPC_S_ENTRY_TYPE_MISMATCH 0x00000782 +#define RPC_S_NOT_ALL_OBJS_EXPORTED 0x00000783 +#define RPC_S_INTERFACE_NOT_EXPORTED 0x00000784 +#define RPC_S_PROFILE_NOT_ADDED 0x00000785 +#define RPC_S_PRF_ELT_NOT_ADDED 0x00000786 +#define RPC_S_PRF_ELT_NOT_REMOVED 0x00000787 +#define RPC_S_GRP_ELT_NOT_ADDED 0x00000788 +#define RPC_S_GRP_ELT_NOT_REMOVED 0x00000789 +#define ERROR_KM_DRIVER_BLOCKED 0x0000078A +#define ERROR_CONTEXT_EXPIRED 0x0000078B +#define ERROR_PER_USER_TRUST_QUOTA_EXCEEDED 0x0000078C +#define ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED 0x0000078D +#define ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED 0x0000078E +#define ERROR_AUTHENTICATION_FIREWALL_FAILED 0x0000078F +#define ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED 0x00000790 +#define ERROR_NTLM_BLOCKED 0x00000791 +#define ERROR_PASSWORD_CHANGE_REQUIRED 0x00000792 +#define ERROR_INVALID_PIXEL_FORMAT 0x000007D0 +#define ERROR_BAD_DRIVER 0x000007D1 +#define ERROR_INVALID_WINDOW_STYLE 0x000007D2 +#define ERROR_METAFILE_NOT_SUPPORTED 0x000007D3 +#define ERROR_TRANSFORM_NOT_SUPPORTED 0x000007D4 +#define ERROR_CLIPPING_NOT_SUPPORTED 0x000007D5 +#define ERROR_INVALID_CMM 0x000007DA +#define ERROR_INVALID_PROFILE 0x000007DB +#define ERROR_TAG_NOT_FOUND 0x000007DC +#define ERROR_TAG_NOT_PRESENT 0x000007DD +#define ERROR_DUPLICATE_TAG 0x000007DE +#define ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE 0x000007DF +#define ERROR_PROFILE_NOT_FOUND 0x000007E0 +#define ERROR_INVALID_COLORSPACE 0x000007E1 +#define ERROR_ICM_NOT_ENABLED 0x000007E2 +#define ERROR_DELETING_ICM_XFORM 0x000007E3 +#define ERROR_INVALID_TRANSFORM 0x000007E4 +#define ERROR_COLORSPACE_MISMATCH 0x000007E5 +#define ERROR_INVALID_COLORINDEX 0x000007E6 +#define ERROR_PROFILE_DOES_NOT_MATCH_DEVICE 0x000007E7 +#define ERROR_CONNECTED_OTHER_PASSWORD 0x0000083C +#define ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT 0x0000083D +#define ERROR_BAD_USERNAME 0x0000089A +#define ERROR_NOT_CONNECTED 0x000008CA +#define ERROR_OPEN_FILES 0x00000961 +#define ERROR_ACTIVE_CONNECTIONS 0x00000962 +#define ERROR_DEVICE_IN_USE 0x00000964 +#define ERROR_UNKNOWN_PRINT_MONITOR 0x00000BB8 +#define ERROR_PRINTER_DRIVER_IN_USE 0x00000BB9 +#define ERROR_SPOOL_FILE_NOT_FOUND 0x00000BBA +#define ERROR_SPL_NO_STARTDOC 0x00000BBB +#define ERROR_SPL_NO_ADDJOB 0x00000BBC +#define ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED 0x00000BBD +#define ERROR_PRINT_MONITOR_ALREADY_INSTALLED 0x00000BBE +#define ERROR_INVALID_PRINT_MONITOR 0x00000BBF +#define ERROR_PRINT_MONITOR_IN_USE 0x00000BC0 +#define ERROR_PRINTER_HAS_JOBS_QUEUED 0x00000BC1 +#define ERROR_SUCCESS_REBOOT_REQUIRED 0x00000BC2 +#define ERROR_SUCCESS_RESTART_REQUIRED 0x00000BC3 +#define ERROR_PRINTER_NOT_FOUND 0x00000BC4 +#define ERROR_PRINTER_DRIVER_WARNED 0x00000BC5 +#define ERROR_PRINTER_DRIVER_BLOCKED 0x00000BC6 +#define ERROR_PRINTER_DRIVER_PACKAGE_IN_USE 0x00000BC7 +#define ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND 0x00000BC8 +#define ERROR_FAIL_REBOOT_REQUIRED 0x00000BC9 +#define ERROR_FAIL_REBOOT_INITIATED 0x00000BCA +#define ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED 0x00000BCB +#define ERROR_PRINT_JOB_RESTART_REQUIRED 0x00000BCC +#define ERROR_INVALID_PRINTER_DRIVER_MANIFEST 0x00000BCD +#define ERROR_PRINTER_NOT_SHAREABLE 0x00000BCE +#define ERROR_REQUEST_PAUSED 0x00000BEA +#define ERROR_IO_REISSUE_AS_CACHED 0x00000F6E + +/* System Error Codes (4000-5999) */ + +#define ERROR_WINS_INTERNAL 0x00000FA0 +#define ERROR_CAN_NOT_DEL_LOCAL_WINS 0x00000FA1 +#define ERROR_STATIC_INIT 0x00000FA2 +#define ERROR_INC_BACKUP 0x00000FA3 +#define ERROR_FULL_BACKUP 0x00000FA4 +#define ERROR_REC_NON_EXISTENT 0x00000FA5 +#define ERROR_RPL_NOT_ALLOWED 0x00000FA6 +#define PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED 0x00000FD2 +#define PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO 0x00000FD3 +#define PEERDIST_ERROR_MISSING_DATA 0x00000FD4 +#define PEERDIST_ERROR_NO_MORE 0x00000FD5 +#define PEERDIST_ERROR_NOT_INITIALIZED 0x00000FD6 +#define PEERDIST_ERROR_ALREADY_INITIALIZED 0x00000FD7 +#define PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS 0x00000FD8 +#define PEERDIST_ERROR_INVALIDATED 0x00000FD9 +#define PEERDIST_ERROR_ALREADY_EXISTS 0x00000FDA +#define PEERDIST_ERROR_OPERATION_NOTFOUND 0x00000FDB +#define PEERDIST_ERROR_ALREADY_COMPLETED 0x00000FDC +#define PEERDIST_ERROR_OUT_OF_BOUNDS 0x00000FDD +#define PEERDIST_ERROR_VERSION_UNSUPPORTED 0x00000FDE +#define PEERDIST_ERROR_INVALID_CONFIGURATION 0x00000FDF +#define PEERDIST_ERROR_NOT_LICENSED 0x00000FE0 +#define PEERDIST_ERROR_SERVICE_UNAVAILABLE 0x00000FE1 +#define PEERDIST_ERROR_TRUST_FAILURE 0x00000FE2 +#define ERROR_DHCP_ADDRESS_CONFLICT 0x00001004 +#define ERROR_WMI_GUID_NOT_FOUND 0x00001068 +#define ERROR_WMI_INSTANCE_NOT_FOUND 0x00001069 +#define ERROR_WMI_ITEMID_NOT_FOUND 0x0000106A +#define ERROR_WMI_TRY_AGAIN 0x0000106B +#define ERROR_WMI_DP_NOT_FOUND 0x0000106C +#define ERROR_WMI_UNRESOLVED_INSTANCE_REF 0x0000106D +#define ERROR_WMI_ALREADY_ENABLED 0x0000106E +#define ERROR_WMI_GUID_DISCONNECTED 0x0000106F +#define ERROR_WMI_SERVER_UNAVAILABLE 0x00001070 +#define ERROR_WMI_DP_FAILED 0x00001071 +#define ERROR_WMI_INVALID_MOF 0x00001072 +#define ERROR_WMI_INVALID_REGINFO 0x00001073 +#define ERROR_WMI_ALREADY_DISABLED 0x00001074 +#define ERROR_WMI_READ_ONLY 0x00001075 +#define ERROR_WMI_SET_FAILURE 0x00001076 +#define ERROR_NOT_APPCONTAINER 0x0000109A +#define ERROR_APPCONTAINER_REQUIRED 0x0000109B +#define ERROR_NOT_SUPPORTED_IN_APPCONTAINER 0x0000109C +#define ERROR_INVALID_PACKAGE_SID_LENGTH 0x0000109D +#define ERROR_INVALID_MEDIA 0x000010CC +#define ERROR_INVALID_LIBRARY 0x000010CD +#define ERROR_INVALID_MEDIA_POOL 0x000010CE +#define ERROR_DRIVE_MEDIA_MISMATCH 0x000010CF +#define ERROR_MEDIA_OFFLINE 0x000010D0 +#define ERROR_LIBRARY_OFFLINE 0x000010D1 +#define ERROR_EMPTY 0x000010D2 +#define ERROR_NOT_EMPTY 0x000010D3 +#define ERROR_MEDIA_UNAVAILABLE 0x000010D4 +#define ERROR_RESOURCE_DISABLED 0x000010D5 +#define ERROR_INVALID_CLEANER 0x000010D6 +#define ERROR_UNABLE_TO_CLEAN 0x000010D7 +#define ERROR_OBJECT_NOT_FOUND 0x000010D8 +#define ERROR_DATABASE_FAILURE 0x000010D9 +#define ERROR_DATABASE_FULL 0x000010DA +#define ERROR_MEDIA_INCOMPATIBLE 0x000010DB +#define ERROR_RESOURCE_NOT_PRESENT 0x000010DC +#define ERROR_INVALID_OPERATION 0x000010DD +#define ERROR_MEDIA_NOT_AVAILABLE 0x000010DE +#define ERROR_DEVICE_NOT_AVAILABLE 0x000010DF +#define ERROR_REQUEST_REFUSED 0x000010E0 +#define ERROR_INVALID_DRIVE_OBJECT 0x000010E1 +#define ERROR_LIBRARY_FULL 0x000010E2 +#define ERROR_MEDIUM_NOT_ACCESSIBLE 0x000010E3 +#define ERROR_UNABLE_TO_LOAD_MEDIUM 0x000010E4 +#define ERROR_UNABLE_TO_INVENTORY_DRIVE 0x000010E5 +#define ERROR_UNABLE_TO_INVENTORY_SLOT 0x000010E6 +#define ERROR_UNABLE_TO_INVENTORY_TRANSPORT 0x000010E7 +#define ERROR_TRANSPORT_FULL 0x000010E8 +#define ERROR_CONTROLLING_IEPORT 0x000010E9 +#define ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA 0x000010EA +#define ERROR_CLEANER_SLOT_SET 0x000010EB +#define ERROR_CLEANER_SLOT_NOT_SET 0x000010EC +#define ERROR_CLEANER_CARTRIDGE_SPENT 0x000010ED +#define ERROR_UNEXPECTED_OMID 0x000010EE +#define ERROR_CANT_DELETE_LAST_ITEM 0x000010EF +#define ERROR_MESSAGE_EXCEEDS_MAX_SIZE 0x000010F0 +#define ERROR_VOLUME_CONTAINS_SYS_FILES 0x000010F1 +#define ERROR_INDIGENOUS_TYPE 0x000010F2 +#define ERROR_NO_SUPPORTING_DRIVES 0x000010F3 +#define ERROR_CLEANER_CARTRIDGE_INSTALLED 0x000010F4 +#define ERROR_IEPORT_FULL 0x000010F5 +#define ERROR_FILE_OFFLINE 0x000010FE +#define ERROR_REMOTE_STORAGE_NOT_ACTIVE 0x000010FF +#define ERROR_REMOTE_STORAGE_MEDIA_ERROR 0x00001100 +#define ERROR_NOT_A_REPARSE_POINT 0x00001126 +#define ERROR_REPARSE_ATTRIBUTE_CONFLICT 0x00001127 +#define ERROR_INVALID_REPARSE_DATA 0x00001128 +#define ERROR_REPARSE_TAG_INVALID 0x00001129 +#define ERROR_REPARSE_TAG_MISMATCH 0x0000112A +#define ERROR_APP_DATA_NOT_FOUND 0x00001130 +#define ERROR_APP_DATA_EXPIRED 0x00001131 +#define ERROR_APP_DATA_CORRUPT 0x00001132 +#define ERROR_APP_DATA_LIMIT_EXCEEDED 0x00001133 +#define ERROR_APP_DATA_REBOOT_REQUIRED 0x00001134 +#define ERROR_SECUREBOOT_ROLLBACK_DETECTED 0x00001144 +#define ERROR_SECUREBOOT_POLICY_VIOLATION 0x00001145 +#define ERROR_SECUREBOOT_INVALID_POLICY 0x00001146 +#define ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND 0x00001147 +#define ERROR_SECUREBOOT_POLICY_NOT_SIGNED 0x00001148 +#define ERROR_SECUREBOOT_NOT_ENABLED 0x00001149 +#define ERROR_SECUREBOOT_FILE_REPLACED 0x0000114A +#define ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED 0x00001158 +#define ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED 0x00001159 +#define ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED 0x0000115A +#define ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED 0x0000115B +#define ERROR_VOLUME_NOT_SIS_ENABLED 0x00001194 +#define ERROR_DEPENDENT_RESOURCE_EXISTS 0x00001389 +#define ERROR_DEPENDENCY_NOT_FOUND 0x0000138A +#define ERROR_DEPENDENCY_ALREADY_EXISTS 0x0000138B +#define ERROR_RESOURCE_NOT_ONLINE 0x0000138C +#define ERROR_HOST_NODE_NOT_AVAILABLE 0x0000138D +#define ERROR_RESOURCE_NOT_AVAILABLE 0x0000138E +#define ERROR_RESOURCE_NOT_FOUND 0x0000138F +#define ERROR_SHUTDOWN_CLUSTER 0x00001390 +#define ERROR_CANT_EVICT_ACTIVE_NODE 0x00001391 +#define ERROR_OBJECT_ALREADY_EXISTS 0x00001392 +#define ERROR_OBJECT_IN_LIST 0x00001393 +#define ERROR_GROUP_NOT_AVAILABLE 0x00001394 +#define ERROR_GROUP_NOT_FOUND 0x00001395 +#define ERROR_GROUP_NOT_ONLINE 0x00001396 +#define ERROR_HOST_NODE_NOT_RESOURCE_OWNER 0x00001397 +#define ERROR_HOST_NODE_NOT_GROUP_OWNER 0x00001398 +#define ERROR_RESMON_CREATE_FAILED 0x00001399 +#define ERROR_RESMON_ONLINE_FAILED 0x0000139A +#define ERROR_RESOURCE_ONLINE 0x0000139B +#define ERROR_QUORUM_RESOURCE 0x0000139C +#define ERROR_NOT_QUORUM_CAPABLE 0x0000139D +#define ERROR_CLUSTER_SHUTTING_DOWN 0x0000139E +#define ERROR_INVALID_STATE 0x0000139F +#define ERROR_RESOURCE_PROPERTIES_STORED 0x000013A0 +#define ERROR_NOT_QUORUM_CLASS 0x000013A1 +#define ERROR_CORE_RESOURCE 0x000013A2 +#define ERROR_QUORUM_RESOURCE_ONLINE_FAILED 0x000013A3 +#define ERROR_QUORUMLOG_OPEN_FAILED 0x000013A4 +#define ERROR_CLUSTERLOG_CORRUPT 0x000013A5 +#define ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE 0x000013A6 +#define ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE 0x000013A7 +#define ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND 0x000013A8 +#define ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE 0x000013A9 +#define ERROR_QUORUM_OWNER_ALIVE 0x000013AA +#define ERROR_NETWORK_NOT_AVAILABLE 0x000013AB +#define ERROR_NODE_NOT_AVAILABLE 0x000013AC +#define ERROR_ALL_NODES_NOT_AVAILABLE 0x000013AD +#define ERROR_RESOURCE_FAILED 0x000013AE +#define ERROR_CLUSTER_INVALID_NODE 0x000013AF +#define ERROR_CLUSTER_NODE_EXISTS 0x000013B0 +#define ERROR_CLUSTER_JOIN_IN_PROGRESS 0x000013B1 +#define ERROR_CLUSTER_NODE_NOT_FOUND 0x000013B2 +#define ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND 0x000013B3 +#define ERROR_CLUSTER_NETWORK_EXISTS 0x000013B4 +#define ERROR_CLUSTER_NETWORK_NOT_FOUND 0x000013B5 +#define ERROR_CLUSTER_NETINTERFACE_EXISTS 0x000013B6 +#define ERROR_CLUSTER_NETINTERFACE_NOT_FOUND 0x000013B7 +#define ERROR_CLUSTER_INVALID_REQUEST 0x000013B8 +#define ERROR_CLUSTER_INVALID_NETWORK_PROVIDER 0x000013B9 +#define ERROR_CLUSTER_NODE_DOWN 0x000013BA +#define ERROR_CLUSTER_NODE_UNREACHABLE 0x000013BB +#define ERROR_CLUSTER_NODE_NOT_MEMBER 0x000013BC +#define ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS 0x000013BD +#define ERROR_CLUSTER_INVALID_NETWORK 0x000013BE +#define ERROR_CLUSTER_NODE_UP 0x000013C0 +#define ERROR_CLUSTER_IPADDR_IN_USE 0x000013C1 +#define ERROR_CLUSTER_NODE_NOT_PAUSED 0x000013C2 +#define ERROR_CLUSTER_NO_SECURITY_CONTEXT 0x000013C3 +#define ERROR_CLUSTER_NETWORK_NOT_INTERNAL 0x000013C4 +#define ERROR_CLUSTER_NODE_ALREADY_UP 0x000013C5 +#define ERROR_CLUSTER_NODE_ALREADY_DOWN 0x000013C6 +#define ERROR_CLUSTER_NETWORK_ALREADY_ONLINE 0x000013C7 +#define ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE 0x000013C8 +#define ERROR_CLUSTER_NODE_ALREADY_MEMBER 0x000013C9 +#define ERROR_CLUSTER_LAST_INTERNAL_NETWORK 0x000013CA +#define ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS 0x000013CB +#define ERROR_INVALID_OPERATION_ON_QUORUM 0x000013CC +#define ERROR_DEPENDENCY_NOT_ALLOWED 0x000013CD +#define ERROR_CLUSTER_NODE_PAUSED 0x000013CE +#define ERROR_NODE_CANT_HOST_RESOURCE 0x000013CF +#define ERROR_CLUSTER_NODE_NOT_READY 0x000013D0 +#define ERROR_CLUSTER_NODE_SHUTTING_DOWN 0x000013D1 +#define ERROR_CLUSTER_JOIN_ABORTED 0x000013D2 +#define ERROR_CLUSTER_INCOMPATIBLE_VERSIONS 0x000013D3 +#define ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED 0x000013D4 +#define ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED 0x000013D5 +#define ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND 0x000013D6 +#define ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED 0x000013D7 +#define ERROR_CLUSTER_RESNAME_NOT_FOUND 0x000013D8 +#define ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED 0x000013D9 +#define ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST 0x000013DA +#define ERROR_CLUSTER_DATABASE_SEQMISMATCH 0x000013DB +#define ERROR_RESMON_INVALID_STATE 0x000013DC +#define ERROR_CLUSTER_GUM_NOT_LOCKER 0x000013DD +#define ERROR_QUORUM_DISK_NOT_FOUND 0x000013DE +#define ERROR_DATABASE_BACKUP_CORRUPT 0x000013DF +#define ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT 0x000013E0 +#define ERROR_RESOURCE_PROPERTY_UNCHANGEABLE 0x000013E1 +#define ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE 0x00001702 +#define ERROR_CLUSTER_QUORUMLOG_NOT_FOUND 0x00001703 +#define ERROR_CLUSTER_MEMBERSHIP_HALT 0x00001704 +#define ERROR_CLUSTER_INSTANCE_ID_MISMATCH 0x00001705 +#define ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP 0x00001706 +#define ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH 0x00001707 +#define ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP 0x00001708 +#define ERROR_CLUSTER_PARAMETER_MISMATCH 0x00001709 +#define ERROR_NODE_CANNOT_BE_CLUSTERED 0x0000170A +#define ERROR_CLUSTER_WRONG_OS_VERSION 0x0000170B +#define ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME 0x0000170C +#define ERROR_CLUSCFG_ALREADY_COMMITTED 0x0000170D +#define ERROR_CLUSCFG_ROLLBACK_FAILED 0x0000170E +#define ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT 0x0000170F +#define ERROR_CLUSTER_OLD_VERSION 0x00001710 +#define ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME 0x00001711 +#define ERROR_CLUSTER_NO_NET_ADAPTERS 0x00001712 +#define ERROR_CLUSTER_POISONED 0x00001713 +#define ERROR_CLUSTER_GROUP_MOVING 0x00001714 +#define ERROR_CLUSTER_RESOURCE_TYPE_BUSY 0x00001715 +#define ERROR_RESOURCE_CALL_TIMED_OUT 0x00001716 +#define ERROR_INVALID_CLUSTER_IPV6_ADDRESS 0x00001717 +#define ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION 0x00001718 +#define ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS 0x00001719 +#define ERROR_CLUSTER_PARTIAL_SEND 0x0000171A +#define ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION 0x0000171B +#define ERROR_CLUSTER_INVALID_STRING_TERMINATION 0x0000171C +#define ERROR_CLUSTER_INVALID_STRING_FORMAT 0x0000171D +#define ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS 0x0000171E +#define ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS 0x0000171F +#define ERROR_CLUSTER_NULL_DATA 0x00001720 +#define ERROR_CLUSTER_PARTIAL_READ 0x00001721 +#define ERROR_CLUSTER_PARTIAL_WRITE 0x00001722 +#define ERROR_CLUSTER_CANT_DESERIALIZE_DATA 0x00001723 +#define ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT 0x00001724 +#define ERROR_CLUSTER_NO_QUORUM 0x00001725 +#define ERROR_CLUSTER_INVALID_IPV6_NETWORK 0x00001726 +#define ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK 0x00001727 +#define ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP 0x00001728 +#define ERROR_DEPENDENCY_TREE_TOO_COMPLEX 0x00001729 +#define ERROR_EXCEPTION_IN_RESOURCE_CALL 0x0000172A +#define ERROR_CLUSTER_RHS_FAILED_INITIALIZATION 0x0000172B +#define ERROR_CLUSTER_NOT_INSTALLED 0x0000172C +#define ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE 0x0000172D +#define ERROR_CLUSTER_MAX_NODES_IN_CLUSTER 0x0000172E +#define ERROR_CLUSTER_TOO_MANY_NODES 0x0000172F +#define ERROR_CLUSTER_OBJECT_ALREADY_USED 0x00001730 +#define ERROR_NONCORE_GROUPS_FOUND 0x00001731 +#define ERROR_FILE_SHARE_RESOURCE_CONFLICT 0x00001732 +#define ERROR_CLUSTER_EVICT_INVALID_REQUEST 0x00001733 +#define ERROR_CLUSTER_SINGLETON_RESOURCE 0x00001734 +#define ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE 0x00001735 +#define ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED 0x00001736 +#define ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR 0x00001737 +#define ERROR_CLUSTER_GROUP_BUSY 0x00001738 +#define ERROR_CLUSTER_NOT_SHARED_VOLUME 0x00001739 +#define ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR 0x0000173A +#define ERROR_CLUSTER_SHARED_VOLUMES_IN_USE 0x0000173B +#define ERROR_CLUSTER_USE_SHARED_VOLUMES_API 0x0000173C +#define ERROR_CLUSTER_BACKUP_IN_PROGRESS 0x0000173D +#define ERROR_NON_CSV_PATH 0x0000173E +#define ERROR_CSV_VOLUME_NOT_LOCAL 0x0000173F +#define ERROR_CLUSTER_WATCHDOG_TERMINATING 0x00001740 +#define ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES 0x00001741 +#define ERROR_CLUSTER_INVALID_NODE_WEIGHT 0x00001742 +#define ERROR_CLUSTER_RESOURCE_VETOED_CALL 0x00001743 +#define ERROR_RESMON_SYSTEM_RESOURCES_LACKING 0x00001744 +#define ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION 0x00001745 +#define ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE 0x00001746 +#define ERROR_CLUSTER_GROUP_QUEUED 0x00001747 +#define ERROR_CLUSTER_RESOURCE_LOCKED_STATUS 0x00001748 +#define ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED 0x00001749 +#define ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS 0x0000174A +#define ERROR_CLUSTER_DISK_NOT_CONNECTED 0x0000174B +#define ERROR_DISK_NOT_CSV_CAPABLE 0x0000174C +#define ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE 0x0000174D +#define ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED 0x0000174E +#define ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED 0x0000174F +#define ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES 0x00001750 +#define ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES 0x00001751 +#define ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE 0x00001752 +#define ERROR_CLUSTER_AFFINITY_CONFLICT 0x00001753 +#define ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE 0x00001754 + +/* System Error Codes (6000-8199) */ + +#define ERROR_ENCRYPTION_FAILED 0x00001770 +#define ERROR_DECRYPTION_FAILED 0x00001771 +#define ERROR_FILE_ENCRYPTED 0x00001772 +#define ERROR_NO_RECOVERY_POLICY 0x00001773 +#define ERROR_NO_EFS 0x00001774 +#define ERROR_WRONG_EFS 0x00001775 +#define ERROR_NO_USER_KEYS 0x00001776 +#define ERROR_FILE_NOT_ENCRYPTED 0x00001777 +#define ERROR_NOT_EXPORT_FORMAT 0x00001778 +#define ERROR_FILE_READ_ONLY 0x00001779 +#define ERROR_DIR_EFS_DISALLOWED 0x0000177A +#define ERROR_EFS_SERVER_NOT_TRUSTED 0x0000177B +#define ERROR_BAD_RECOVERY_POLICY 0x0000177C +#define ERROR_EFS_ALG_BLOB_TOO_BIG 0x0000177D +#define ERROR_VOLUME_NOT_SUPPORT_EFS 0x0000177E +#define ERROR_EFS_DISABLED 0x0000177F +#define ERROR_EFS_VERSION_NOT_SUPPORT 0x00001780 +#define ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE 0x00001781 +#define ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER 0x00001782 +#define ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE 0x00001783 +#define ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE 0x00001784 +#define ERROR_CS_ENCRYPTION_FILE_NOT_CSE 0x00001785 +#define ERROR_ENCRYPTION_POLICY_DENIES_OPERATION 0x00001786 +#define ERROR_NO_BROWSER_SERVERS_FOUND 0x000017E6 +#define SCHED_E_SERVICE_NOT_LOCALSYSTEM 0x00001838 +#define ERROR_LOG_SECTOR_INVALID 0x000019C8 +#define ERROR_LOG_SECTOR_PARITY_INVALID 0x000019C9 +#define ERROR_LOG_SECTOR_REMAPPED 0x000019CA +#define ERROR_LOG_BLOCK_INCOMPLETE 0x000019CB +#define ERROR_LOG_INVALID_RANGE 0x000019CC +#define ERROR_LOG_BLOCKS_EXHAUSTED 0x000019CD +#define ERROR_LOG_READ_CONTEXT_INVALID 0x000019CE +#define ERROR_LOG_RESTART_INVALID 0x000019CF +#define ERROR_LOG_BLOCK_VERSION 0x000019D0 +#define ERROR_LOG_BLOCK_INVALID 0x000019D1 +#define ERROR_LOG_READ_MODE_INVALID 0x000019D2 +#define ERROR_LOG_NO_RESTART 0x000019D3 +#define ERROR_LOG_METADATA_CORRUPT 0x000019D4 +#define ERROR_LOG_METADATA_INVALID 0x000019D5 +#define ERROR_LOG_METADATA_INCONSISTENT 0x000019D6 +#define ERROR_LOG_RESERVATION_INVALID 0x000019D7 +#define ERROR_LOG_CANT_DELETE 0x000019D8 +#define ERROR_LOG_CONTAINER_LIMIT_EXCEEDED 0x000019D9 +#define ERROR_LOG_START_OF_LOG 0x000019DA +#define ERROR_LOG_POLICY_ALREADY_INSTALLED 0x000019DB +#define ERROR_LOG_POLICY_NOT_INSTALLED 0x000019DC +#define ERROR_LOG_POLICY_INVALID 0x000019DD +#define ERROR_LOG_POLICY_CONFLICT 0x000019DE +#define ERROR_LOG_PINNED_ARCHIVE_TAIL 0x000019DF +#define ERROR_LOG_RECORD_NONEXISTENT 0x000019E0 +#define ERROR_LOG_RECORDS_RESERVED_INVALID 0x000019E1 +#define ERROR_LOG_SPACE_RESERVED_INVALID 0x000019E2 +#define ERROR_LOG_TAIL_INVALID 0x000019E3 +#define ERROR_LOG_FULL 0x000019E4 +#define ERROR_COULD_NOT_RESIZE_LOG 0x000019E5 +#define ERROR_LOG_MULTIPLEXED 0x000019E6 +#define ERROR_LOG_DEDICATED 0x000019E7 +#define ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS 0x000019E8 +#define ERROR_LOG_ARCHIVE_IN_PROGRESS 0x000019E9 +#define ERROR_LOG_EPHEMERAL 0x000019EA +#define ERROR_LOG_NOT_ENOUGH_CONTAINERS 0x000019EB +#define ERROR_LOG_CLIENT_ALREADY_REGISTERED 0x000019EC +#define ERROR_LOG_CLIENT_NOT_REGISTERED 0x000019ED +#define ERROR_LOG_FULL_HANDLER_IN_PROGRESS 0x000019EE +#define ERROR_LOG_CONTAINER_READ_FAILED 0x000019EF +#define ERROR_LOG_CONTAINER_WRITE_FAILED 0x000019F0 +#define ERROR_LOG_CONTAINER_OPEN_FAILED 0x000019F1 +#define ERROR_LOG_CONTAINER_STATE_INVALID 0x000019F2 +#define ERROR_LOG_STATE_INVALID 0x000019F3 +#define ERROR_LOG_PINNED 0x000019F4 +#define ERROR_LOG_METADATA_FLUSH_FAILED 0x000019F5 +#define ERROR_LOG_INCONSISTENT_SECURITY 0x000019F6 +#define ERROR_LOG_APPENDED_FLUSH_FAILED 0x000019F7 +#define ERROR_LOG_PINNED_RESERVATION 0x000019F8 +#define ERROR_INVALID_TRANSACTION 0x00001A2C +#define ERROR_TRANSACTION_NOT_ACTIVE 0x00001A2D +#define ERROR_TRANSACTION_REQUEST_NOT_VALID 0x00001A2E +#define ERROR_TRANSACTION_NOT_REQUESTED 0x00001A2F +#define ERROR_TRANSACTION_ALREADY_ABORTED 0x00001A30 +#define ERROR_TRANSACTION_ALREADY_COMMITTED 0x00001A31 +#define ERROR_TM_INITIALIZATION_FAILED 0x00001A32 +#define ERROR_RESOURCEMANAGER_READ_ONLY 0x00001A33 +#define ERROR_TRANSACTION_NOT_JOINED 0x00001A34 +#define ERROR_TRANSACTION_SUPERIOR_EXISTS 0x00001A35 +#define ERROR_CRM_PROTOCOL_ALREADY_EXISTS 0x00001A36 +#define ERROR_TRANSACTION_PROPAGATION_FAILED 0x00001A37 +#define ERROR_CRM_PROTOCOL_NOT_FOUND 0x00001A38 +#define ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER 0x00001A39 +#define ERROR_CURRENT_TRANSACTION_NOT_VALID 0x00001A3A +#define ERROR_TRANSACTION_NOT_FOUND 0x00001A3B +#define ERROR_RESOURCEMANAGER_NOT_FOUND 0x00001A3C +#define ERROR_ENLISTMENT_NOT_FOUND 0x00001A3D +#define ERROR_TRANSACTIONMANAGER_NOT_FOUND 0x00001A3E +#define ERROR_TRANSACTIONMANAGER_NOT_ONLINE 0x00001A3F +#define ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION 0x00001A40 +#define ERROR_TRANSACTION_NOT_ROOT 0x00001A41 +#define ERROR_TRANSACTION_OBJECT_EXPIRED 0x00001A42 +#define ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED 0x00001A43 +#define ERROR_TRANSACTION_RECORD_TOO_LONG 0x00001A44 +#define ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED 0x00001A45 +#define ERROR_TRANSACTION_INTEGRITY_VIOLATED 0x00001A46 +#define ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH 0x00001A47 +#define ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT 0x00001A48 +#define ERROR_TRANSACTION_MUST_WRITETHROUGH 0x00001A49 +#define ERROR_TRANSACTION_NO_SUPERIOR 0x00001A4A +#define ERROR_HEURISTIC_DAMAGE_POSSIBLE 0x00001A4B +#define ERROR_TRANSACTIONAL_CONFLICT 0x00001A90 +#define ERROR_RM_NOT_ACTIVE 0x00001A91 +#define ERROR_RM_METADATA_CORRUPT 0x00001A92 +#define ERROR_DIRECTORY_NOT_RM 0x00001A93 +#define ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE 0x00001A95 +#define ERROR_LOG_RESIZE_INVALID_SIZE 0x00001A96 +#define ERROR_OBJECT_NO_LONGER_EXISTS 0x00001A97 +#define ERROR_STREAM_MINIVERSION_NOT_FOUND 0x00001A98 +#define ERROR_STREAM_MINIVERSION_NOT_VALID 0x00001A99 +#define ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION 0x00001A9A +#define ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT 0x00001A9B +#define ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS 0x00001A9C +#define ERROR_REMOTE_FILE_VERSION_MISMATCH 0x00001A9E +#define ERROR_HANDLE_NO_LONGER_VALID 0x00001A9F +#define ERROR_NO_TXF_METADATA 0x00001AA0 +#define ERROR_LOG_CORRUPTION_DETECTED 0x00001AA1 +#define ERROR_CANT_RECOVER_WITH_HANDLE_OPEN 0x00001AA2 +#define ERROR_RM_DISCONNECTED 0x00001AA3 +#define ERROR_ENLISTMENT_NOT_SUPERIOR 0x00001AA4 +#define ERROR_RECOVERY_NOT_NEEDED 0x00001AA5 +#define ERROR_RM_ALREADY_STARTED 0x00001AA6 +#define ERROR_FILE_IDENTITY_NOT_PERSISTENT 0x00001AA7 +#define ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY 0x00001AA8 +#define ERROR_CANT_CROSS_RM_BOUNDARY 0x00001AA9 +#define ERROR_TXF_DIR_NOT_EMPTY 0x00001AAA +#define ERROR_INDOUBT_TRANSACTIONS_EXIST 0x00001AAB +#define ERROR_TM_VOLATILE 0x00001AAC +#define ERROR_ROLLBACK_TIMER_EXPIRED 0x00001AAD +#define ERROR_TXF_ATTRIBUTE_CORRUPT 0x00001AAE +#define ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION 0x00001AAF +#define ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED 0x00001AB0 +#define ERROR_LOG_GROWTH_FAILED 0x00001AB1 +#define ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE 0x00001AB2 +#define ERROR_TXF_METADATA_ALREADY_PRESENT 0x00001AB3 +#define ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET 0x00001AB4 +#define ERROR_TRANSACTION_REQUIRED_PROMOTION 0x00001AB5 +#define ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION 0x00001AB6 +#define ERROR_TRANSACTIONS_NOT_FROZEN 0x00001AB7 +#define ERROR_TRANSACTION_FREEZE_IN_PROGRESS 0x00001AB8 +#define ERROR_NOT_SNAPSHOT_VOLUME 0x00001AB9 +#define ERROR_NO_SAVEPOINT_WITH_OPEN_FILES 0x00001ABA +#define ERROR_DATA_LOST_REPAIR 0x00001ABB +#define ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION 0x00001ABC +#define ERROR_TM_IDENTITY_MISMATCH 0x00001ABD +#define ERROR_FLOATED_SECTION 0x00001ABE +#define ERROR_CANNOT_ACCEPT_TRANSACTED_WORK 0x00001ABF +#define ERROR_CANNOT_ABORT_TRANSACTIONS 0x00001AC0 +#define ERROR_BAD_CLUSTERS 0x00001AC1 +#define ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION 0x00001AC2 +#define ERROR_VOLUME_DIRTY 0x00001AC3 +#define ERROR_NO_LINK_TRACKING_IN_TRANSACTION 0x00001AC4 +#define ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION 0x00001AC5 +#define ERROR_EXPIRED_HANDLE 0x00001AC6 +#define ERROR_TRANSACTION_NOT_ENLISTED 0x00001AC7 +#define ERROR_CTX_WINSTATION_NAME_INVALID 0x00001B59 +#define ERROR_CTX_INVALID_PD 0x00001B5A +#define ERROR_CTX_PD_NOT_FOUND 0x00001B5B +#define ERROR_CTX_WD_NOT_FOUND 0x00001B5C +#define ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY 0x00001B5D +#define ERROR_CTX_SERVICE_NAME_COLLISION 0x00001B5E +#define ERROR_CTX_CLOSE_PENDING 0x00001B5F +#define ERROR_CTX_NO_OUTBUF 0x00001B60 +#define ERROR_CTX_MODEM_INF_NOT_FOUND 0x00001B61 +#define ERROR_CTX_INVALID_MODEMNAME 0x00001B62 +#define ERROR_CTX_MODEM_RESPONSE_ERROR 0x00001B63 +#define ERROR_CTX_MODEM_RESPONSE_TIMEOUT 0x00001B64 +#define ERROR_CTX_MODEM_RESPONSE_NO_CARRIER 0x00001B65 +#define ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE 0x00001B66 +#define ERROR_CTX_MODEM_RESPONSE_BUSY 0x00001B67 +#define ERROR_CTX_MODEM_RESPONSE_VOICE 0x00001B68 +#define ERROR_CTX_TD_ERROR 0x00001B69 +#define ERROR_CTX_WINSTATION_NOT_FOUND 0x00001B6E +#define ERROR_CTX_WINSTATION_ALREADY_EXISTS 0x00001B6F +#define ERROR_CTX_WINSTATION_BUSY 0x00001B70 +#define ERROR_CTX_BAD_VIDEO_MODE 0x00001B71 +#define ERROR_CTX_GRAPHICS_INVALID 0x00001B7B +#define ERROR_CTX_LOGON_DISABLED 0x00001B7D +#define ERROR_CTX_NOT_CONSOLE 0x00001B7E +#define ERROR_CTX_CLIENT_QUERY_TIMEOUT 0x00001B80 +#define ERROR_CTX_CONSOLE_DISCONNECT 0x00001B81 +#define ERROR_CTX_CONSOLE_CONNECT 0x00001B82 +#define ERROR_CTX_SHADOW_DENIED 0x00001B84 +#define ERROR_CTX_WINSTATION_ACCESS_DENIED 0x00001B85 +#define ERROR_CTX_INVALID_WD 0x00001B89 +#define ERROR_CTX_SHADOW_INVALID 0x00001B8A +#define ERROR_CTX_SHADOW_DISABLED 0x00001B8B +#define ERROR_CTX_CLIENT_LICENSE_IN_USE 0x00001B8C +#define ERROR_CTX_CLIENT_LICENSE_NOT_SET 0x00001B8D +#define ERROR_CTX_LICENSE_NOT_AVAILABLE 0x00001B8E +#define ERROR_CTX_LICENSE_CLIENT_INVALID 0x00001B8F +#define ERROR_CTX_LICENSE_EXPIRED 0x00001B90 +#define ERROR_CTX_SHADOW_NOT_RUNNING 0x00001B91 +#define ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE 0x00001B92 +#define ERROR_ACTIVATION_COUNT_EXCEEDED 0x00001B93 +#define ERROR_CTX_WINSTATIONS_DISABLED 0x00001B94 +#define ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED 0x00001B95 +#define ERROR_CTX_SESSION_IN_USE 0x00001B96 +#define ERROR_CTX_NO_FORCE_LOGOFF 0x00001B97 +#define ERROR_CTX_ACCOUNT_RESTRICTION 0x00001B98 +#define ERROR_RDP_PROTOCOL_ERROR 0x00001B99 +#define ERROR_CTX_CDM_CONNECT 0x00001B9A +#define ERROR_CTX_CDM_DISCONNECT 0x00001B9B +#define ERROR_CTX_SECURITY_LAYER_ERROR 0x00001B9C +#define ERROR_TS_INCOMPATIBLE_SESSIONS 0x00001B9D +#define ERROR_TS_VIDEO_SUBSYSTEM_ERROR 0x00001B9E +#define FRS_ERR_INVALID_API_SEQUENCE 0x00001F41 +#define FRS_ERR_STARTING_SERVICE 0x00001F42 +#define FRS_ERR_STOPPING_SERVICE 0x00001F43 +#define FRS_ERR_INTERNAL_API 0x00001F44 +#define FRS_ERR_INTERNAL 0x00001F45 +#define FRS_ERR_SERVICE_COMM 0x00001F46 +#define FRS_ERR_INSUFFICIENT_PRIV 0x00001F47 +#define FRS_ERR_AUTHENTICATION 0x00001F48 +#define FRS_ERR_PARENT_INSUFFICIENT_PRIV 0x00001F49 +#define FRS_ERR_PARENT_AUTHENTICATION 0x00001F4A +#define FRS_ERR_CHILD_TO_PARENT_COMM 0x00001F4B +#define FRS_ERR_PARENT_TO_CHILD_COMM 0x00001F4C +#define FRS_ERR_SYSVOL_POPULATE 0x00001F4D +#define FRS_ERR_SYSVOL_POPULATE_TIMEOUT 0x00001F4E +#define FRS_ERR_SYSVOL_IS_BUSY 0x00001F4F +#define FRS_ERR_SYSVOL_DEMOTE 0x00001F50 +#define FRS_ERR_INVALID_SERVICE_PARAMETER 0x00001F51 + +/* System Error Codes (8200-8999) */ + +#define ERROR_DS_NOT_INSTALLED 0x00002008 +#define ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY 0x00002009 +#define ERROR_DS_NO_ATTRIBUTE_OR_VALUE 0x0000200A +#define ERROR_DS_INVALID_ATTRIBUTE_SYNTAX 0x0000200B +#define ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED 0x0000200C +#define ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS 0x0000200D +#define ERROR_DS_BUSY 0x0000200E +#define ERROR_DS_UNAVAILABLE 0x0000200F +#define ERROR_DS_NO_RIDS_ALLOCATED 0x00002010 +#define ERROR_DS_NO_MORE_RIDS 0x00002011 +#define ERROR_DS_INCORRECT_ROLE_OWNER 0x00002012 +#define ERROR_DS_RIDMGR_INIT_ERROR 0x00002013 +#define ERROR_DS_OBJ_CLASS_VIOLATION 0x00002014 +#define ERROR_DS_CANT_ON_NON_LEAF 0x00002015 +#define ERROR_DS_CANT_ON_RDN 0x00002016 +#define ERROR_DS_CANT_MOD_OBJ_CLASS 0x00002017 +#define ERROR_DS_CROSS_DOM_MOVE_ERROR 0x00002018 +#define ERROR_DS_GC_NOT_AVAILABLE 0x00002019 +#define ERROR_SHARED_POLICY 0x0000201A +#define ERROR_POLICY_OBJECT_NOT_FOUND 0x0000201B +#define ERROR_POLICY_ONLY_IN_DS 0x0000201C +#define ERROR_PROMOTION_ACTIVE 0x0000201D +#define ERROR_NO_PROMOTION_ACTIVE 0x0000201E +#define ERROR_DS_OPERATIONS_ERROR 0x00002020 +#define ERROR_DS_PROTOCOL_ERROR 0x00002021 +#define ERROR_DS_TIMELIMIT_EXCEEDED 0x00002022 +#define ERROR_DS_SIZELIMIT_EXCEEDED 0x00002023 +#define ERROR_DS_ADMIN_LIMIT_EXCEEDED 0x00002024 +#define ERROR_DS_COMPARE_FALSE 0x00002025 +#define ERROR_DS_COMPARE_TRUE 0x00002026 +#define ERROR_DS_AUTH_METHOD_NOT_SUPPORTED 0x00002027 +#define ERROR_DS_STRONG_AUTH_REQUIRED 0x00002028 +#define ERROR_DS_INAPPROPRIATE_AUTH 0x00002029 +#define ERROR_DS_AUTH_UNKNOWN 0x0000202A +#define ERROR_DS_REFERRAL 0x0000202B +#define ERROR_DS_UNAVAILABLE_CRIT_EXTENSION 0x0000202C +#define ERROR_DS_CONFIDENTIALITY_REQUIRED 0x0000202D +#define ERROR_DS_INAPPROPRIATE_MATCHING 0x0000202E +#define ERROR_DS_CONSTRAINT_VIOLATION 0x0000202F +#define ERROR_DS_NO_SUCH_OBJECT 0x00002030 +#define ERROR_DS_ALIAS_PROBLEM 0x00002031 +#define ERROR_DS_INVALID_DN_SYNTAX 0x00002032 +#define ERROR_DS_IS_LEAF 0x00002033 +#define ERROR_DS_ALIAS_DEREF_PROBLEM 0x00002034 +#define ERROR_DS_UNWILLING_TO_PERFORM 0x00002035 +#define ERROR_DS_LOOP_DETECT 0x00002036 +#define ERROR_DS_NAMING_VIOLATION 0x00002037 +#define ERROR_DS_OBJECT_RESULTS_TOO_LARGE 0x00002038 +#define ERROR_DS_AFFECTS_MULTIPLE_DSAS 0x00002039 +#define ERROR_DS_SERVER_DOWN 0x0000203A +#define ERROR_DS_LOCAL_ERROR 0x0000203B +#define ERROR_DS_ENCODING_ERROR 0x0000203C +#define ERROR_DS_DECODING_ERROR 0x0000203D +#define ERROR_DS_FILTER_UNKNOWN 0x0000203E +#define ERROR_DS_PARAM_ERROR 0x0000203F +#define ERROR_DS_NOT_SUPPORTED 0x00002040 +#define ERROR_DS_NO_RESULTS_RETURNED 0x00002041 +#define ERROR_DS_CONTROL_NOT_FOUND 0x00002042 +#define ERROR_DS_CLIENT_LOOP 0x00002043 +#define ERROR_DS_REFERRAL_LIMIT_EXCEEDED 0x00002044 +#define ERROR_DS_SORT_CONTROL_MISSING 0x00002045 +#define ERROR_DS_OFFSET_RANGE_ERROR 0x00002046 +#define ERROR_DS_RIDMGR_DISABLED 0x00002047 +#define ERROR_DS_ROOT_MUST_BE_NC 0x0000206D +#define ERROR_DS_ADD_REPLICA_INHIBITED 0x0000206E +#define ERROR_DS_ATT_NOT_DEF_IN_SCHEMA 0x0000206F +#define ERROR_DS_MAX_OBJ_SIZE_EXCEEDED 0x00002070 +#define ERROR_DS_OBJ_STRING_NAME_EXISTS 0x00002071 +#define ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA 0x00002072 +#define ERROR_DS_RDN_DOESNT_MATCH_SCHEMA 0x00002073 +#define ERROR_DS_NO_REQUESTED_ATTS_FOUND 0x00002074 +#define ERROR_DS_USER_BUFFER_TO_SMALL 0x00002075 +#define ERROR_DS_ATT_IS_NOT_ON_OBJ 0x00002076 +#define ERROR_DS_ILLEGAL_MOD_OPERATION 0x00002077 +#define ERROR_DS_OBJ_TOO_LARGE 0x00002078 +#define ERROR_DS_BAD_INSTANCE_TYPE 0x00002079 +#define ERROR_DS_MASTERDSA_REQUIRED 0x0000207A +#define ERROR_DS_OBJECT_CLASS_REQUIRED 0x0000207B +#define ERROR_DS_MISSING_REQUIRED_ATT 0x0000207C +#define ERROR_DS_ATT_NOT_DEF_FOR_CLASS 0x0000207D +#define ERROR_DS_ATT_ALREADY_EXISTS 0x0000207E +#define ERROR_DS_CANT_ADD_ATT_VALUES 0x00002080 +#define ERROR_DS_SINGLE_VALUE_CONSTRAINT 0x00002081 +#define ERROR_DS_RANGE_CONSTRAINT 0x00002082 +#define ERROR_DS_ATT_VAL_ALREADY_EXISTS 0x00002083 +#define ERROR_DS_CANT_REM_MISSING_ATT 0x00002084 +#define ERROR_DS_CANT_REM_MISSING_ATT_VAL 0x00002085 +#define ERROR_DS_ROOT_CANT_BE_SUBREF 0x00002086 +#define ERROR_DS_NO_CHAINING 0x00002087 +#define ERROR_DS_NO_CHAINED_EVAL 0x00002088 +#define ERROR_DS_NO_PARENT_OBJECT 0x00002089 +#define ERROR_DS_PARENT_IS_AN_ALIAS 0x0000208A +#define ERROR_DS_CANT_MIX_MASTER_AND_REPS 0x0000208B +#define ERROR_DS_CHILDREN_EXIST 0x0000208C +#define ERROR_DS_OBJ_NOT_FOUND 0x0000208D +#define ERROR_DS_ALIASED_OBJ_MISSING 0x0000208E +#define ERROR_DS_BAD_NAME_SYNTAX 0x0000208F +#define ERROR_DS_ALIAS_POINTS_TO_ALIAS 0x00002090 +#define ERROR_DS_CANT_DEREF_ALIAS 0x00002091 +#define ERROR_DS_OUT_OF_SCOPE 0x00002092 +#define ERROR_DS_OBJECT_BEING_REMOVED 0x00002093 +#define ERROR_DS_CANT_DELETE_DSA_OBJ 0x00002094 +#define ERROR_DS_GENERIC_ERROR 0x00002095 +#define ERROR_DS_DSA_MUST_BE_INT_MASTER 0x00002096 +#define ERROR_DS_CLASS_NOT_DSA 0x00002097 +#define ERROR_DS_INSUFF_ACCESS_RIGHTS 0x00002098 +#define ERROR_DS_ILLEGAL_SUPERIOR 0x00002099 +#define ERROR_DS_ATTRIBUTE_OWNED_BY_SAM 0x0000209A +#define ERROR_DS_NAME_TOO_MANY_PARTS 0x0000209B +#define ERROR_DS_NAME_TOO_LONG 0x0000209C +#define ERROR_DS_NAME_VALUE_TOO_LONG 0x0000209D +#define ERROR_DS_NAME_UNPARSEABLE 0x0000209E +#define ERROR_DS_NAME_TYPE_UNKNOWN 0x0000209F +#define ERROR_DS_NOT_AN_OBJECT 0x000020A0 +#define ERROR_DS_SEC_DESC_TOO_SHORT 0x000020A1 +#define ERROR_DS_SEC_DESC_INVALID 0x000020A2 +#define ERROR_DS_NO_DELETED_NAME 0x000020A3 +#define ERROR_DS_SUBREF_MUST_HAVE_PARENT 0x000020A4 +#define ERROR_DS_NCNAME_MUST_BE_NC 0x000020A5 +#define ERROR_DS_CANT_ADD_SYSTEM_ONLY 0x000020A6 +#define ERROR_DS_CLASS_MUST_BE_CONCRETE 0x000020A7 +#define ERROR_DS_INVALID_DMD 0x000020A8 +#define ERROR_DS_OBJ_GUID_EXISTS 0x000020A9 +#define ERROR_DS_NOT_ON_BACKLINK 0x000020AA +#define ERROR_DS_NO_CROSSREF_FOR_NC 0x000020AB +#define ERROR_DS_SHUTTING_DOWN 0x000020AC +#define ERROR_DS_UNKNOWN_OPERATION 0x000020AD +#define ERROR_DS_INVALID_ROLE_OWNER 0x000020AE +#define ERROR_DS_COULDNT_CONTACT_FSMO 0x000020AF +#define ERROR_DS_CROSS_NC_DN_RENAME 0x000020B0 +#define ERROR_DS_CANT_MOD_SYSTEM_ONLY 0x000020B1 +#define ERROR_DS_REPLICATOR_ONLY 0x000020B2 +#define ERROR_DS_OBJ_CLASS_NOT_DEFINED 0x000020B3 +#define ERROR_DS_OBJ_CLASS_NOT_SUBCLASS 0x000020B4 +#define ERROR_DS_NAME_REFERENCE_INVALID 0x000020B5 +#define ERROR_DS_CROSS_REF_EXISTS 0x000020B6 +#define ERROR_DS_CANT_DEL_MASTER_CROSSREF 0x000020B7 +#define ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD 0x000020B8 +#define ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX 0x000020B9 +#define ERROR_DS_DUP_RDN 0x000020BA +#define ERROR_DS_DUP_OID 0x000020BB +#define ERROR_DS_DUP_MAPI_ID 0x000020BC +#define ERROR_DS_DUP_SCHEMA_ID_GUID 0x000020BD +#define ERROR_DS_DUP_LDAP_DISPLAY_NAME 0x000020BE +#define ERROR_DS_SEMANTIC_ATT_TEST 0x000020BF +#define ERROR_DS_SYNTAX_MISMATCH 0x000020C0 +#define ERROR_DS_EXISTS_IN_MUST_HAVE 0x000020C1 +#define ERROR_DS_EXISTS_IN_MAY_HAVE 0x000020C2 +#define ERROR_DS_NONEXISTENT_MAY_HAVE 0x000020C3 +#define ERROR_DS_NONEXISTENT_MUST_HAVE 0x000020C4 +#define ERROR_DS_AUX_CLS_TEST_FAIL 0x000020C5 +#define ERROR_DS_NONEXISTENT_POSS_SUP 0x000020C6 +#define ERROR_DS_SUB_CLS_TEST_FAIL 0x000020C7 +#define ERROR_DS_BAD_RDN_ATT_ID_SYNTAX 0x000020C8 +#define ERROR_DS_EXISTS_IN_AUX_CLS 0x000020C9 +#define ERROR_DS_EXISTS_IN_SUB_CLS 0x000020CA +#define ERROR_DS_EXISTS_IN_POSS_SUP 0x000020CB +#define ERROR_DS_RECALCSCHEMA_FAILED 0x000020CC +#define ERROR_DS_TREE_DELETE_NOT_FINISHED 0x000020CD +#define ERROR_DS_CANT_DELETE 0x000020CE +#define ERROR_DS_ATT_SCHEMA_REQ_ID 0x000020CF +#define ERROR_DS_BAD_ATT_SCHEMA_SYNTAX 0x000020D0 +#define ERROR_DS_CANT_CACHE_ATT 0x000020D1 +#define ERROR_DS_CANT_CACHE_CLASS 0x000020D2 +#define ERROR_DS_CANT_REMOVE_ATT_CACHE 0x000020D3 +#define ERROR_DS_CANT_REMOVE_CLASS_CACHE 0x000020D4 +#define ERROR_DS_CANT_RETRIEVE_DN 0x000020D5 +#define ERROR_DS_MISSING_SUPREF 0x000020D6 +#define ERROR_DS_CANT_RETRIEVE_INSTANCE 0x000020D7 +#define ERROR_DS_CODE_INCONSISTENCY 0x000020D8 +#define ERROR_DS_DATABASE_ERROR 0x000020D9 +#define ERROR_DS_GOVERNSID_MISSING 0x000020DA +#define ERROR_DS_MISSING_EXPECTED_ATT 0x000020DB +#define ERROR_DS_NCNAME_MISSING_CR_REF 0x000020DC +#define ERROR_DS_SECURITY_CHECKING_ERROR 0x000020DD +#define ERROR_DS_SCHEMA_NOT_LOADED 0x000020DE +#define ERROR_DS_SCHEMA_ALLOC_FAILED 0x000020DF +#define ERROR_DS_ATT_SCHEMA_REQ_SYNTAX 0x000020E0 +#define ERROR_DS_GCVERIFY_ERROR 0x000020E1 +#define ERROR_DS_DRA_SCHEMA_MISMATCH 0x000020E2 +#define ERROR_DS_CANT_FIND_DSA_OBJ 0x000020E3 +#define ERROR_DS_CANT_FIND_EXPECTED_NC 0x000020E4 +#define ERROR_DS_CANT_FIND_NC_IN_CACHE 0x000020E5 +#define ERROR_DS_CANT_RETRIEVE_CHILD 0x000020E6 +#define ERROR_DS_SECURITY_ILLEGAL_MODIFY 0x000020E7 +#define ERROR_DS_CANT_REPLACE_HIDDEN_REC 0x000020E8 +#define ERROR_DS_BAD_HIERARCHY_FILE 0x000020E9 +#define ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED 0x000020EA +#define ERROR_DS_CONFIG_PARAM_MISSING 0x000020EB +#define ERROR_DS_COUNTING_AB_INDICES_FAILED 0x000020EC +#define ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED 0x000020ED +#define ERROR_DS_INTERNAL_FAILURE 0x000020EE +#define ERROR_DS_UNKNOWN_ERROR 0x000020EF +#define ERROR_DS_ROOT_REQUIRES_CLASS_TOP 0x000020F0 +#define ERROR_DS_REFUSING_FSMO_ROLES 0x000020F1 +#define ERROR_DS_MISSING_FSMO_SETTINGS 0x000020F2 +#define ERROR_DS_UNABLE_TO_SURRENDER_ROLES 0x000020F3 +#define ERROR_DS_DRA_GENERIC 0x000020F4 +#define ERROR_DS_DRA_INVALID_PARAMETER 0x000020F5 +#define ERROR_DS_DRA_BUSY 0x000020F6 +#define ERROR_DS_DRA_BAD_DN 0x000020F7 +#define ERROR_DS_DRA_BAD_NC 0x000020F8 +#define ERROR_DS_DRA_DN_EXISTS 0x000020F9 +#define ERROR_DS_DRA_INTERNAL_ERROR 0x000020FA +#define ERROR_DS_DRA_INCONSISTENT_DIT 0x000020FB +#define ERROR_DS_DRA_CONNECTION_FAILED 0x000020FC +#define ERROR_DS_DRA_BAD_INSTANCE_TYPE 0x000020FD +#define ERROR_DS_DRA_OUT_OF_MEM 0x000020FE +#define ERROR_DS_DRA_MAIL_PROBLEM 0x000020FF +#define ERROR_DS_DRA_REF_ALREADY_EXISTS 0x00002100 +#define ERROR_DS_DRA_REF_NOT_FOUND 0x00002101 +#define ERROR_DS_DRA_OBJ_IS_REP_SOURCE 0x00002102 +#define ERROR_DS_DRA_DB_ERROR 0x00002103 +#define ERROR_DS_DRA_NO_REPLICA 0x00002104 +#define ERROR_DS_DRA_ACCESS_DENIED 0x00002105 +#define ERROR_DS_DRA_NOT_SUPPORTED 0x00002106 +#define ERROR_DS_DRA_RPC_CANCELLED 0x00002107 +#define ERROR_DS_DRA_SOURCE_DISABLED 0x00002108 +#define ERROR_DS_DRA_SINK_DISABLED 0x00002109 +#define ERROR_DS_DRA_NAME_COLLISION 0x0000210A +#define ERROR_DS_DRA_SOURCE_REINSTALLED 0x0000210B +#define ERROR_DS_DRA_MISSING_PARENT 0x0000210C +#define ERROR_DS_DRA_PREEMPTED 0x0000210D +#define ERROR_DS_DRA_ABANDON_SYNC 0x0000210E +#define ERROR_DS_DRA_SHUTDOWN 0x0000210F +#define ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET 0x00002110 +#define ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA 0x00002111 +#define ERROR_DS_DRA_EXTN_CONNECTION_FAILED 0x00002112 +#define ERROR_DS_INSTALL_SCHEMA_MISMATCH 0x00002113 +#define ERROR_DS_DUP_LINK_ID 0x00002114 +#define ERROR_DS_NAME_ERROR_RESOLVING 0x00002115 +#define ERROR_DS_NAME_ERROR_NOT_FOUND 0x00002116 +#define ERROR_DS_NAME_ERROR_NOT_UNIQUE 0x00002117 +#define ERROR_DS_NAME_ERROR_NO_MAPPING 0x00002118 +#define ERROR_DS_NAME_ERROR_DOMAIN_ONLY 0x00002119 +#define ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING 0x0000211A +#define ERROR_DS_CONSTRUCTED_ATT_MOD 0x0000211B +#define ERROR_DS_WRONG_OM_OBJ_CLASS 0x0000211C +#define ERROR_DS_DRA_REPL_PENDING 0x0000211D +#define ERROR_DS_DS_REQUIRED 0x0000211E +#define ERROR_DS_INVALID_LDAP_DISPLAY_NAME 0x0000211F +#define ERROR_DS_NON_BASE_SEARCH 0x00002120 +#define ERROR_DS_CANT_RETRIEVE_ATTS 0x00002121 +#define ERROR_DS_BACKLINK_WITHOUT_LINK 0x00002122 +#define ERROR_DS_EPOCH_MISMATCH 0x00002123 +#define ERROR_DS_SRC_NAME_MISMATCH 0x00002124 +#define ERROR_DS_SRC_AND_DST_NC_IDENTICAL 0x00002125 +#define ERROR_DS_DST_NC_MISMATCH 0x00002126 +#define ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC 0x00002127 +#define ERROR_DS_SRC_GUID_MISMATCH 0x00002128 +#define ERROR_DS_CANT_MOVE_DELETED_OBJECT 0x00002129 +#define ERROR_DS_PDC_OPERATION_IN_PROGRESS 0x0000212A +#define ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD 0x0000212B +#define ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION 0x0000212C +#define ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS 0x0000212D +#define ERROR_DS_NC_MUST_HAVE_NC_PARENT 0x0000212E +#define ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE 0x0000212F +#define ERROR_DS_DST_DOMAIN_NOT_NATIVE 0x00002130 +#define ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER 0x00002131 +#define ERROR_DS_CANT_MOVE_ACCOUNT_GROUP 0x00002132 +#define ERROR_DS_CANT_MOVE_RESOURCE_GROUP 0x00002133 +#define ERROR_DS_INVALID_SEARCH_FLAG 0x00002134 +#define ERROR_DS_NO_TREE_DELETE_ABOVE_NC 0x00002135 +#define ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE 0x00002136 +#define ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE 0x00002137 +#define ERROR_DS_SAM_INIT_FAILURE 0x00002138 +#define ERROR_DS_SENSITIVE_GROUP_VIOLATION 0x00002139 +#define ERROR_DS_CANT_MOD_PRIMARYGROUPID 0x0000213A +#define ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD 0x0000213B +#define ERROR_DS_NONSAFE_SCHEMA_CHANGE 0x0000213C +#define ERROR_DS_SCHEMA_UPDATE_DISALLOWED 0x0000213D +#define ERROR_DS_CANT_CREATE_UNDER_SCHEMA 0x0000213E +#define ERROR_DS_INSTALL_NO_SRC_SCH_VERSION 0x0000213F +#define ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE 0x00002140 +#define ERROR_DS_INVALID_GROUP_TYPE 0x00002141 +#define ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN 0x00002142 +#define ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN 0x00002143 +#define ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER 0x00002144 +#define ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER 0x00002145 +#define ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER 0x00002146 +#define ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER 0x00002147 +#define ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER 0x00002148 +#define ERROR_DS_HAVE_PRIMARY_MEMBERS 0x00002149 +#define ERROR_DS_STRING_SD_CONVERSION_FAILED 0x0000214A +#define ERROR_DS_NAMING_MASTER_GC 0x0000214B +#define ERROR_DS_DNS_LOOKUP_FAILURE 0x0000214C +#define ERROR_DS_COULDNT_UPDATE_SPNS 0x0000214D +#define ERROR_DS_CANT_RETRIEVE_SD 0x0000214E +#define ERROR_DS_KEY_NOT_UNIQUE 0x0000214F +#define ERROR_DS_WRONG_LINKED_ATT_SYNTAX 0x00002150 +#define ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD 0x00002151 +#define ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY 0x00002152 +#define ERROR_DS_CANT_START 0x00002153 +#define ERROR_DS_INIT_FAILURE 0x00002154 +#define ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION 0x00002155 +#define ERROR_DS_SOURCE_DOMAIN_IN_FOREST 0x00002156 +#define ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST 0x00002157 +#define ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED 0x00002158 +#define ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN 0x00002159 +#define ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER 0x0000215A +#define ERROR_DS_SRC_SID_EXISTS_IN_FOREST 0x0000215B +#define ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH 0x0000215C +#define ERROR_SAM_INIT_FAILURE 0x0000215D +#define ERROR_DS_DRA_SCHEMA_INFO_SHIP 0x0000215E +#define ERROR_DS_DRA_SCHEMA_CONFLICT 0x0000215F +#define ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT 0x00002160 +#define ERROR_DS_DRA_OBJ_NC_MISMATCH 0x00002161 +#define ERROR_DS_NC_STILL_HAS_DSAS 0x00002162 +#define ERROR_DS_GC_REQUIRED 0x00002163 +#define ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY 0x00002164 +#define ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS 0x00002165 +#define ERROR_DS_CANT_ADD_TO_GC 0x00002166 +#define ERROR_DS_NO_CHECKPOINT_WITH_PDC 0x00002167 +#define ERROR_DS_SOURCE_AUDITING_NOT_ENABLED 0x00002168 +#define ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC 0x00002169 +#define ERROR_DS_INVALID_NAME_FOR_SPN 0x0000216A +#define ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS 0x0000216B +#define ERROR_DS_UNICODEPWD_NOT_IN_QUOTES 0x0000216C +#define ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED 0x0000216D +#define ERROR_DS_MUST_BE_RUN_ON_DST_DC 0x0000216E +#define ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER 0x0000216F +#define ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ 0x00002170 +#define ERROR_DS_INIT_FAILURE_CONSOLE 0x00002171 +#define ERROR_DS_SAM_INIT_FAILURE_CONSOLE 0x00002172 +#define ERROR_DS_FOREST_VERSION_TOO_HIGH 0x00002173 +#define ERROR_DS_DOMAIN_VERSION_TOO_HIGH 0x00002174 +#define ERROR_DS_FOREST_VERSION_TOO_LOW 0x00002175 +#define ERROR_DS_DOMAIN_VERSION_TOO_LOW 0x00002176 +#define ERROR_DS_INCOMPATIBLE_VERSION 0x00002177 +#define ERROR_DS_LOW_DSA_VERSION 0x00002178 +#define ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN 0x00002179 +#define ERROR_DS_NOT_SUPPORTED_SORT_ORDER 0x0000217A +#define ERROR_DS_NAME_NOT_UNIQUE 0x0000217B +#define ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4 0x0000217C +#define ERROR_DS_OUT_OF_VERSION_STORE 0x0000217D +#define ERROR_DS_INCOMPATIBLE_CONTROLS_USED 0x0000217E +#define ERROR_DS_NO_REF_DOMAIN 0x0000217F +#define ERROR_DS_RESERVED_LINK_ID 0x00002180 +#define ERROR_DS_LINK_ID_NOT_AVAILABLE 0x00002181 +#define ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER 0x00002182 +#define ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE 0x00002183 +#define ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC 0x00002184 +#define ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG 0x00002185 +#define ERROR_DS_MODIFYDN_WRONG_GRANDPARENT 0x00002186 +#define ERROR_DS_NAME_ERROR_TRUST_REFERRAL 0x00002187 +#define ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER 0x00002188 +#define ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD 0x00002189 +#define ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2 0x0000218A +#define ERROR_DS_THREAD_LIMIT_EXCEEDED 0x0000218B +#define ERROR_DS_NOT_CLOSEST 0x0000218C +#define ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF 0x0000218D +#define ERROR_DS_SINGLE_USER_MODE_FAILED 0x0000218E +#define ERROR_DS_NTDSCRIPT_SYNTAX_ERROR 0x0000218F +#define ERROR_DS_NTDSCRIPT_PROCESS_ERROR 0x00002190 +#define ERROR_DS_DIFFERENT_REPL_EPOCHS 0x00002191 +#define ERROR_DS_DRS_EXTENSIONS_CHANGED 0x00002192 +#define ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR 0x00002193 +#define ERROR_DS_NO_MSDS_INTID 0x00002194 +#define ERROR_DS_DUP_MSDS_INTID 0x00002195 +#define ERROR_DS_EXISTS_IN_RDNATTID 0x00002196 +#define ERROR_DS_AUTHORIZATION_FAILED 0x00002197 +#define ERROR_DS_INVALID_SCRIPT 0x00002198 +#define ERROR_DS_REMOTE_CROSSREF_OP_FAILED 0x00002199 +#define ERROR_DS_CROSS_REF_BUSY 0x0000219A +#define ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN 0x0000219B +#define ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC 0x0000219C +#define ERROR_DS_DUPLICATE_ID_FOUND 0x0000219D +#define ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT 0x0000219E +#define ERROR_DS_GROUP_CONVERSION_ERROR 0x0000219F +#define ERROR_DS_CANT_MOVE_APP_BASIC_GROUP 0x000021A0 +#define ERROR_DS_CANT_MOVE_APP_QUERY_GROUP 0x000021A1 +#define ERROR_DS_ROLE_NOT_VERIFIED 0x000021A2 +#define ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL 0x000021A3 +#define ERROR_DS_DOMAIN_RENAME_IN_PROGRESS 0x000021A4 +#define ERROR_DS_EXISTING_AD_CHILD_NC 0x000021A5 +#define ERROR_DS_REPL_LIFETIME_EXCEEDED 0x000021A6 +#define ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER 0x000021A7 +#define ERROR_DS_LDAP_SEND_QUEUE_FULL 0x000021A8 +#define ERROR_DS_DRA_OUT_SCHEDULE_WINDOW 0x000021A9 +#define ERROR_DS_POLICY_NOT_KNOWN 0x000021AA +#define ERROR_NO_SITE_SETTINGS_OBJECT 0x000021AB +#define ERROR_NO_SECRETS 0x000021AC +#define ERROR_NO_WRITABLE_DC_FOUND 0x000021AD +#define ERROR_DS_NO_SERVER_OBJECT 0x000021AE +#define ERROR_DS_NO_NTDSA_OBJECT 0x000021AF +#define ERROR_DS_NON_ASQ_SEARCH 0x000021B0 +#define ERROR_DS_AUDIT_FAILURE 0x000021B1 +#define ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE 0x000021B2 +#define ERROR_DS_INVALID_SEARCH_FLAG_TUPLE 0x000021B3 +#define ERROR_DS_HIERARCHY_TABLE_TOO_DEEP 0x000021B4 +#define ERROR_DS_DRA_CORRUPT_UTD_VECTOR 0x000021B5 +#define ERROR_DS_DRA_SECRETS_DENIED 0x000021B6 +#define ERROR_DS_RESERVED_MAPI_ID 0x000021B7 +#define ERROR_DS_MAPI_ID_NOT_AVAILABLE 0x000021B8 +#define ERROR_DS_DRA_MISSING_KRBTGT_SECRET 0x000021B9 +#define ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST 0x000021BA +#define ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST 0x000021BB +#define ERROR_INVALID_USER_PRINCIPAL_NAME 0x000021BC +#define ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS 0x000021BD +#define ERROR_DS_OID_NOT_FOUND 0x000021BE +#define ERROR_DS_DRA_RECYCLED_TARGET 0x000021BF +#define ERROR_DS_DISALLOWED_NC_REDIRECT 0x000021C0 +#define ERROR_DS_HIGH_ADLDS_FFL 0x000021C1 +#define ERROR_DS_HIGH_DSA_VERSION 0x000021C2 +#define ERROR_DS_LOW_ADLDS_FFL 0x000021C3 +#define ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION 0x000021C4 +#define ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED 0x000021C5 +#define ERROR_INCORRECT_ACCOUNT_TYPE 0x000021C6 + +/* System Error Codes (9000-11999) */ + +#define DNS_ERROR_RCODE_FORMAT_ERROR 0x00002329 +#define DNS_ERROR_RCODE_SERVER_FAILURE 0x0000232A +#define DNS_ERROR_RCODE_NAME_ERROR 0x0000232B +#define DNS_ERROR_RCODE_NOT_IMPLEMENTED 0x0000232C +#define DNS_ERROR_RCODE_REFUSED 0x0000232D +#define DNS_ERROR_RCODE_YXDOMAIN 0x0000232E +#define DNS_ERROR_RCODE_YXRRSET 0x0000232F +#define DNS_ERROR_RCODE_NXRRSET 0x00002330 +#define DNS_ERROR_RCODE_NOTAUTH 0x00002331 +#define DNS_ERROR_RCODE_NOTZONE 0x00002332 +#define DNS_ERROR_RCODE_BADSIG 0x00002338 +#define DNS_ERROR_RCODE_BADKEY 0x00002339 +#define DNS_ERROR_RCODE_BADTIME 0x0000233A +#define DNS_ERROR_KEYMASTER_REQUIRED 0x0000238D +#define DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE 0x0000238E +#define DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1 0x0000238F +#define DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS 0x00002390 +#define DNS_ERROR_UNSUPPORTED_ALGORITHM 0x00002391 +#define DNS_ERROR_INVALID_KEY_SIZE 0x00002392 +#define DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE 0x00002393 +#define DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION 0x00002394 +#define DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR 0x00002395 +#define DNS_ERROR_UNEXPECTED_CNG_ERROR 0x00002396 +#define DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION 0x00002397 +#define DNS_ERROR_KSP_NOT_ACCESSIBLE 0x00002398 +#define DNS_ERROR_TOO_MANY_SKDS 0x00002399 +#define DNS_ERROR_INVALID_ROLLOVER_PERIOD 0x0000239A +#define DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET 0x0000239B +#define DNS_ERROR_ROLLOVER_IN_PROGRESS 0x0000239C +#define DNS_ERROR_STANDBY_KEY_NOT_PRESENT 0x0000239D +#define DNS_ERROR_NOT_ALLOWED_ON_ZSK 0x0000239E +#define DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD 0x0000239F +#define DNS_ERROR_ROLLOVER_ALREADY_QUEUED 0x000023A0 +#define DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE 0x000023A1 +#define DNS_ERROR_BAD_KEYMASTER 0x000023A2 +#define DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD 0x000023A3 +#define DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT 0x000023A4 +#define DNS_ERROR_DNSSEC_IS_DISABLED 0x000023A5 +#define DNS_ERROR_INVALID_XML 0x000023A6 +#define DNS_ERROR_NO_VALID_TRUST_ANCHORS 0x000023A7 +#define DNS_ERROR_ROLLOVER_NOT_POKEABLE 0x000023A8 +#define DNS_ERROR_NSEC3_NAME_COLLISION 0x000023A9 +#define DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1 0x000023AA +#define DNS_INFO_NO_RECORDS 0x0000251D +#define DNS_ERROR_BAD_PACKET 0x0000251E +#define DNS_ERROR_NO_PACKET 0x0000251F +#define DNS_ERROR_RCODE 0x00002520 +#define DNS_ERROR_UNSECURE_PACKET 0x00002521 +#define DNS_REQUEST_PENDING 0x00002522 +#define DNS_ERROR_INVALID_TYPE 0x0000254F +#define DNS_ERROR_INVALID_IP_ADDRESS 0x00002550 +#define DNS_ERROR_INVALID_PROPERTY 0x00002551 +#define DNS_ERROR_TRY_AGAIN_LATER 0x00002552 +#define DNS_ERROR_NOT_UNIQUE 0x00002553 +#define DNS_ERROR_NON_RFC_NAME 0x00002554 +#define DNS_STATUS_FQDN 0x00002555 +#define DNS_STATUS_DOTTED_NAME 0x00002556 +#define DNS_STATUS_SINGLE_PART_NAME 0x00002557 +#define DNS_ERROR_INVALID_NAME_CHAR 0x00002558 +#define DNS_ERROR_NUMERIC_NAME 0x00002559 +#define DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER 0x0000255A +#define DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION 0x0000255B +#define DNS_ERROR_CANNOT_FIND_ROOT_HINTS 0x0000255C +#define DNS_ERROR_INCONSISTENT_ROOT_HINTS 0x0000255D +#define DNS_ERROR_DWORD_VALUE_TOO_SMALL 0x0000255E +#define DNS_ERROR_DWORD_VALUE_TOO_LARGE 0x0000255F +#define DNS_ERROR_BACKGROUND_LOADING 0x00002560 +#define DNS_ERROR_NOT_ALLOWED_ON_RODC 0x00002561 +#define DNS_ERROR_NOT_ALLOWED_UNDER_DNAME 0x00002562 +#define DNS_ERROR_DELEGATION_REQUIRED 0x00002563 +#define DNS_ERROR_INVALID_POLICY_TABLE 0x00002564 +#define DNS_ERROR_ZONE_DOES_NOT_EXIST 0x00002581 +#define DNS_ERROR_NO_ZONE_INFO 0x00002582 +#define DNS_ERROR_INVALID_ZONE_OPERATION 0x00002583 +#define DNS_ERROR_ZONE_CONFIGURATION_ERROR 0x00002584 +#define DNS_ERROR_ZONE_HAS_NO_SOA_RECORD 0x00002585 +#define DNS_ERROR_ZONE_HAS_NO_NS_RECORDS 0x00002586 +#define DNS_ERROR_ZONE_LOCKED 0x00002587 +#define DNS_ERROR_ZONE_CREATION_FAILED 0x00002588 +#define DNS_ERROR_ZONE_ALREADY_EXISTS 0x00002589 +#define DNS_ERROR_AUTOZONE_ALREADY_EXISTS 0x0000258A +#define DNS_ERROR_INVALID_ZONE_TYPE 0x0000258B +#define DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP 0x0000258C +#define DNS_ERROR_ZONE_NOT_SECONDARY 0x0000258D +#define DNS_ERROR_NEED_SECONDARY_ADDRESSES 0x0000258E +#define DNS_ERROR_WINS_INIT_FAILED 0x0000258F +#define DNS_ERROR_NEED_WINS_SERVERS 0x00002590 +#define DNS_ERROR_NBSTAT_INIT_FAILED 0x00002591 +#define DNS_ERROR_SOA_DELETE_INVALID 0x00002592 +#define DNS_ERROR_FORWARDER_ALREADY_EXISTS 0x00002593 +#define DNS_ERROR_ZONE_REQUIRES_MASTER_IP 0x00002594 +#define DNS_ERROR_ZONE_IS_SHUTDOWN 0x00002595 +#define DNS_ERROR_ZONE_LOCKED_FOR_SIGNING 0x00002596 +#define DNS_ERROR_PRIMARY_REQUIRES_DATAFILE 0x000025B3 +#define DNS_ERROR_INVALID_DATAFILE_NAME 0x000025B4 +#define DNS_ERROR_DATAFILE_OPEN_FAILURE 0x000025B5 +#define DNS_ERROR_FILE_WRITEBACK_FAILED 0x000025B6 +#define DNS_ERROR_DATAFILE_PARSING 0x000025B7 +#define DNS_ERROR_RECORD_DOES_NOT_EXIST 0x000025E5 +#define DNS_ERROR_RECORD_FORMAT 0x000025E6 +#define DNS_ERROR_NODE_CREATION_FAILED 0x000025E7 +#define DNS_ERROR_UNKNOWN_RECORD_TYPE 0x000025E8 +#define DNS_ERROR_RECORD_TIMED_OUT 0x000025E9 +#define DNS_ERROR_NAME_NOT_IN_ZONE 0x000025EA +#define DNS_ERROR_CNAME_LOOP 0x000025EB +#define DNS_ERROR_NODE_IS_CNAME 0x000025EC +#define DNS_ERROR_CNAME_COLLISION 0x000025ED +#define DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT 0x000025EE +#define DNS_ERROR_RECORD_ALREADY_EXISTS 0x000025EF +#define DNS_ERROR_SECONDARY_DATA 0x000025F0 +#define DNS_ERROR_NO_CREATE_CACHE_DATA 0x000025F1 +#define DNS_ERROR_NAME_DOES_NOT_EXIST 0x000025F2 +#define DNS_WARNING_PTR_CREATE_FAILED 0x000025F3 +#define DNS_WARNING_DOMAIN_UNDELETED 0x000025F4 +#define DNS_ERROR_DS_UNAVAILABLE 0x000025F5 +#define DNS_ERROR_DS_ZONE_ALREADY_EXISTS 0x000025F6 +#define DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE 0x000025F7 +#define DNS_ERROR_NODE_IS_DNAME 0x000025F8 +#define DNS_ERROR_DNAME_COLLISION 0x000025F9 +#define DNS_ERROR_ALIAS_LOOP 0x000025FA +#define DNS_INFO_AXFR_COMPLETE 0x00002617 +#define DNS_ERROR_AXFR 0x00002618 +#define DNS_INFO_ADDED_LOCAL_WINS 0x00002619 +#define DNS_STATUS_CONTINUE_NEEDED 0x00002649 +#define DNS_ERROR_NO_TCPIP 0x0000267B +#define DNS_ERROR_NO_DNS_SERVERS 0x0000267C +#define DNS_ERROR_DP_DOES_NOT_EXIST 0x000026AD +#define DNS_ERROR_DP_ALREADY_EXISTS 0x000026AE +#define DNS_ERROR_DP_NOT_ENLISTED 0x000026AF +#define DNS_ERROR_DP_ALREADY_ENLISTED 0x000026B0 +#define DNS_ERROR_DP_NOT_AVAILABLE 0x000026B1 +#define DNS_ERROR_DP_FSMO_ERROR 0x000026B2 +#define WSAEINTR 0x00002714 +#define WSAEBADF 0x00002719 +#define WSAEACCES 0x0000271D +#define WSAEFAULT 0x0000271E +#define WSAEINVAL 0x00002726 +#define WSAEMFILE 0x00002728 +#define WSAEWOULDBLOCK 0x00002733 +#define WSAEINPROGRESS 0x00002734 +#define WSAEALREADY 0x00002735 +#define WSAENOTSOCK 0x00002736 +#define WSAEDESTADDRREQ 0x00002737 +#define WSAEMSGSIZE 0x00002738 +#define WSAEPROTOTYPE 0x00002739 +#define WSAENOPROTOOPT 0x0000273A +#define WSAEPROTONOSUPPORT 0x0000273B +#define WSAESOCKTNOSUPPORT 0x0000273C +#define WSAEOPNOTSUPP 0x0000273D +#define WSAEPFNOSUPPORT 0x0000273E +#define WSAEAFNOSUPPORT 0x0000273F +#define WSAEADDRINUSE 0x00002740 +#define WSAEADDRNOTAVAIL 0x00002741 +#define WSAENETDOWN 0x00002742 +#define WSAENETUNREACH 0x00002743 +#define WSAENETRESET 0x00002744 +#define WSAECONNABORTED 0x00002745 +#define WSAECONNRESET 0x00002746 +#define WSAENOBUFS 0x00002747 +#define WSAEISCONN 0x00002748 +#define WSAENOTCONN 0x00002749 +#define WSAESHUTDOWN 0x0000274A +#define WSAETOOMANYREFS 0x0000274B +#define WSAETIMEDOUT 0x0000274C +#define WSAECONNREFUSED 0x0000274D +#define WSAELOOP 0x0000274E +#define WSAENAMETOOLONG 0x0000274F +#define WSAEHOSTDOWN 0x00002750 +#define WSAEHOSTUNREACH 0x00002751 +#define WSAENOTEMPTY 0x00002752 +#define WSAEPROCLIM 0x00002753 +#define WSAEUSERS 0x00002754 +#define WSAEDQUOT 0x00002755 +#define WSAESTALE 0x00002756 +#define WSAEREMOTE 0x00002757 +#define WSASYSNOTREADY 0x0000276B +#define WSAVERNOTSUPPORTED 0x0000276C +#define WSANOTINITIALISED 0x0000276D +#define WSAEDISCON 0x00002775 +#define WSAENOMORE 0x00002776 +#define WSAECANCELLED 0x00002777 +#define WSAEINVALIDPROCTABLE 0x00002778 +#define WSAEINVALIDPROVIDER 0x00002779 +#define WSAEPROVIDERFAILEDINIT 0x0000277A +#define WSASYSCALLFAILURE 0x0000277B +#define WSASERVICE_NOT_FOUND 0x0000277C +#define WSATYPE_NOT_FOUND 0x0000277D +#define WSA_E_NO_MORE 0x0000277E +#define WSA_E_CANCELLED 0x0000277F +#define WSAEREFUSED 0x00002780 +#define WSAHOST_NOT_FOUND 0x00002AF9 +#define WSATRY_AGAIN 0x00002AFA +#define WSANO_RECOVERY 0x00002AFB +#define WSANO_DATA 0x00002AFC +#define WSA_QOS_RECEIVERS 0x00002AFD +#define WSA_QOS_SENDERS 0x00002AFE +#define WSA_QOS_NO_SENDERS 0x00002AFF +#define WSA_QOS_NO_RECEIVERS 0x00002B00 +#define WSA_QOS_REQUEST_CONFIRMED 0x00002B01 +#define WSA_QOS_ADMISSION_FAILURE 0x00002B02 +#define WSA_QOS_POLICY_FAILURE 0x00002B03 +#define WSA_QOS_BAD_STYLE 0x00002B04 +#define WSA_QOS_BAD_OBJECT 0x00002B05 +#define WSA_QOS_TRAFFIC_CTRL_ERROR 0x00002B06 +#define WSA_QOS_GENERIC_ERROR 0x00002B07 +#define WSA_QOS_ESERVICETYPE 0x00002B08 +#define WSA_QOS_EFLOWSPEC 0x00002B09 +#define WSA_QOS_EPROVSPECBUF 0x00002B0A +#define WSA_QOS_EFILTERSTYLE 0x00002B0B +#define WSA_QOS_EFILTERTYPE 0x00002B0C +#define WSA_QOS_EFILTERCOUNT 0x00002B0D +#define WSA_QOS_EOBJLENGTH 0x00002B0E +#define WSA_QOS_EFLOWCOUNT 0x00002B0F +#define WSA_QOS_EUNKOWNPSOBJ 0x00002B10 +#define WSA_QOS_EPOLICYOBJ 0x00002B11 +#define WSA_QOS_EFLOWDESC 0x00002B12 +#define WSA_QOS_EPSFLOWSPEC 0x00002B13 +#define WSA_QOS_EPSFILTERSPEC 0x00002B14 +#define WSA_QOS_ESDMODEOBJ 0x00002B15 +#define WSA_QOS_ESHAPERATEOBJ 0x00002B16 +#define WSA_QOS_RESERVED_PETYPE 0x00002B17 +#define WSA_SECURE_HOST_NOT_FOUND 0x00002B18 +#define WSA_IPSEC_NAME_POLICY_ERROR 0x00002B19 + +/* System Error Codes (12000-15999) */ + +/* ERROR_INTERNET_* : (12000 - 12175) defined in WinInet.h */ + +#define ERROR_IPSEC_QM_POLICY_EXISTS 0x000032C8 +#define ERROR_IPSEC_QM_POLICY_NOT_FOUND 0x000032C9 +#define ERROR_IPSEC_QM_POLICY_IN_USE 0x000032CA +#define ERROR_IPSEC_MM_POLICY_EXISTS 0x000032CB +#define ERROR_IPSEC_MM_POLICY_NOT_FOUND 0x000032CC +#define ERROR_IPSEC_MM_POLICY_IN_USE 0x000032CD +#define ERROR_IPSEC_MM_FILTER_EXISTS 0x000032CE +#define ERROR_IPSEC_MM_FILTER_NOT_FOUND 0x000032CF +#define ERROR_IPSEC_TRANSPORT_FILTER_EXISTS 0x000032D0 +#define ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND 0x000032D1 +#define ERROR_IPSEC_MM_AUTH_EXISTS 0x000032D2 +#define ERROR_IPSEC_MM_AUTH_NOT_FOUND 0x000032D3 +#define ERROR_IPSEC_MM_AUTH_IN_USE 0x000032D4 +#define ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND 0x000032D5 +#define ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND 0x000032D6 +#define ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND 0x000032D7 +#define ERROR_IPSEC_TUNNEL_FILTER_EXISTS 0x000032D8 +#define ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND 0x000032D9 +#define ERROR_IPSEC_MM_FILTER_PENDING_DELETION 0x000032DA +#define ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION 0x000032DB +#define ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION 0x000032DC +#define ERROR_IPSEC_MM_POLICY_PENDING_DELETION 0x000032DD +#define ERROR_IPSEC_MM_AUTH_PENDING_DELETION 0x000032DE +#define ERROR_IPSEC_QM_POLICY_PENDING_DELETION 0x000032DF +#define WARNING_IPSEC_MM_POLICY_PRUNED 0x000032E0 +#define WARNING_IPSEC_QM_POLICY_PRUNED 0x000032E1 +#define ERROR_IPSEC_IKE_NEG_STATUS_BEGIN 0x000035E8 +#define ERROR_IPSEC_IKE_AUTH_FAIL 0x000035E9 +#define ERROR_IPSEC_IKE_ATTRIB_FAIL 0x000035EA +#define ERROR_IPSEC_IKE_NEGOTIATION_PENDING 0x000035EB +#define ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR 0x000035EC +#define ERROR_IPSEC_IKE_TIMED_OUT 0x000035ED +#define ERROR_IPSEC_IKE_NO_CERT 0x000035EE +#define ERROR_IPSEC_IKE_SA_DELETED 0x000035EF +#define ERROR_IPSEC_IKE_SA_REAPED 0x000035F0 +#define ERROR_IPSEC_IKE_MM_ACQUIRE_DROP 0x000035F1 +#define ERROR_IPSEC_IKE_QM_ACQUIRE_DROP 0x000035F2 +#define ERROR_IPSEC_IKE_QUEUE_DROP_MM 0x000035F3 +#define ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM 0x000035F4 +#define ERROR_IPSEC_IKE_DROP_NO_RESPONSE 0x000035F5 +#define ERROR_IPSEC_IKE_MM_DELAY_DROP 0x000035F6 +#define ERROR_IPSEC_IKE_QM_DELAY_DROP 0x000035F7 +#define ERROR_IPSEC_IKE_ERROR 0x000035F8 +#define ERROR_IPSEC_IKE_CRL_FAILED 0x000035F9 +#define ERROR_IPSEC_IKE_INVALID_KEY_USAGE 0x000035FA +#define ERROR_IPSEC_IKE_INVALID_CERT_TYPE 0x000035FB +#define ERROR_IPSEC_IKE_NO_PRIVATE_KEY 0x000035FC +#define ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY 0x000035FD +#define ERROR_IPSEC_IKE_DH_FAIL 0x000035FE +#define ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED 0x000035FF +#define ERROR_IPSEC_IKE_INVALID_HEADER 0x00003600 +#define ERROR_IPSEC_IKE_NO_POLICY 0x00003601 +#define ERROR_IPSEC_IKE_INVALID_SIGNATURE 0x00003602 +#define ERROR_IPSEC_IKE_KERBEROS_ERROR 0x00003603 +#define ERROR_IPSEC_IKE_NO_PUBLIC_KEY 0x00003604 +#define ERROR_IPSEC_IKE_PROCESS_ERR 0x00003605 +#define ERROR_IPSEC_IKE_PROCESS_ERR_SA 0x00003606 +#define ERROR_IPSEC_IKE_PROCESS_ERR_PROP 0x00003607 +#define ERROR_IPSEC_IKE_PROCESS_ERR_TRANS 0x00003608 +#define ERROR_IPSEC_IKE_PROCESS_ERR_KE 0x00003609 +#define ERROR_IPSEC_IKE_PROCESS_ERR_ID 0x0000360A +#define ERROR_IPSEC_IKE_PROCESS_ERR_CERT 0x0000360B +#define ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ 0x0000360C +#define ERROR_IPSEC_IKE_PROCESS_ERR_HASH 0x0000360D +#define ERROR_IPSEC_IKE_PROCESS_ERR_SIG 0x0000360E +#define ERROR_IPSEC_IKE_PROCESS_ERR_NONCE 0x0000360F +#define ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY 0x00003610 +#define ERROR_IPSEC_IKE_PROCESS_ERR_DELETE 0x00003611 +#define ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR 0x00003612 +#define ERROR_IPSEC_IKE_INVALID_PAYLOAD 0x00003613 +#define ERROR_IPSEC_IKE_LOAD_SOFT_SA 0x00003614 +#define ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN 0x00003615 +#define ERROR_IPSEC_IKE_INVALID_COOKIE 0x00003616 +#define ERROR_IPSEC_IKE_NO_PEER_CERT 0x00003617 +#define ERROR_IPSEC_IKE_PEER_CRL_FAILED 0x00003618 +#define ERROR_IPSEC_IKE_POLICY_CHANGE 0x00003619 +#define ERROR_IPSEC_IKE_NO_MM_POLICY 0x0000361A +#define ERROR_IPSEC_IKE_NOTCBPRIV 0x0000361B +#define ERROR_IPSEC_IKE_SECLOADFAIL 0x0000361C +#define ERROR_IPSEC_IKE_FAILSSPINIT 0x0000361D +#define ERROR_IPSEC_IKE_FAILQUERYSSP 0x0000361E +#define ERROR_IPSEC_IKE_SRVACQFAIL 0x0000361F +#define ERROR_IPSEC_IKE_SRVQUERYCRED 0x00003620 +#define ERROR_IPSEC_IKE_GETSPIFAIL 0x00003621 +#define ERROR_IPSEC_IKE_INVALID_FILTER 0x00003622 +#define ERROR_IPSEC_IKE_OUT_OF_MEMORY 0x00003623 +#define ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED 0x00003624 +#define ERROR_IPSEC_IKE_INVALID_POLICY 0x00003625 +#define ERROR_IPSEC_IKE_UNKNOWN_DOI 0x00003626 +#define ERROR_IPSEC_IKE_INVALID_SITUATION 0x00003627 +#define ERROR_IPSEC_IKE_DH_FAILURE 0x00003628 +#define ERROR_IPSEC_IKE_INVALID_GROUP 0x00003629 +#define ERROR_IPSEC_IKE_ENCRYPT 0x0000362A +#define ERROR_IPSEC_IKE_DECRYPT 0x0000362B +#define ERROR_IPSEC_IKE_POLICY_MATCH 0x0000362C +#define ERROR_IPSEC_IKE_UNSUPPORTED_ID 0x0000362D +#define ERROR_IPSEC_IKE_INVALID_HASH 0x0000362E +#define ERROR_IPSEC_IKE_INVALID_HASH_ALG 0x0000362F +#define ERROR_IPSEC_IKE_INVALID_HASH_SIZE 0x00003630 +#define ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG 0x00003631 +#define ERROR_IPSEC_IKE_INVALID_AUTH_ALG 0x00003632 +#define ERROR_IPSEC_IKE_INVALID_SIG 0x00003633 +#define ERROR_IPSEC_IKE_LOAD_FAILED 0x00003634 +#define ERROR_IPSEC_IKE_RPC_DELETE 0x00003635 +#define ERROR_IPSEC_IKE_BENIGN_REINIT 0x00003636 +#define ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY 0x00003637 +#define ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION 0x00003638 +#define ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN 0x00003639 +#define ERROR_IPSEC_IKE_MM_LIMIT 0x0000363A +#define ERROR_IPSEC_IKE_NEGOTIATION_DISABLED 0x0000363B +#define ERROR_IPSEC_IKE_QM_LIMIT 0x0000363C +#define ERROR_IPSEC_IKE_MM_EXPIRED 0x0000363D +#define ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID 0x0000363E +#define ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH 0x0000363F +#define ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID 0x00003640 +#define ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD 0x00003641 +#define ERROR_IPSEC_IKE_DOS_COOKIE_SENT 0x00003642 +#define ERROR_IPSEC_IKE_SHUTTING_DOWN 0x00003643 +#define ERROR_IPSEC_IKE_CGA_AUTH_FAILED 0x00003644 +#define ERROR_IPSEC_IKE_PROCESS_ERR_NATOA 0x00003645 +#define ERROR_IPSEC_IKE_INVALID_MM_FOR_QM 0x00003646 +#define ERROR_IPSEC_IKE_QM_EXPIRED 0x00003647 +#define ERROR_IPSEC_IKE_TOO_MANY_FILTERS 0x00003648 +#define ERROR_IPSEC_IKE_NEG_STATUS_END 0x00003649 +#define ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL 0x0000364A +#define ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE 0x0000364B +#define ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING 0x0000364C +#define ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING 0x0000364D +#define ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS 0x0000364E +#define ERROR_IPSEC_IKE_RATELIMIT_DROP 0x0000364F +#define ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE 0x00003650 +#define ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE 0x00003651 +#define ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE 0x00003652 +#define ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY 0x00003653 +#define ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE 0x00003654 +#define ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END 0x00003655 +#define ERROR_IPSEC_BAD_SPI 0x00003656 +#define ERROR_IPSEC_SA_LIFETIME_EXPIRED 0x00003657 +#define ERROR_IPSEC_WRONG_SA 0x00003658 +#define ERROR_IPSEC_REPLAY_CHECK_FAILED 0x00003659 +#define ERROR_IPSEC_INVALID_PACKET 0x0000365A +#define ERROR_IPSEC_INTEGRITY_CHECK_FAILED 0x0000365B +#define ERROR_IPSEC_CLEAR_TEXT_DROP 0x0000365C +#define ERROR_IPSEC_AUTH_FIREWALL_DROP 0x0000365D +#define ERROR_IPSEC_THROTTLE_DROP 0x0000365E +#define ERROR_IPSEC_DOSP_BLOCK 0x00003665 +#define ERROR_IPSEC_DOSP_RECEIVED_MULTICAST 0x00003666 +#define ERROR_IPSEC_DOSP_INVALID_PACKET 0x00003667 +#define ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED 0x00003668 +#define ERROR_IPSEC_DOSP_MAX_ENTRIES 0x00003669 +#define ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED 0x0000366A +#define ERROR_IPSEC_DOSP_NOT_INSTALLED 0x0000366B +#define ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES 0x0000366C +#define ERROR_SXS_SECTION_NOT_FOUND 0x000036B0 +#define ERROR_SXS_CANT_GEN_ACTCTX 0x000036B1 +#define ERROR_SXS_INVALID_ACTCTXDATA_FORMAT 0x000036B2 +#define ERROR_SXS_ASSEMBLY_NOT_FOUND 0x000036B3 +#define ERROR_SXS_MANIFEST_FORMAT_ERROR 0x000036B4 +#define ERROR_SXS_MANIFEST_PARSE_ERROR 0x000036B5 +#define ERROR_SXS_ACTIVATION_CONTEXT_DISABLED 0x000036B6 +#define ERROR_SXS_KEY_NOT_FOUND 0x000036B7 +#define ERROR_SXS_VERSION_CONFLICT 0x000036B8 +#define ERROR_SXS_WRONG_SECTION_TYPE 0x000036B9 +#define ERROR_SXS_THREAD_QUERIES_DISABLED 0x000036BA +#define ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET 0x000036BB +#define ERROR_SXS_UNKNOWN_ENCODING_GROUP 0x000036BC +#define ERROR_SXS_UNKNOWN_ENCODING 0x000036BD +#define ERROR_SXS_INVALID_XML_NAMESPACE_URI 0x000036BE +#define ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED 0x000036BF +#define ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED 0x000036C0 +#define ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE 0x000036C1 +#define ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE 0x000036C2 +#define ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE 0x000036C3 +#define ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT 0x000036C4 +#define ERROR_SXS_DUPLICATE_DLL_NAME 0x000036C5 +#define ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME 0x000036C6 +#define ERROR_SXS_DUPLICATE_CLSID 0x000036C7 +#define ERROR_SXS_DUPLICATE_IID 0x000036C8 +#define ERROR_SXS_DUPLICATE_TLBID 0x000036C9 +#define ERROR_SXS_DUPLICATE_PROGID 0x000036CA +#define ERROR_SXS_DUPLICATE_ASSEMBLY_NAME 0x000036CB +#define ERROR_SXS_FILE_HASH_MISMATCH 0x000036CC +#define ERROR_SXS_POLICY_PARSE_ERROR 0x000036CD +#define ERROR_SXS_XML_E_MISSINGQUOTE 0x000036CE +#define ERROR_SXS_XML_E_COMMENTSYNTAX 0x000036CF +#define ERROR_SXS_XML_E_BADSTARTNAMECHAR 0x000036D0 +#define ERROR_SXS_XML_E_BADNAMECHAR 0x000036D1 +#define ERROR_SXS_XML_E_BADCHARINSTRING 0x000036D2 +#define ERROR_SXS_XML_E_XMLDECLSYNTAX 0x000036D3 +#define ERROR_SXS_XML_E_BADCHARDATA 0x000036D4 +#define ERROR_SXS_XML_E_MISSINGWHITESPACE 0x000036D5 +#define ERROR_SXS_XML_E_EXPECTINGTAGEND 0x000036D6 +#define ERROR_SXS_XML_E_MISSINGSEMICOLON 0x000036D7 +#define ERROR_SXS_XML_E_UNBALANCEDPAREN 0x000036D8 +#define ERROR_SXS_XML_E_INTERNALERROR 0x000036D9 +#define ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE 0x000036DA +#define ERROR_SXS_XML_E_INCOMPLETE_ENCODING 0x000036DB +#define ERROR_SXS_XML_E_MISSING_PAREN 0x000036DC +#define ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE 0x000036DD +#define ERROR_SXS_XML_E_MULTIPLE_COLONS 0x000036DE +#define ERROR_SXS_XML_E_INVALID_DECIMAL 0x000036DF +#define ERROR_SXS_XML_E_INVALID_HEXIDECIMAL 0x000036E0 +#define ERROR_SXS_XML_E_INVALID_UNICODE 0x000036E1 +#define ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK 0x000036E2 +#define ERROR_SXS_XML_E_UNEXPECTEDENDTAG 0x000036E3 +#define ERROR_SXS_XML_E_UNCLOSEDTAG 0x000036E4 +#define ERROR_SXS_XML_E_DUPLICATEATTRIBUTE 0x000036E5 +#define ERROR_SXS_XML_E_MULTIPLEROOTS 0x000036E6 +#define ERROR_SXS_XML_E_INVALIDATROOTLEVEL 0x000036E7 +#define ERROR_SXS_XML_E_BADXMLDECL 0x000036E8 +#define ERROR_SXS_XML_E_MISSINGROOT 0x000036E9 +#define ERROR_SXS_XML_E_UNEXPECTEDEOF 0x000036EA +#define ERROR_SXS_XML_E_BADPEREFINSUBSET 0x000036EB +#define ERROR_SXS_XML_E_UNCLOSEDSTARTTAG 0x000036EC +#define ERROR_SXS_XML_E_UNCLOSEDENDTAG 0x000036ED +#define ERROR_SXS_XML_E_UNCLOSEDSTRING 0x000036EE +#define ERROR_SXS_XML_E_UNCLOSEDCOMMENT 0x000036EF +#define ERROR_SXS_XML_E_UNCLOSEDDECL 0x000036F0 +#define ERROR_SXS_XML_E_UNCLOSEDCDATA 0x000036F1 +#define ERROR_SXS_XML_E_RESERVEDNAMESPACE 0x000036F2 +#define ERROR_SXS_XML_E_INVALIDENCODING 0x000036F3 +#define ERROR_SXS_XML_E_INVALIDSWITCH 0x000036F4 +#define ERROR_SXS_XML_E_BADXMLCASE 0x000036F5 +#define ERROR_SXS_XML_E_INVALID_STANDALONE 0x000036F6 +#define ERROR_SXS_XML_E_UNEXPECTED_STANDALONE 0x000036F7 +#define ERROR_SXS_XML_E_INVALID_VERSION 0x000036F8 +#define ERROR_SXS_XML_E_MISSINGEQUALS 0x000036F9 +#define ERROR_SXS_PROTECTION_RECOVERY_FAILED 0x000036FA +#define ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT 0x000036FB +#define ERROR_SXS_PROTECTION_CATALOG_NOT_VALID 0x000036FC +#define ERROR_SXS_UNTRANSLATABLE_HRESULT 0x000036FD +#define ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING 0x000036FE +#define ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE 0x000036FF +#define ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME 0x00003700 +#define ERROR_SXS_ASSEMBLY_MISSING 0x00003701 +#define ERROR_SXS_CORRUPT_ACTIVATION_STACK 0x00003702 +#define ERROR_SXS_CORRUPTION 0x00003703 +#define ERROR_SXS_EARLY_DEACTIVATION 0x00003704 +#define ERROR_SXS_INVALID_DEACTIVATION 0x00003705 +#define ERROR_SXS_MULTIPLE_DEACTIVATION 0x00003706 +#define ERROR_SXS_PROCESS_TERMINATION_REQUESTED 0x00003707 +#define ERROR_SXS_RELEASE_ACTIVATION_CONTEXT 0x00003708 +#define ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY 0x00003709 +#define ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE 0x0000370A +#define ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME 0x0000370B +#define ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE 0x0000370C +#define ERROR_SXS_IDENTITY_PARSE_ERROR 0x0000370D +#define ERROR_MALFORMED_SUBSTITUTION_STRING 0x0000370E +#define ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN 0x0000370F +#define ERROR_UNMAPPED_SUBSTITUTION_STRING 0x00003710 +#define ERROR_SXS_ASSEMBLY_NOT_LOCKED 0x00003711 +#define ERROR_SXS_COMPONENT_STORE_CORRUPT 0x00003712 +#define ERROR_ADVANCED_INSTALLER_FAILED 0x00003713 +#define ERROR_XML_ENCODING_MISMATCH 0x00003714 +#define ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT 0x00003715 +#define ERROR_SXS_IDENTITIES_DIFFERENT 0x00003716 +#define ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT 0x00003717 +#define ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY 0x00003718 +#define ERROR_SXS_MANIFEST_TOO_BIG 0x00003719 +#define ERROR_SXS_SETTING_NOT_REGISTERED 0x0000371A +#define ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE 0x0000371B +#define ERROR_SMI_PRIMITIVE_INSTALLER_FAILED 0x0000371C +#define ERROR_GENERIC_COMMAND_FAILED 0x0000371D +#define ERROR_SXS_FILE_HASH_MISSING 0x0000371E +#define ERROR_EVT_INVALID_CHANNEL_PATH 0x00003A98 +#define ERROR_EVT_INVALID_QUERY 0x00003A99 +#define ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND 0x00003A9A +#define ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND 0x00003A9B +#define ERROR_EVT_INVALID_PUBLISHER_NAME 0x00003A9C +#define ERROR_EVT_INVALID_EVENT_DATA 0x00003A9D +#define ERROR_EVT_CHANNEL_NOT_FOUND 0x00003A9F +#define ERROR_EVT_MALFORMED_XML_TEXT 0x00003AA0 +#define ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL 0x00003AA1 +#define ERROR_EVT_CONFIGURATION_ERROR 0x00003AA2 +#define ERROR_EVT_QUERY_RESULT_STALE 0x00003AA3 +#define ERROR_EVT_QUERY_RESULT_INVALID_POSITION 0x00003AA4 +#define ERROR_EVT_NON_VALIDATING_MSXML 0x00003AA5 +#define ERROR_EVT_FILTER_ALREADYSCOPED 0x00003AA6 +#define ERROR_EVT_FILTER_NOTELTSET 0x00003AA7 +#define ERROR_EVT_FILTER_INVARG 0x00003AA8 +#define ERROR_EVT_FILTER_INVTEST 0x00003AA9 +#define ERROR_EVT_FILTER_INVTYPE 0x00003AAA +#define ERROR_EVT_FILTER_PARSEERR 0x00003AAB +#define ERROR_EVT_FILTER_UNSUPPORTEDOP 0x00003AAC +#define ERROR_EVT_FILTER_UNEXPECTEDTOKEN 0x00003AAD +#define ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL 0x00003AAE +#define ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE 0x00003AAF +#define ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE 0x00003AB0 +#define ERROR_EVT_CHANNEL_CANNOT_ACTIVATE 0x00003AB1 +#define ERROR_EVT_FILTER_TOO_COMPLEX 0x00003AB2 +#define ERROR_EVT_MESSAGE_NOT_FOUND 0x00003AB3 +#define ERROR_EVT_MESSAGE_ID_NOT_FOUND 0x00003AB4 +#define ERROR_EVT_UNRESOLVED_VALUE_INSERT 0x00003AB5 +#define ERROR_EVT_UNRESOLVED_PARAMETER_INSERT 0x00003AB6 +#define ERROR_EVT_MAX_INSERTS_REACHED 0x00003AB7 +#define ERROR_EVT_EVENT_DEFINITION_NOT_FOUND 0x00003AB8 +#define ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND 0x00003AB9 +#define ERROR_EVT_VERSION_TOO_OLD 0x00003ABA +#define ERROR_EVT_VERSION_TOO_NEW 0x00003ABB +#define ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY 0x00003ABC +#define ERROR_EVT_PUBLISHER_DISABLED 0x00003ABD +#define ERROR_EVT_FILTER_OUT_OF_RANGE 0x00003ABE +#define ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE 0x00003AE8 +#define ERROR_EC_LOG_DISABLED 0x00003AE9 +#define ERROR_EC_CIRCULAR_FORWARDING 0x00003AEA +#define ERROR_EC_CREDSTORE_FULL 0x00003AEB +#define ERROR_EC_CRED_NOT_FOUND 0x00003AEC +#define ERROR_EC_NO_ACTIVE_CHANNEL 0x00003AED +#define ERROR_MUI_FILE_NOT_FOUND 0x00003AFC +#define ERROR_MUI_INVALID_FILE 0x00003AFD +#define ERROR_MUI_INVALID_RC_CONFIG 0x00003AFE +#define ERROR_MUI_INVALID_LOCALE_NAME 0x00003AFF +#define ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME 0x00003B00 +#define ERROR_MUI_FILE_NOT_LOADED 0x00003B01 +#define ERROR_RESOURCE_ENUM_USER_STOP 0x00003B02 +#define ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED 0x00003B03 +#define ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME 0x00003B04 +#define ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE 0x00003B06 +#define ERROR_MRM_INVALID_PRICONFIG 0x00003B07 +#define ERROR_MRM_INVALID_FILE_TYPE 0x00003B08 +#define ERROR_MRM_UNKNOWN_QUALIFIER 0x00003B09 +#define ERROR_MRM_INVALID_QUALIFIER_VALUE 0x00003B0A +#define ERROR_MRM_NO_CANDIDATE 0x00003B0B +#define ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE 0x00003B0C +#define ERROR_MRM_RESOURCE_TYPE_MISMATCH 0x00003B0D +#define ERROR_MRM_DUPLICATE_MAP_NAME 0x00003B0E +#define ERROR_MRM_DUPLICATE_ENTRY 0x00003B0F +#define ERROR_MRM_INVALID_RESOURCE_IDENTIFIER 0x00003B10 +#define ERROR_MRM_FILEPATH_TOO_LONG 0x00003B11 +#define ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE 0x00003B12 +#define ERROR_MRM_INVALID_PRI_FILE 0x00003B16 +#define ERROR_MRM_NAMED_RESOURCE_NOT_FOUND 0x00003B17 +#define ERROR_MRM_MAP_NOT_FOUND 0x00003B1F +#define ERROR_MRM_UNSUPPORTED_PROFILE_TYPE 0x00003B20 +#define ERROR_MRM_INVALID_QUALIFIER_OPERATOR 0x00003B21 +#define ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE 0x00003B22 +#define ERROR_MRM_AUTOMERGE_ENABLED 0x00003B23 +#define ERROR_MRM_TOO_MANY_RESOURCES 0x00003B24 +#define ERROR_MCA_INVALID_CAPABILITIES_STRING 0x00003B60 +#define ERROR_MCA_INVALID_VCP_VERSION 0x00003B61 +#define ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION 0x00003B62 +#define ERROR_MCA_MCCS_VERSION_MISMATCH 0x00003B63 +#define ERROR_MCA_UNSUPPORTED_MCCS_VERSION 0x00003B64 +#define ERROR_MCA_INTERNAL_ERROR 0x00003B65 +#define ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED 0x00003B66 +#define ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE 0x00003B67 +#define ERROR_AMBIGUOUS_SYSTEM_DEVICE 0x00003B92 +#define ERROR_SYSTEM_DEVICE_NOT_FOUND 0x00003BC3 +#define ERROR_HASH_NOT_SUPPORTED 0x00003BC4 +#define ERROR_HASH_NOT_PRESENT 0x00003BC5 +#define ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED 0x00003BD9 +#define ERROR_GPIO_CLIENT_INFORMATION_INVALID 0x00003BDA +#define ERROR_GPIO_VERSION_NOT_SUPPORTED 0x00003BDB +#define ERROR_GPIO_INVALID_REGISTRATION_PACKET 0x00003BDC +#define ERROR_GPIO_OPERATION_DENIED 0x00003BDD +#define ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE 0x00003BDE +#define ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED 0x00003BDF +#define ERROR_CANNOT_SWITCH_RUNLEVEL 0x00003C28 +#define ERROR_INVALID_RUNLEVEL_SETTING 0x00003C29 +#define ERROR_RUNLEVEL_SWITCH_TIMEOUT 0x00003C2A +#define ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT 0x00003C2B +#define ERROR_RUNLEVEL_SWITCH_IN_PROGRESS 0x00003C2C +#define ERROR_SERVICES_FAILED_AUTOSTART 0x00003C2D +#define ERROR_COM_TASK_STOP_PENDING 0x00003C8D +#define ERROR_INSTALL_OPEN_PACKAGE_FAILED 0x00003CF0 +#define ERROR_INSTALL_PACKAGE_NOT_FOUND 0x00003CF1 +#define ERROR_INSTALL_INVALID_PACKAGE 0x00003CF2 +#define ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED 0x00003CF3 +#define ERROR_INSTALL_OUT_OF_DISK_SPACE 0x00003CF4 +#define ERROR_INSTALL_NETWORK_FAILURE 0x00003CF5 +#define ERROR_INSTALL_REGISTRATION_FAILURE 0x00003CF6 +#define ERROR_INSTALL_DEREGISTRATION_FAILURE 0x00003CF7 +#define ERROR_INSTALL_CANCEL 0x00003CF8 +#define ERROR_INSTALL_FAILED 0x00003CF9 +#define ERROR_REMOVE_FAILED 0x00003CFA +#define ERROR_PACKAGE_ALREADY_EXISTS 0x00003CFB +#define ERROR_NEEDS_REMEDIATION 0x00003CFC +#define ERROR_INSTALL_PREREQUISITE_FAILED 0x00003CFD +#define ERROR_PACKAGE_REPOSITORY_CORRUPTED 0x00003CFE +#define ERROR_INSTALL_POLICY_FAILURE 0x00003CFF +#define ERROR_PACKAGE_UPDATING 0x00003D00 +#define ERROR_DEPLOYMENT_BLOCKED_BY_POLICY 0x00003D01 +#define ERROR_PACKAGES_IN_USE 0x00003D02 +#define ERROR_RECOVERY_FILE_CORRUPT 0x00003D03 +#define ERROR_INVALID_STAGED_SIGNATURE 0x00003D04 +#define ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED 0x00003D05 +#define ERROR_INSTALL_PACKAGE_DOWNGRADE 0x00003D06 +#define ERROR_SYSTEM_NEEDS_REMEDIATION 0x00003D07 +#define ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN 0x00003D08 +#define ERROR_RESILIENCY_FILE_CORRUPT 0x00003D09 +#define ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING 0x00003D0A +#define APPMODEL_ERROR_NO_PACKAGE 0x00003D54 +#define APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT 0x00003D55 +#define APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT 0x00003D56 +#define APPMODEL_ERROR_NO_APPLICATION 0x00003D57 +#define ERROR_STATE_LOAD_STORE_FAILED 0x00003DB8 +#define ERROR_STATE_GET_VERSION_FAILED 0x00003DB9 +#define ERROR_STATE_SET_VERSION_FAILED 0x00003DBA +#define ERROR_STATE_STRUCTURED_RESET_FAILED 0x00003DBB +#define ERROR_STATE_OPEN_CONTAINER_FAILED 0x00003DBC +#define ERROR_STATE_CREATE_CONTAINER_FAILED 0x00003DBD +#define ERROR_STATE_DELETE_CONTAINER_FAILED 0x00003DBE +#define ERROR_STATE_READ_SETTING_FAILED 0x00003DBF +#define ERROR_STATE_WRITE_SETTING_FAILED 0x00003DC0 +#define ERROR_STATE_DELETE_SETTING_FAILED 0x00003DC1 +#define ERROR_STATE_QUERY_SETTING_FAILED 0x00003DC2 +#define ERROR_STATE_READ_COMPOSITE_SETTING_FAILED 0x00003DC3 +#define ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED 0x00003DC4 +#define ERROR_STATE_ENUMERATE_CONTAINER_FAILED 0x00003DC5 +#define ERROR_STATE_ENUMERATE_SETTINGS_FAILED 0x00003DC6 +#define ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED 0x00003DC7 +#define ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED 0x00003DC8 +#define ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED 0x00003DC9 +#define ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED 0x00003DCA +#define ERROR_API_UNAVAILABLE 0x00003DE1 + +#ifndef FACILITY_WEBSERVICES +#define FACILITY_WEBSERVICES 61 +#define WS_S_ASYNC 0x003D0000 +#define WS_S_END 0x003D0001 +#define WS_E_INVALID_FORMAT 0x803D0000 +#define WS_E_OBJECT_FAULTED 0x803D0001 +#define WS_E_NUMERIC_OVERFLOW 0x803D0002 +#define WS_E_INVALID_OPERATION 0x803D0003 +#define WS_E_OPERATION_ABORTED 0x803D0004 +#define WS_E_ENDPOINT_ACCESS_DENIED 0x803D0005 +#define WS_E_OPERATION_TIMED_OUT 0x803D0006 +#define WS_E_OPERATION_ABANDONED 0x803D0007 +#define WS_E_QUOTA_EXCEEDED 0x803D0008 +#define WS_E_NO_TRANSLATION_AVAILABLE 0x803D0009 +#define WS_E_SECURITY_VERIFICATION_FAILURE 0x803D000A +#define WS_E_ADDRESS_IN_USE 0x803D000B +#define WS_E_ADDRESS_NOT_AVAILABLE 0x803D000C +#define WS_E_ENDPOINT_NOT_FOUND 0x803D000D +#define WS_E_ENDPOINT_NOT_AVAILABLE 0x803D000E +#define WS_E_ENDPOINT_FAILURE 0x803D000F +#define WS_E_ENDPOINT_UNREACHABLE 0x803D0010 +#define WS_E_ENDPOINT_ACTION_NOT_SUPPORTED 0x803D0011 +#define WS_E_ENDPOINT_TOO_BUSY 0x803D0012 +#define WS_E_ENDPOINT_FAULT_RECEIVED 0x803D0013 +#define WS_E_ENDPOINT_DISCONNECTED 0x803D0014 +#define WS_E_PROXY_FAILURE 0x803D0015 +#define WS_E_PROXY_ACCESS_DENIED 0x803D0016 +#define WS_E_NOT_SUPPORTED 0x803D0017 +#define WS_E_PROXY_REQUIRES_BASIC_AUTH 0x803D0018 +#define WS_E_PROXY_REQUIRES_DIGEST_AUTH 0x803D0019 +#define WS_E_PROXY_REQUIRES_NTLM_AUTH 0x803D001A +#define WS_E_PROXY_REQUIRES_NEGOTIATE_AUTH 0x803D001B +#define WS_E_SERVER_REQUIRES_BASIC_AUTH 0x803D001C +#define WS_E_SERVER_REQUIRES_DIGEST_AUTH 0x803D001D +#define WS_E_SERVER_REQUIRES_NTLM_AUTH 0x803D001E +#define WS_E_SERVER_REQUIRES_NEGOTIATE_AUTH 0x803D001F +#define WS_E_INVALID_ENDPOINT_URL 0x803D0020 +#define WS_E_OTHER 0x803D0021 +#define WS_E_SECURITY_TOKEN_EXPIRED 0x803D0022 +#define WS_E_SECURITY_SYSTEM_FAILURE 0x803D0023 +#endif + +#define NTE_BAD_UID WINPR_CXX_COMPAT_CAST(LONG, 0x80090001) +#define NTE_BAD_HASH WINPR_CXX_COMPAT_CAST(LONG, 0x80090002) +#define NTE_BAD_KEY WINPR_CXX_COMPAT_CAST(LONG, 0x80090003) +#define NTE_BAD_LEN WINPR_CXX_COMPAT_CAST(LONG, 0x80090004) +#define NTE_BAD_DATA WINPR_CXX_COMPAT_CAST(LONG, 0x80090005) +#define NTE_BAD_SIGNATURE WINPR_CXX_COMPAT_CAST(LONG, 0x80090006) +#define NTE_BAD_VER WINPR_CXX_COMPAT_CAST(LONG, 0x80090007) +#define NTE_BAD_ALGID WINPR_CXX_COMPAT_CAST(LONG, 0x80090008) +#define NTE_BAD_FLAGS WINPR_CXX_COMPAT_CAST(LONG, 0x80090009) +#define NTE_BAD_TYPE WINPR_CXX_COMPAT_CAST(LONG, 0x8009000A) +#define NTE_BAD_KEY_STATE WINPR_CXX_COMPAT_CAST(LONG, 0x8009000B) +#define NTE_BAD_HASH_STATE WINPR_CXX_COMPAT_CAST(LONG, 0x8009000C) +#define NTE_NO_KEY WINPR_CXX_COMPAT_CAST(LONG, 0x8009000D) +#define NTE_NO_MEMORY WINPR_CXX_COMPAT_CAST(LONG, 0x8009000E) +#define NTE_EXISTS WINPR_CXX_COMPAT_CAST(LONG, 0x8009000F) +#define NTE_PERM WINPR_CXX_COMPAT_CAST(LONG, 0x80090010) +#define NTE_NOT_FOUND WINPR_CXX_COMPAT_CAST(LONG, 0x80090011) +#define NTE_DOUBLE_ENCRYPT WINPR_CXX_COMPAT_CAST(LONG, 0x80090012) +#define NTE_BAD_PROVIDER WINPR_CXX_COMPAT_CAST(LONG, 0x80090013) +#define NTE_BAD_PROV_TYPE WINPR_CXX_COMPAT_CAST(LONG, 0x80090014) +#define NTE_BAD_PUBLIC_KEY WINPR_CXX_COMPAT_CAST(LONG, 0x80090015) +#define NTE_BAD_KEYSET WINPR_CXX_COMPAT_CAST(LONG, 0x80090016) +#define NTE_PROV_TYPE_NOT_DEF WINPR_CXX_COMPAT_CAST(LONG, 0x80090017) +#define NTE_PROV_TYPE_ENTRY_BAD WINPR_CXX_COMPAT_CAST(LONG, 0x80090018) +#define NTE_KEYSET_NOT_DEF WINPR_CXX_COMPAT_CAST(LONG, 0x80090019) +#define NTE_KEYSET_ENTRY_BAD WINPR_CXX_COMPAT_CAST(LONG, 0x8009001A) +#define NTE_PROV_TYPE_NO_MATCH WINPR_CXX_COMPAT_CAST(LONG, 0x8009001B) +#define NTE_SIGNATURE_FILE_BAD WINPR_CXX_COMPAT_CAST(LONG, 0x8009001C) +#define NTE_PROVIDER_DLL_FAIL WINPR_CXX_COMPAT_CAST(LONG, 0x8009001D) +#define NTE_PROV_DLL_NOT_FOUND WINPR_CXX_COMPAT_CAST(LONG, 0x8009001E) +#define NTE_BAD_KEYSET_PARAM WINPR_CXX_COMPAT_CAST(LONG, 0x8009001F) +#define NTE_FAIL WINPR_CXX_COMPAT_CAST(LONG, 0x80090020) +#define NTE_SYS_ERR WINPR_CXX_COMPAT_CAST(LONG, 0x80090021) +#define NTE_SILENT_CONTEXT WINPR_CXX_COMPAT_CAST(LONG, 0x80090022) +#define NTE_TOKEN_KEYSET_STORAGE_FULL WINPR_CXX_COMPAT_CAST(LONG, 0x80090023) +#define NTE_TEMPORARY_PROFILE WINPR_CXX_COMPAT_CAST(LONG, 0x80090024) +#define NTE_FIXEDPARAMETER WINPR_CXX_COMPAT_CAST(LONG, 0x80090025) +#define NTE_NO_MORE_ITEMS ERROR_NO_MORE_ITEMS +#define NTE_NOT_SUPPORTED ERROR_NOT_SUPPORTED +#define NTE_INVALID_PARAMETER WINPR_CXX_COMPAT_CAST(LONG, 0x80090027) + +#define EXCEPTION_MAXIMUM_PARAMETERS 15 + +typedef struct s_EXCEPTION_RECORD EXCEPTION_RECORD; +typedef struct s_EXCEPTION_RECORD* PEXCEPTION_RECORD; + +struct s_EXCEPTION_RECORD +{ + DWORD ExceptionCode; + DWORD ExceptionFlags; + PEXCEPTION_RECORD ExceptionRecord; + PVOID ExceptionAddress; + DWORD NumberParameters; + ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS]; +}; + +typedef void* PCONTEXT; + +typedef struct s_EXCEPTION_POINTERS +{ + PEXCEPTION_RECORD ExceptionRecord; + PCONTEXT ContextRecord; +} EXCEPTION_POINTERS, *PEXCEPTION_POINTERS; + +typedef LONG (*PTOP_LEVEL_EXCEPTION_FILTER)(PEXCEPTION_POINTERS ExceptionInfo); +typedef PTOP_LEVEL_EXCEPTION_FILTER LPTOP_LEVEL_EXCEPTION_FILTER; + +typedef LONG (*PVECTORED_EXCEPTION_HANDLER)(PEXCEPTION_POINTERS ExceptionInfo); + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API UINT GetErrorMode(void); + + WINPR_API UINT SetErrorMode(UINT uMode); + + WINPR_API DWORD GetLastError(void); + + WINPR_API VOID SetLastError(DWORD dwErrCode); + + WINPR_API VOID RestoreLastError(DWORD dwErrCode); + + WINPR_API VOID RaiseException(DWORD dwExceptionCode, DWORD dwExceptionFlags, + DWORD nNumberOfArguments, CONST ULONG_PTR* lpArguments); + + WINPR_API LONG UnhandledExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo); + + WINPR_API LPTOP_LEVEL_EXCEPTION_FILTER + SetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter); + + WINPR_API PVOID AddVectoredExceptionHandler(ULONG First, PVECTORED_EXCEPTION_HANDLER Handler); + + WINPR_API ULONG RemoveVectoredExceptionHandler(PVOID Handle); + + WINPR_API PVOID AddVectoredContinueHandler(ULONG First, PVECTORED_EXCEPTION_HANDLER Handler); + + WINPR_API ULONG RemoveVectoredContinueHandler(PVOID Handle); + +#ifdef __cplusplus +} +#endif + +#endif + +#endif /* WINPR_ERROR_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/file.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/file.h new file mode 100644 index 0000000000000000000000000000000000000000..3c7466c814ef576eb7646526d344e06967142b88 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/file.h @@ -0,0 +1,560 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2016 David PHAM-VAN + * + * 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 +#include + +#include +#include +#include +#include + +#ifndef _WIN32 + +#include + +#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_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_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_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_API BOOL MoveFileExA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags); + + WINPR_API BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags); + + 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 */ + +WINPR_API BOOL ValidFileNameComponent(LPCWSTR lpFileName); + +#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 DWORD GetLogicalDriveStringsA(DWORD nBufferLength, LPSTR lpBuffer); + + WINPR_API DWORD GetLogicalDriveStringsW(DWORD nBufferLength, LPWSTR lpBuffer); + + 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_API char* GetNamedPipeNameWithoutPrefixA(LPCSTR lpName); + WINPR_API char* GetNamedPipeUnixDomainSocketBaseFilePathA(void); + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/handle.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/handle.h new file mode 100644 index 0000000000000000000000000000000000000000..ca2b4b7f9743917e922338470be4e9cb0c5b5603 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/handle.h @@ -0,0 +1,64 @@ +/** + * WinPR: Windows Portable Runtime + * Handle Management + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/image.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/image.h new file mode 100644 index 0000000000000000000000000000000000000000..71cd6d0f555f374218a9eea416b92833111abba5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/image.h @@ -0,0 +1,194 @@ +/** + * WinPR: Windows Portable Runtime + * Image Utils + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#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 NULL in case of failure, a pointer to an allocated buffer otherwise. Use \b free + * as deallocator + */ + WINPR_ATTR_MALLOC(free, 1) + 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_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 NULL + */ + 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 NULL + */ + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ini.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ini.h new file mode 100644 index 0000000000000000000000000000000000000000..6deefaeed05f40908bc184bca48d8afd5364a662 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ini.h @@ -0,0 +1,157 @@ +/** + * WinPR: Windows Portable Runtime + * .ini config file + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +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 NULL + * @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 NULL + * @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 NULL + * + * @return A newly allocated string, use \b free after use. \b NULL 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 NULL + * @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 NULL + * @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 NULL + * @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 NULL + * @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 NULL + */ + 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 NULL + * @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 NULL + * @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 NULL + * @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 NULL + */ + WINPR_API void IniFile_Free(wIniFile* ini); + + /** @brief Create a new ini instance + * + * @return The newly allocated instance or \b NULL if failed. + */ + WINPR_ATTR_MALLOC(IniFile_Free, 1) + WINPR_API wIniFile* IniFile_New(void); + + /** @brief Clone a ini instance + * + * @param ini The instance to free, may be \b NULL + * + * @return the cloned instance or \b NULL in case of \b ini was \b NULL or failure + */ + WINPR_API wIniFile* IniFile_Clone(const wIniFile* ini); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_UTILS_INI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/input.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/input.h new file mode 100644 index 0000000000000000000000000000000000000000..c7ec1f1c9de368f0dc6c49b4f78f9f1e4003d177 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/input.h @@ -0,0 +1,910 @@ +/** + * WinPR: Windows Portable Runtime + * Input Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +/** + * 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/interlocked.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/interlocked.h new file mode 100644 index 0000000000000000000000000000000000000000..a0f9521166741afae18066a9c12fd4e36fecac18 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/interlocked.h @@ -0,0 +1,216 @@ +/** + * WinPR: Windows Portable Runtime + * Interlocked Singly-Linked Lists + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include + +#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 +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/intrin.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/intrin.h new file mode 100644 index 0000000000000000000000000000000000000000..0e61d4dfdd3d2b7c3641818a827dec121009dbba --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/intrin.h @@ -0,0 +1,93 @@ +/** + * WinPR: Windows Portable Runtime + * C Run-Time Library Routines + * + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 Bernhard Miklautz + * + * + * 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/io.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/io.h new file mode 100644 index 0000000000000000000000000000000000000000..8976529c01afaaa61609b99adc424198b4bb9126 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/io.h @@ -0,0 +1,261 @@ +/** + * WinPR: Windows Portable Runtime + * Asynchronous I/O Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER + +#ifdef _WIN32 + +#include + +#else + +#include + +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_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; + +WINPR_API NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtensionSize, + PUNICODE_STRING DeviceName, DEVICE_TYPE DeviceType, + ULONG DeviceCharacteristics, BOOLEAN Exclusive, + PDEVICE_OBJECT_EX* DeviceObject); + +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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/json.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/json.h new file mode 100644 index 0000000000000000000000000000000000000000..b3116ea93f8f25b708f4e2d02a80fc3839efe6a6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/json.h @@ -0,0 +1,392 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * JSON parser wrapper + * + * Copyright 2024 Armin Novak + * 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 +#include +#include + +/** @defgroup WINPR_JSON WinPR JSON wrapper + * @since version 3.6.0 + * @brief Wrapper around cJSON or JSONC 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 NULL if failed + * @since version 3.6.0 + */ + WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1) + 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 NULL if failed + * @since version 3.6.0 + */ + WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1) + WINPR_API WINPR_JSON* WINPR_JSON_ParseWithLength(const char* value, size_t buffer_length); + + /** + * @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 NULL 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 + * @return A pointer to the object identified by @ref string or \b NULL + * @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 insensitive matching + * + * @param object the JSON instance to query + * @param string the name of the object + * @return A pointer to the object identified by @ref string or \b NULL + * @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 NULL + * @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 NULL 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_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 NULL + * @param item An item to add, must not be \b NULL + * @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 NULL + * @since version 3.6.0 + */ + 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 NULL + * @since version 3.6.0 + */ + WINPR_API char* WINPR_JSON_PrintUnformatted(WINPR_JSON* item); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/library.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/library.h new file mode 100644 index 0000000000000000000000000000000000000000..15bb849477ed935990f2ff7afb9361b5d2c90fdf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/library.h @@ -0,0 +1,129 @@ +/** + * WinPR: Windows Portable Runtime + * Library Loader + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#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 NULL + */ +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/memory.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/memory.h new file mode 100644 index 0000000000000000000000000000000000000000..431778aa9178829ef4fc32cccfcc20ff6d7293e8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/memory.h @@ -0,0 +1,82 @@ +/** + * WinPR: Windows Portable Runtime + * Memory Allocation + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include + +#include +#include + +#ifndef _WIN32 + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateFileMappingA(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes, + DWORD flProtect, DWORD dwMaximumSizeHigh, + DWORD dwMaximumSizeLow, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateFileMappingW(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes, + DWORD flProtect, DWORD dwMaximumSizeHigh, + DWORD dwMaximumSizeLow, LPCWSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE OpenFileMappingA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ncrypt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ncrypt.h new file mode 100644 index 0000000000000000000000000000000000000000..022fa9ea358df8151e994d0e019c0715d0dd9057 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ncrypt.h @@ -0,0 +1,233 @@ +/** + * WinPR: Windows Portable Runtime + * NCrypt library + * + * Copyright 2021 David Fort + * + * 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 +#include +#else + +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#ifndef __SECSTATUS_DEFINED__ +typedef LONG SECURITY_STATUS; +#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 NULL 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_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/nt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/nt.h new file mode 100644 index 0000000000000000000000000000000000000000..672d2ee85531ca241bb7a679f24c9449b868206e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/nt.h @@ -0,0 +1,1572 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Native System Services + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_NT_H +#define WINPR_NT_H + +#include +#include +#include +#include + +#define STATUS_CAST(t, val) WINPR_CXX_COMPAT_CAST(t, val) + +#ifndef _WIN32 + +/* Defined in winnt.h, do not redefine */ +#define STATUS_WAIT_0 STATUS_CAST(NTSTATUS, 0x00000000L) +#define STATUS_ABANDONED_WAIT_0 STATUS_CAST(NTSTATUS, 0x00000080L) +#define STATUS_USER_APC STATUS_CAST(NTSTATUS, 0x000000C0L) +#define STATUS_TIMEOUT STATUS_CAST(NTSTATUS, 0x00000102L) +#define STATUS_PENDING STATUS_CAST(NTSTATUS, 0x00000103L) +#define DBG_EXCEPTION_HANDLED STATUS_CAST(NTSTATUS, 0x00010001L) +#define DBG_CONTINUE STATUS_CAST(NTSTATUS, 0x00010002L) +#define STATUS_SEGMENT_NOTIFICATION STATUS_CAST(NTSTATUS, 0x40000005L) +#define STATUS_FATAL_APP_EXIT STATUS_CAST(NTSTATUS, 0x40000015L) +#define DBG_TERMINATE_THREAD STATUS_CAST(NTSTATUS, 0x40010003L) +#define DBG_TERMINATE_PROCESS STATUS_CAST(NTSTATUS, 0x40010004L) +#define DBG_CONTROL_C STATUS_CAST(NTSTATUS, 0x40010005L) +#define DBG_PRINTEXCEPTION_C STATUS_CAST(NTSTATUS, 0x40010006L) +#define DBG_RIPEXCEPTION STATUS_CAST(NTSTATUS, 0x40010007L) +#define DBG_CONTROL_BREAK STATUS_CAST(NTSTATUS, 0x40010008L) +#define DBG_COMMAND_EXCEPTION STATUS_CAST(NTSTATUS, 0x40010009L) +#define STATUS_GUARD_PAGE_VIOLATION STATUS_CAST(NTSTATUS, 0x80000001L) +#define STATUS_DATATYPE_MISALIGNMENT STATUS_CAST(NTSTATUS, 0x80000002L) +#define STATUS_BREAKPOINT STATUS_CAST(NTSTATUS, 0x80000003L) +#define STATUS_SINGLE_STEP STATUS_CAST(NTSTATUS, 0x80000004L) +#define STATUS_LONGJUMP STATUS_CAST(NTSTATUS, 0x80000026L) +#define STATUS_UNWIND_CONSOLIDATE STATUS_CAST(NTSTATUS, 0x80000029L) +#define DBG_EXCEPTION_NOT_HANDLED STATUS_CAST(NTSTATUS, 0x80010001L) +#define STATUS_ACCESS_VIOLATION STATUS_CAST(NTSTATUS, 0xC0000005L) +#define STATUS_IN_PAGE_ERROR STATUS_CAST(NTSTATUS, 0xC0000006L) +#define STATUS_INVALID_HANDLE STATUS_CAST(NTSTATUS, 0xC0000008L) +#define STATUS_INVALID_PARAMETER STATUS_CAST(NTSTATUS, 0xC000000DL) +#define STATUS_NO_MEMORY STATUS_CAST(NTSTATUS, 0xC0000017L) +#define STATUS_ILLEGAL_INSTRUCTION STATUS_CAST(NTSTATUS, 0xC000001DL) +#define STATUS_NONCONTINUABLE_EXCEPTION STATUS_CAST(NTSTATUS, 0xC0000025L) +#define STATUS_INVALID_DISPOSITION STATUS_CAST(NTSTATUS, 0xC0000026L) +#define STATUS_ARRAY_BOUNDS_EXCEEDED STATUS_CAST(NTSTATUS, 0xC000008CL) +#define STATUS_FLOAT_DENORMAL_OPERAND STATUS_CAST(NTSTATUS, 0xC000008DL) +#define STATUS_FLOAT_DIVIDE_BY_ZERO STATUS_CAST(NTSTATUS, 0xC000008EL) +#define STATUS_FLOAT_INEXACT_RESULT STATUS_CAST(NTSTATUS, 0xC000008FL) +#define STATUS_FLOAT_INVALID_OPERATION STATUS_CAST(NTSTATUS, 0xC0000090L) +#define STATUS_FLOAT_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0000091L) +#define STATUS_FLOAT_STACK_CHECK STATUS_CAST(NTSTATUS, 0xC0000092L) +#define STATUS_FLOAT_UNDERFLOW STATUS_CAST(NTSTATUS, 0xC0000093L) +#define STATUS_INTEGER_DIVIDE_BY_ZERO STATUS_CAST(NTSTATUS, 0xC0000094L) +#define STATUS_INTEGER_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0000095L) +#define STATUS_PRIVILEGED_INSTRUCTION STATUS_CAST(NTSTATUS, 0xC0000096L) +#define STATUS_STACK_OVERFLOW STATUS_CAST(NTSTATUS, 0xC00000FDL) +#define STATUS_DLL_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000135L) +#define STATUS_ORDINAL_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000138L) +#define STATUS_ENTRYPOINT_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000139L) +#define STATUS_CONTROL_C_EXIT STATUS_CAST(NTSTATUS, 0xC000013AL) +#define STATUS_DLL_INIT_FAILED STATUS_CAST(NTSTATUS, 0xC0000142L) +#define STATUS_FLOAT_MULTIPLE_FAULTS STATUS_CAST(NTSTATUS, 0xC00002B4L) +#define STATUS_FLOAT_MULTIPLE_TRAPS STATUS_CAST(NTSTATUS, 0xC00002B5L) +#define STATUS_REG_NAT_CONSUMPTION STATUS_CAST(NTSTATUS, 0xC00002C9L) +#define STATUS_STACK_BUFFER_OVERRUN STATUS_CAST(NTSTATUS, 0xC0000409L) +#define STATUS_INVALID_CRUNTIME_PARAMETER STATUS_CAST(NTSTATUS, 0xC0000417L) +#define STATUS_ASSERTION_FAILURE STATUS_CAST(NTSTATUS, 0xC0000420L) +#define STATUS_SXS_EARLY_DEACTIVATION STATUS_CAST(NTSTATUS, 0xC015000FL) +#define STATUS_SXS_INVALID_DEACTIVATION STATUS_CAST(NTSTATUS, 0xC0150010L) + +#endif + +/* Defined in wincred.h, do not redefine */ + +#if defined(_WIN32) && !defined(_UWP) + +#include + +#else + +#define STATUS_LOGON_FAILURE STATUS_CAST(NTSTATUS, 0xC000006DL) +#define STATUS_WRONG_PASSWORD STATUS_CAST(NTSTATUS, 0xC000006AL) +#define STATUS_PASSWORD_EXPIRED STATUS_CAST(NTSTATUS, 0xC0000071L) +#define STATUS_PASSWORD_MUST_CHANGE STATUS_CAST(NTSTATUS, 0xC0000224L) +#define STATUS_ACCESS_DENIED STATUS_CAST(NTSTATUS, 0xC0000022L) +#define STATUS_DOWNGRADE_DETECTED STATUS_CAST(NTSTATUS, 0xC0000388L) +#define STATUS_AUTHENTICATION_FIREWALL_FAILED STATUS_CAST(NTSTATUS, 0xC0000413L) +#define STATUS_ACCOUNT_DISABLED STATUS_CAST(NTSTATUS, 0xC0000072L) +#define STATUS_ACCOUNT_RESTRICTION STATUS_CAST(NTSTATUS, 0xC000006EL) +#define STATUS_ACCOUNT_LOCKED_OUT STATUS_CAST(NTSTATUS, 0xC0000234L) +#define STATUS_ACCOUNT_EXPIRED STATUS_CAST(NTSTATUS, 0xC0000193L) +#define STATUS_LOGON_TYPE_NOT_GRANTED STATUS_CAST(NTSTATUS, 0xC000015BL) + +#endif + +#define FACILITY_DEBUGGER 0x1 +#define FACILITY_RPC_RUNTIME 0x2 +#define FACILITY_RPC_STUBS 0x3 +#define FACILITY_IO_ERROR_CODE 0x4 +#define FACILITY_TERMINAL_SERVER 0xA +#define FACILITY_USB_ERROR_CODE 0x10 +#define FACILITY_HID_ERROR_CODE 0x11 +#define FACILITY_FIREWIRE_ERROR_CODE 0x12 +#define FACILITY_CLUSTER_ERROR_CODE 0x13 +#define FACILITY_ACPI_ERROR_CODE 0x14 +#define FACILITY_SXS_ERROR_CODE 0x15 + +/** + * NTSTATUS codes + */ + +#if !defined(STATUS_SUCCESS) +#define STATUS_SUCCESS STATUS_CAST(NTSTATUS, 0x00000000) +#endif + +#define STATUS_SEVERITY_SUCCESS 0x0 +#define STATUS_SEVERITY_INFORMATIONAL 0x1 +#define STATUS_SEVERITY_WARNING 0x2 +#define STATUS_SEVERITY_ERROR 0x3 + +#define STATUS_WAIT_1 STATUS_CAST(NTSTATUS, 0x00000001) +#define STATUS_WAIT_2 STATUS_CAST(NTSTATUS, 0x00000002) +#define STATUS_WAIT_3 STATUS_CAST(NTSTATUS, 0x00000003) +#define STATUS_WAIT_63 STATUS_CAST(NTSTATUS, 0x0000003f) +#define STATUS_ABANDONED STATUS_CAST(NTSTATUS, 0x00000080) +#define STATUS_ABANDONED_WAIT_63 STATUS_CAST(NTSTATUS, 0x000000BF) +//#define STATUS_USER_APC STATUS_CAST(NTSTATUS,0x000000C0) +#define STATUS_KERNEL_APC STATUS_CAST(NTSTATUS, 0x00000100) +#define STATUS_ALERTED STATUS_CAST(NTSTATUS, 0x00000101) +//#define STATUS_TIMEOUT STATUS_CAST(NTSTATUS,0x00000102) +//#define STATUS_PENDING STATUS_CAST(NTSTATUS,0x00000103) +#define STATUS_REPARSE STATUS_CAST(NTSTATUS, 0x00000104) +#define STATUS_MORE_ENTRIES STATUS_CAST(NTSTATUS, 0x00000105) +#define STATUS_NOT_ALL_ASSIGNED STATUS_CAST(NTSTATUS, 0x00000106) +#define STATUS_SOME_NOT_MAPPED STATUS_CAST(NTSTATUS, 0x00000107) +#define STATUS_OPLOCK_BREAK_IN_PROGRESS STATUS_CAST(NTSTATUS, 0x00000108) +#define STATUS_VOLUME_MOUNTED STATUS_CAST(NTSTATUS, 0x00000109) +#define STATUS_RXACT_COMMITTED STATUS_CAST(NTSTATUS, 0x0000010A) +#define STATUS_NOTIFY_CLEANUP STATUS_CAST(NTSTATUS, 0x0000010B) +#define STATUS_NOTIFY_ENUM_DIR STATUS_CAST(NTSTATUS, 0x0000010C) +#define STATUS_NO_QUOTAS_FOR_ACCOUNT STATUS_CAST(NTSTATUS, 0x0000010D) +#define STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED STATUS_CAST(NTSTATUS, 0x0000010E) +#define STATUS_PAGE_FAULT_TRANSITION STATUS_CAST(NTSTATUS, 0x00000110) +#define STATUS_PAGE_FAULT_DEMAND_ZERO STATUS_CAST(NTSTATUS, 0x00000111) +#define STATUS_PAGE_FAULT_COPY_ON_WRITE STATUS_CAST(NTSTATUS, 0x00000112) +#define STATUS_PAGE_FAULT_GUARD_PAGE STATUS_CAST(NTSTATUS, 0x00000113) +#define STATUS_PAGE_FAULT_PAGING_FILE STATUS_CAST(NTSTATUS, 0x00000114) +#define STATUS_CACHE_PAGE_LOCKED STATUS_CAST(NTSTATUS, 0x00000115) +#define STATUS_CRASH_DUMP STATUS_CAST(NTSTATUS, 0x00000116) +#define STATUS_BUFFER_ALL_ZEROS STATUS_CAST(NTSTATUS, 0x00000117) +#define STATUS_REPARSE_OBJECT STATUS_CAST(NTSTATUS, 0x00000118) +#define STATUS_RESOURCE_REQUIREMENTS_CHANGED STATUS_CAST(NTSTATUS, 0x00000119) +#define STATUS_TRANSLATION_COMPLETE STATUS_CAST(NTSTATUS, 0x00000120) +#define STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY STATUS_CAST(NTSTATUS, 0x00000121) +#define STATUS_NOTHING_TO_TERMINATE STATUS_CAST(NTSTATUS, 0x00000122) +#define STATUS_PROCESS_NOT_IN_JOB STATUS_CAST(NTSTATUS, 0x00000123) +#define STATUS_PROCESS_IN_JOB STATUS_CAST(NTSTATUS, 0x00000124) +#define STATUS_VOLSNAP_HIBERNATE_READY STATUS_CAST(NTSTATUS, 0x00000125) +#define STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY STATUS_CAST(NTSTATUS, 0x00000126) + +#define STATUS_OBJECT_NAME_EXISTS STATUS_CAST(NTSTATUS, 0x40000000) +#define STATUS_THREAD_WAS_SUSPENDED STATUS_CAST(NTSTATUS, 0x40000001) +#define STATUS_WORKING_SET_LIMIT_RANGE STATUS_CAST(NTSTATUS, 0x40000002) +#define STATUS_IMAGE_NOT_AT_BASE STATUS_CAST(NTSTATUS, 0x40000003) +#define STATUS_RXACT_STATE_CREATED STATUS_CAST(NTSTATUS, 0x40000004) +//#define STATUS_SEGMENT_NOTIFICATION STATUS_CAST(NTSTATUS,0x40000005) +#define STATUS_LOCAL_USER_SESSION_KEY STATUS_CAST(NTSTATUS, 0x40000006) +#define STATUS_BAD_CURRENT_DIRECTORY STATUS_CAST(NTSTATUS, 0x40000007) +#define STATUS_SERIAL_MORE_WRITES STATUS_CAST(NTSTATUS, 0x40000008) +#define STATUS_REGISTRY_RECOVERED STATUS_CAST(NTSTATUS, 0x40000009) +#define STATUS_FT_READ_RECOVERY_FROM_BACKUP STATUS_CAST(NTSTATUS, 0x4000000A) +#define STATUS_FT_WRITE_RECOVERY STATUS_CAST(NTSTATUS, 0x4000000B) +#define STATUS_SERIAL_COUNTER_TIMEOUT STATUS_CAST(NTSTATUS, 0x4000000C) +#define STATUS_NULL_LM_PASSWORD STATUS_CAST(NTSTATUS, 0x4000000D) +#define STATUS_IMAGE_MACHINE_TYPE_MISMATCH STATUS_CAST(NTSTATUS, 0x4000000E) +#define STATUS_RECEIVE_PARTIAL STATUS_CAST(NTSTATUS, 0x4000000F) +#define STATUS_RECEIVE_EXPEDITED STATUS_CAST(NTSTATUS, 0x40000010) +#define STATUS_RECEIVE_PARTIAL_EXPEDITED STATUS_CAST(NTSTATUS, 0x40000011) +#define STATUS_EVENT_DONE STATUS_CAST(NTSTATUS, 0x40000012) +#define STATUS_EVENT_PENDING STATUS_CAST(NTSTATUS, 0x40000013) +#define STATUS_CHECKING_FILE_SYSTEM STATUS_CAST(NTSTATUS, 0x40000014) +//#define STATUS_FATAL_APP_EXIT STATUS_CAST(NTSTATUS,0x40000015) +#define STATUS_PREDEFINED_HANDLE STATUS_CAST(NTSTATUS, 0x40000016) +#define STATUS_WAS_UNLOCKED STATUS_CAST(NTSTATUS, 0x40000017) +#define STATUS_SERVICE_NOTIFICATION STATUS_CAST(NTSTATUS, 0x40000018) +#define STATUS_WAS_LOCKED STATUS_CAST(NTSTATUS, 0x40000019) +#define STATUS_LOG_HARD_ERROR STATUS_CAST(NTSTATUS, 0x4000001A) +#define STATUS_ALREADY_WIN32 STATUS_CAST(NTSTATUS, 0x4000001B) +#define STATUS_WX86_UNSIMULATE STATUS_CAST(NTSTATUS, 0x4000001C) +#define STATUS_WX86_CONTINUE STATUS_CAST(NTSTATUS, 0x4000001D) +#define STATUS_WX86_SINGLE_STEP STATUS_CAST(NTSTATUS, 0x4000001E) +#define STATUS_WX86_BREAKPOINT STATUS_CAST(NTSTATUS, 0x4000001F) +#define STATUS_WX86_EXCEPTION_CONTINUE STATUS_CAST(NTSTATUS, 0x40000020) +#define STATUS_WX86_EXCEPTION_LASTCHANCE STATUS_CAST(NTSTATUS, 0x40000021) +#define STATUS_WX86_EXCEPTION_CHAIN STATUS_CAST(NTSTATUS, 0x40000022) +#define STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE STATUS_CAST(NTSTATUS, 0x40000023) +#define STATUS_NO_YIELD_PERFORMED STATUS_CAST(NTSTATUS, 0x40000024) +#define STATUS_TIMER_RESUME_IGNORED STATUS_CAST(NTSTATUS, 0x40000025) +#define STATUS_ARBITRATION_UNHANDLED STATUS_CAST(NTSTATUS, 0x40000026) +#define STATUS_CARDBUS_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0x40000027) +#define STATUS_WX86_CREATEWX86TIB STATUS_CAST(NTSTATUS, 0x40000028) +#define STATUS_MP_PROCESSOR_MISMATCH STATUS_CAST(NTSTATUS, 0x40000029) +#define STATUS_HIBERNATED STATUS_CAST(NTSTATUS, 0x4000002A) +#define STATUS_RESUME_HIBERNATION STATUS_CAST(NTSTATUS, 0x4000002B) +#define STATUS_FIRMWARE_UPDATED STATUS_CAST(NTSTATUS, 0x4000002C) +#define STATUS_WAKE_SYSTEM STATUS_CAST(NTSTATUS, 0x40000294) +#define STATUS_DS_SHUTTING_DOWN STATUS_CAST(NTSTATUS, 0x40000370) + +#define RPC_NT_UUID_LOCAL_ONLY STATUS_CAST(NTSTATUS, 0x40020056) +#define RPC_NT_SEND_INCOMPLETE STATUS_CAST(NTSTATUS, 0x400200AF) + +#define STATUS_CTX_CDM_CONNECT STATUS_CAST(NTSTATUS, 0x400A0004) +#define STATUS_CTX_CDM_DISCONNECT STATUS_CAST(NTSTATUS, 0x400A0005) + +#define STATUS_SXS_RELEASE_ACTIVATION_CONTEXT STATUS_CAST(NTSTATUS, 0x4015000D) + +//#define STATUS_GUARD_PAGE_VIOLATION STATUS_CAST(NTSTATUS,0x80000001) +//#define STATUS_DATATYPE_MISALIGNMENT STATUS_CAST(NTSTATUS,0x80000002) +//#define STATUS_BREAKPOINT STATUS_CAST(NTSTATUS,0x80000003) +//#define STATUS_SINGLE_STEP STATUS_CAST(NTSTATUS,0x80000004) +#define STATUS_BUFFER_OVERFLOW STATUS_CAST(NTSTATUS, 0x80000005) +#define STATUS_NO_MORE_FILES STATUS_CAST(NTSTATUS, 0x80000006) +#define STATUS_WAKE_SYSTEM_DEBUGGER STATUS_CAST(NTSTATUS, 0x80000007) + +#define STATUS_HANDLES_CLOSED STATUS_CAST(NTSTATUS, 0x8000000A) +#define STATUS_NO_INHERITANCE STATUS_CAST(NTSTATUS, 0x8000000B) +#define STATUS_GUID_SUBSTITUTION_MADE STATUS_CAST(NTSTATUS, 0x8000000C) +#define STATUS_PARTIAL_COPY STATUS_CAST(NTSTATUS, 0x8000000D) +#define STATUS_DEVICE_PAPER_EMPTY STATUS_CAST(NTSTATUS, 0x8000000E) +#define STATUS_DEVICE_POWERED_OFF STATUS_CAST(NTSTATUS, 0x8000000F) +#define STATUS_DEVICE_OFF_LINE STATUS_CAST(NTSTATUS, 0x80000010) +#define STATUS_DEVICE_BUSY STATUS_CAST(NTSTATUS, 0x80000011) +#define STATUS_NO_MORE_EAS STATUS_CAST(NTSTATUS, 0x80000012) +#define STATUS_INVALID_EA_NAME STATUS_CAST(NTSTATUS, 0x80000013) +#define STATUS_EA_LIST_INCONSISTENT STATUS_CAST(NTSTATUS, 0x80000014) +#define STATUS_INVALID_EA_FLAG STATUS_CAST(NTSTATUS, 0x80000015) +#define STATUS_VERIFY_REQUIRED STATUS_CAST(NTSTATUS, 0x80000016) +#define STATUS_EXTRANEOUS_INFORMATION STATUS_CAST(NTSTATUS, 0x80000017) +#define STATUS_RXACT_COMMIT_NECESSARY STATUS_CAST(NTSTATUS, 0x80000018) +#define STATUS_NO_MORE_ENTRIES STATUS_CAST(NTSTATUS, 0x8000001A) +#define STATUS_FILEMARK_DETECTED STATUS_CAST(NTSTATUS, 0x8000001B) +#define STATUS_MEDIA_CHANGED STATUS_CAST(NTSTATUS, 0x8000001C) +#define STATUS_BUS_RESET STATUS_CAST(NTSTATUS, 0x8000001D) +#define STATUS_END_OF_MEDIA STATUS_CAST(NTSTATUS, 0x8000001E) +#define STATUS_BEGINNING_OF_MEDIA STATUS_CAST(NTSTATUS, 0x8000001F) +#define STATUS_MEDIA_CHECK STATUS_CAST(NTSTATUS, 0x80000020) +#define STATUS_SETMARK_DETECTED STATUS_CAST(NTSTATUS, 0x80000021) +#define STATUS_NO_DATA_DETECTED STATUS_CAST(NTSTATUS, 0x80000022) +#define STATUS_REDIRECTOR_HAS_OPEN_HANDLES STATUS_CAST(NTSTATUS, 0x80000023) +#define STATUS_SERVER_HAS_OPEN_HANDLES STATUS_CAST(NTSTATUS, 0x80000024) +#define STATUS_ALREADY_DISCONNECTED STATUS_CAST(NTSTATUS, 0x80000025) +//#define STATUS_LONGJUMP STATUS_CAST(NTSTATUS,0x80000026) +#define STATUS_CLEANER_CARTRIDGE_INSTALLED STATUS_CAST(NTSTATUS, 0x80000027) +#define STATUS_PLUGPLAY_QUERY_VETOED STATUS_CAST(NTSTATUS, 0x80000028) +//#define STATUS_UNWIND_CONSOLIDATE STATUS_CAST(NTSTATUS,0x80000029) +#define STATUS_REGISTRY_HIVE_RECOVERED STATUS_CAST(NTSTATUS, 0x8000002A) +#define STATUS_DLL_MIGHT_BE_INSECURE STATUS_CAST(NTSTATUS, 0x8000002B) +#define STATUS_DLL_MIGHT_BE_INCOMPATIBLE STATUS_CAST(NTSTATUS, 0x8000002C) + +#define STATUS_DEVICE_REQUIRES_CLEANING STATUS_CAST(NTSTATUS, 0x80000288) +#define STATUS_DEVICE_DOOR_OPEN STATUS_CAST(NTSTATUS, 0x80000289) + +#define STATUS_CLUSTER_NODE_ALREADY_UP STATUS_CAST(NTSTATUS, 0x80130001) +#define STATUS_CLUSTER_NODE_ALREADY_DOWN STATUS_CAST(NTSTATUS, 0x80130002) +#define STATUS_CLUSTER_NETWORK_ALREADY_ONLINE STATUS_CAST(NTSTATUS, 0x80130003) +#define STATUS_CLUSTER_NETWORK_ALREADY_OFFLINE STATUS_CAST(NTSTATUS, 0x80130004) +#define STATUS_CLUSTER_NODE_ALREADY_MEMBER STATUS_CAST(NTSTATUS, 0x80130005) + +//#define STATUS_WAIT_0 STATUS_CAST(NTSTATUS,0x00000000) +#define STATUS_UNSUCCESSFUL STATUS_CAST(NTSTATUS, 0xC0000001) +#define STATUS_NOT_IMPLEMENTED STATUS_CAST(NTSTATUS, 0xC0000002) +#define STATUS_INVALID_INFO_CLASS STATUS_CAST(NTSTATUS, 0xC0000003) +#define STATUS_INFO_LENGTH_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000004) +//#define STATUS_ACCESS_VIOLATION STATUS_CAST(NTSTATUS,0xC0000005) +//#define STATUS_IN_PAGE_ERROR STATUS_CAST(NTSTATUS,0xC0000006) +#define STATUS_PAGEFILE_QUOTA STATUS_CAST(NTSTATUS, 0xC0000007) +//#define STATUS_INVALID_HANDLE STATUS_CAST(NTSTATUS,0xC0000008) +#define STATUS_BAD_INITIAL_STACK STATUS_CAST(NTSTATUS, 0xC0000009) +#define STATUS_BAD_INITIAL_PC STATUS_CAST(NTSTATUS, 0xC000000A) +#define STATUS_INVALID_CID STATUS_CAST(NTSTATUS, 0xC000000B) +#define STATUS_TIMER_NOT_CANCELED STATUS_CAST(NTSTATUS, 0xC000000C) +//#define STATUS_INVALID_PARAMETER STATUS_CAST(NTSTATUS,0xC000000D) +#define STATUS_NO_SUCH_DEVICE STATUS_CAST(NTSTATUS, 0xC000000E) +#define STATUS_NO_SUCH_FILE STATUS_CAST(NTSTATUS, 0xC000000F) +#define STATUS_INVALID_DEVICE_REQUEST STATUS_CAST(NTSTATUS, 0xC0000010) +#define STATUS_END_OF_FILE STATUS_CAST(NTSTATUS, 0xC0000011) +#define STATUS_WRONG_VOLUME STATUS_CAST(NTSTATUS, 0xC0000012) +#define STATUS_NO_MEDIA_IN_DEVICE STATUS_CAST(NTSTATUS, 0xC0000013) +#define STATUS_UNRECOGNIZED_MEDIA STATUS_CAST(NTSTATUS, 0xC0000014) +#define STATUS_NONEXISTENT_SECTOR STATUS_CAST(NTSTATUS, 0xC0000015) +#define STATUS_MORE_PROCESSING_REQUIRED STATUS_CAST(NTSTATUS, 0xC0000016) +//#define STATUS_NO_MEMORY STATUS_CAST(NTSTATUS,0xC0000017) +#define STATUS_CONFLICTING_ADDRESSES STATUS_CAST(NTSTATUS, 0xC0000018) +#define STATUS_NOT_MAPPED_VIEW STATUS_CAST(NTSTATUS, 0xC0000019) +#define STATUS_UNABLE_TO_FREE_VM STATUS_CAST(NTSTATUS, 0xC000001A) +#define STATUS_UNABLE_TO_DELETE_SECTION STATUS_CAST(NTSTATUS, 0xC000001B) +#define STATUS_INVALID_SYSTEM_SERVICE STATUS_CAST(NTSTATUS, 0xC000001C) +//#define STATUS_ILLEGAL_INSTRUCTION STATUS_CAST(NTSTATUS,0xC000001D) +#define STATUS_INVALID_LOCK_SEQUENCE STATUS_CAST(NTSTATUS, 0xC000001E) +#define STATUS_INVALID_VIEW_SIZE STATUS_CAST(NTSTATUS, 0xC000001F) +#define STATUS_INVALID_FILE_FOR_SECTION STATUS_CAST(NTSTATUS, 0xC0000020) +#define STATUS_ALREADY_COMMITTED STATUS_CAST(NTSTATUS, 0xC0000021) +//#define STATUS_ACCESS_DENIED STATUS_CAST(NTSTATUS,0xC0000022) +#define STATUS_BUFFER_TOO_SMALL STATUS_CAST(NTSTATUS, 0xC0000023) +#define STATUS_OBJECT_TYPE_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000024) +//#define STATUS_NONCONTINUABLE_EXCEPTION STATUS_CAST(NTSTATUS,0xC0000025) +//#define STATUS_INVALID_DISPOSITION STATUS_CAST(NTSTATUS,0xC0000026) +#define STATUS_UNWIND STATUS_CAST(NTSTATUS, 0xC0000027) +#define STATUS_BAD_STACK STATUS_CAST(NTSTATUS, 0xC0000028) +#define STATUS_INVALID_UNWIND_TARGET STATUS_CAST(NTSTATUS, 0xC0000029) +#define STATUS_NOT_LOCKED STATUS_CAST(NTSTATUS, 0xC000002A) +#define STATUS_PARITY_ERROR STATUS_CAST(NTSTATUS, 0xC000002B) +#define STATUS_UNABLE_TO_DECOMMIT_VM STATUS_CAST(NTSTATUS, 0xC000002C) +#define STATUS_NOT_COMMITTED STATUS_CAST(NTSTATUS, 0xC000002D) +#define STATUS_INVALID_PORT_ATTRIBUTES STATUS_CAST(NTSTATUS, 0xC000002E) +#define STATUS_PORT_MESSAGE_TOO_LONG STATUS_CAST(NTSTATUS, 0xC000002F) +#define STATUS_INVALID_PARAMETER_MIX STATUS_CAST(NTSTATUS, 0xC0000030) +#define STATUS_INVALID_QUOTA_LOWER STATUS_CAST(NTSTATUS, 0xC0000031) +#define STATUS_DISK_CORRUPT_ERROR STATUS_CAST(NTSTATUS, 0xC0000032) +#define STATUS_OBJECT_NAME_INVALID STATUS_CAST(NTSTATUS, 0xC0000033) +#define STATUS_OBJECT_NAME_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000034) +#define STATUS_OBJECT_NAME_COLLISION STATUS_CAST(NTSTATUS, 0xC0000035) +#define STATUS_PORT_DISCONNECTED STATUS_CAST(NTSTATUS, 0xC0000037) +#define STATUS_DEVICE_ALREADY_ATTACHED STATUS_CAST(NTSTATUS, 0xC0000038) +#define STATUS_OBJECT_PATH_INVALID STATUS_CAST(NTSTATUS, 0xC0000039) +#define STATUS_OBJECT_PATH_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000003A) +#define STATUS_OBJECT_PATH_SYNTAX_BAD STATUS_CAST(NTSTATUS, 0xC000003B) +#define STATUS_DATA_OVERRUN STATUS_CAST(NTSTATUS, 0xC000003C) +#define STATUS_DATA_LATE_ERROR STATUS_CAST(NTSTATUS, 0xC000003D) +#define STATUS_DATA_ERROR STATUS_CAST(NTSTATUS, 0xC000003E) +#define STATUS_CRC_ERROR STATUS_CAST(NTSTATUS, 0xC000003F) +#define STATUS_SECTION_TOO_BIG STATUS_CAST(NTSTATUS, 0xC0000040) +#define STATUS_PORT_CONNECTION_REFUSED STATUS_CAST(NTSTATUS, 0xC0000041) +#define STATUS_INVALID_PORT_HANDLE STATUS_CAST(NTSTATUS, 0xC0000042) +#define STATUS_SHARING_VIOLATION STATUS_CAST(NTSTATUS, 0xC0000043) +#define STATUS_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000044) +#define STATUS_INVALID_PAGE_PROTECTION STATUS_CAST(NTSTATUS, 0xC0000045) +#define STATUS_MUTANT_NOT_OWNED STATUS_CAST(NTSTATUS, 0xC0000046) +#define STATUS_SEMAPHORE_LIMIT_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000047) +#define STATUS_PORT_ALREADY_SET STATUS_CAST(NTSTATUS, 0xC0000048) +#define STATUS_SECTION_NOT_IMAGE STATUS_CAST(NTSTATUS, 0xC0000049) +#define STATUS_SUSPEND_COUNT_EXCEEDED STATUS_CAST(NTSTATUS, 0xC000004A) +#define STATUS_THREAD_IS_TERMINATING STATUS_CAST(NTSTATUS, 0xC000004B) +#define STATUS_BAD_WORKING_SET_LIMIT STATUS_CAST(NTSTATUS, 0xC000004C) +#define STATUS_INCOMPATIBLE_FILE_MAP STATUS_CAST(NTSTATUS, 0xC000004D) +#define STATUS_SECTION_PROTECTION STATUS_CAST(NTSTATUS, 0xC000004E) +#define STATUS_EAS_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC000004F) +#define STATUS_EA_TOO_LARGE STATUS_CAST(NTSTATUS, 0xC0000050) +#define STATUS_NONEXISTENT_EA_ENTRY STATUS_CAST(NTSTATUS, 0xC0000051) +#define STATUS_NO_EAS_ON_FILE STATUS_CAST(NTSTATUS, 0xC0000052) +#define STATUS_EA_CORRUPT_ERROR STATUS_CAST(NTSTATUS, 0xC0000053) +#define STATUS_FILE_LOCK_CONFLICT STATUS_CAST(NTSTATUS, 0xC0000054) +#define STATUS_LOCK_NOT_GRANTED STATUS_CAST(NTSTATUS, 0xC0000055) +#define STATUS_DELETE_PENDING STATUS_CAST(NTSTATUS, 0xC0000056) +#define STATUS_CTL_FILE_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC0000057) +#define STATUS_UNKNOWN_REVISION STATUS_CAST(NTSTATUS, 0xC0000058) +#define STATUS_REVISION_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000059) +#define STATUS_INVALID_OWNER STATUS_CAST(NTSTATUS, 0xC000005A) +#define STATUS_INVALID_PRIMARY_GROUP STATUS_CAST(NTSTATUS, 0xC000005B) +#define STATUS_NO_IMPERSONATION_TOKEN STATUS_CAST(NTSTATUS, 0xC000005C) +#define STATUS_CANT_DISABLE_MANDATORY STATUS_CAST(NTSTATUS, 0xC000005D) +#define STATUS_NO_LOGON_SERVERS STATUS_CAST(NTSTATUS, 0xC000005E) +#ifndef STATUS_NO_SUCH_LOGON_SESSION +#define STATUS_NO_SUCH_LOGON_SESSION STATUS_CAST(NTSTATUS, 0xC000005F) +#endif +#define STATUS_NO_SUCH_PRIVILEGE STATUS_CAST(NTSTATUS, 0xC0000060) +#define STATUS_PRIVILEGE_NOT_HELD STATUS_CAST(NTSTATUS, 0xC0000061) +#define STATUS_INVALID_ACCOUNT_NAME STATUS_CAST(NTSTATUS, 0xC0000062) +#define STATUS_USER_EXISTS STATUS_CAST(NTSTATUS, 0xC0000063) +#ifndef STATUS_NO_SUCH_USER +#define STATUS_NO_SUCH_USER STATUS_CAST(NTSTATUS, 0xC0000064) +#endif +#define STATUS_GROUP_EXISTS STATUS_CAST(NTSTATUS, 0xC0000065) +#define STATUS_NO_SUCH_GROUP STATUS_CAST(NTSTATUS, 0xC0000066) +#define STATUS_MEMBER_IN_GROUP STATUS_CAST(NTSTATUS, 0xC0000067) +#define STATUS_MEMBER_NOT_IN_GROUP STATUS_CAST(NTSTATUS, 0xC0000068) +#define STATUS_LAST_ADMIN STATUS_CAST(NTSTATUS, 0xC0000069) +//#define STATUS_WRONG_PASSWORD STATUS_CAST(NTSTATUS,0xC000006A) +#define STATUS_ILL_FORMED_PASSWORD STATUS_CAST(NTSTATUS, 0xC000006B) +#define STATUS_PASSWORD_RESTRICTION STATUS_CAST(NTSTATUS, 0xC000006C) +//#define STATUS_LOGON_FAILURE STATUS_CAST(NTSTATUS,0xC000006D) +//#define STATUS_ACCOUNT_RESTRICTION STATUS_CAST(NTSTATUS,0xC000006E) +#define STATUS_INVALID_LOGON_HOURS STATUS_CAST(NTSTATUS, 0xC000006F) +#define STATUS_INVALID_WORKSTATION STATUS_CAST(NTSTATUS, 0xC0000070) +//#define STATUS_PASSWORD_EXPIRED STATUS_CAST(NTSTATUS,0xC0000071) +//#define STATUS_ACCOUNT_DISABLED STATUS_CAST(NTSTATUS,0xC0000072) +#define STATUS_NONE_MAPPED STATUS_CAST(NTSTATUS, 0xC0000073) +#define STATUS_TOO_MANY_LUIDS_REQUESTED STATUS_CAST(NTSTATUS, 0xC0000074) +#define STATUS_LUIDS_EXHAUSTED STATUS_CAST(NTSTATUS, 0xC0000075) +#define STATUS_INVALID_SUB_AUTHORITY STATUS_CAST(NTSTATUS, 0xC0000076) +#define STATUS_INVALID_ACL STATUS_CAST(NTSTATUS, 0xC0000077) +#define STATUS_INVALID_SID STATUS_CAST(NTSTATUS, 0xC0000078) +#define STATUS_INVALID_SECURITY_DESCR STATUS_CAST(NTSTATUS, 0xC0000079) +#define STATUS_PROCEDURE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000007A) +#define STATUS_INVALID_IMAGE_FORMAT STATUS_CAST(NTSTATUS, 0xC000007B) +#define STATUS_NO_TOKEN STATUS_CAST(NTSTATUS, 0xC000007C) +#define STATUS_BAD_INHERITANCE_ACL STATUS_CAST(NTSTATUS, 0xC000007D) +#define STATUS_RANGE_NOT_LOCKED STATUS_CAST(NTSTATUS, 0xC000007E) +#define STATUS_DISK_FULL STATUS_CAST(NTSTATUS, 0xC000007F) +#define STATUS_SERVER_DISABLED STATUS_CAST(NTSTATUS, 0xC0000080) +#define STATUS_SERVER_NOT_DISABLED STATUS_CAST(NTSTATUS, 0xC0000081) +#define STATUS_TOO_MANY_GUIDS_REQUESTED STATUS_CAST(NTSTATUS, 0xC0000082) +#define STATUS_GUIDS_EXHAUSTED STATUS_CAST(NTSTATUS, 0xC0000083) +#define STATUS_INVALID_ID_AUTHORITY STATUS_CAST(NTSTATUS, 0xC0000084) +#define STATUS_AGENTS_EXHAUSTED STATUS_CAST(NTSTATUS, 0xC0000085) +#define STATUS_INVALID_VOLUME_LABEL STATUS_CAST(NTSTATUS, 0xC0000086) +#define STATUS_SECTION_NOT_EXTENDED STATUS_CAST(NTSTATUS, 0xC0000087) +#define STATUS_NOT_MAPPED_DATA STATUS_CAST(NTSTATUS, 0xC0000088) +#define STATUS_RESOURCE_DATA_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000089) +#define STATUS_RESOURCE_TYPE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000008A) +#define STATUS_RESOURCE_NAME_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000008B) +//#define STATUS_ARRAY_BOUNDS_EXCEEDED STATUS_CAST(NTSTATUS,0xC000008C) +//#define STATUS_FLOAT_DENORMAL_OPERAND STATUS_CAST(NTSTATUS,0xC000008D) +//#define STATUS_FLOAT_DIVIDE_BY_ZERO STATUS_CAST(NTSTATUS,0xC000008E) +//#define STATUS_FLOAT_INEXACT_RESULT STATUS_CAST(NTSTATUS,0xC000008F) +//#define STATUS_FLOAT_INVALID_OPERATION STATUS_CAST(NTSTATUS,0xC0000090) +//#define STATUS_FLOAT_OVERFLOW STATUS_CAST(NTSTATUS,0xC0000091) +//#define STATUS_FLOAT_STACK_CHECK STATUS_CAST(NTSTATUS,0xC0000092) +//#define STATUS_FLOAT_UNDERFLOW STATUS_CAST(NTSTATUS,0xC0000093) +//#define STATUS_INTEGER_DIVIDE_BY_ZERO STATUS_CAST(NTSTATUS,0xC0000094) +//#define STATUS_INTEGER_OVERFLOW STATUS_CAST(NTSTATUS,0xC0000095) +//#define STATUS_PRIVILEGED_INSTRUCTION STATUS_CAST(NTSTATUS,0xC0000096) +#define STATUS_TOO_MANY_PAGING_FILES STATUS_CAST(NTSTATUS, 0xC0000097) +#define STATUS_FILE_INVALID STATUS_CAST(NTSTATUS, 0xC0000098) +#define STATUS_ALLOTTED_SPACE_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000099) +#define STATUS_INSUFFICIENT_RESOURCES STATUS_CAST(NTSTATUS, 0xC000009A) +#define STATUS_DFS_EXIT_PATH_FOUND STATUS_CAST(NTSTATUS, 0xC000009B) +#define STATUS_DEVICE_DATA_ERROR STATUS_CAST(NTSTATUS, 0xC000009C) +#define STATUS_DEVICE_NOT_CONNECTED STATUS_CAST(NTSTATUS, 0xC000009D) +#define STATUS_DEVICE_POWER_FAILURE STATUS_CAST(NTSTATUS, 0xC000009E) +#define STATUS_FREE_VM_NOT_AT_BASE STATUS_CAST(NTSTATUS, 0xC000009F) +#define STATUS_MEMORY_NOT_ALLOCATED STATUS_CAST(NTSTATUS, 0xC00000A0) +#define STATUS_WORKING_SET_QUOTA STATUS_CAST(NTSTATUS, 0xC00000A1) +#define STATUS_MEDIA_WRITE_PROTECTED STATUS_CAST(NTSTATUS, 0xC00000A2) +#define STATUS_DEVICE_NOT_READY STATUS_CAST(NTSTATUS, 0xC00000A3) +#define STATUS_INVALID_GROUP_ATTRIBUTES STATUS_CAST(NTSTATUS, 0xC00000A4) +#define STATUS_BAD_IMPERSONATION_LEVEL STATUS_CAST(NTSTATUS, 0xC00000A5) +#define STATUS_CANT_OPEN_ANONYMOUS STATUS_CAST(NTSTATUS, 0xC00000A6) +#define STATUS_BAD_VALIDATION_CLASS STATUS_CAST(NTSTATUS, 0xC00000A7) +#define STATUS_BAD_TOKEN_TYPE STATUS_CAST(NTSTATUS, 0xC00000A8) +#define STATUS_BAD_MASTER_BOOT_RECORD STATUS_CAST(NTSTATUS, 0xC00000A9) +#define STATUS_INSTRUCTION_MISALIGNMENT STATUS_CAST(NTSTATUS, 0xC00000AA) +#define STATUS_INSTANCE_NOT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC00000AB) +#define STATUS_PIPE_NOT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC00000AC) +#define STATUS_INVALID_PIPE_STATE STATUS_CAST(NTSTATUS, 0xC00000AD) +#define STATUS_PIPE_BUSY STATUS_CAST(NTSTATUS, 0xC00000AE) +#define STATUS_ILLEGAL_FUNCTION STATUS_CAST(NTSTATUS, 0xC00000AF) +#define STATUS_PIPE_DISCONNECTED STATUS_CAST(NTSTATUS, 0xC00000B0) +#define STATUS_PIPE_CLOSING STATUS_CAST(NTSTATUS, 0xC00000B1) +#define STATUS_PIPE_CONNECTED STATUS_CAST(NTSTATUS, 0xC00000B2) +#define STATUS_PIPE_LISTENING STATUS_CAST(NTSTATUS, 0xC00000B3) +#define STATUS_INVALID_READ_MODE STATUS_CAST(NTSTATUS, 0xC00000B4) +#define STATUS_IO_TIMEOUT STATUS_CAST(NTSTATUS, 0xC00000B5) +#define STATUS_FILE_FORCED_CLOSED STATUS_CAST(NTSTATUS, 0xC00000B6) +#define STATUS_PROFILING_NOT_STARTED STATUS_CAST(NTSTATUS, 0xC00000B7) +#define STATUS_PROFILING_NOT_STOPPED STATUS_CAST(NTSTATUS, 0xC00000B8) +#define STATUS_COULD_NOT_INTERPRET STATUS_CAST(NTSTATUS, 0xC00000B9) +#define STATUS_FILE_IS_A_DIRECTORY STATUS_CAST(NTSTATUS, 0xC00000BA) +#define STATUS_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC00000BB) +#define STATUS_REMOTE_NOT_LISTENING STATUS_CAST(NTSTATUS, 0xC00000BC) +#define STATUS_DUPLICATE_NAME STATUS_CAST(NTSTATUS, 0xC00000BD) +#define STATUS_BAD_NETWORK_PATH STATUS_CAST(NTSTATUS, 0xC00000BE) +#define STATUS_NETWORK_BUSY STATUS_CAST(NTSTATUS, 0xC00000BF) +#define STATUS_DEVICE_DOES_NOT_EXIST STATUS_CAST(NTSTATUS, 0xC00000C0) +#define STATUS_TOO_MANY_COMMANDS STATUS_CAST(NTSTATUS, 0xC00000C1) +#define STATUS_ADAPTER_HARDWARE_ERROR STATUS_CAST(NTSTATUS, 0xC00000C2) +#define STATUS_INVALID_NETWORK_RESPONSE STATUS_CAST(NTSTATUS, 0xC00000C3) +#define STATUS_UNEXPECTED_NETWORK_ERROR STATUS_CAST(NTSTATUS, 0xC00000C4) +#define STATUS_BAD_REMOTE_ADAPTER STATUS_CAST(NTSTATUS, 0xC00000C5) +#define STATUS_PRINT_QUEUE_FULL STATUS_CAST(NTSTATUS, 0xC00000C6) +#define STATUS_NO_SPOOL_SPACE STATUS_CAST(NTSTATUS, 0xC00000C7) +#define STATUS_PRINT_CANCELLED STATUS_CAST(NTSTATUS, 0xC00000C8) +#define STATUS_NETWORK_NAME_DELETED STATUS_CAST(NTSTATUS, 0xC00000C9) +#define STATUS_NETWORK_ACCESS_DENIED STATUS_CAST(NTSTATUS, 0xC00000CA) +#define STATUS_BAD_DEVICE_TYPE STATUS_CAST(NTSTATUS, 0xC00000CB) +#define STATUS_BAD_NETWORK_NAME STATUS_CAST(NTSTATUS, 0xC00000CC) +#define STATUS_TOO_MANY_NAMES STATUS_CAST(NTSTATUS, 0xC00000CD) +#define STATUS_TOO_MANY_SESSIONS STATUS_CAST(NTSTATUS, 0xC00000CE) +#define STATUS_SHARING_PAUSED STATUS_CAST(NTSTATUS, 0xC00000CF) +#define STATUS_REQUEST_NOT_ACCEPTED STATUS_CAST(NTSTATUS, 0xC00000D0) +#define STATUS_REDIRECTOR_PAUSED STATUS_CAST(NTSTATUS, 0xC00000D1) +#define STATUS_NET_WRITE_FAULT STATUS_CAST(NTSTATUS, 0xC00000D2) +#define STATUS_PROFILING_AT_LIMIT STATUS_CAST(NTSTATUS, 0xC00000D3) +#define STATUS_NOT_SAME_DEVICE STATUS_CAST(NTSTATUS, 0xC00000D4) +#define STATUS_FILE_RENAMED STATUS_CAST(NTSTATUS, 0xC00000D5) +#define STATUS_VIRTUAL_CIRCUIT_CLOSED STATUS_CAST(NTSTATUS, 0xC00000D6) +#define STATUS_NO_SECURITY_ON_OBJECT STATUS_CAST(NTSTATUS, 0xC00000D7) +#define STATUS_CANT_WAIT STATUS_CAST(NTSTATUS, 0xC00000D8) +#define STATUS_PIPE_EMPTY STATUS_CAST(NTSTATUS, 0xC00000D9) +#define STATUS_CANT_ACCESS_DOMAIN_INFO STATUS_CAST(NTSTATUS, 0xC00000DA) +#define STATUS_CANT_TERMINATE_SELF STATUS_CAST(NTSTATUS, 0xC00000DB) +#define STATUS_INVALID_SERVER_STATE STATUS_CAST(NTSTATUS, 0xC00000DC) +#define STATUS_INVALID_DOMAIN_STATE STATUS_CAST(NTSTATUS, 0xC00000DD) +#define STATUS_INVALID_DOMAIN_ROLE STATUS_CAST(NTSTATUS, 0xC00000DE) +#define STATUS_NO_SUCH_DOMAIN STATUS_CAST(NTSTATUS, 0xC00000DF) +#define STATUS_DOMAIN_EXISTS STATUS_CAST(NTSTATUS, 0xC00000E0) +#define STATUS_DOMAIN_LIMIT_EXCEEDED STATUS_CAST(NTSTATUS, 0xC00000E1) +#define STATUS_OPLOCK_NOT_GRANTED STATUS_CAST(NTSTATUS, 0xC00000E2) +#define STATUS_INVALID_OPLOCK_PROTOCOL STATUS_CAST(NTSTATUS, 0xC00000E3) +#define STATUS_INTERNAL_DB_CORRUPTION STATUS_CAST(NTSTATUS, 0xC00000E4) +#define STATUS_INTERNAL_ERROR STATUS_CAST(NTSTATUS, 0xC00000E5) +#define STATUS_GENERIC_NOT_MAPPED STATUS_CAST(NTSTATUS, 0xC00000E6) +#define STATUS_BAD_DESCRIPTOR_FORMAT STATUS_CAST(NTSTATUS, 0xC00000E7) +#define STATUS_INVALID_USER_BUFFER STATUS_CAST(NTSTATUS, 0xC00000E8) +#define STATUS_UNEXPECTED_IO_ERROR STATUS_CAST(NTSTATUS, 0xC00000E9) +#define STATUS_UNEXPECTED_MM_CREATE_ERR STATUS_CAST(NTSTATUS, 0xC00000EA) +#define STATUS_UNEXPECTED_MM_MAP_ERROR STATUS_CAST(NTSTATUS, 0xC00000EB) +#define STATUS_UNEXPECTED_MM_EXTEND_ERR STATUS_CAST(NTSTATUS, 0xC00000EC) +#define STATUS_NOT_LOGON_PROCESS STATUS_CAST(NTSTATUS, 0xC00000ED) +#define STATUS_LOGON_SESSION_EXISTS STATUS_CAST(NTSTATUS, 0xC00000EE) +#define STATUS_INVALID_PARAMETER_1 STATUS_CAST(NTSTATUS, 0xC00000EF) +#define STATUS_INVALID_PARAMETER_2 STATUS_CAST(NTSTATUS, 0xC00000F0) +#define STATUS_INVALID_PARAMETER_3 STATUS_CAST(NTSTATUS, 0xC00000F1) +#define STATUS_INVALID_PARAMETER_4 STATUS_CAST(NTSTATUS, 0xC00000F2) +#define STATUS_INVALID_PARAMETER_5 STATUS_CAST(NTSTATUS, 0xC00000F3) +#define STATUS_INVALID_PARAMETER_6 STATUS_CAST(NTSTATUS, 0xC00000F4) +#define STATUS_INVALID_PARAMETER_7 STATUS_CAST(NTSTATUS, 0xC00000F5) +#define STATUS_INVALID_PARAMETER_8 STATUS_CAST(NTSTATUS, 0xC00000F6) +#define STATUS_INVALID_PARAMETER_9 STATUS_CAST(NTSTATUS, 0xC00000F7) +#define STATUS_INVALID_PARAMETER_10 STATUS_CAST(NTSTATUS, 0xC00000F8) +#define STATUS_INVALID_PARAMETER_11 STATUS_CAST(NTSTATUS, 0xC00000F9) +#define STATUS_INVALID_PARAMETER_12 STATUS_CAST(NTSTATUS, 0xC00000FA) +#define STATUS_REDIRECTOR_NOT_STARTED STATUS_CAST(NTSTATUS, 0xC00000FB) +#define STATUS_REDIRECTOR_STARTED STATUS_CAST(NTSTATUS, 0xC00000FC) +//#define STATUS_STACK_OVERFLOW STATUS_CAST(NTSTATUS,0xC00000FD) +#define STATUS_NO_SUCH_PACKAGE STATUS_CAST(NTSTATUS, 0xC00000FE) +#define STATUS_BAD_FUNCTION_TABLE STATUS_CAST(NTSTATUS, 0xC00000FF) +#define STATUS_VARIABLE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000100) +#define STATUS_DIRECTORY_NOT_EMPTY STATUS_CAST(NTSTATUS, 0xC0000101) +#define STATUS_FILE_CORRUPT_ERROR STATUS_CAST(NTSTATUS, 0xC0000102) +#define STATUS_NOT_A_DIRECTORY STATUS_CAST(NTSTATUS, 0xC0000103) +#define STATUS_BAD_LOGON_SESSION_STATE STATUS_CAST(NTSTATUS, 0xC0000104) +#define STATUS_LOGON_SESSION_COLLISION STATUS_CAST(NTSTATUS, 0xC0000105) +#define STATUS_NAME_TOO_LONG STATUS_CAST(NTSTATUS, 0xC0000106) +#define STATUS_FILES_OPEN STATUS_CAST(NTSTATUS, 0xC0000107) +#define STATUS_CONNECTION_IN_USE STATUS_CAST(NTSTATUS, 0xC0000108) +#define STATUS_MESSAGE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000109) +#define STATUS_PROCESS_IS_TERMINATING STATUS_CAST(NTSTATUS, 0xC000010A) +#define STATUS_INVALID_LOGON_TYPE STATUS_CAST(NTSTATUS, 0xC000010B) +#define STATUS_NO_GUID_TRANSLATION STATUS_CAST(NTSTATUS, 0xC000010C) +#define STATUS_CANNOT_IMPERSONATE STATUS_CAST(NTSTATUS, 0xC000010D) +#define STATUS_IMAGE_ALREADY_LOADED STATUS_CAST(NTSTATUS, 0xC000010E) +#define STATUS_ABIOS_NOT_PRESENT STATUS_CAST(NTSTATUS, 0xC000010F) +#define STATUS_ABIOS_LID_NOT_EXIST STATUS_CAST(NTSTATUS, 0xC0000110) +#define STATUS_ABIOS_LID_ALREADY_OWNED STATUS_CAST(NTSTATUS, 0xC0000111) +#define STATUS_ABIOS_NOT_LID_OWNER STATUS_CAST(NTSTATUS, 0xC0000112) +#define STATUS_ABIOS_INVALID_COMMAND STATUS_CAST(NTSTATUS, 0xC0000113) +#define STATUS_ABIOS_INVALID_LID STATUS_CAST(NTSTATUS, 0xC0000114) +#define STATUS_ABIOS_SELECTOR_NOT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC0000115) +#define STATUS_ABIOS_INVALID_SELECTOR STATUS_CAST(NTSTATUS, 0xC0000116) +#define STATUS_NO_LDT STATUS_CAST(NTSTATUS, 0xC0000117) +#define STATUS_INVALID_LDT_SIZE STATUS_CAST(NTSTATUS, 0xC0000118) +#define STATUS_INVALID_LDT_OFFSET STATUS_CAST(NTSTATUS, 0xC0000119) +#define STATUS_INVALID_LDT_DESCRIPTOR STATUS_CAST(NTSTATUS, 0xC000011A) +#define STATUS_INVALID_IMAGE_NE_FORMAT STATUS_CAST(NTSTATUS, 0xC000011B) +#define STATUS_RXACT_INVALID_STATE STATUS_CAST(NTSTATUS, 0xC000011C) +#define STATUS_RXACT_COMMIT_FAILURE STATUS_CAST(NTSTATUS, 0xC000011D) +#define STATUS_MAPPED_FILE_SIZE_ZERO STATUS_CAST(NTSTATUS, 0xC000011E) +#define STATUS_TOO_MANY_OPENED_FILES STATUS_CAST(NTSTATUS, 0xC000011F) +#define STATUS_CANCELLED STATUS_CAST(NTSTATUS, 0xC0000120) +#define STATUS_CANNOT_DELETE STATUS_CAST(NTSTATUS, 0xC0000121) +#define STATUS_INVALID_COMPUTER_NAME STATUS_CAST(NTSTATUS, 0xC0000122) +#define STATUS_FILE_DELETED STATUS_CAST(NTSTATUS, 0xC0000123) +#define STATUS_SPECIAL_ACCOUNT STATUS_CAST(NTSTATUS, 0xC0000124) +#define STATUS_SPECIAL_GROUP STATUS_CAST(NTSTATUS, 0xC0000125) +#define STATUS_SPECIAL_USER STATUS_CAST(NTSTATUS, 0xC0000126) +#define STATUS_MEMBERS_PRIMARY_GROUP STATUS_CAST(NTSTATUS, 0xC0000127) +#define STATUS_FILE_CLOSED STATUS_CAST(NTSTATUS, 0xC0000128) +#define STATUS_TOO_MANY_THREADS STATUS_CAST(NTSTATUS, 0xC0000129) +#define STATUS_THREAD_NOT_IN_PROCESS STATUS_CAST(NTSTATUS, 0xC000012A) +#define STATUS_TOKEN_ALREADY_IN_USE STATUS_CAST(NTSTATUS, 0xC000012B) +#define STATUS_PAGEFILE_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC000012C) +#define STATUS_COMMITMENT_LIMIT STATUS_CAST(NTSTATUS, 0xC000012D) +#define STATUS_INVALID_IMAGE_LE_FORMAT STATUS_CAST(NTSTATUS, 0xC000012E) +#define STATUS_INVALID_IMAGE_NOT_MZ STATUS_CAST(NTSTATUS, 0xC000012F) +#define STATUS_INVALID_IMAGE_PROTECT STATUS_CAST(NTSTATUS, 0xC0000130) +#define STATUS_INVALID_IMAGE_WIN_16 STATUS_CAST(NTSTATUS, 0xC0000131) +#define STATUS_LOGON_SERVER_CONFLICT STATUS_CAST(NTSTATUS, 0xC0000132) +#define STATUS_TIME_DIFFERENCE_AT_DC STATUS_CAST(NTSTATUS, 0xC0000133) +#define STATUS_SYNCHRONIZATION_REQUIRED STATUS_CAST(NTSTATUS, 0xC0000134) +//#define STATUS_DLL_NOT_FOUND STATUS_CAST(NTSTATUS,0xC0000135) +#define STATUS_OPEN_FAILED STATUS_CAST(NTSTATUS, 0xC0000136) +#define STATUS_IO_PRIVILEGE_FAILED STATUS_CAST(NTSTATUS, 0xC0000137) +//#define STATUS_ORDINAL_NOT_FOUND STATUS_CAST(NTSTATUS,0xC0000138) +//#define STATUS_ENTRYPOINT_NOT_FOUND STATUS_CAST(NTSTATUS,0xC0000139) +//#define STATUS_CONTROL_C_EXIT STATUS_CAST(NTSTATUS,0xC000013A) +#define STATUS_LOCAL_DISCONNECT STATUS_CAST(NTSTATUS, 0xC000013B) +#define STATUS_REMOTE_DISCONNECT STATUS_CAST(NTSTATUS, 0xC000013C) +#define STATUS_REMOTE_RESOURCES STATUS_CAST(NTSTATUS, 0xC000013D) +#define STATUS_LINK_FAILED STATUS_CAST(NTSTATUS, 0xC000013E) +#define STATUS_LINK_TIMEOUT STATUS_CAST(NTSTATUS, 0xC000013F) +#define STATUS_INVALID_CONNECTION STATUS_CAST(NTSTATUS, 0xC0000140) +#define STATUS_INVALID_ADDRESS STATUS_CAST(NTSTATUS, 0xC0000141) +//#define STATUS_DLL_INIT_FAILED STATUS_CAST(NTSTATUS,0xC0000142) +#define STATUS_MISSING_SYSTEMFILE STATUS_CAST(NTSTATUS, 0xC0000143) +#define STATUS_UNHANDLED_EXCEPTION STATUS_CAST(NTSTATUS, 0xC0000144) +#define STATUS_APP_INIT_FAILURE STATUS_CAST(NTSTATUS, 0xC0000145) +#define STATUS_PAGEFILE_CREATE_FAILED STATUS_CAST(NTSTATUS, 0xC0000146) +#define STATUS_NO_PAGEFILE STATUS_CAST(NTSTATUS, 0xC0000147) +#define STATUS_INVALID_LEVEL STATUS_CAST(NTSTATUS, 0xC0000148) +#define STATUS_WRONG_PASSWORD_CORE STATUS_CAST(NTSTATUS, 0xC0000149) +#define STATUS_ILLEGAL_FLOAT_CONTEXT STATUS_CAST(NTSTATUS, 0xC000014A) +#define STATUS_PIPE_BROKEN STATUS_CAST(NTSTATUS, 0xC000014B) +#define STATUS_REGISTRY_CORRUPT STATUS_CAST(NTSTATUS, 0xC000014C) +#define STATUS_REGISTRY_IO_FAILED STATUS_CAST(NTSTATUS, 0xC000014D) +#define STATUS_NO_EVENT_PAIR STATUS_CAST(NTSTATUS, 0xC000014E) +#define STATUS_UNRECOGNIZED_VOLUME STATUS_CAST(NTSTATUS, 0xC000014F) +#define STATUS_SERIAL_NO_DEVICE_INITED STATUS_CAST(NTSTATUS, 0xC0000150) +#define STATUS_NO_SUCH_ALIAS STATUS_CAST(NTSTATUS, 0xC0000151) +#define STATUS_MEMBER_NOT_IN_ALIAS STATUS_CAST(NTSTATUS, 0xC0000152) +#define STATUS_MEMBER_IN_ALIAS STATUS_CAST(NTSTATUS, 0xC0000153) +#define STATUS_ALIAS_EXISTS STATUS_CAST(NTSTATUS, 0xC0000154) +#define STATUS_LOGON_NOT_GRANTED STATUS_CAST(NTSTATUS, 0xC0000155) +#define STATUS_TOO_MANY_SECRETS STATUS_CAST(NTSTATUS, 0xC0000156) +#define STATUS_SECRET_TOO_LONG STATUS_CAST(NTSTATUS, 0xC0000157) +#define STATUS_INTERNAL_DB_ERROR STATUS_CAST(NTSTATUS, 0xC0000158) +#define STATUS_FULLSCREEN_MODE STATUS_CAST(NTSTATUS, 0xC0000159) +#define STATUS_TOO_MANY_CONTEXT_IDS STATUS_CAST(NTSTATUS, 0xC000015A) +//#define STATUS_LOGON_TYPE_NOT_GRANTED STATUS_CAST(NTSTATUS,0xC000015B) +#define STATUS_NOT_REGISTRY_FILE STATUS_CAST(NTSTATUS, 0xC000015C) +#define STATUS_NT_CROSS_ENCRYPTION_REQUIRED STATUS_CAST(NTSTATUS, 0xC000015D) +#define STATUS_DOMAIN_CTRLR_CONFIG_ERROR STATUS_CAST(NTSTATUS, 0xC000015E) +#define STATUS_FT_MISSING_MEMBER STATUS_CAST(NTSTATUS, 0xC000015F) +#define STATUS_ILL_FORMED_SERVICE_ENTRY STATUS_CAST(NTSTATUS, 0xC0000160) +#define STATUS_ILLEGAL_CHARACTER STATUS_CAST(NTSTATUS, 0xC0000161) +#define STATUS_UNMAPPABLE_CHARACTER STATUS_CAST(NTSTATUS, 0xC0000162) +#define STATUS_UNDEFINED_CHARACTER STATUS_CAST(NTSTATUS, 0xC0000163) +#define STATUS_FLOPPY_VOLUME STATUS_CAST(NTSTATUS, 0xC0000164) +#define STATUS_FLOPPY_ID_MARK_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000165) +#define STATUS_FLOPPY_WRONG_CYLINDER STATUS_CAST(NTSTATUS, 0xC0000166) +#define STATUS_FLOPPY_UNKNOWN_ERROR STATUS_CAST(NTSTATUS, 0xC0000167) +#define STATUS_FLOPPY_BAD_REGISTERS STATUS_CAST(NTSTATUS, 0xC0000168) +#define STATUS_DISK_RECALIBRATE_FAILED STATUS_CAST(NTSTATUS, 0xC0000169) +#define STATUS_DISK_OPERATION_FAILED STATUS_CAST(NTSTATUS, 0xC000016A) +#define STATUS_DISK_RESET_FAILED STATUS_CAST(NTSTATUS, 0xC000016B) +#define STATUS_SHARED_IRQ_BUSY STATUS_CAST(NTSTATUS, 0xC000016C) +#define STATUS_FT_ORPHANING STATUS_CAST(NTSTATUS, 0xC000016D) +#define STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT STATUS_CAST(NTSTATUS, 0xC000016E) + +#define STATUS_PARTITION_FAILURE STATUS_CAST(NTSTATUS, 0xC0000172) +#define STATUS_INVALID_BLOCK_LENGTH STATUS_CAST(NTSTATUS, 0xC0000173) +#define STATUS_DEVICE_NOT_PARTITIONED STATUS_CAST(NTSTATUS, 0xC0000174) +#define STATUS_UNABLE_TO_LOCK_MEDIA STATUS_CAST(NTSTATUS, 0xC0000175) +#define STATUS_UNABLE_TO_UNLOAD_MEDIA STATUS_CAST(NTSTATUS, 0xC0000176) +#define STATUS_EOM_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0000177) +#define STATUS_NO_MEDIA STATUS_CAST(NTSTATUS, 0xC0000178) +#define STATUS_NO_SUCH_MEMBER STATUS_CAST(NTSTATUS, 0xC000017A) +#define STATUS_INVALID_MEMBER STATUS_CAST(NTSTATUS, 0xC000017B) +#define STATUS_KEY_DELETED STATUS_CAST(NTSTATUS, 0xC000017C) +#define STATUS_NO_LOG_SPACE STATUS_CAST(NTSTATUS, 0xC000017D) +#define STATUS_TOO_MANY_SIDS STATUS_CAST(NTSTATUS, 0xC000017E) +#define STATUS_LM_CROSS_ENCRYPTION_REQUIRED STATUS_CAST(NTSTATUS, 0xC000017F) +#define STATUS_KEY_HAS_CHILDREN STATUS_CAST(NTSTATUS, 0xC0000180) +#define STATUS_CHILD_MUST_BE_VOLATILE STATUS_CAST(NTSTATUS, 0xC0000181) +#define STATUS_DEVICE_CONFIGURATION_ERROR STATUS_CAST(NTSTATUS, 0xC0000182) +#define STATUS_DRIVER_INTERNAL_ERROR STATUS_CAST(NTSTATUS, 0xC0000183) +#define STATUS_INVALID_DEVICE_STATE STATUS_CAST(NTSTATUS, 0xC0000184) +#define STATUS_IO_DEVICE_ERROR STATUS_CAST(NTSTATUS, 0xC0000185) +#define STATUS_DEVICE_PROTOCOL_ERROR STATUS_CAST(NTSTATUS, 0xC0000186) +#define STATUS_BACKUP_CONTROLLER STATUS_CAST(NTSTATUS, 0xC0000187) +#define STATUS_LOG_FILE_FULL STATUS_CAST(NTSTATUS, 0xC0000188) +#define STATUS_TOO_LATE STATUS_CAST(NTSTATUS, 0xC0000189) +#define STATUS_NO_TRUST_LSA_SECRET STATUS_CAST(NTSTATUS, 0xC000018A) +#define STATUS_NO_TRUST_SAM_ACCOUNT STATUS_CAST(NTSTATUS, 0xC000018B) +#define STATUS_TRUSTED_DOMAIN_FAILURE STATUS_CAST(NTSTATUS, 0xC000018C) +#define STATUS_TRUSTED_RELATIONSHIP_FAILURE STATUS_CAST(NTSTATUS, 0xC000018D) +#define STATUS_EVENTLOG_FILE_CORRUPT STATUS_CAST(NTSTATUS, 0xC000018E) +#define STATUS_EVENTLOG_CANT_START STATUS_CAST(NTSTATUS, 0xC000018F) +#define STATUS_TRUST_FAILURE STATUS_CAST(NTSTATUS, 0xC0000190) +#define STATUS_MUTANT_LIMIT_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000191) +#define STATUS_NETLOGON_NOT_STARTED STATUS_CAST(NTSTATUS, 0xC0000192) +//#define STATUS_ACCOUNT_EXPIRED STATUS_CAST(NTSTATUS,0xC0000193) +#define STATUS_POSSIBLE_DEADLOCK STATUS_CAST(NTSTATUS, 0xC0000194) +#define STATUS_NETWORK_CREDENTIAL_CONFLICT STATUS_CAST(NTSTATUS, 0xC0000195) +#define STATUS_REMOTE_SESSION_LIMIT STATUS_CAST(NTSTATUS, 0xC0000196) +#define STATUS_EVENTLOG_FILE_CHANGED STATUS_CAST(NTSTATUS, 0xC0000197) +#define STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT STATUS_CAST(NTSTATUS, 0xC0000198) +#define STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT STATUS_CAST(NTSTATUS, 0xC0000199) +#define STATUS_NOLOGON_SERVER_TRUST_ACCOUNT STATUS_CAST(NTSTATUS, 0xC000019A) +#define STATUS_DOMAIN_TRUST_INCONSISTENT STATUS_CAST(NTSTATUS, 0xC000019B) +#define STATUS_FS_DRIVER_REQUIRED STATUS_CAST(NTSTATUS, 0xC000019C) +#define STATUS_NO_USER_SESSION_KEY STATUS_CAST(NTSTATUS, 0xC0000202) +#define STATUS_USER_SESSION_DELETED STATUS_CAST(NTSTATUS, 0xC0000203) +#define STATUS_RESOURCE_LANG_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000204) +#define STATUS_INSUFF_SERVER_RESOURCES STATUS_CAST(NTSTATUS, 0xC0000205) +#define STATUS_INVALID_BUFFER_SIZE STATUS_CAST(NTSTATUS, 0xC0000206) +#define STATUS_INVALID_ADDRESS_COMPONENT STATUS_CAST(NTSTATUS, 0xC0000207) +#define STATUS_INVALID_ADDRESS_WILDCARD STATUS_CAST(NTSTATUS, 0xC0000208) +#define STATUS_TOO_MANY_ADDRESSES STATUS_CAST(NTSTATUS, 0xC0000209) +#define STATUS_ADDRESS_ALREADY_EXISTS STATUS_CAST(NTSTATUS, 0xC000020A) +#define STATUS_ADDRESS_CLOSED STATUS_CAST(NTSTATUS, 0xC000020B) +#define STATUS_CONNECTION_DISCONNECTED STATUS_CAST(NTSTATUS, 0xC000020C) +#define STATUS_CONNECTION_RESET STATUS_CAST(NTSTATUS, 0xC000020D) +#define STATUS_TOO_MANY_NODES STATUS_CAST(NTSTATUS, 0xC000020E) +#define STATUS_TRANSACTION_ABORTED STATUS_CAST(NTSTATUS, 0xC000020F) +#define STATUS_TRANSACTION_TIMED_OUT STATUS_CAST(NTSTATUS, 0xC0000210) +#define STATUS_TRANSACTION_NO_RELEASE STATUS_CAST(NTSTATUS, 0xC0000211) +#define STATUS_TRANSACTION_NO_MATCH STATUS_CAST(NTSTATUS, 0xC0000212) +#define STATUS_TRANSACTION_RESPONDED STATUS_CAST(NTSTATUS, 0xC0000213) +#define STATUS_TRANSACTION_INVALID_ID STATUS_CAST(NTSTATUS, 0xC0000214) +#define STATUS_TRANSACTION_INVALID_TYPE STATUS_CAST(NTSTATUS, 0xC0000215) +#define STATUS_NOT_SERVER_SESSION STATUS_CAST(NTSTATUS, 0xC0000216) +#define STATUS_NOT_CLIENT_SESSION STATUS_CAST(NTSTATUS, 0xC0000217) +#define STATUS_CANNOT_LOAD_REGISTRY_FILE STATUS_CAST(NTSTATUS, 0xC0000218) +#define STATUS_DEBUG_ATTACH_FAILED STATUS_CAST(NTSTATUS, 0xC0000219) +#define STATUS_SYSTEM_PROCESS_TERMINATED STATUS_CAST(NTSTATUS, 0xC000021A) +#define STATUS_DATA_NOT_ACCEPTED STATUS_CAST(NTSTATUS, 0xC000021B) +#define STATUS_NO_BROWSER_SERVERS_FOUND STATUS_CAST(NTSTATUS, 0xC000021C) +#define STATUS_VDM_HARD_ERROR STATUS_CAST(NTSTATUS, 0xC000021D) +#define STATUS_DRIVER_CANCEL_TIMEOUT STATUS_CAST(NTSTATUS, 0xC000021E) +#define STATUS_REPLY_MESSAGE_MISMATCH STATUS_CAST(NTSTATUS, 0xC000021F) +#define STATUS_MAPPED_ALIGNMENT STATUS_CAST(NTSTATUS, 0xC0000220) +#define STATUS_IMAGE_CHECKSUM_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000221) +#define STATUS_LOST_WRITEBEHIND_DATA STATUS_CAST(NTSTATUS, 0xC0000222) +#define STATUS_CLIENT_SERVER_PARAMETERS_INVALID STATUS_CAST(NTSTATUS, 0xC0000223) +//#define STATUS_PASSWORD_MUST_CHANGE STATUS_CAST(NTSTATUS,0xC0000224) +#define STATUS_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000225) +#define STATUS_NOT_TINY_STREAM STATUS_CAST(NTSTATUS, 0xC0000226) +#define STATUS_RECOVERY_FAILURE STATUS_CAST(NTSTATUS, 0xC0000227) +#define STATUS_STACK_OVERFLOW_READ STATUS_CAST(NTSTATUS, 0xC0000228) +#define STATUS_FAIL_CHECK STATUS_CAST(NTSTATUS, 0xC0000229) +#define STATUS_DUPLICATE_OBJECTID STATUS_CAST(NTSTATUS, 0xC000022A) +#define STATUS_OBJECTID_EXISTS STATUS_CAST(NTSTATUS, 0xC000022B) +#define STATUS_CONVERT_TO_LARGE STATUS_CAST(NTSTATUS, 0xC000022C) +#define STATUS_RETRY STATUS_CAST(NTSTATUS, 0xC000022D) +#define STATUS_FOUND_OUT_OF_SCOPE STATUS_CAST(NTSTATUS, 0xC000022E) +#define STATUS_ALLOCATE_BUCKET STATUS_CAST(NTSTATUS, 0xC000022F) +#define STATUS_PROPSET_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000230) +#define STATUS_MARSHALL_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0000231) +#define STATUS_INVALID_VARIANT STATUS_CAST(NTSTATUS, 0xC0000232) +#define STATUS_DOMAIN_CONTROLLER_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000233) +//#define STATUS_ACCOUNT_LOCKED_OUT STATUS_CAST(NTSTATUS,0xC0000234) +#define STATUS_HANDLE_NOT_CLOSABLE STATUS_CAST(NTSTATUS, 0xC0000235) +#define STATUS_CONNECTION_REFUSED STATUS_CAST(NTSTATUS, 0xC0000236) +#define STATUS_GRACEFUL_DISCONNECT STATUS_CAST(NTSTATUS, 0xC0000237) +#define STATUS_ADDRESS_ALREADY_ASSOCIATED STATUS_CAST(NTSTATUS, 0xC0000238) +#define STATUS_ADDRESS_NOT_ASSOCIATED STATUS_CAST(NTSTATUS, 0xC0000239) +#define STATUS_CONNECTION_INVALID STATUS_CAST(NTSTATUS, 0xC000023A) +#define STATUS_CONNECTION_ACTIVE STATUS_CAST(NTSTATUS, 0xC000023B) +#define STATUS_NETWORK_UNREACHABLE STATUS_CAST(NTSTATUS, 0xC000023C) +#define STATUS_HOST_UNREACHABLE STATUS_CAST(NTSTATUS, 0xC000023D) +#define STATUS_PROTOCOL_UNREACHABLE STATUS_CAST(NTSTATUS, 0xC000023E) +#define STATUS_PORT_UNREACHABLE STATUS_CAST(NTSTATUS, 0xC000023F) +#define STATUS_REQUEST_ABORTED STATUS_CAST(NTSTATUS, 0xC0000240) +#define STATUS_CONNECTION_ABORTED STATUS_CAST(NTSTATUS, 0xC0000241) +#define STATUS_BAD_COMPRESSION_BUFFER STATUS_CAST(NTSTATUS, 0xC0000242) +#define STATUS_USER_MAPPED_FILE STATUS_CAST(NTSTATUS, 0xC0000243) +#define STATUS_AUDIT_FAILED STATUS_CAST(NTSTATUS, 0xC0000244) +#define STATUS_TIMER_RESOLUTION_NOT_SET STATUS_CAST(NTSTATUS, 0xC0000245) +#define STATUS_CONNECTION_COUNT_LIMIT STATUS_CAST(NTSTATUS, 0xC0000246) +#define STATUS_LOGIN_TIME_RESTRICTION STATUS_CAST(NTSTATUS, 0xC0000247) +#define STATUS_LOGIN_WKSTA_RESTRICTION STATUS_CAST(NTSTATUS, 0xC0000248) +#define STATUS_IMAGE_MP_UP_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000249) +#define STATUS_INSUFFICIENT_LOGON_INFO STATUS_CAST(NTSTATUS, 0xC0000250) +#define STATUS_BAD_DLL_ENTRYPOINT STATUS_CAST(NTSTATUS, 0xC0000251) +#define STATUS_BAD_SERVICE_ENTRYPOINT STATUS_CAST(NTSTATUS, 0xC0000252) +#define STATUS_LPC_REPLY_LOST STATUS_CAST(NTSTATUS, 0xC0000253) +#define STATUS_IP_ADDRESS_CONFLICT1 STATUS_CAST(NTSTATUS, 0xC0000254) +#define STATUS_IP_ADDRESS_CONFLICT2 STATUS_CAST(NTSTATUS, 0xC0000255) +#define STATUS_REGISTRY_QUOTA_LIMIT STATUS_CAST(NTSTATUS, 0xC0000256) +#define STATUS_PATH_NOT_COVERED STATUS_CAST(NTSTATUS, 0xC0000257) +#define STATUS_NO_CALLBACK_ACTIVE STATUS_CAST(NTSTATUS, 0xC0000258) +#define STATUS_LICENSE_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000259) +#define STATUS_PWD_TOO_SHORT STATUS_CAST(NTSTATUS, 0xC000025A) +#define STATUS_PWD_TOO_RECENT STATUS_CAST(NTSTATUS, 0xC000025B) +#define STATUS_PWD_HISTORY_CONFLICT STATUS_CAST(NTSTATUS, 0xC000025C) +#define STATUS_PLUGPLAY_NO_DEVICE STATUS_CAST(NTSTATUS, 0xC000025E) +#define STATUS_UNSUPPORTED_COMPRESSION STATUS_CAST(NTSTATUS, 0xC000025F) +#define STATUS_INVALID_HW_PROFILE STATUS_CAST(NTSTATUS, 0xC0000260) +#define STATUS_INVALID_PLUGPLAY_DEVICE_PATH STATUS_CAST(NTSTATUS, 0xC0000261) +#define STATUS_DRIVER_ORDINAL_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000262) +#define STATUS_DRIVER_ENTRYPOINT_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000263) +#define STATUS_RESOURCE_NOT_OWNED STATUS_CAST(NTSTATUS, 0xC0000264) +#define STATUS_TOO_MANY_LINKS STATUS_CAST(NTSTATUS, 0xC0000265) +#define STATUS_QUOTA_LIST_INCONSISTENT STATUS_CAST(NTSTATUS, 0xC0000266) +#define STATUS_FILE_IS_OFFLINE STATUS_CAST(NTSTATUS, 0xC0000267) +#define STATUS_EVALUATION_EXPIRATION STATUS_CAST(NTSTATUS, 0xC0000268) +#define STATUS_ILLEGAL_DLL_RELOCATION STATUS_CAST(NTSTATUS, 0xC0000269) +#define STATUS_LICENSE_VIOLATION STATUS_CAST(NTSTATUS, 0xC000026A) +#define STATUS_DLL_INIT_FAILED_LOGOFF STATUS_CAST(NTSTATUS, 0xC000026B) +#define STATUS_DRIVER_UNABLE_TO_LOAD STATUS_CAST(NTSTATUS, 0xC000026C) +#define STATUS_DFS_UNAVAILABLE STATUS_CAST(NTSTATUS, 0xC000026D) +#define STATUS_VOLUME_DISMOUNTED STATUS_CAST(NTSTATUS, 0xC000026E) +#define STATUS_WX86_INTERNAL_ERROR STATUS_CAST(NTSTATUS, 0xC000026F) +#define STATUS_WX86_FLOAT_STACK_CHECK STATUS_CAST(NTSTATUS, 0xC0000270) +#define STATUS_VALIDATE_CONTINUE STATUS_CAST(NTSTATUS, 0xC0000271) +#define STATUS_NO_MATCH STATUS_CAST(NTSTATUS, 0xC0000272) +#define STATUS_NO_MORE_MATCHES STATUS_CAST(NTSTATUS, 0xC0000273) +#define STATUS_NOT_A_REPARSE_POINT STATUS_CAST(NTSTATUS, 0xC0000275) +#define STATUS_IO_REPARSE_TAG_INVALID STATUS_CAST(NTSTATUS, 0xC0000276) +#define STATUS_IO_REPARSE_TAG_MISMATCH STATUS_CAST(NTSTATUS, 0xC0000277) +#define STATUS_IO_REPARSE_DATA_INVALID STATUS_CAST(NTSTATUS, 0xC0000278) +#define STATUS_IO_REPARSE_TAG_NOT_HANDLED STATUS_CAST(NTSTATUS, 0xC0000279) +#define STATUS_REPARSE_POINT_NOT_RESOLVED STATUS_CAST(NTSTATUS, 0xC0000280) +#define STATUS_DIRECTORY_IS_A_REPARSE_POINT STATUS_CAST(NTSTATUS, 0xC0000281) +#define STATUS_RANGE_LIST_CONFLICT STATUS_CAST(NTSTATUS, 0xC0000282) +#define STATUS_SOURCE_ELEMENT_EMPTY STATUS_CAST(NTSTATUS, 0xC0000283) +#define STATUS_DESTINATION_ELEMENT_FULL STATUS_CAST(NTSTATUS, 0xC0000284) +#define STATUS_ILLEGAL_ELEMENT_ADDRESS STATUS_CAST(NTSTATUS, 0xC0000285) +#define STATUS_MAGAZINE_NOT_PRESENT STATUS_CAST(NTSTATUS, 0xC0000286) +#define STATUS_REINITIALIZATION_NEEDED STATUS_CAST(NTSTATUS, 0xC0000287) +#define STATUS_ENCRYPTION_FAILED STATUS_CAST(NTSTATUS, 0xC000028A) +#define STATUS_DECRYPTION_FAILED STATUS_CAST(NTSTATUS, 0xC000028B) +#define STATUS_RANGE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000028C) +#define STATUS_NO_RECOVERY_POLICY STATUS_CAST(NTSTATUS, 0xC000028D) +#define STATUS_NO_EFS STATUS_CAST(NTSTATUS, 0xC000028E) +#define STATUS_WRONG_EFS STATUS_CAST(NTSTATUS, 0xC000028F) +#define STATUS_NO_USER_KEYS STATUS_CAST(NTSTATUS, 0xC0000290) +#define STATUS_FILE_NOT_ENCRYPTED STATUS_CAST(NTSTATUS, 0xC0000291) +#define STATUS_NOT_EXPORT_FORMAT STATUS_CAST(NTSTATUS, 0xC0000292) +#define STATUS_FILE_ENCRYPTED STATUS_CAST(NTSTATUS, 0xC0000293) +#define STATUS_WMI_GUID_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000295) +#define STATUS_WMI_INSTANCE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000296) +#define STATUS_WMI_ITEMID_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0000297) +#define STATUS_WMI_TRY_AGAIN STATUS_CAST(NTSTATUS, 0xC0000298) +#define STATUS_SHARED_POLICY STATUS_CAST(NTSTATUS, 0xC0000299) +#define STATUS_POLICY_OBJECT_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC000029A) +#define STATUS_POLICY_ONLY_IN_DS STATUS_CAST(NTSTATUS, 0xC000029B) +#define STATUS_VOLUME_NOT_UPGRADED STATUS_CAST(NTSTATUS, 0xC000029C) +#define STATUS_REMOTE_STORAGE_NOT_ACTIVE STATUS_CAST(NTSTATUS, 0xC000029D) +#define STATUS_REMOTE_STORAGE_MEDIA_ERROR STATUS_CAST(NTSTATUS, 0xC000029E) +#define STATUS_NO_TRACKING_SERVICE STATUS_CAST(NTSTATUS, 0xC000029F) +#define STATUS_SERVER_SID_MISMATCH STATUS_CAST(NTSTATUS, 0xC00002A0) +#define STATUS_DS_NO_ATTRIBUTE_OR_VALUE STATUS_CAST(NTSTATUS, 0xC00002A1) +#define STATUS_DS_INVALID_ATTRIBUTE_SYNTAX STATUS_CAST(NTSTATUS, 0xC00002A2) +#define STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED STATUS_CAST(NTSTATUS, 0xC00002A3) +#define STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS STATUS_CAST(NTSTATUS, 0xC00002A4) +#define STATUS_DS_BUSY STATUS_CAST(NTSTATUS, 0xC00002A5) +#define STATUS_DS_UNAVAILABLE STATUS_CAST(NTSTATUS, 0xC00002A6) +#define STATUS_DS_NO_RIDS_ALLOCATED STATUS_CAST(NTSTATUS, 0xC00002A7) +#define STATUS_DS_NO_MORE_RIDS STATUS_CAST(NTSTATUS, 0xC00002A8) +#define STATUS_DS_INCORRECT_ROLE_OWNER STATUS_CAST(NTSTATUS, 0xC00002A9) +#define STATUS_DS_RIDMGR_INIT_ERROR STATUS_CAST(NTSTATUS, 0xC00002AA) +#define STATUS_DS_OBJ_CLASS_VIOLATION STATUS_CAST(NTSTATUS, 0xC00002AB) +#define STATUS_DS_CANT_ON_NON_LEAF STATUS_CAST(NTSTATUS, 0xC00002AC) +#define STATUS_DS_CANT_ON_RDN STATUS_CAST(NTSTATUS, 0xC00002AD) +#define STATUS_DS_CANT_MOD_OBJ_CLASS STATUS_CAST(NTSTATUS, 0xC00002AE) +#define STATUS_DS_CROSS_DOM_MOVE_FAILED STATUS_CAST(NTSTATUS, 0xC00002AF) +#define STATUS_DS_GC_NOT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC00002B0) +#define STATUS_DIRECTORY_SERVICE_REQUIRED STATUS_CAST(NTSTATUS, 0xC00002B1) +#define STATUS_REPARSE_ATTRIBUTE_CONFLICT STATUS_CAST(NTSTATUS, 0xC00002B2) +#define STATUS_CANT_ENABLE_DENY_ONLY STATUS_CAST(NTSTATUS, 0xC00002B3) +//#define STATUS_FLOAT_MULTIPLE_FAULTS STATUS_CAST(NTSTATUS,0xC00002B4) +//#define STATUS_FLOAT_MULTIPLE_TRAPS STATUS_CAST(NTSTATUS,0xC00002B5) +#define STATUS_DEVICE_REMOVED STATUS_CAST(NTSTATUS, 0xC00002B6) +#define STATUS_JOURNAL_DELETE_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC00002B7) +#define STATUS_JOURNAL_NOT_ACTIVE STATUS_CAST(NTSTATUS, 0xC00002B8) +#define STATUS_NOINTERFACE STATUS_CAST(NTSTATUS, 0xC00002B9) +#define STATUS_DS_ADMIN_LIMIT_EXCEEDED STATUS_CAST(NTSTATUS, 0xC00002C1) +#define STATUS_DRIVER_FAILED_SLEEP STATUS_CAST(NTSTATUS, 0xC00002C2) +#define STATUS_MUTUAL_AUTHENTICATION_FAILED STATUS_CAST(NTSTATUS, 0xC00002C3) +#define STATUS_CORRUPT_SYSTEM_FILE STATUS_CAST(NTSTATUS, 0xC00002C4) +#define STATUS_DATATYPE_MISALIGNMENT_ERROR STATUS_CAST(NTSTATUS, 0xC00002C5) +#define STATUS_WMI_READ_ONLY STATUS_CAST(NTSTATUS, 0xC00002C6) +#define STATUS_WMI_SET_FAILURE STATUS_CAST(NTSTATUS, 0xC00002C7) +#define STATUS_COMMITMENT_MINIMUM STATUS_CAST(NTSTATUS, 0xC00002C8) +//#define STATUS_REG_NAT_CONSUMPTION STATUS_CAST(NTSTATUS,0xC00002C9) +#define STATUS_TRANSPORT_FULL STATUS_CAST(NTSTATUS, 0xC00002CA) +#define STATUS_DS_SAM_INIT_FAILURE STATUS_CAST(NTSTATUS, 0xC00002CB) +#define STATUS_ONLY_IF_CONNECTED STATUS_CAST(NTSTATUS, 0xC00002CC) +#define STATUS_DS_SENSITIVE_GROUP_VIOLATION STATUS_CAST(NTSTATUS, 0xC00002CD) +#define STATUS_PNP_RESTART_ENUMERATION STATUS_CAST(NTSTATUS, 0xC00002CE) +#define STATUS_JOURNAL_ENTRY_DELETED STATUS_CAST(NTSTATUS, 0xC00002CF) +#define STATUS_DS_CANT_MOD_PRIMARYGROUPID STATUS_CAST(NTSTATUS, 0xC00002D0) +#define STATUS_SYSTEM_IMAGE_BAD_SIGNATURE STATUS_CAST(NTSTATUS, 0xC00002D1) +#define STATUS_PNP_REBOOT_REQUIRED STATUS_CAST(NTSTATUS, 0xC00002D2) +#define STATUS_POWER_STATE_INVALID STATUS_CAST(NTSTATUS, 0xC00002D3) +#define STATUS_DS_INVALID_GROUP_TYPE STATUS_CAST(NTSTATUS, 0xC00002D4) +#define STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN STATUS_CAST(NTSTATUS, 0xC00002D5) +#define STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN STATUS_CAST(NTSTATUS, 0xC00002D6) +#define STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER STATUS_CAST(NTSTATUS, 0xC00002D7) +#define STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER STATUS_CAST(NTSTATUS, 0xC00002D8) +#define STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER STATUS_CAST(NTSTATUS, 0xC00002D9) +#define STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER STATUS_CAST(NTSTATUS, 0xC00002DA) +#define STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER STATUS_CAST(NTSTATUS, 0xC00002DB) +#define STATUS_DS_HAVE_PRIMARY_MEMBERS STATUS_CAST(NTSTATUS, 0xC00002DC) +#define STATUS_WMI_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC00002DD) +#define STATUS_INSUFFICIENT_POWER STATUS_CAST(NTSTATUS, 0xC00002DE) +#define STATUS_SAM_NEED_BOOTKEY_PASSWORD STATUS_CAST(NTSTATUS, 0xC00002DF) +#define STATUS_SAM_NEED_BOOTKEY_FLOPPY STATUS_CAST(NTSTATUS, 0xC00002E0) +#define STATUS_DS_CANT_START STATUS_CAST(NTSTATUS, 0xC00002E1) +#define STATUS_DS_INIT_FAILURE STATUS_CAST(NTSTATUS, 0xC00002E2) +#define STATUS_SAM_INIT_FAILURE STATUS_CAST(NTSTATUS, 0xC00002E3) +#define STATUS_DS_GC_REQUIRED STATUS_CAST(NTSTATUS, 0xC00002E4) +#define STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY STATUS_CAST(NTSTATUS, 0xC00002E5) +#define STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS STATUS_CAST(NTSTATUS, 0xC00002E6) +#define STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC00002E7) +#define STATUS_MULTIPLE_FAULT_VIOLATION STATUS_CAST(NTSTATUS, 0xC00002E8) +#define STATUS_CURRENT_DOMAIN_NOT_ALLOWED STATUS_CAST(NTSTATUS, 0xC00002E9) +#define STATUS_CANNOT_MAKE STATUS_CAST(NTSTATUS, 0xC00002EA) +#define STATUS_SYSTEM_SHUTDOWN STATUS_CAST(NTSTATUS, 0xC00002EB) +#define STATUS_DS_INIT_FAILURE_CONSOLE STATUS_CAST(NTSTATUS, 0xC00002EC) +#define STATUS_DS_SAM_INIT_FAILURE_CONSOLE STATUS_CAST(NTSTATUS, 0xC00002ED) +#define STATUS_UNFINISHED_CONTEXT_DELETED STATUS_CAST(NTSTATUS, 0xC00002EE) +#define STATUS_NO_TGT_REPLY STATUS_CAST(NTSTATUS, 0xC00002EF) +#define STATUS_OBJECTID_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC00002F0) +#define STATUS_NO_IP_ADDRESSES STATUS_CAST(NTSTATUS, 0xC00002F1) +#define STATUS_WRONG_CREDENTIAL_HANDLE STATUS_CAST(NTSTATUS, 0xC00002F2) +#define STATUS_CRYPTO_SYSTEM_INVALID STATUS_CAST(NTSTATUS, 0xC00002F3) +#define STATUS_MAX_REFERRALS_EXCEEDED STATUS_CAST(NTSTATUS, 0xC00002F4) +#define STATUS_MUST_BE_KDC STATUS_CAST(NTSTATUS, 0xC00002F5) +#define STATUS_STRONG_CRYPTO_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC00002F6) +#define STATUS_TOO_MANY_PRINCIPALS STATUS_CAST(NTSTATUS, 0xC00002F7) +#define STATUS_NO_PA_DATA STATUS_CAST(NTSTATUS, 0xC00002F8) +#define STATUS_PKINIT_NAME_MISMATCH STATUS_CAST(NTSTATUS, 0xC00002F9) +#define STATUS_SMARTCARD_LOGON_REQUIRED STATUS_CAST(NTSTATUS, 0xC00002FA) +#define STATUS_KDC_INVALID_REQUEST STATUS_CAST(NTSTATUS, 0xC00002FB) +#define STATUS_KDC_UNABLE_TO_REFER STATUS_CAST(NTSTATUS, 0xC00002FC) +#define STATUS_KDC_UNKNOWN_ETYPE STATUS_CAST(NTSTATUS, 0xC00002FD) +#define STATUS_SHUTDOWN_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC00002FE) +#define STATUS_SERVER_SHUTDOWN_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC00002FF) +#define STATUS_NOT_SUPPORTED_ON_SBS STATUS_CAST(NTSTATUS, 0xC0000300) +#define STATUS_WMI_GUID_DISCONNECTED STATUS_CAST(NTSTATUS, 0xC0000301) +#define STATUS_WMI_ALREADY_DISABLED STATUS_CAST(NTSTATUS, 0xC0000302) +#define STATUS_WMI_ALREADY_ENABLED STATUS_CAST(NTSTATUS, 0xC0000303) +#define STATUS_MFT_TOO_FRAGMENTED STATUS_CAST(NTSTATUS, 0xC0000304) +#define STATUS_COPY_PROTECTION_FAILURE STATUS_CAST(NTSTATUS, 0xC0000305) +#define STATUS_CSS_AUTHENTICATION_FAILURE STATUS_CAST(NTSTATUS, 0xC0000306) +#define STATUS_CSS_KEY_NOT_PRESENT STATUS_CAST(NTSTATUS, 0xC0000307) +#define STATUS_CSS_KEY_NOT_ESTABLISHED STATUS_CAST(NTSTATUS, 0xC0000308) +#define STATUS_CSS_SCRAMBLED_SECTOR STATUS_CAST(NTSTATUS, 0xC0000309) +#define STATUS_CSS_REGION_MISMATCH STATUS_CAST(NTSTATUS, 0xC000030A) +#define STATUS_CSS_RESETS_EXHAUSTED STATUS_CAST(NTSTATUS, 0xC000030B) +#define STATUS_PKINIT_FAILURE STATUS_CAST(NTSTATUS, 0xC0000320) +#define STATUS_SMARTCARD_SUBSYSTEM_FAILURE STATUS_CAST(NTSTATUS, 0xC0000321) +#define STATUS_NO_KERB_KEY STATUS_CAST(NTSTATUS, 0xC0000322) +#define STATUS_HOST_DOWN STATUS_CAST(NTSTATUS, 0xC0000350) +#define STATUS_UNSUPPORTED_PREAUTH STATUS_CAST(NTSTATUS, 0xC0000351) +#define STATUS_EFS_ALG_BLOB_TOO_BIG STATUS_CAST(NTSTATUS, 0xC0000352) +#define STATUS_PORT_NOT_SET STATUS_CAST(NTSTATUS, 0xC0000353) +#define STATUS_DEBUGGER_INACTIVE STATUS_CAST(NTSTATUS, 0xC0000354) +#define STATUS_DS_VERSION_CHECK_FAILURE STATUS_CAST(NTSTATUS, 0xC0000355) +#define STATUS_AUDITING_DISABLED STATUS_CAST(NTSTATUS, 0xC0000356) +#define STATUS_PRENT4_MACHINE_ACCOUNT STATUS_CAST(NTSTATUS, 0xC0000357) +#define STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER STATUS_CAST(NTSTATUS, 0xC0000358) +#define STATUS_INVALID_IMAGE_WIN_32 STATUS_CAST(NTSTATUS, 0xC0000359) +#define STATUS_INVALID_IMAGE_WIN_64 STATUS_CAST(NTSTATUS, 0xC000035A) +#define STATUS_BAD_BINDINGS STATUS_CAST(NTSTATUS, 0xC000035B) +#define STATUS_NETWORK_SESSION_EXPIRED STATUS_CAST(NTSTATUS, 0xC000035C) +#define STATUS_APPHELP_BLOCK STATUS_CAST(NTSTATUS, 0xC000035D) +#define STATUS_ALL_SIDS_FILTERED STATUS_CAST(NTSTATUS, 0xC000035E) +#define STATUS_NOT_SAFE_MODE_DRIVER STATUS_CAST(NTSTATUS, 0xC000035F) +#define STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT STATUS_CAST(NTSTATUS, 0xC0000361) +#define STATUS_ACCESS_DISABLED_BY_POLICY_PATH STATUS_CAST(NTSTATUS, 0xC0000362) +#define STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER STATUS_CAST(NTSTATUS, 0xC0000363) +#define STATUS_ACCESS_DISABLED_BY_POLICY_OTHER STATUS_CAST(NTSTATUS, 0xC0000364) +#define STATUS_FAILED_DRIVER_ENTRY STATUS_CAST(NTSTATUS, 0xC0000365) +#define STATUS_DEVICE_ENUMERATION_ERROR STATUS_CAST(NTSTATUS, 0xC0000366) +#define STATUS_WAIT_FOR_OPLOCK STATUS_CAST(NTSTATUS, 0x00000367) +#define STATUS_MOUNT_POINT_NOT_RESOLVED STATUS_CAST(NTSTATUS, 0xC0000368) +#define STATUS_INVALID_DEVICE_OBJECT_PARAMETER STATUS_CAST(NTSTATUS, 0xC0000369) +/* The following is not a typo. It's the same spelling as in the Microsoft headers */ +#define STATUS_MCA_OCCURED STATUS_CAST(NTSTATUS, 0xC000036A) +#define STATUS_DRIVER_BLOCKED_CRITICAL STATUS_CAST(NTSTATUS, 0xC000036B) +#define STATUS_DRIVER_BLOCKED STATUS_CAST(NTSTATUS, 0xC000036C) +#define STATUS_DRIVER_DATABASE_ERROR STATUS_CAST(NTSTATUS, 0xC000036D) +#define STATUS_SYSTEM_HIVE_TOO_LARGE STATUS_CAST(NTSTATUS, 0xC000036E) +#define STATUS_INVALID_IMPORT_OF_NON_DLL STATUS_CAST(NTSTATUS, 0xC000036F) +#define STATUS_SMARTCARD_WRONG_PIN STATUS_CAST(NTSTATUS, 0xC0000380) +#define STATUS_SMARTCARD_CARD_BLOCKED STATUS_CAST(NTSTATUS, 0xC0000381) +#define STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED STATUS_CAST(NTSTATUS, 0xC0000382) +#define STATUS_SMARTCARD_NO_CARD STATUS_CAST(NTSTATUS, 0xC0000383) +#define STATUS_SMARTCARD_NO_KEY_CONTAINER STATUS_CAST(NTSTATUS, 0xC0000384) +#define STATUS_SMARTCARD_NO_CERTIFICATE STATUS_CAST(NTSTATUS, 0xC0000385) +#define STATUS_SMARTCARD_NO_KEYSET STATUS_CAST(NTSTATUS, 0xC0000386) +#define STATUS_SMARTCARD_IO_ERROR STATUS_CAST(NTSTATUS, 0xC0000387) +//#define STATUS_DOWNGRADE_DETECTED STATUS_CAST(NTSTATUS,0xC0000388) +#define STATUS_SMARTCARD_CERT_REVOKED STATUS_CAST(NTSTATUS, 0xC0000389) +#define STATUS_ISSUING_CA_UNTRUSTED STATUS_CAST(NTSTATUS, 0xC000038A) +#define STATUS_REVOCATION_OFFLINE_C STATUS_CAST(NTSTATUS, 0xC000038B) +#define STATUS_PKINIT_CLIENT_FAILURE STATUS_CAST(NTSTATUS, 0xC000038C) +#define STATUS_SMARTCARD_CERT_EXPIRED STATUS_CAST(NTSTATUS, 0xC000038D) +#define STATUS_DRIVER_FAILED_PRIOR_UNLOAD STATUS_CAST(NTSTATUS, 0xC000038E) +#define STATUS_SMARTCARD_SILENT_CONTEXT STATUS_CAST(NTSTATUS, 0xC000038F) +#define STATUS_PER_USER_TRUST_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000401) +#define STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000402) +#define STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000403) +#define STATUS_DS_NAME_NOT_UNIQUE STATUS_CAST(NTSTATUS, 0xC0000404) +#define STATUS_DS_DUPLICATE_ID_FOUND STATUS_CAST(NTSTATUS, 0xC0000405) +#define STATUS_DS_GROUP_CONVERSION_ERROR STATUS_CAST(NTSTATUS, 0xC0000406) +#define STATUS_VOLSNAP_PREPARE_HIBERNATE STATUS_CAST(NTSTATUS, 0xC0000407) +#define STATUS_USER2USER_REQUIRED STATUS_CAST(NTSTATUS, 0xC0000408) +//#define STATUS_STACK_BUFFER_OVERRUN STATUS_CAST(NTSTATUS,0xC0000409) +#define STATUS_NO_S4U_PROT_SUPPORT STATUS_CAST(NTSTATUS, 0xC000040A) +#define STATUS_CROSSREALM_DELEGATION_FAILURE STATUS_CAST(NTSTATUS, 0xC000040B) +#define STATUS_REVOCATION_OFFLINE_KDC STATUS_CAST(NTSTATUS, 0xC000040C) +#define STATUS_ISSUING_CA_UNTRUSTED_KDC STATUS_CAST(NTSTATUS, 0xC000040D) +#define STATUS_KDC_CERT_EXPIRED STATUS_CAST(NTSTATUS, 0xC000040E) +#define STATUS_KDC_CERT_REVOKED STATUS_CAST(NTSTATUS, 0xC000040F) +#define STATUS_PARAMETER_QUOTA_EXCEEDED STATUS_CAST(NTSTATUS, 0xC0000410) +#define STATUS_HIBERNATION_FAILURE STATUS_CAST(NTSTATUS, 0xC0000411) +#define STATUS_DELAY_LOAD_FAILED STATUS_CAST(NTSTATUS, 0xC0000412) +//#define STATUS_AUTHENTICATION_FIREWALL_FAILED STATUS_CAST(NTSTATUS,0xC0000413) +#define STATUS_VDM_DISALLOWED STATUS_CAST(NTSTATUS, 0xC0000414) +#define STATUS_HUNG_DISPLAY_DRIVER_THREAD STATUS_CAST(NTSTATUS, 0xC0000415) +//#define STATUS_INVALID_CRUNTIME_PARAMETER STATUS_CAST(NTSTATUS,0xC0000417) +//#define STATUS_ASSERTION_FAILURE STATUS_CAST(NTSTATUS,0xC0000420L) +#define STATUS_CALLBACK_POP_STACK STATUS_CAST(NTSTATUS, 0xC0000423) +#define STATUS_WOW_ASSERTION STATUS_CAST(NTSTATUS, 0xC0009898) + +#define RPC_NT_INVALID_STRING_BINDING STATUS_CAST(NTSTATUS, 0xC0020001) +#define RPC_NT_WRONG_KIND_OF_BINDING STATUS_CAST(NTSTATUS, 0xC0020002) +#define RPC_NT_INVALID_BINDING STATUS_CAST(NTSTATUS, 0xC0020003) +#define RPC_NT_PROTSEQ_NOT_SUPPORTED STATUS_CAST(NTSTATUS, 0xC0020004) +#define RPC_NT_INVALID_RPC_PROTSEQ STATUS_CAST(NTSTATUS, 0xC0020005) +#define RPC_NT_INVALID_STRING_UUID STATUS_CAST(NTSTATUS, 0xC0020006) +#define RPC_NT_INVALID_ENDPOINT_FORMAT STATUS_CAST(NTSTATUS, 0xC0020007) +#define RPC_NT_INVALID_NET_ADDR STATUS_CAST(NTSTATUS, 0xC0020008) +#define RPC_NT_NO_ENDPOINT_FOUND STATUS_CAST(NTSTATUS, 0xC0020009) +#define RPC_NT_INVALID_TIMEOUT STATUS_CAST(NTSTATUS, 0xC002000A) +#define RPC_NT_OBJECT_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC002000B) +#define RPC_NT_ALREADY_REGISTERED STATUS_CAST(NTSTATUS, 0xC002000C) +#define RPC_NT_TYPE_ALREADY_REGISTERED STATUS_CAST(NTSTATUS, 0xC002000D) +#define RPC_NT_ALREADY_LISTENING STATUS_CAST(NTSTATUS, 0xC002000E) +#define RPC_NT_NO_PROTSEQS_REGISTERED STATUS_CAST(NTSTATUS, 0xC002000F) +#define RPC_NT_NOT_LISTENING STATUS_CAST(NTSTATUS, 0xC0020010) +#define RPC_NT_UNKNOWN_MGR_TYPE STATUS_CAST(NTSTATUS, 0xC0020011) +#define RPC_NT_UNKNOWN_IF STATUS_CAST(NTSTATUS, 0xC0020012) +#define RPC_NT_NO_BINDINGS STATUS_CAST(NTSTATUS, 0xC0020013) +#define RPC_NT_NO_PROTSEQS STATUS_CAST(NTSTATUS, 0xC0020014) +#define RPC_NT_CANT_CREATE_ENDPOINT STATUS_CAST(NTSTATUS, 0xC0020015) +#define RPC_NT_OUT_OF_RESOURCES STATUS_CAST(NTSTATUS, 0xC0020016) +#define RPC_NT_SERVER_UNAVAILABLE STATUS_CAST(NTSTATUS, 0xC0020017) +#define RPC_NT_SERVER_TOO_BUSY STATUS_CAST(NTSTATUS, 0xC0020018) +#define RPC_NT_INVALID_NETWORK_OPTIONS STATUS_CAST(NTSTATUS, 0xC0020019) +#define RPC_NT_NO_CALL_ACTIVE STATUS_CAST(NTSTATUS, 0xC002001A) +#define RPC_NT_CALL_FAILED STATUS_CAST(NTSTATUS, 0xC002001B) +#define RPC_NT_CALL_FAILED_DNE STATUS_CAST(NTSTATUS, 0xC002001C) +#define RPC_NT_PROTOCOL_ERROR STATUS_CAST(NTSTATUS, 0xC002001D) +#define RPC_NT_UNSUPPORTED_TRANS_SYN STATUS_CAST(NTSTATUS, 0xC002001F) +#define RPC_NT_UNSUPPORTED_TYPE STATUS_CAST(NTSTATUS, 0xC0020021) +#define RPC_NT_INVALID_TAG STATUS_CAST(NTSTATUS, 0xC0020022) +#define RPC_NT_INVALID_BOUND STATUS_CAST(NTSTATUS, 0xC0020023) +#define RPC_NT_NO_ENTRY_NAME STATUS_CAST(NTSTATUS, 0xC0020024) +#define RPC_NT_INVALID_NAME_SYNTAX STATUS_CAST(NTSTATUS, 0xC0020025) +#define RPC_NT_UNSUPPORTED_NAME_SYNTAX STATUS_CAST(NTSTATUS, 0xC0020026) +#define RPC_NT_UUID_NO_ADDRESS STATUS_CAST(NTSTATUS, 0xC0020028) +#define RPC_NT_DUPLICATE_ENDPOINT STATUS_CAST(NTSTATUS, 0xC0020029) +#define RPC_NT_UNKNOWN_AUTHN_TYPE STATUS_CAST(NTSTATUS, 0xC002002A) +#define RPC_NT_MAX_CALLS_TOO_SMALL STATUS_CAST(NTSTATUS, 0xC002002B) +#define RPC_NT_STRING_TOO_LONG STATUS_CAST(NTSTATUS, 0xC002002C) +#define RPC_NT_PROTSEQ_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC002002D) +#define RPC_NT_PROCNUM_OUT_OF_RANGE STATUS_CAST(NTSTATUS, 0xC002002E) +#define RPC_NT_BINDING_HAS_NO_AUTH STATUS_CAST(NTSTATUS, 0xC002002F) +#define RPC_NT_UNKNOWN_AUTHN_SERVICE STATUS_CAST(NTSTATUS, 0xC0020030) +#define RPC_NT_UNKNOWN_AUTHN_LEVEL STATUS_CAST(NTSTATUS, 0xC0020031) +#define RPC_NT_INVALID_AUTH_IDENTITY STATUS_CAST(NTSTATUS, 0xC0020032) +#define RPC_NT_UNKNOWN_AUTHZ_SERVICE STATUS_CAST(NTSTATUS, 0xC0020033) +#define EPT_NT_INVALID_ENTRY STATUS_CAST(NTSTATUS, 0xC0020034) +#define EPT_NT_CANT_PERFORM_OP STATUS_CAST(NTSTATUS, 0xC0020035) +#define EPT_NT_NOT_REGISTERED STATUS_CAST(NTSTATUS, 0xC0020036) +#define RPC_NT_NOTHING_TO_EXPORT STATUS_CAST(NTSTATUS, 0xC0020037) +#define RPC_NT_INCOMPLETE_NAME STATUS_CAST(NTSTATUS, 0xC0020038) +#define RPC_NT_INVALID_VERS_OPTION STATUS_CAST(NTSTATUS, 0xC0020039) +#define RPC_NT_NO_MORE_MEMBERS STATUS_CAST(NTSTATUS, 0xC002003A) +#define RPC_NT_NOT_ALL_OBJS_UNEXPORTED STATUS_CAST(NTSTATUS, 0xC002003B) +#define RPC_NT_INTERFACE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC002003C) +#define RPC_NT_ENTRY_ALREADY_EXISTS STATUS_CAST(NTSTATUS, 0xC002003D) +#define RPC_NT_ENTRY_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC002003E) +#define RPC_NT_NAME_SERVICE_UNAVAILABLE STATUS_CAST(NTSTATUS, 0xC002003F) +#define RPC_NT_INVALID_NAF_ID STATUS_CAST(NTSTATUS, 0xC0020040) +#define RPC_NT_CANNOT_SUPPORT STATUS_CAST(NTSTATUS, 0xC0020041) +#define RPC_NT_NO_CONTEXT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC0020042) +#define RPC_NT_INTERNAL_ERROR STATUS_CAST(NTSTATUS, 0xC0020043) +#define RPC_NT_ZERO_DIVIDE STATUS_CAST(NTSTATUS, 0xC0020044) +#define RPC_NT_ADDRESS_ERROR STATUS_CAST(NTSTATUS, 0xC0020045) +#define RPC_NT_FP_DIV_ZERO STATUS_CAST(NTSTATUS, 0xC0020046) +#define RPC_NT_FP_UNDERFLOW STATUS_CAST(NTSTATUS, 0xC0020047) +#define RPC_NT_FP_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0020048) +#define RPC_NT_CALL_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC0020049) +#define RPC_NT_NO_MORE_BINDINGS STATUS_CAST(NTSTATUS, 0xC002004A) +#define RPC_NT_GROUP_MEMBER_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC002004B) +#define EPT_NT_CANT_CREATE STATUS_CAST(NTSTATUS, 0xC002004C) +#define RPC_NT_INVALID_OBJECT STATUS_CAST(NTSTATUS, 0xC002004D) +#define RPC_NT_NO_INTERFACES STATUS_CAST(NTSTATUS, 0xC002004F) +#define RPC_NT_CALL_CANCELLED STATUS_CAST(NTSTATUS, 0xC0020050) +#define RPC_NT_BINDING_INCOMPLETE STATUS_CAST(NTSTATUS, 0xC0020051) +#define RPC_NT_COMM_FAILURE STATUS_CAST(NTSTATUS, 0xC0020052) +#define RPC_NT_UNSUPPORTED_AUTHN_LEVEL STATUS_CAST(NTSTATUS, 0xC0020053) +#define RPC_NT_NO_PRINC_NAME STATUS_CAST(NTSTATUS, 0xC0020054) +#define RPC_NT_NOT_RPC_ERROR STATUS_CAST(NTSTATUS, 0xC0020055) +#define RPC_NT_SEC_PKG_ERROR STATUS_CAST(NTSTATUS, 0xC0020057) +#define RPC_NT_NOT_CANCELLED STATUS_CAST(NTSTATUS, 0xC0020058) +#define RPC_NT_INVALID_ASYNC_HANDLE STATUS_CAST(NTSTATUS, 0xC0020062) +#define RPC_NT_INVALID_ASYNC_CALL STATUS_CAST(NTSTATUS, 0xC0020063) + +#define RPC_NT_NO_MORE_ENTRIES STATUS_CAST(NTSTATUS, 0xC0030001) +#define RPC_NT_SS_CHAR_TRANS_OPEN_FAIL STATUS_CAST(NTSTATUS, 0xC0030002) +#define RPC_NT_SS_CHAR_TRANS_SHORT_FILE STATUS_CAST(NTSTATUS, 0xC0030003) +#define RPC_NT_SS_IN_NULL_CONTEXT STATUS_CAST(NTSTATUS, 0xC0030004) +#define RPC_NT_SS_CONTEXT_MISMATCH STATUS_CAST(NTSTATUS, 0xC0030005) +#define RPC_NT_SS_CONTEXT_DAMAGED STATUS_CAST(NTSTATUS, 0xC0030006) +#define RPC_NT_SS_HANDLES_MISMATCH STATUS_CAST(NTSTATUS, 0xC0030007) +#define RPC_NT_SS_CANNOT_GET_CALL_HANDLE STATUS_CAST(NTSTATUS, 0xC0030008) +#define RPC_NT_NULL_REF_POINTER STATUS_CAST(NTSTATUS, 0xC0030009) +#define RPC_NT_ENUM_VALUE_OUT_OF_RANGE STATUS_CAST(NTSTATUS, 0xC003000A) +#define RPC_NT_BYTE_COUNT_TOO_SMALL STATUS_CAST(NTSTATUS, 0xC003000B) +#define RPC_NT_BAD_STUB_DATA STATUS_CAST(NTSTATUS, 0xC003000C) +#define RPC_NT_INVALID_ES_ACTION STATUS_CAST(NTSTATUS, 0xC0030059) +#define RPC_NT_WRONG_ES_VERSION STATUS_CAST(NTSTATUS, 0xC003005A) +#define RPC_NT_WRONG_STUB_VERSION STATUS_CAST(NTSTATUS, 0xC003005B) +#define RPC_NT_INVALID_PIPE_OBJECT STATUS_CAST(NTSTATUS, 0xC003005C) +#define RPC_NT_INVALID_PIPE_OPERATION STATUS_CAST(NTSTATUS, 0xC003005D) +#define RPC_NT_WRONG_PIPE_VERSION STATUS_CAST(NTSTATUS, 0xC003005E) +#define RPC_NT_PIPE_CLOSED STATUS_CAST(NTSTATUS, 0xC003005F) +#define RPC_NT_PIPE_DISCIPLINE_ERROR STATUS_CAST(NTSTATUS, 0xC0030060) +#define RPC_NT_PIPE_EMPTY STATUS_CAST(NTSTATUS, 0xC0030061) + +#define STATUS_PNP_BAD_MPS_TABLE STATUS_CAST(NTSTATUS, 0xC0040035) +#define STATUS_PNP_TRANSLATION_FAILED STATUS_CAST(NTSTATUS, 0xC0040036) +#define STATUS_PNP_IRQ_TRANSLATION_FAILED STATUS_CAST(NTSTATUS, 0xC0040037) +#define STATUS_PNP_INVALID_ID STATUS_CAST(NTSTATUS, 0xC0040038) + +#define STATUS_ACPI_INVALID_OPCODE STATUS_CAST(NTSTATUS, 0xC0140001L) +#define STATUS_ACPI_STACK_OVERFLOW STATUS_CAST(NTSTATUS, 0xC0140002L) +#define STATUS_ACPI_ASSERT_FAILED STATUS_CAST(NTSTATUS, 0xC0140003L) +#define STATUS_ACPI_INVALID_INDEX STATUS_CAST(NTSTATUS, 0xC0140004L) +#define STATUS_ACPI_INVALID_ARGUMENT STATUS_CAST(NTSTATUS, 0xC0140005L) +#define STATUS_ACPI_FATAL STATUS_CAST(NTSTATUS, 0xC0140006L) +#define STATUS_ACPI_INVALID_SUPERNAME STATUS_CAST(NTSTATUS, 0xC0140007L) +#define STATUS_ACPI_INVALID_ARGTYPE STATUS_CAST(NTSTATUS, 0xC0140008L) +#define STATUS_ACPI_INVALID_OBJTYPE STATUS_CAST(NTSTATUS, 0xC0140009L) +#define STATUS_ACPI_INVALID_TARGETTYPE STATUS_CAST(NTSTATUS, 0xC014000AL) +#define STATUS_ACPI_INCORRECT_ARGUMENT_COUNT STATUS_CAST(NTSTATUS, 0xC014000BL) +#define STATUS_ACPI_ADDRESS_NOT_MAPPED STATUS_CAST(NTSTATUS, 0xC014000CL) +#define STATUS_ACPI_INVALID_EVENTTYPE STATUS_CAST(NTSTATUS, 0xC014000DL) +#define STATUS_ACPI_HANDLER_COLLISION STATUS_CAST(NTSTATUS, 0xC014000EL) +#define STATUS_ACPI_INVALID_DATA STATUS_CAST(NTSTATUS, 0xC014000FL) +#define STATUS_ACPI_INVALID_REGION STATUS_CAST(NTSTATUS, 0xC0140010L) +#define STATUS_ACPI_INVALID_ACCESS_SIZE STATUS_CAST(NTSTATUS, 0xC0140011L) +#define STATUS_ACPI_ACQUIRE_GLOBAL_LOCK STATUS_CAST(NTSTATUS, 0xC0140012L) +#define STATUS_ACPI_ALREADY_INITIALIZED STATUS_CAST(NTSTATUS, 0xC0140013L) +#define STATUS_ACPI_NOT_INITIALIZED STATUS_CAST(NTSTATUS, 0xC0140014L) +#define STATUS_ACPI_INVALID_MUTEX_LEVEL STATUS_CAST(NTSTATUS, 0xC0140015L) +#define STATUS_ACPI_MUTEX_NOT_OWNED STATUS_CAST(NTSTATUS, 0xC0140016L) +#define STATUS_ACPI_MUTEX_NOT_OWNER STATUS_CAST(NTSTATUS, 0xC0140017L) +#define STATUS_ACPI_RS_ACCESS STATUS_CAST(NTSTATUS, 0xC0140018L) +#define STATUS_ACPI_INVALID_TABLE STATUS_CAST(NTSTATUS, 0xC0140019L) +#define STATUS_ACPI_REG_HANDLER_FAILED STATUS_CAST(NTSTATUS, 0xC0140020L) +#define STATUS_ACPI_POWER_REQUEST_FAILED STATUS_CAST(NTSTATUS, 0xC0140021L) + +#define STATUS_CTX_WINSTATION_NAME_INVALID STATUS_CAST(NTSTATUS, 0xC00A0001) +#define STATUS_CTX_INVALID_PD STATUS_CAST(NTSTATUS, 0xC00A0002) +#define STATUS_CTX_PD_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC00A0003) +#define STATUS_CTX_CLOSE_PENDING STATUS_CAST(NTSTATUS, 0xC00A0006) +#define STATUS_CTX_NO_OUTBUF STATUS_CAST(NTSTATUS, 0xC00A0007) +#define STATUS_CTX_MODEM_INF_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC00A0008) +#define STATUS_CTX_INVALID_MODEMNAME STATUS_CAST(NTSTATUS, 0xC00A0009) +#define STATUS_CTX_RESPONSE_ERROR STATUS_CAST(NTSTATUS, 0xC00A000A) +#define STATUS_CTX_MODEM_RESPONSE_TIMEOUT STATUS_CAST(NTSTATUS, 0xC00A000B) +#define STATUS_CTX_MODEM_RESPONSE_NO_CARRIER STATUS_CAST(NTSTATUS, 0xC00A000C) +#define STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE STATUS_CAST(NTSTATUS, 0xC00A000D) +#define STATUS_CTX_MODEM_RESPONSE_BUSY STATUS_CAST(NTSTATUS, 0xC00A000E) +#define STATUS_CTX_MODEM_RESPONSE_VOICE STATUS_CAST(NTSTATUS, 0xC00A000F) +#define STATUS_CTX_TD_ERROR STATUS_CAST(NTSTATUS, 0xC00A0010) +#define STATUS_CTX_LICENSE_CLIENT_INVALID STATUS_CAST(NTSTATUS, 0xC00A0012) +#define STATUS_CTX_LICENSE_NOT_AVAILABLE STATUS_CAST(NTSTATUS, 0xC00A0013) +#define STATUS_CTX_LICENSE_EXPIRED STATUS_CAST(NTSTATUS, 0xC00A0014) +#define STATUS_CTX_WINSTATION_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC00A0015) +#define STATUS_CTX_WINSTATION_NAME_COLLISION STATUS_CAST(NTSTATUS, 0xC00A0016) +#define STATUS_CTX_WINSTATION_BUSY STATUS_CAST(NTSTATUS, 0xC00A0017) +#define STATUS_CTX_BAD_VIDEO_MODE STATUS_CAST(NTSTATUS, 0xC00A0018) +#define STATUS_CTX_GRAPHICS_INVALID STATUS_CAST(NTSTATUS, 0xC00A0022) +#define STATUS_CTX_NOT_CONSOLE STATUS_CAST(NTSTATUS, 0xC00A0024) +#define STATUS_CTX_CLIENT_QUERY_TIMEOUT STATUS_CAST(NTSTATUS, 0xC00A0026) +#define STATUS_CTX_CONSOLE_DISCONNECT STATUS_CAST(NTSTATUS, 0xC00A0027) +#define STATUS_CTX_CONSOLE_CONNECT STATUS_CAST(NTSTATUS, 0xC00A0028) +#define STATUS_CTX_SHADOW_DENIED STATUS_CAST(NTSTATUS, 0xC00A002A) +#define STATUS_CTX_WINSTATION_ACCESS_DENIED STATUS_CAST(NTSTATUS, 0xC00A002B) +#define STATUS_CTX_INVALID_WD STATUS_CAST(NTSTATUS, 0xC00A002E) +#define STATUS_CTX_WD_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC00A002F) +#define STATUS_CTX_SHADOW_INVALID STATUS_CAST(NTSTATUS, 0xC00A0030) +#define STATUS_CTX_SHADOW_DISABLED STATUS_CAST(NTSTATUS, 0xC00A0031) +#define STATUS_RDP_PROTOCOL_ERROR STATUS_CAST(NTSTATUS, 0xC00A0032) +#define STATUS_CTX_CLIENT_LICENSE_NOT_SET STATUS_CAST(NTSTATUS, 0xC00A0033) +#define STATUS_CTX_CLIENT_LICENSE_IN_USE STATUS_CAST(NTSTATUS, 0xC00A0034) +#define STATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE STATUS_CAST(NTSTATUS, 0xC00A0035) +#define STATUS_CTX_SHADOW_NOT_RUNNING STATUS_CAST(NTSTATUS, 0xC00A0036) + +#define STATUS_CLUSTER_INVALID_NODE STATUS_CAST(NTSTATUS, 0xC0130001) +#define STATUS_CLUSTER_NODE_EXISTS STATUS_CAST(NTSTATUS, 0xC0130002) +#define STATUS_CLUSTER_JOIN_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC0130003) +#define STATUS_CLUSTER_NODE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0130004) +#define STATUS_CLUSTER_LOCAL_NODE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0130005) +#define STATUS_CLUSTER_NETWORK_EXISTS STATUS_CAST(NTSTATUS, 0xC0130006) +#define STATUS_CLUSTER_NETWORK_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0130007) +#define STATUS_CLUSTER_NETINTERFACE_EXISTS STATUS_CAST(NTSTATUS, 0xC0130008) +#define STATUS_CLUSTER_NETINTERFACE_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0130009) +#define STATUS_CLUSTER_INVALID_REQUEST STATUS_CAST(NTSTATUS, 0xC013000A) +#define STATUS_CLUSTER_INVALID_NETWORK_PROVIDER STATUS_CAST(NTSTATUS, 0xC013000B) +#define STATUS_CLUSTER_NODE_DOWN STATUS_CAST(NTSTATUS, 0xC013000C) +#define STATUS_CLUSTER_NODE_UNREACHABLE STATUS_CAST(NTSTATUS, 0xC013000D) +#define STATUS_CLUSTER_NODE_NOT_MEMBER STATUS_CAST(NTSTATUS, 0xC013000E) +#define STATUS_CLUSTER_JOIN_NOT_IN_PROGRESS STATUS_CAST(NTSTATUS, 0xC013000F) +#define STATUS_CLUSTER_INVALID_NETWORK STATUS_CAST(NTSTATUS, 0xC0130010) +#define STATUS_CLUSTER_NO_NET_ADAPTERS STATUS_CAST(NTSTATUS, 0xC0130011) +#define STATUS_CLUSTER_NODE_UP STATUS_CAST(NTSTATUS, 0xC0130012) +#define STATUS_CLUSTER_NODE_PAUSED STATUS_CAST(NTSTATUS, 0xC0130013) +#define STATUS_CLUSTER_NODE_NOT_PAUSED STATUS_CAST(NTSTATUS, 0xC0130014) +#define STATUS_CLUSTER_NO_SECURITY_CONTEXT STATUS_CAST(NTSTATUS, 0xC0130015) +#define STATUS_CLUSTER_NETWORK_NOT_INTERNAL STATUS_CAST(NTSTATUS, 0xC0130016) +#define STATUS_CLUSTER_POISONED STATUS_CAST(NTSTATUS, 0xC0130017) + +#define STATUS_SXS_SECTION_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0150001) +#define STATUS_SXS_CANT_GEN_ACTCTX STATUS_CAST(NTSTATUS, 0xC0150002) +#define STATUS_SXS_INVALID_ACTCTXDATA_FORMAT STATUS_CAST(NTSTATUS, 0xC0150003) +#define STATUS_SXS_ASSEMBLY_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0150004) +#define STATUS_SXS_MANIFEST_FORMAT_ERROR STATUS_CAST(NTSTATUS, 0xC0150005) +#define STATUS_SXS_MANIFEST_PARSE_ERROR STATUS_CAST(NTSTATUS, 0xC0150006) +#define STATUS_SXS_ACTIVATION_CONTEXT_DISABLED STATUS_CAST(NTSTATUS, 0xC0150007) +#define STATUS_SXS_KEY_NOT_FOUND STATUS_CAST(NTSTATUS, 0xC0150008) +#define STATUS_SXS_VERSION_CONFLICT STATUS_CAST(NTSTATUS, 0xC0150009) +#define STATUS_SXS_WRONG_SECTION_TYPE STATUS_CAST(NTSTATUS, 0xC015000A) +#define STATUS_SXS_THREAD_QUERIES_DISABLED STATUS_CAST(NTSTATUS, 0xC015000B) +#define STATUS_SXS_ASSEMBLY_MISSING STATUS_CAST(NTSTATUS, 0xC015000C) +#define STATUS_SXS_PROCESS_DEFAULT_ALREADY_SET STATUS_CAST(NTSTATUS, 0xC015000E) +//#define STATUS_SXS_EARLY_DEACTIVATION STATUS_CAST(NTSTATUS,0xC015000F) +//#define STATUS_SXS_INVALID_DEACTIVATION STATUS_CAST(NTSTATUS,0xC0150010) +#define STATUS_SXS_MULTIPLE_DEACTIVATION STATUS_CAST(NTSTATUS, 0xC0150011) +#define STATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY STATUS_CAST(NTSTATUS, 0xC0150012) +#define STATUS_SXS_PROCESS_TERMINATION_REQUESTED STATUS_CAST(NTSTATUS, 0xC0150013) +#define STATUS_SXS_CORRUPT_ACTIVATION_STACK STATUS_CAST(NTSTATUS, 0xC0150014) +#define STATUS_SXS_CORRUPTION STATUS_CAST(NTSTATUS, 0xC0150015) +#define STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE STATUS_CAST(NTSTATUS, 0xC0150016) +#define STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME STATUS_CAST(NTSTATUS, 0xC0150017) +#define STATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE STATUS_CAST(NTSTATUS, 0xC0150018) +#define STATUS_SXS_IDENTITY_PARSE_ERROR STATUS_CAST(NTSTATUS, 0xC0150019) +#define STATUS_SXS_COMPONENT_STORE_CORRUPT STATUS_CAST(NTSTATUS, 0xC015001A) +#define STATUS_SXS_FILE_HASH_MISMATCH STATUS_CAST(NTSTATUS, 0xC015001B) +#define STATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT STATUS_CAST(NTSTATUS, 0xC015001C) +#define STATUS_SXS_IDENTITIES_DIFFERENT STATUS_CAST(NTSTATUS, 0xC015001D) +#define STATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT STATUS_CAST(NTSTATUS, 0xC015001E) +#define STATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY STATUS_CAST(NTSTATUS, 0xC015001F) +#define STATUS_ADVANCED_INSTALLER_FAILED STATUS_CAST(NTSTATUS, 0xC0150020) +#define STATUS_XML_ENCODING_MISMATCH STATUS_CAST(NTSTATUS, 0xC0150021) +#define STATUS_SXS_MANIFEST_TOO_BIG STATUS_CAST(NTSTATUS, 0xC0150022) +#define STATUS_SXS_SETTING_NOT_REGISTERED STATUS_CAST(NTSTATUS, 0xC0150023) +#define STATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE STATUS_CAST(NTSTATUS, 0xC0150024) +#define STATUS_SXS_PRIMITIVE_INSTALLER_FAILED STATUS_CAST(NTSTATUS, 0xC0150025) +#define STATUS_GENERIC_COMMAND_FAILED STATUS_CAST(NTSTATUS, 0xC0150026) +#define STATUS_SXS_FILE_HASH_MISSING STATUS_CAST(NTSTATUS, 0xC0150027) + +/* Defined in winternl.h, always define since we do not include this header */ + +/* defined in ntstatus.h */ +#if !defined(NTSTATUS_FROM_WIN32) && !defined(INLINE_NTSTATUS_FROM_WIN32) +static INLINE NTSTATUS NTSTATUS_FROM_WIN32(long x) +{ + return x <= 0 ? STATUS_CAST(NTSTATUS, x) + : STATUS_CAST(NTSTATUS, ((x)&0x0000FFFF) | (0x7 << 16) | 0xC0000000); +} +#endif + +#if defined(_WIN32) && !defined(__MINGW32__) + +/** + * winternl.h contains an incomplete definition of enum FILE_INFORMATION_CLASS + * avoid conflict by prefixing the winternl.h definition by _WINTERNL_ and then + * make a complete definition of enum FILE_INFORMATION_CLASS ourselves. + * + * For more information, refer to [MS-FSCC]: File System Control Codes: + * http://msdn.microsoft.com/en-us/library/cc231987.aspx + */ + +#define FILE_INFORMATION_CLASS _WINTERNL_FILE_INFORMATION_CLASS +#define _FILE_INFORMATION_CLASS _WINTERNL__FILE_INFORMATION_CLASS +#define FileDirectoryInformation _WINTERNL_FileDirectoryInformation + +#include + +#undef FILE_INFORMATION_CLASS +#undef _FILE_INFORMATION_CLASS +#undef FileDirectoryInformation + +#elif defined(_WIN32) +#include +#endif + +#ifndef __MINGW32__ +typedef enum +{ + FileDirectoryInformation = 1, + FileFullDirectoryInformation, + FileBothDirectoryInformation, + FileBasicInformation, + FileStandardInformation, + FileInternalInformation, + FileEaInformation, + FileAccessInformation, + FileNameInformation, + FileRenameInformation, + FileLinkInformation, + FileNamesInformation, + FileDispositionInformation, + FilePositionInformation, + FileFullEaInformation, + FileModeInformation, + FileAlignmentInformation, + FileAllInformation, + FileAllocationInformation, + FileEndOfFileInformation, + FileAlternateNameInformation, + FileStreamInformation, + FilePipeInformation, + FilePipeLocalInformation, + FilePipeRemoteInformation, + FileMailslotQueryInformation, + FileMailslotSetInformation, + FileCompressionInformation, + FileObjectIdInformation, + FileUnknownInformation1, + FileMoveClusterInformation, + FileQuotaInformation, + FileReparsePointInformation, + FileNetworkOpenInformation, + FileAttributeTagInformation, + FileTrackingInformation, + FileIdBothDirectoryInformation, + FileIdFullDirectoryInformation, + FileValidDataLengthInformation, + FileShortNameInformation +} FILE_INFORMATION_CLASS; +#endif /* !__MINGW32__ */ + +#if !defined(_WIN32) || defined(__MINGW32__) +/* defined in */ +#define FILE_SUPERSEDED 0x00000000 +#define FILE_OPENED 0x00000001 +#define FILE_CREATED 0x00000002 +#define FILE_OVERWRITTEN 0x00000003 +#define FILE_EXISTS 0x00000004 +#define FILE_DOES_NOT_EXIST 0x00000005 +#endif + +#if !defined(_WIN32) || defined(_UWP) + +#define FILE_SUPERSEDE 0x00000000 +#define FILE_OPEN 0x00000001 +#define FILE_CREATE 0x00000002 +#define FILE_OPEN_IF 0x00000003 +#define FILE_OVERWRITE 0x00000004 +#define FILE_OVERWRITE_IF 0x00000005 +#define FILE_MAXIMUM_DISPOSITION 0x00000005 + +#define FILE_DIRECTORY_FILE 0x00000001 +#define FILE_WRITE_THROUGH 0x00000002 +#define FILE_SEQUENTIAL_ONLY 0x00000004 +#define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008 + +#define FILE_SYNCHRONOUS_IO_ALERT 0x00000010 +#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 +#define FILE_NON_DIRECTORY_FILE 0x00000040 +#define FILE_CREATE_TREE_CONNECTION 0x00000080 + +#define FILE_COMPLETE_IF_OPLOCKED 0x00000100 +#define FILE_NO_EA_KNOWLEDGE 0x00000200 +#define FILE_OPEN_REMOTE_INSTANCE 0x00000400 +#define FILE_RANDOM_ACCESS 0x00000800 + +#define FILE_DELETE_ON_CLOSE 0x00001000 +#define FILE_OPEN_BY_FILE_ID 0x00002000 +#define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000 +#define FILE_NO_COMPRESSION 0x00008000 + +#define FILE_OPEN_REQUIRING_OPLOCK 0x00010000 + +#define FILE_RESERVE_OPFILTER 0x00100000 +#define FILE_OPEN_REPARSE_POINT 0x00200000 +#define FILE_OPEN_NO_RECALL 0x00400000 +#define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000 + +#define FILE_VALID_OPTION_FLAGS 0x00FFFFFF +#define FILE_VALID_PIPE_OPTION_FLAGS 0x00000032 +#define FILE_VALID_MAILSLOT_OPTION_FLAGS 0x00000032 +#define FILE_VALID_SET_FLAGS 0x00000036 + +typedef CONST char* PCSZ; + +typedef struct +{ + USHORT Length; + USHORT MaximumLength; + PCHAR Buffer; +} STRING; +typedef STRING* PSTRING; + +typedef STRING ANSI_STRING; +typedef PSTRING PANSI_STRING; +typedef PSTRING PCANSI_STRING; + +typedef STRING OEM_STRING; +typedef PSTRING POEM_STRING; +typedef CONST STRING* PCOEM_STRING; + +typedef struct +{ + USHORT Length; + USHORT MaximumLength; + PWSTR Buffer; +} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING; + +#define OBJ_INHERIT 0x00000002L +#define OBJ_PERMANENT 0x00000010L +#define OBJ_EXCLUSIVE 0x00000020L +#define OBJ_CASE_INSENSITIVE 0x00000040L +#define OBJ_OPENIF 0x00000080L +#define OBJ_OPENLINK 0x00000100L +#define OBJ_KERNEL_HANDLE 0x00000200L +#define OBJ_FORCE_ACCESS_CHECK 0x00000400L +#define OBJ_VALID_ATTRIBUTES 0x000007F2L + +typedef struct +{ + ULONG Length; + HANDLE RootDirectory; + PUNICODE_STRING ObjectName; + ULONG Attributes; + PVOID SecurityDescriptor; + PVOID SecurityQualityOfService; +} OBJECT_ATTRIBUTES; +typedef OBJECT_ATTRIBUTES* POBJECT_ATTRIBUTES; + +typedef struct +{ + union + { +#ifdef _WIN32 + NTSTATUS Status; +#else + NTSTATUS status; +#endif + PVOID Pointer; + }; + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; + +typedef VOID (*PIO_APC_ROUTINE)(PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG Reserved); + +#endif + +#if !defined(_WIN32) + +typedef struct S_PEB PEB; +typedef struct S_PEB* PPEB; + +typedef struct S_TEB TEB; +typedef struct S_TEB* PTEB; + +/** + * Process Environment Block + */ + +typedef struct +{ + DWORD ThreadId; + TEB* ThreadEnvironmentBlock; +} THREAD_BLOCK_ID; + +struct S_PEB +{ + DWORD ThreadCount; + DWORD ThreadArraySize; + THREAD_BLOCK_ID* Threads; +}; + +/* + * Thread Environment Block + */ + +struct S_TEB +{ + PEB* ProcessEnvironmentBlock; + + DWORD LastErrorValue; + PVOID TlsSlots[64]; +}; + +#define GENERIC_READ 0x80000000 +#define GENERIC_WRITE 0x40000000 +#define GENERIC_EXECUTE 0x20000000 +#define GENERIC_ALL 0x10000000 + +#define DELETE 0x00010000 +#define READ_CONTROL 0x00020000 +#define WRITE_DAC 0x00040000 +#define WRITE_OWNER 0x00080000 +#define SYNCHRONIZE 0x00100000 +#define STANDARD_RIGHTS_REQUIRED 0x000F0000 +#define STANDARD_RIGHTS_READ 0x00020000 +#define STANDARD_RIGHTS_WRITE 0x00020000 +#define STANDARD_RIGHTS_EXECUTE 0x00020000 +#define STANDARD_RIGHTS_ALL 0x001F0000 +#define SPECIFIC_RIGHTS_ALL 0x0000FFFF +#define ACCESS_SYSTEM_SECURITY 0x01000000 +#define MAXIMUM_ALLOWED 0x02000000 + +#define FILE_READ_DATA 0x0001 +#define FILE_LIST_DIRECTORY 0x0001 +#define FILE_WRITE_DATA 0x0002 +#define FILE_ADD_FILE 0x0002 +#define FILE_APPEND_DATA 0x0004 +#define FILE_ADD_SUBDIRECTORY 0x0004 +#define FILE_CREATE_PIPE_INSTANCE 0x0004 +#define FILE_READ_EA 0x0008 +#define FILE_WRITE_EA 0x0010 +#define FILE_EXECUTE 0x0020 +#define FILE_TRAVERSE 0x0020 +#define FILE_DELETE_CHILD 0x0040 +#define FILE_READ_ATTRIBUTES 0x0080 +#define FILE_WRITE_ATTRIBUTES 0x0100 + +#define FILE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF) +#define FILE_GENERIC_READ \ + (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE) +#define FILE_GENERIC_WRITE \ + (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | \ + FILE_APPEND_DATA | SYNCHRONIZE) +#define FILE_GENERIC_EXECUTE \ + (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE) + +#define FILE_SHARE_READ 0x00000001 +#define FILE_SHARE_WRITE 0x00000002 +#define FILE_SHARE_DELETE 0x00000004 + +typedef DWORD ACCESS_MASK; +typedef ACCESS_MASK* PACCESS_MASK; + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API PTEB NtCurrentTeb(void); + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API const char* NtStatus2Tag(NTSTATUS ntstatus); + WINPR_API const char* Win32ErrorCode2Tag(UINT16 code); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_NT_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ntlm.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ntlm.h new file mode 100644 index 0000000000000000000000000000000000000000..85b3f29895a40b1eba661cbe729f6ebfe821c83a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ntlm.h @@ -0,0 +1,68 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pack.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pack.h new file mode 100644 index 0000000000000000000000000000000000000000..f97ba9a69b6cbb9d934e206ba963c9ddf2ba5925 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pack.h @@ -0,0 +1,100 @@ +/** + * WinPR: Windows Portable Runtime + * Pragma Pack + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 // enables packing + * + * #define WINPR_PACK_POP + * #include // 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 diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/path.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/path.h new file mode 100644 index 0000000000000000000000000000000000000000..8b8aa90e4d46d2655809a506353efc35c82cd94a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/path.h @@ -0,0 +1,386 @@ +/** + * WinPR: Windows Portable Runtime + * Path Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include + +//#define WINPR_HAVE_PATHCCH_H 1 + +#ifdef WINPR_HAVE_PATHCCH_H + +#include + +#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 NULL 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 NULL) + * + * @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 NULL in case of failure. Use \b + * free to clean up the allocated string. + * + * + * @since version 3.9.0 + */ + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* winpr_GetConfigFilePath(BOOL system, const char* filename); + + WINPR_API const char* GetKnownPathIdString(int id); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetKnownPath(eKnownPathTypes id); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetKnownSubPath(eKnownPathTypes id, const char* path); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetEnvironmentPath(char* name); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetEnvironmentSubPath(char* name, const char* path); + + WINPR_ATTR_MALLOC(free, 1) + WINPR_API char* GetCombinedPath(const char* basePath, const char* subPath); + + 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 +#endif + +#endif /* WINPR_PATH_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pipe.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pipe.h new file mode 100644 index 0000000000000000000000000000000000000000..a31d5ebd2bbca9f928cfed3afc3c7ac759beea38 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pipe.h @@ -0,0 +1,130 @@ +/** + * WinPR: Windows Portable Runtime + * Pipe Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include + +#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_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_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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/platform.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..a88066a17b86f7b107cdcfce02e5e9c04e7ab131 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/platform.h @@ -0,0 +1,598 @@ +/** + * WinPR: Windows Portable Runtime + * Platform-Specific Definitions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +/* 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(__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(__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 */ + +#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_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_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 +#define _M_AMD64 1 +#endif +#endif + +/* Intel ia64 */ +#if defined(__ia64) || defined(__ia64__) || defined(_M_IA64) +#ifndef _M_IA64 +#define _M_IA64 1 +#endif +#endif + +/* Intel x86 or AMD64 (_M_IX86_AMD64) */ + +#if defined(_M_IX86) || defined(_M_AMD64) +#ifndef _M_IX86_AMD64 +#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 +#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 +#define _M_MIPS 1 +#endif +#endif + +/* MIPS64 (_M_MIPS64) */ + +#if defined(mips64) || defined(__mips64) || defined(__mips64__) || defined(__MIPS64__) +#ifndef _M_MIPS64 +#define _M_MIPS64 1 +#endif +#endif + +/* PowerPC (_M_PPC) */ + +#if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) || \ + defined(_ARCH_PPC) +#ifndef _M_PPC +#define _M_PPC 1 +#endif +#endif + +/* Intel Itanium (_M_IA64) */ + +#if defined(__ia64) || defined(__ia64__) || defined(_IA64) || defined(__IA64__) +#ifndef _M_IA64 +#define _M_IA64 1 +#endif +#endif + +/* Alpha (_M_ALPHA) */ + +#if defined(__alpha) || defined(__alpha__) +#ifndef _M_ALPHA +#define _M_ALPHA 1 +#endif +#endif + +/* SPARC (_M_SPARC) */ + +#if defined(__sparc) || defined(__sparc__) +#ifndef _M_SPARC +#define _M_SPARC 1 +#endif +#endif + +/* E2K (_M_E2K) */ + +#if defined(__e2k__) +#ifndef _M_E2K +#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 +#define _WINRT 1 +#endif +#endif +#endif + +#if defined(__cplusplus_winrt) +#ifndef _WINRT +#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 + +#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) + +/* iOS (__IOS__) */ + +#ifndef __IOS__ +#define __IOS__ 1 +#endif + +#elif (TARGET_OS_MAC == 1) + +/* Mac OS X (__MACOSX__) */ + +#ifndef __MACOSX__ +#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 +#define __sun 1 +#endif +#endif + +/* IRIX (__sgi) */ + +#if defined(sgi) +#ifndef __sgi +#define __sgi 1 +#endif +#endif + +/* AIX (_AIX) */ + +#if defined(__TOS_AIX__) +#ifndef _AIX +#define _AIX 1 +#endif +#endif + +/* HP-UX (__hpux) */ + +#if defined(hpux) || defined(_hpux) +#ifndef __hpux +#define __hpux 1 +#endif +#endif + +/* BeOS (__BEOS__) */ + +/* QNX (__QNXNTO__) */ + +/** + * Endianness: + * http://sourceforge.net/p/predef/wiki/Endianness/ + */ + +#if defined(__gnu_linux__) +#include +#endif + +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ + defined(__DragonFly__) || defined(__APPLE__) +#include +#endif + +/* Big-Endian */ + +#ifdef __BYTE_ORDER + +#if (__BYTE_ORDER == __BIG_ENDIAN) +#ifndef __BIG_ENDIAN__ +#define __BIG_ENDIAN__ 1 +#endif +#endif + +#else + +#if defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || defined(_MIPSEB) || \ + defined(__MIPSEB) || defined(__MIPSEB__) +#ifndef __BIG_ENDIAN__ +#define __BIG_ENDIAN__ 1 +#endif +#endif + +#endif /* __BYTE_ORDER */ + +/* Little-Endian */ + +#ifdef __BYTE_ORDER + +#if (__BYTE_ORDER == __LITTLE_ENDIAN) +#ifndef __LITTLE_ENDIAN__ +#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__ +#define __LITTLE_ENDIAN__ 1 +#endif +#endif + +#endif /* __BYTE_ORDER */ + +WINPR_PRAGMA_DIAG_POP + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) +#define WINPR_DEPRECATED(obj) [[deprecated]] obj +#define WINPR_DEPRECATED_VAR(text, obj) [[deprecated(text)]] obj +#define WINPR_NORETURN(obj) [[noreturn]] obj +#elif defined(WIN32) && !defined(__CYGWIN__) +#define WINPR_DEPRECATED(obj) __declspec(deprecated) obj +#define WINPR_DEPRECATED_VAR(text, obj) __declspec(deprecated(text)) obj +#define WINPR_NORETURN(obj) __declspec(noreturn) obj +#elif defined(__GNUC__) +#define WINPR_DEPRECATED(obj) obj __attribute__((deprecated)) +#define WINPR_DEPRECATED_VAR(text, obj) obj __attribute__((deprecated(text))) +#define WINPR_NORETURN(obj) __attribute__((__noreturn__)) obj +#else +#define WINPR_DEPRECATED(obj) obj +#define WINPR_DEPRECATED_VAR(text, obj) obj +#define WINPR_NORETURN(obj) obj +#endif + +#ifdef _WIN32 +#define INLINE __inline +#else +#define INLINE inline +#endif + +#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) +#define WINPR_API __attribute__((visibility("default"))) +#else +#define WINPR_API +#endif +#endif +#else /* WINPR_DLL */ +#define WINPR_API +#endif + +#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ <= 10) +#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \ + __attribute__((malloc, warn_unused_result)) /** @since version 3.3.0 */ +#elif defined(__GNUC__) +#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \ + __attribute__((malloc(deallocator, ptrindex), warn_unused_result)) /** @since version 3.3.0 */ +#else +#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 /**/ +#else +#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 _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 + +#if defined(__GNUC__) || defined(__clang__) +#define WINPR_ALIGN64 __attribute__((aligned(8))) /** @since version 3.4.0 */ +#else +#ifdef _WIN32 +#define WINPR_ALIGN64 __declspec(align(8)) /** @since version 3.4.0 */ +#else +#define WINPR_ALIGN64 /** @since version 3.4.0 */ +#endif +#endif + +#define WINPR_UNUSED(x) (void)(x) + +#endif /* WINPR_PLATFORM_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pool.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pool.h new file mode 100644 index 0000000000000000000000000000000000000000..da3aa90d4ac700e56efb0bdf768ce9259d8dc381 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/pool.h @@ -0,0 +1,282 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include + +#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 = { 0 }; + *pcbe = empty; + pcbe->Version = 1; + } + + static INLINE VOID DestroyThreadpoolEnvironment(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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/print.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/print.h new file mode 100644 index 0000000000000000000000000000000000000000..7710378b884dd2e882c35416cb251443a9bb5576 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/print.h @@ -0,0 +1,54 @@ +/** + * WinPR: Windows Portable Runtime + * Print Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include +#include + +#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_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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/registry.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/registry.h new file mode 100644 index 0000000000000000000000000000000000000000..e596a396b1560f7902fa2c34bf403a1c125faaa6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/registry.h @@ -0,0 +1,426 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Registry + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#if defined(_WIN32) && !defined(_UWP) + +#include + +#else + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include + +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/rpc.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/rpc.h new file mode 100644 index 0000000000000000000000000000000000000000..4bfb3af1526df0e35d139f3b81c4da475ac83f11 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/rpc.h @@ -0,0 +1,725 @@ +/** + * WinPR: Windows Portable Runtime + * Microsoft Remote Procedure Call (MSRPC) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +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 + +#else + +#include +#include +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sam.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sam.h new file mode 100644 index 0000000000000000000000000000000000000000..c1efaa1f438652a3bea5ba0f99608a5d783b2113 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sam.h @@ -0,0 +1,59 @@ +/** + * WinPR: Windows Portable Runtime + * Security Accounts Manager (SAM) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/schannel.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/schannel.h new file mode 100644 index 0000000000000000000000000000000000000000..e4d5fabd3c936d68dc6c4e049961bc505530904f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/schannel.h @@ -0,0 +1,284 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#if defined(_WIN32) && !defined(_UWP) + +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/secapi.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/secapi.h new file mode 100644 index 0000000000000000000000000000000000000000..6eccb4cbb2411c47cfd9f5538748fbd1c66fa0bb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/secapi.h @@ -0,0 +1,79 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package + * + * Copyright 2023 David Fort + * + * 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 +#else + +#include + +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, + KerbCertificateLogon = 13, + KerbCertificateS4ULogon = 14, + KerbCertificateUnlockLogon = 15, + KerbNoElevationLogon = 83, + KerbLuidLogon = 84 +} 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 + +#endif /* _WIN32 */ + +#ifndef KERB_LOGON_FLAG_REDIRECTED +#define KERB_LOGON_FLAG_REDIRECTED 0x2 +#endif + +#endif /* WINPR_SECAPI_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/security.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/security.h new file mode 100644 index 0000000000000000000000000000000000000000..0d71b2113fa1e2ec8959279e055bee5e80d07c68 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/security.h @@ -0,0 +1,449 @@ +/** + * WinPR: Windows Portable Runtime + * Security Definitions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +/** + * Windows Integrity Mechanism Design: + * http://msdn.microsoft.com/en-us/library/bb625963.aspx + */ + +#ifndef _WIN32 + +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/shell.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/shell.h new file mode 100644 index 0000000000000000000000000000000000000000..376ebb102d33bb48ac0a14e6f000b2a2df771271 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/shell.h @@ -0,0 +1,108 @@ +/** + * WinPR: Windows Portable Runtime + * Shell Functions + * + * Copyright 2015 Dell Software + * Copyright 2016 David PHAM-VAN + * + * 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 +#include +#include +#include +#include + +#ifdef _WIN32 + +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/smartcard.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/smartcard.h new file mode 100644 index 0000000000000000000000000000000000000000..23eac318ba5d8206166fe9725dd6618a84eb46db --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/smartcard.h @@ -0,0 +1,1217 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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_SMARTCARD_H +#define WINPR_SMARTCARD_H + +#include +#include +#include + +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#ifndef _WINSCARD_H_ +#define _WINSCARD_H_ /* do not include winscard.h */ +#endif + +WINPR_PRAGMA_DIAG_POP + +#ifndef SCARD_S_SUCCESS + +#define SCARD_S_SUCCESS NO_ERROR + +#define SCARD_F_INTERNAL_ERROR -2146435071l // (0x80100001L) +#define SCARD_E_CANCELLED -2146435070l // (0x80100002L) +#define SCARD_E_INVALID_HANDLE -2146435069l // (0x80100003L) +#define SCARD_E_INVALID_PARAMETER -2146435068l // (0x80100004L) +#define SCARD_E_INVALID_TARGET -2146435067l // (0x80100005L) +#define SCARD_E_NO_MEMORY -2146435066l // (0x80100006L) +#define SCARD_F_WAITED_TOO_LONG -2146435065l // (0x80100007L) +#define SCARD_E_INSUFFICIENT_BUFFER -2146435064l // (0x80100008L) +#define SCARD_E_UNKNOWN_READER -2146435063l // (0x80100009L) +#define SCARD_E_TIMEOUT -2146435062l // (0x8010000AL) +#define SCARD_E_SHARING_VIOLATION -2146435061l // (0x8010000BL) +#define SCARD_E_NO_SMARTCARD -2146435060l // (0x8010000CL) +#define SCARD_E_UNKNOWN_CARD -2146435059l // (0x8010000DL) +#define SCARD_E_CANT_DISPOSE -2146435058l // (0x8010000EL) +#define SCARD_E_PROTO_MISMATCH -2146435057l // (0x8010000FL) +#define SCARD_E_NOT_READY -2146435056l // (0x80100010L) +#define SCARD_E_INVALID_VALUE -2146435055l // (0x80100011L) +#define SCARD_E_SYSTEM_CANCELLED -2146435054l // (0x80100012L) +#define SCARD_F_COMM_ERROR -2146435053l // (0x80100013L) +#define SCARD_F_UNKNOWN_ERROR -2146435052l // (0x80100014L) +#define SCARD_E_INVALID_ATR -2146435051l // (0x80100015L) +#define SCARD_E_NOT_TRANSACTED -2146435050l // (0x80100016L) +#define SCARD_E_READER_UNAVAILABLE -2146435049l // (0x80100017L) +#define SCARD_P_SHUTDOWN -2146435048l // (0x80100018L) +#define SCARD_E_PCI_TOO_SMALL -2146435047l // (0x80100019L) +#define SCARD_E_READER_UNSUPPORTED -2146435046l // (0x8010001AL) +#define SCARD_E_DUPLICATE_READER -2146435045l // (0x8010001BL) +#define SCARD_E_CARD_UNSUPPORTED -2146435044l // (0x8010001CL) +#define SCARD_E_NO_SERVICE -2146435043l // (0x8010001DL) +#define SCARD_E_SERVICE_STOPPED -2146435042l // (0x8010001EL) +#define SCARD_E_UNEXPECTED -2146435041l // (0x8010001FL) +#define SCARD_E_ICC_INSTALLATION -2146435040l // (0x80100020L) +#define SCARD_E_ICC_CREATEORDER -2146435039l // (0x80100021L) +#define SCARD_E_UNSUPPORTED_FEATURE -2146435038l // (0x80100022L) +#define SCARD_E_DIR_NOT_FOUND -2146435037l // (0x80100023L) +#define SCARD_E_FILE_NOT_FOUND -2146435036l // (0x80100024L) +#define SCARD_E_NO_DIR -2146435035l // (0x80100025L) +#define SCARD_E_NO_FILE -2146435034l // (0x80100026L) +#define SCARD_E_NO_ACCESS -2146435033l // (0x80100027L) +#define SCARD_E_WRITE_TOO_MANY -2146435032l // (0x80100028L) +#define SCARD_E_BAD_SEEK -2146435031l // (0x80100029L) +#define SCARD_E_INVALID_CHV -2146435030l // (0x8010002AL) +#define SCARD_E_UNKNOWN_RES_MNG -2146435029l // (0x8010002BL) +#define SCARD_E_NO_SUCH_CERTIFICATE -2146435028l // (0x8010002CL) +#define SCARD_E_CERTIFICATE_UNAVAILABLE -2146435027l // (0x8010002DL) +#define SCARD_E_NO_READERS_AVAILABLE -2146435026l // (0x8010002EL) +#define SCARD_E_COMM_DATA_LOST -2146435025l // (0x8010002FL) +#define SCARD_E_NO_KEY_CONTAINER -2146435024l // (0x80100030L) +#define SCARD_E_SERVER_TOO_BUSY -2146435023l // (0x80100031L) +#define SCARD_E_PIN_CACHE_EXPIRED -2146435022l // (0x80100032L) +#define SCARD_E_NO_PIN_CACHE -2146435021l // (0x80100033L) +#define SCARD_E_READ_ONLY_CARD -2146435020l // (0x80100034L) + +#define SCARD_W_UNSUPPORTED_CARD -2146434971l // (0x80100065L) +#define SCARD_W_UNRESPONSIVE_CARD -2146434970l // (0x80100066L) +#define SCARD_W_UNPOWERED_CARD -2146434969l // (0x80100067L) +#define SCARD_W_RESET_CARD -2146434968l // (0x80100068L) +#define SCARD_W_REMOVED_CARD -2146434967l // (0x80100069L) +#define SCARD_W_SECURITY_VIOLATION -2146434966l // (0x8010006AL) +#define SCARD_W_WRONG_CHV -2146434965l // (0x8010006BL) +#define SCARD_W_CHV_BLOCKED -2146434964l // (0x8010006CL) +#define SCARD_W_EOF -2146434963l // (0x8010006DL) +#define SCARD_W_CANCELLED_BY_USER -2146434962l // (0x8010006EL) +#define SCARD_W_CARD_NOT_AUTHENTICATED -2146434961l // (0x8010006FL) +#define SCARD_W_CACHE_ITEM_NOT_FOUND -2146434960l // (0x80100070L) +#define SCARD_W_CACHE_ITEM_STALE -2146434959l // (0x80100071L) +#define SCARD_W_CACHE_ITEM_TOO_BIG -2146434958l // (0x80100072L) + +#endif + +/* ------------------------ missing definition with mingw --------------------*/ +#ifndef SCARD_E_PIN_CACHE_EXPIRED +#define SCARD_E_PIN_CACHE_EXPIRED -2146435022l // (0x80100032L) +#endif + +#ifndef SCARD_E_NO_PIN_CACHE +#define SCARD_E_NO_PIN_CACHE -2146435021l // (0x80100033L) +#endif + +#ifndef SCARD_E_READ_ONLY_CARD +#define SCARD_E_READ_ONLY_CARD -2146435020l // (0x80100034L) +#endif + +#ifndef SCARD_W_CACHE_ITEM_TOO_BIG +#define SCARD_W_CACHE_ITEM_TOO_BIG -2146434958l // (0x80100072L) +#endif +/* -------------------------------------------------------------------------- */ + +#define SCARD_ATR_LENGTH 33 + +#define SCARD_PROTOCOL_UNDEFINED 0x00000000u +#define SCARD_PROTOCOL_T0 0x00000001u +#define SCARD_PROTOCOL_T1 0x00000002u +#define SCARD_PROTOCOL_RAW 0x00010000u + +#define SCARD_PROTOCOL_Tx (SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1) +#define SCARD_PROTOCOL_DEFAULT 0x80000000u +#define SCARD_PROTOCOL_OPTIMAL 0x00000000u + +#define SCARD_POWER_DOWN 0 +#define SCARD_COLD_RESET 1 +#define SCARD_WARM_RESET 2 + +#define SCARD_CTL_CODE(code) \ + CTL_CODE(FILE_DEVICE_SMARTCARD, (code), METHOD_BUFFERED, FILE_ANY_ACCESS) + +#define IOCTL_SMARTCARD_POWER SCARD_CTL_CODE(1) +#define IOCTL_SMARTCARD_GET_ATTRIBUTE SCARD_CTL_CODE(2) +#define IOCTL_SMARTCARD_SET_ATTRIBUTE SCARD_CTL_CODE(3) +#define IOCTL_SMARTCARD_CONFISCATE SCARD_CTL_CODE(4) +#define IOCTL_SMARTCARD_TRANSMIT SCARD_CTL_CODE(5) +#define IOCTL_SMARTCARD_EJECT SCARD_CTL_CODE(6) +#define IOCTL_SMARTCARD_SWALLOW SCARD_CTL_CODE(7) +#define IOCTL_SMARTCARD_IS_PRESENT SCARD_CTL_CODE(10) +#define IOCTL_SMARTCARD_IS_ABSENT SCARD_CTL_CODE(11) +#define IOCTL_SMARTCARD_SET_PROTOCOL SCARD_CTL_CODE(12) +#define IOCTL_SMARTCARD_GET_STATE SCARD_CTL_CODE(14) +#define IOCTL_SMARTCARD_GET_LAST_ERROR SCARD_CTL_CODE(15) +#define IOCTL_SMARTCARD_GET_PERF_CNTR SCARD_CTL_CODE(16) + +#define IOCTL_SMARTCARD_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400) + +#define MAXIMUM_ATTR_STRING_LENGTH 32 +#define MAXIMUM_SMARTCARD_READERS 10 + +#define SCARD_ATTR_VALUE(Class, Tag) ((((ULONG)(Class)) << 16) | ((ULONG)(Tag))) + +#define SCARD_CLASS_VENDOR_INFO 1 +#define SCARD_CLASS_COMMUNICATIONS 2 +#define SCARD_CLASS_PROTOCOL 3 +#define SCARD_CLASS_POWER_MGMT 4 +#define SCARD_CLASS_SECURITY 5 +#define SCARD_CLASS_MECHANICAL 6 +#define SCARD_CLASS_VENDOR_DEFINED 7 +#define SCARD_CLASS_IFD_PROTOCOL 8 +#define SCARD_CLASS_ICC_STATE 9 +#define SCARD_CLASS_PERF 0x7FFE +#define SCARD_CLASS_SYSTEM 0x7FFF + +#define SCARD_ATTR_VENDOR_NAME SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0100) +#define SCARD_ATTR_VENDOR_IFD_TYPE SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0101) +#define SCARD_ATTR_VENDOR_IFD_VERSION SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0102) +#define SCARD_ATTR_VENDOR_IFD_SERIAL_NO SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_INFO, 0x0103) +#define SCARD_ATTR_CHANNEL_ID SCARD_ATTR_VALUE(SCARD_CLASS_COMMUNICATIONS, 0x0110) +#define SCARD_ATTR_PROTOCOL_TYPES SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0120) +#define SCARD_ATTR_DEFAULT_CLK SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0121) +#define SCARD_ATTR_MAX_CLK SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0122) +#define SCARD_ATTR_DEFAULT_DATA_RATE SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0123) +#define SCARD_ATTR_MAX_DATA_RATE SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0124) +#define SCARD_ATTR_MAX_IFSD SCARD_ATTR_VALUE(SCARD_CLASS_PROTOCOL, 0x0125) +#define SCARD_ATTR_POWER_MGMT_SUPPORT SCARD_ATTR_VALUE(SCARD_CLASS_POWER_MGMT, 0x0131) +#define SCARD_ATTR_USER_TO_CARD_AUTH_DEVICE SCARD_ATTR_VALUE(SCARD_CLASS_SECURITY, 0x0140) +#define SCARD_ATTR_USER_AUTH_INPUT_DEVICE SCARD_ATTR_VALUE(SCARD_CLASS_SECURITY, 0x0142) +#define SCARD_ATTR_CHARACTERISTICS SCARD_ATTR_VALUE(SCARD_CLASS_MECHANICAL, 0x0150) + +#define SCARD_ATTR_CURRENT_PROTOCOL_TYPE SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0201) +#define SCARD_ATTR_CURRENT_CLK SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0202) +#define SCARD_ATTR_CURRENT_F SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0203) +#define SCARD_ATTR_CURRENT_D SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0204) +#define SCARD_ATTR_CURRENT_N SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0205) +#define SCARD_ATTR_CURRENT_W SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0206) +#define SCARD_ATTR_CURRENT_IFSC SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0207) +#define SCARD_ATTR_CURRENT_IFSD SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0208) +#define SCARD_ATTR_CURRENT_BWT SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x0209) +#define SCARD_ATTR_CURRENT_CWT SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x020a) +#define SCARD_ATTR_CURRENT_EBC_ENCODING SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x020b) +#define SCARD_ATTR_EXTENDED_BWT SCARD_ATTR_VALUE(SCARD_CLASS_IFD_PROTOCOL, 0x020c) + +#define SCARD_ATTR_ICC_PRESENCE SCARD_ATTR_VALUE(SCARD_CLASS_ICC_STATE, 0x0300) +#define SCARD_ATTR_ICC_INTERFACE_STATUS SCARD_ATTR_VALUE(SCARD_CLASS_ICC_STATE, 0x0301) +#define SCARD_ATTR_CURRENT_IO_STATE SCARD_ATTR_VALUE(SCARD_CLASS_ICC_STATE, 0x0302) +#define SCARD_ATTR_ATR_STRING SCARD_ATTR_VALUE(SCARD_CLASS_ICC_STATE, 0x0303) +#define SCARD_ATTR_ICC_TYPE_PER_ATR SCARD_ATTR_VALUE(SCARD_CLASS_ICC_STATE, 0x0304) + +#define SCARD_ATTR_ESC_RESET SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED, 0xA000) +#define SCARD_ATTR_ESC_CANCEL SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED, 0xA003) +#define SCARD_ATTR_ESC_AUTHREQUEST SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED, 0xA005) +#define SCARD_ATTR_MAXINPUT SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED, 0xA007) + +#define SCARD_ATTR_DEVICE_UNIT SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0001) +#define SCARD_ATTR_DEVICE_IN_USE SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0002) +#define SCARD_ATTR_DEVICE_FRIENDLY_NAME_A SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0003) +#define SCARD_ATTR_DEVICE_SYSTEM_NAME_A SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0004) +#define SCARD_ATTR_DEVICE_FRIENDLY_NAME_W SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0005) +#define SCARD_ATTR_DEVICE_SYSTEM_NAME_W SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0006) +#define SCARD_ATTR_SUPRESS_T1_IFS_REQUEST SCARD_ATTR_VALUE(SCARD_CLASS_SYSTEM, 0x0007) + +#define SCARD_PERF_NUM_TRANSMISSIONS SCARD_ATTR_VALUE(SCARD_CLASS_PERF, 0x0001) +#define SCARD_PERF_BYTES_TRANSMITTED SCARD_ATTR_VALUE(SCARD_CLASS_PERF, 0x0002) +#define SCARD_PERF_TRANSMISSION_TIME SCARD_ATTR_VALUE(SCARD_CLASS_PERF, 0x0003) + +#ifdef UNICODE +#define SCARD_ATTR_DEVICE_FRIENDLY_NAME SCARD_ATTR_DEVICE_FRIENDLY_NAME_W +#define SCARD_ATTR_DEVICE_SYSTEM_NAME SCARD_ATTR_DEVICE_SYSTEM_NAME_W +#else +#define SCARD_ATTR_DEVICE_FRIENDLY_NAME SCARD_ATTR_DEVICE_FRIENDLY_NAME_A +#define SCARD_ATTR_DEVICE_SYSTEM_NAME SCARD_ATTR_DEVICE_SYSTEM_NAME_A +#endif + +#define SCARD_T0_HEADER_LENGTH 7 +#define SCARD_T0_CMD_LENGTH 5 + +#define SCARD_T1_PROLOGUE_LENGTH 3 +#define SCARD_T1_EPILOGUE_LENGTH 2 +#define SCARD_T1_MAX_IFS 254 + +#define SCARD_UNKNOWN 0 +#define SCARD_ABSENT 1 +#define SCARD_PRESENT 2 +#define SCARD_SWALLOWED 3 +#define SCARD_POWERED 4 +#define SCARD_NEGOTIABLE 5 +#define SCARD_SPECIFIC 6 + +#pragma pack(push, 1) + +typedef struct +{ + DWORD dwProtocol; + DWORD cbPciLength; +} SCARD_IO_REQUEST, *PSCARD_IO_REQUEST, *LPSCARD_IO_REQUEST; +typedef const SCARD_IO_REQUEST* LPCSCARD_IO_REQUEST; + +typedef struct +{ + BYTE bCla, bIns, bP1, bP2, bP3; +} SCARD_T0_COMMAND, *LPSCARD_T0_COMMAND; + +typedef struct +{ + SCARD_IO_REQUEST ioRequest; + BYTE bSw1, bSw2; + union + { + SCARD_T0_COMMAND CmdBytes; + BYTE rgbHeader[5]; + } DUMMYUNIONNAME; +} SCARD_T0_REQUEST; + +typedef SCARD_T0_REQUEST *PSCARD_T0_REQUEST, *LPSCARD_T0_REQUEST; + +typedef struct +{ + SCARD_IO_REQUEST ioRequest; +} SCARD_T1_REQUEST; +typedef SCARD_T1_REQUEST *PSCARD_T1_REQUEST, *LPSCARD_T1_REQUEST; + +#define SCARD_READER_SWALLOWS 0x00000001 +#define SCARD_READER_EJECTS 0x00000002 +#define SCARD_READER_CONFISCATES 0x00000004 + +#define SCARD_READER_TYPE_SERIAL 0x01 +#define SCARD_READER_TYPE_PARALELL 0x02 +#define SCARD_READER_TYPE_KEYBOARD 0x04 +#define SCARD_READER_TYPE_SCSI 0x08 +#define SCARD_READER_TYPE_IDE 0x10 +#define SCARD_READER_TYPE_USB 0x20 +#define SCARD_READER_TYPE_PCMCIA 0x40 +#define SCARD_READER_TYPE_TPM 0x80 +#define SCARD_READER_TYPE_NFC 0x100 +#define SCARD_READER_TYPE_UICC 0x200 +#define SCARD_READER_TYPE_VENDOR 0xF0 + +#ifndef WINSCARDAPI +#define WINSCARDAPI WINPR_API +#endif + +typedef ULONG_PTR SCARDCONTEXT; +typedef SCARDCONTEXT *PSCARDCONTEXT, *LPSCARDCONTEXT; + +typedef ULONG_PTR SCARDHANDLE; +typedef SCARDHANDLE *PSCARDHANDLE, *LPSCARDHANDLE; + +#define SCARD_AUTOALLOCATE UINT32_MAX + +#define SCARD_SCOPE_USER 0 +#define SCARD_SCOPE_TERMINAL 1 +#define SCARD_SCOPE_SYSTEM 2 + +#define SCARD_STATE_UNAWARE 0x00000000 +#define SCARD_STATE_IGNORE 0x00000001 +#define SCARD_STATE_CHANGED 0x00000002 +#define SCARD_STATE_UNKNOWN 0x00000004 +#define SCARD_STATE_UNAVAILABLE 0x00000008 +#define SCARD_STATE_EMPTY 0x00000010 +#define SCARD_STATE_PRESENT 0x00000020 +#define SCARD_STATE_ATRMATCH 0x00000040 +#define SCARD_STATE_EXCLUSIVE 0x00000080 +#define SCARD_STATE_INUSE 0x00000100 +#define SCARD_STATE_MUTE 0x00000200 +#define SCARD_STATE_UNPOWERED 0x00000400 + +#define SCARD_SHARE_EXCLUSIVE 1 +#define SCARD_SHARE_SHARED 2 +#define SCARD_SHARE_DIRECT 3 + +#define SCARD_LEAVE_CARD 0 +#define SCARD_RESET_CARD 1 +#define SCARD_UNPOWER_CARD 2 +#define SCARD_EJECT_CARD 3 + +#define SC_DLG_MINIMAL_UI 0x01 +#define SC_DLG_NO_UI 0x02 +#define SC_DLG_FORCE_UI 0x04 + +#define SCERR_NOCARDNAME 0x4000 +#define SCERR_NOGUIDS 0x8000 + +typedef SCARDHANDLE(WINAPI* LPOCNCONNPROCA)(SCARDCONTEXT hSCardContext, LPSTR szReader, + LPSTR mszCards, PVOID pvUserData); +typedef SCARDHANDLE(WINAPI* LPOCNCONNPROCW)(SCARDCONTEXT hSCardContext, LPWSTR szReader, + LPWSTR mszCards, PVOID pvUserData); + +typedef BOOL(WINAPI* LPOCNCHKPROC)(SCARDCONTEXT hSCardContext, SCARDHANDLE hCard, PVOID pvUserData); +typedef void(WINAPI* LPOCNDSCPROC)(SCARDCONTEXT hSCardContext, SCARDHANDLE hCard, PVOID pvUserData); + +#define SCARD_READER_SEL_AUTH_PACKAGE ((DWORD)-629) + +#define SCARD_AUDIT_CHV_FAILURE 0x0 +#define SCARD_AUDIT_CHV_SUCCESS 0x1 + +#define SCardListCardTypes SCardListCards + +#define PCSCardIntroduceCardType(hContext, szCardName, pbAtr, pbAtrMask, cbAtrLen, \ + pguidPrimaryProvider, rgguidInterfaces, dwInterfaceCount) \ + SCardIntroduceCardType(hContext, szCardName, pguidPrimaryProvider, rgguidInterfaces, \ + dwInterfaceCount, pbAtr, pbAtrMask, cbAtrLen) + +#define SCardGetReaderCapabilities SCardGetAttrib +#define SCardSetReaderCapabilities SCardSetAttrib + +typedef struct +{ + LPSTR szReader; + LPVOID pvUserData; + DWORD dwCurrentState; + DWORD dwEventState; + DWORD cbAtr; + BYTE rgbAtr[36]; +} SCARD_READERSTATEA, *PSCARD_READERSTATEA, *LPSCARD_READERSTATEA; + +typedef struct +{ + LPWSTR szReader; + LPVOID pvUserData; + DWORD dwCurrentState; + DWORD dwEventState; + DWORD cbAtr; + BYTE rgbAtr[36]; +} SCARD_READERSTATEW, *PSCARD_READERSTATEW, *LPSCARD_READERSTATEW; + +typedef struct +{ + DWORD cbAtr; + BYTE rgbAtr[36]; + BYTE rgbMask[36]; +} SCARD_ATRMASK, *PSCARD_ATRMASK, *LPSCARD_ATRMASK; + +typedef struct +{ + DWORD dwStructSize; + LPSTR lpstrGroupNames; + DWORD nMaxGroupNames; + LPCGUID rgguidInterfaces; + DWORD cguidInterfaces; + LPSTR lpstrCardNames; + DWORD nMaxCardNames; + LPOCNCHKPROC lpfnCheck; + LPOCNCONNPROCA lpfnConnect; + LPOCNDSCPROC lpfnDisconnect; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; +} OPENCARD_SEARCH_CRITERIAA, *POPENCARD_SEARCH_CRITERIAA, *LPOPENCARD_SEARCH_CRITERIAA; + +typedef struct +{ + DWORD dwStructSize; + LPWSTR lpstrGroupNames; + DWORD nMaxGroupNames; + LPCGUID rgguidInterfaces; + DWORD cguidInterfaces; + LPWSTR lpstrCardNames; + DWORD nMaxCardNames; + LPOCNCHKPROC lpfnCheck; + LPOCNCONNPROCW lpfnConnect; + LPOCNDSCPROC lpfnDisconnect; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; +} OPENCARD_SEARCH_CRITERIAW, *POPENCARD_SEARCH_CRITERIAW, *LPOPENCARD_SEARCH_CRITERIAW; + +typedef struct +{ + DWORD dwStructSize; + SCARDCONTEXT hSCardContext; + HWND hwndOwner; + DWORD dwFlags; + LPCSTR lpstrTitle; + LPCSTR lpstrSearchDesc; + HICON hIcon; + POPENCARD_SEARCH_CRITERIAA pOpenCardSearchCriteria; + LPOCNCONNPROCA lpfnConnect; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; + LPSTR lpstrRdr; + DWORD nMaxRdr; + LPSTR lpstrCard; + DWORD nMaxCard; + DWORD dwActiveProtocol; + SCARDHANDLE hCardHandle; +} OPENCARDNAME_EXA, *POPENCARDNAME_EXA, *LPOPENCARDNAME_EXA; + +typedef struct +{ + DWORD dwStructSize; + SCARDCONTEXT hSCardContext; + HWND hwndOwner; + DWORD dwFlags; + LPCWSTR lpstrTitle; + LPCWSTR lpstrSearchDesc; + HICON hIcon; + POPENCARD_SEARCH_CRITERIAW pOpenCardSearchCriteria; + LPOCNCONNPROCW lpfnConnect; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; + LPWSTR lpstrRdr; + DWORD nMaxRdr; + LPWSTR lpstrCard; + DWORD nMaxCard; + DWORD dwActiveProtocol; + SCARDHANDLE hCardHandle; +} OPENCARDNAME_EXW, *POPENCARDNAME_EXW, *LPOPENCARDNAME_EXW; + +#define OPENCARDNAMEA_EX OPENCARDNAME_EXA +#define OPENCARDNAMEW_EX OPENCARDNAME_EXW +#define POPENCARDNAMEA_EX POPENCARDNAME_EXA +#define POPENCARDNAMEW_EX POPENCARDNAME_EXW +#define LPOPENCARDNAMEA_EX LPOPENCARDNAME_EXA +#define LPOPENCARDNAMEW_EX LPOPENCARDNAME_EXW + +typedef enum +{ + RSR_MATCH_TYPE_READER_AND_CONTAINER = 1, + RSR_MATCH_TYPE_SERIAL_NUMBER, + RSR_MATCH_TYPE_ALL_CARDS +} READER_SEL_REQUEST_MATCH_TYPE; + +typedef struct +{ + DWORD dwShareMode; + DWORD dwPreferredProtocols; + READER_SEL_REQUEST_MATCH_TYPE MatchType; + union + { + struct + { + DWORD cbReaderNameOffset; + DWORD cchReaderNameLength; + DWORD cbContainerNameOffset; + DWORD cchContainerNameLength; + DWORD dwDesiredCardModuleVersion; + DWORD dwCspFlags; + } ReaderAndContainerParameter; + struct + { + DWORD cbSerialNumberOffset; + DWORD cbSerialNumberLength; + DWORD dwDesiredCardModuleVersion; + } SerialNumberParameter; + }; +} READER_SEL_REQUEST, *PREADER_SEL_REQUEST; + +typedef struct +{ + DWORD cbReaderNameOffset; + DWORD cchReaderNameLength; + DWORD cbCardNameOffset; + DWORD cchCardNameLength; +} READER_SEL_RESPONSE, *PREADER_SEL_RESPONSE; + +typedef struct +{ + DWORD dwStructSize; + HWND hwndOwner; + SCARDCONTEXT hSCardContext; + LPSTR lpstrGroupNames; + DWORD nMaxGroupNames; + LPSTR lpstrCardNames; + DWORD nMaxCardNames; + LPCGUID rgguidInterfaces; + DWORD cguidInterfaces; + LPSTR lpstrRdr; + DWORD nMaxRdr; + LPSTR lpstrCard; + DWORD nMaxCard; + LPCSTR lpstrTitle; + DWORD dwFlags; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; + DWORD dwActiveProtocol; + LPOCNCONNPROCA lpfnConnect; + LPOCNCHKPROC lpfnCheck; + LPOCNDSCPROC lpfnDisconnect; + SCARDHANDLE hCardHandle; +} OPENCARDNAMEA, *POPENCARDNAMEA, *LPOPENCARDNAMEA; + +typedef struct +{ + DWORD dwStructSize; + HWND hwndOwner; + SCARDCONTEXT hSCardContext; + LPWSTR lpstrGroupNames; + DWORD nMaxGroupNames; + LPWSTR lpstrCardNames; + DWORD nMaxCardNames; + LPCGUID rgguidInterfaces; + DWORD cguidInterfaces; + LPWSTR lpstrRdr; + DWORD nMaxRdr; + LPWSTR lpstrCard; + DWORD nMaxCard; + LPCWSTR lpstrTitle; + DWORD dwFlags; + LPVOID pvUserData; + DWORD dwShareMode; + DWORD dwPreferredProtocols; + DWORD dwActiveProtocol; + LPOCNCONNPROCW lpfnConnect; + LPOCNCHKPROC lpfnCheck; + LPOCNDSCPROC lpfnDisconnect; + SCARDHANDLE hCardHandle; +} OPENCARDNAMEW, *POPENCARDNAMEW, *LPOPENCARDNAMEW; + +#pragma pack(pop) + +#ifdef UNICODE +#define LPOCNCONNPROC LPOCNCONNPROCW +#define SCARD_READERSTATE SCARD_READERSTATEW +#define PSCARD_READERSTATE PSCARD_READERSTATEW +#define LPSCARD_READERSTATE LPSCARD_READERSTATEW +#define OPENCARD_SEARCH_CRITERIA OPENCARD_SEARCH_CRITERIAW +#define LOPENCARD_SEARCH_CRITERIA LOPENCARD_SEARCH_CRITERIAW +#define LPOPENCARD_SEARCH_CRITERIA LPOPENCARD_SEARCH_CRITERIAW +#define OPENCARDNAME_EX OPENCARDNAME_EXW +#define LOPENCARDNAME_EX LOPENCARDNAME_EXW +#define LPOPENCARDNAME_EX LPOPENCARDNAME_EXW +#define OPENCARDNAME OPENCARDNAMEW +#define LOPENCARDNAME LOPENCARDNAMEW +#define LPOPENCARDNAME LPOPENCARDNAMEW +#else +#define LPOCNCONNPROC LPOCNCONNPROCA +#define SCARD_READERSTATE SCARD_READERSTATEA +#define PSCARD_READERSTATE PSCARD_READERSTATEA +#define LPSCARD_READERSTATE LPSCARD_READERSTATEA +#define OPENCARD_SEARCH_CRITERIA OPENCARD_SEARCH_CRITERIAA +#define LOPENCARD_SEARCH_CRITERIA LOPENCARD_SEARCH_CRITERIAA +#define LPOPENCARD_SEARCH_CRITERIA LPOPENCARD_SEARCH_CRITERIAA +#define OPENCARDNAME_EX OPENCARDNAME_EXA +#define LOPENCARDNAME_EX LOPENCARDNAME_EXA +#define LPOPENCARDNAME_EX LPOPENCARDNAME_EXA +#define OPENCARDNAME OPENCARDNAMEA +#define LOPENCARDNAME LOPENCARDNAMEA +#define LPOPENCARDNAME LPOPENCARDNAMEA +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API extern const SCARD_IO_REQUEST g_rgSCardT0Pci; + WINPR_API extern const SCARD_IO_REQUEST g_rgSCardT1Pci; + WINPR_API extern const SCARD_IO_REQUEST g_rgSCardRawPci; + +#define SCARD_PCI_T0 (&g_rgSCardT0Pci) +#define SCARD_PCI_T1 (&g_rgSCardT1Pci) +#define SCARD_PCI_RAW (&g_rgSCardRawPci) + + WINSCARDAPI LONG WINAPI SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext); + + WINSCARDAPI LONG WINAPI SCardReleaseContext(SCARDCONTEXT hContext); + + WINSCARDAPI LONG WINAPI SCardIsValidContext(SCARDCONTEXT hContext); + + WINSCARDAPI LONG WINAPI SCardListReaderGroupsA(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups); + WINSCARDAPI LONG WINAPI SCardListReaderGroupsW(SCARDCONTEXT hContext, LPWSTR mszGroups, + LPDWORD pcchGroups); + + WINSCARDAPI LONG WINAPI SCardListReadersA(SCARDCONTEXT hContext, LPCSTR mszGroups, + LPSTR mszReaders, LPDWORD pcchReaders); + WINSCARDAPI LONG WINAPI SCardListReadersW(SCARDCONTEXT hContext, LPCWSTR mszGroups, + LPWSTR mszReaders, LPDWORD pcchReaders); + + WINSCARDAPI LONG WINAPI SCardListCardsA(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + CHAR* mszCards, LPDWORD pcchCards); + + WINSCARDAPI LONG WINAPI SCardListCardsW(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + WCHAR* mszCards, LPDWORD pcchCards); + + WINSCARDAPI LONG WINAPI SCardListInterfacesA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces); + WINSCARDAPI LONG WINAPI SCardListInterfacesW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces); + + WINSCARDAPI LONG WINAPI SCardGetProviderIdA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidProviderId); + WINSCARDAPI LONG WINAPI SCardGetProviderIdW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidProviderId); + + WINSCARDAPI LONG WINAPI SCardGetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, CHAR* szProvider, + LPDWORD pcchProvider); + WINSCARDAPI LONG WINAPI SCardGetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, WCHAR* szProvider, + LPDWORD pcchProvider); + + WINSCARDAPI LONG WINAPI SCardIntroduceReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName); + WINSCARDAPI LONG WINAPI SCardIntroduceReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName); + + WINSCARDAPI LONG WINAPI SCardForgetReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName); + WINSCARDAPI LONG WINAPI SCardForgetReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName); + + WINSCARDAPI LONG WINAPI SCardIntroduceReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szDeviceName); + WINSCARDAPI LONG WINAPI SCardIntroduceReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szDeviceName); + + WINSCARDAPI LONG WINAPI SCardForgetReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName); + WINSCARDAPI LONG WINAPI SCardForgetReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName); + + WINSCARDAPI LONG WINAPI SCardAddReaderToGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName); + WINSCARDAPI LONG WINAPI SCardAddReaderToGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName); + + WINSCARDAPI LONG WINAPI SCardRemoveReaderFromGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName); + WINSCARDAPI LONG WINAPI SCardRemoveReaderFromGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName); + + WINSCARDAPI LONG WINAPI SCardIntroduceCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, + DWORD dwInterfaceCount, LPCBYTE pbAtr, + LPCBYTE pbAtrMask, DWORD cbAtrLen); + WINSCARDAPI LONG WINAPI SCardIntroduceCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, + DWORD dwInterfaceCount, LPCBYTE pbAtr, + LPCBYTE pbAtrMask, DWORD cbAtrLen); + + WINSCARDAPI LONG WINAPI SCardSetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, LPCSTR szProvider); + WINSCARDAPI LONG WINAPI SCardSetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, LPCWSTR szProvider); + + WINSCARDAPI LONG WINAPI SCardForgetCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName); + WINSCARDAPI LONG WINAPI SCardForgetCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName); + + WINSCARDAPI LONG WINAPI SCardFreeMemory(SCARDCONTEXT hContext, LPVOID pvMem); + + WINSCARDAPI HANDLE WINAPI SCardAccessStartedEvent(void); + + WINSCARDAPI void WINAPI SCardReleaseStartedEvent(void); + + WINSCARDAPI LONG WINAPI SCardLocateCardsA(SCARDCONTEXT hContext, LPCSTR mszCards, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders); + WINSCARDAPI LONG WINAPI SCardLocateCardsW(SCARDCONTEXT hContext, LPCWSTR mszCards, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders); + + WINSCARDAPI LONG WINAPI SCardLocateCardsByATRA(SCARDCONTEXT hContext, + LPSCARD_ATRMASK rgAtrMasks, DWORD cAtrs, + LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders); + WINSCARDAPI LONG WINAPI SCardLocateCardsByATRW(SCARDCONTEXT hContext, + LPSCARD_ATRMASK rgAtrMasks, DWORD cAtrs, + LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders); + + WINSCARDAPI LONG WINAPI SCardGetStatusChangeA(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders); + WINSCARDAPI LONG WINAPI SCardGetStatusChangeW(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders); + + WINSCARDAPI LONG WINAPI SCardCancel(SCARDCONTEXT hContext); + + WINSCARDAPI LONG WINAPI SCardConnectA(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol); + WINSCARDAPI LONG WINAPI SCardConnectW(SCARDCONTEXT hContext, LPCWSTR szReader, + DWORD dwShareMode, DWORD dwPreferredProtocols, + LPSCARDHANDLE phCard, LPDWORD pdwActiveProtocol); + + WINSCARDAPI LONG WINAPI SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode, + DWORD dwPreferredProtocols, DWORD dwInitialization, + LPDWORD pdwActiveProtocol); + + WINSCARDAPI LONG WINAPI SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition); + + WINSCARDAPI LONG WINAPI SCardBeginTransaction(SCARDHANDLE hCard); + + WINSCARDAPI LONG WINAPI SCardEndTransaction(SCARDHANDLE hCard, DWORD dwDisposition); + + WINSCARDAPI LONG WINAPI SCardCancelTransaction(SCARDHANDLE hCard); + + WINSCARDAPI LONG WINAPI SCardState(SCARDHANDLE hCard, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen); + + WINSCARDAPI LONG WINAPI SCardStatusA(SCARDHANDLE hCard, LPSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, + LPDWORD pdwProtocol, LPBYTE pbAtr, LPDWORD pcbAtrLen); + WINSCARDAPI LONG WINAPI SCardStatusW(SCARDHANDLE hCard, LPWSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, + LPDWORD pdwProtocol, LPBYTE pbAtr, LPDWORD pcbAtrLen); + + WINSCARDAPI LONG WINAPI SCardTransmit(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, + LPCBYTE pbSendBuffer, DWORD cbSendLength, + LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, + LPDWORD pcbRecvLength); + + WINSCARDAPI LONG WINAPI SCardGetTransmitCount(SCARDHANDLE hCard, LPDWORD pcTransmitCount); + + WINSCARDAPI LONG WINAPI SCardControl(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID lpInBuffer, + DWORD cbInBufferSize, LPVOID lpOutBuffer, + DWORD cbOutBufferSize, LPDWORD lpBytesReturned); + + WINSCARDAPI LONG WINAPI SCardGetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen); + + WINSCARDAPI LONG WINAPI SCardSetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr, + DWORD cbAttrLen); + + WINSCARDAPI LONG WINAPI SCardUIDlgSelectCardA(LPOPENCARDNAMEA_EX pDlgStruc); + WINSCARDAPI LONG WINAPI SCardUIDlgSelectCardW(LPOPENCARDNAMEW_EX pDlgStruc); + + WINSCARDAPI LONG WINAPI GetOpenCardNameA(LPOPENCARDNAMEA pDlgStruc); + WINSCARDAPI LONG WINAPI GetOpenCardNameW(LPOPENCARDNAMEW pDlgStruc); + + WINSCARDAPI LONG WINAPI SCardDlgExtendedError(void); + + WINSCARDAPI LONG WINAPI SCardReadCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD* DataLen); + WINSCARDAPI LONG WINAPI SCardReadCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD* DataLen); + + WINSCARDAPI LONG WINAPI SCardWriteCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD DataLen); + WINSCARDAPI LONG WINAPI SCardWriteCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD DataLen); + + WINSCARDAPI LONG WINAPI SCardGetReaderIconA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon); + WINSCARDAPI LONG WINAPI SCardGetReaderIconW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon); + + WINSCARDAPI LONG WINAPI SCardGetDeviceTypeIdA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPDWORD pdwDeviceTypeId); + WINSCARDAPI LONG WINAPI SCardGetDeviceTypeIdW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPDWORD pdwDeviceTypeId); + + WINSCARDAPI LONG WINAPI SCardGetReaderDeviceInstanceIdA(SCARDCONTEXT hContext, + LPCSTR szReaderName, + LPSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId); + WINSCARDAPI LONG WINAPI SCardGetReaderDeviceInstanceIdW(SCARDCONTEXT hContext, + LPCWSTR szReaderName, + LPWSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId); + + WINSCARDAPI LONG WINAPI SCardListReadersWithDeviceInstanceIdA(SCARDCONTEXT hContext, + LPCSTR szDeviceInstanceId, + LPSTR mszReaders, + LPDWORD pcchReaders); + WINSCARDAPI LONG WINAPI SCardListReadersWithDeviceInstanceIdW(SCARDCONTEXT hContext, + LPCWSTR szDeviceInstanceId, + LPWSTR mszReaders, + LPDWORD pcchReaders); + + WINSCARDAPI LONG WINAPI SCardAudit(SCARDCONTEXT hContext, DWORD dwEvent); + +#ifdef UNICODE +#define SCardListReaderGroups SCardListReaderGroupsW +#define SCardListReaders SCardListReadersW +#define SCardListCards SCardListCardsW +#define SCardListInterfaces SCardListInterfacesW +#define SCardGetProviderId SCardGetProviderIdW +#define SCardGetCardTypeProviderName SCardGetCardTypeProviderNameW +#define SCardIntroduceReaderGroup SCardIntroduceReaderGroupW +#define SCardForgetReaderGroup SCardForgetReaderGroupW +#define SCardIntroduceReader SCardIntroduceReaderW +#define SCardForgetReader SCardForgetReaderW +#define SCardAddReaderToGroup SCardAddReaderToGroupW +#define SCardRemoveReaderFromGroup SCardRemoveReaderFromGroupW +#define SCardIntroduceCardType SCardIntroduceCardTypeW +#define SCardSetCardTypeProviderName SCardSetCardTypeProviderNameW +#define SCardForgetCardType SCardForgetCardTypeW +#define SCardLocateCards SCardLocateCardsW +#define SCardLocateCardsByATR SCardLocateCardsByATRW +#define SCardGetStatusChange SCardGetStatusChangeW +#define SCardConnect SCardConnectW +#define SCardStatus SCardStatusW +#define SCardUIDlgSelectCard SCardUIDlgSelectCardW +#define GetOpenCardName GetOpenCardNameW +#define SCardReadCache SCardReadCacheW +#define SCardWriteCache SCardWriteCacheW +#define SCardGetReaderIcon SCardGetReaderIconW +#define SCardGetDeviceTypeId SCardGetDeviceTypeIdW +#define SCardGetReaderDeviceInstanceId SCardGetReaderDeviceInstanceIdW +#define SCardListReadersWithDeviceInstanceId SCardListReadersWithDeviceInstanceIdW +#else +#define SCardListReaderGroups SCardListReaderGroupsA +#define SCardListReaders SCardListReadersA +#define SCardListCards SCardListCardsA +#define SCardListInterfaces SCardListInterfacesA +#define SCardGetProviderId SCardGetProviderIdA +#define SCardGetCardTypeProviderName SCardGetCardTypeProviderNameA +#define SCardIntroduceReaderGroup SCardIntroduceReaderGroupA +#define SCardForgetReaderGroup SCardForgetReaderGroupA +#define SCardIntroduceReader SCardIntroduceReaderA +#define SCardForgetReader SCardForgetReaderA +#define SCardAddReaderToGroup SCardAddReaderToGroupA +#define SCardRemoveReaderFromGroup SCardRemoveReaderFromGroupA +#define SCardIntroduceCardType SCardIntroduceCardTypeA +#define SCardSetCardTypeProviderName SCardSetCardTypeProviderNameA +#define SCardForgetCardType SCardForgetCardTypeA +#define SCardLocateCards SCardLocateCardsA +#define SCardLocateCardsByATR SCardLocateCardsByATRA +#define SCardGetStatusChange SCardGetStatusChangeA +#define SCardConnect SCardConnectA +#define SCardStatus SCardStatusA +#define SCardUIDlgSelectCard SCardUIDlgSelectCardA +#define GetOpenCardName GetOpenCardNameA +#define SCardReadCache SCardReadCacheA +#define SCardWriteCache SCardWriteCacheA +#define SCardGetReaderIcon SCardGetReaderIconA +#define SCardGetDeviceTypeId SCardGetDeviceTypeIdA +#define SCardGetReaderDeviceInstanceId SCardGetReaderDeviceInstanceIdA +#define SCardListReadersWithDeviceInstanceId SCardListReadersWithDeviceInstanceIdA +#endif + +#ifdef __cplusplus +} +#endif + +/** + * Extended API + */ + +typedef LONG(WINAPI* fnSCardEstablishContext)(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext); + +typedef LONG(WINAPI* fnSCardReleaseContext)(SCARDCONTEXT hContext); + +typedef LONG(WINAPI* fnSCardIsValidContext)(SCARDCONTEXT hContext); + +typedef LONG(WINAPI* fnSCardListReaderGroupsA)(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups); +typedef LONG(WINAPI* fnSCardListReaderGroupsW)(SCARDCONTEXT hContext, LPWSTR mszGroups, + LPDWORD pcchGroups); + +typedef LONG(WINAPI* fnSCardListReadersA)(SCARDCONTEXT hContext, LPCSTR mszGroups, LPSTR mszReaders, + LPDWORD pcchReaders); +typedef LONG(WINAPI* fnSCardListReadersW)(SCARDCONTEXT hContext, LPCWSTR mszGroups, + LPWSTR mszReaders, LPDWORD pcchReaders); + +typedef LONG(WINAPI* fnSCardListCardsA)(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + CHAR* mszCards, LPDWORD pcchCards); + +typedef LONG(WINAPI* fnSCardListCardsW)(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + WCHAR* mszCards, LPDWORD pcchCards); + +typedef LONG(WINAPI* fnSCardListInterfacesA)(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces); +typedef LONG(WINAPI* fnSCardListInterfacesW)(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces); + +typedef LONG(WINAPI* fnSCardGetProviderIdA)(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidProviderId); +typedef LONG(WINAPI* fnSCardGetProviderIdW)(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidProviderId); + +typedef LONG(WINAPI* fnSCardGetCardTypeProviderNameA)(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, CHAR* szProvider, + LPDWORD pcchProvider); +typedef LONG(WINAPI* fnSCardGetCardTypeProviderNameW)(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, WCHAR* szProvider, + LPDWORD pcchProvider); + +typedef LONG(WINAPI* fnSCardIntroduceReaderGroupA)(SCARDCONTEXT hContext, LPCSTR szGroupName); +typedef LONG(WINAPI* fnSCardIntroduceReaderGroupW)(SCARDCONTEXT hContext, LPCWSTR szGroupName); + +typedef LONG(WINAPI* fnSCardForgetReaderGroupA)(SCARDCONTEXT hContext, LPCSTR szGroupName); +typedef LONG(WINAPI* fnSCardForgetReaderGroupW)(SCARDCONTEXT hContext, LPCWSTR szGroupName); + +typedef LONG(WINAPI* fnSCardIntroduceReaderA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szDeviceName); +typedef LONG(WINAPI* fnSCardIntroduceReaderW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szDeviceName); + +typedef LONG(WINAPI* fnSCardForgetReaderA)(SCARDCONTEXT hContext, LPCSTR szReaderName); +typedef LONG(WINAPI* fnSCardForgetReaderW)(SCARDCONTEXT hContext, LPCWSTR szReaderName); + +typedef LONG(WINAPI* fnSCardAddReaderToGroupA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName); +typedef LONG(WINAPI* fnSCardAddReaderToGroupW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName); + +typedef LONG(WINAPI* fnSCardRemoveReaderFromGroupA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName); +typedef LONG(WINAPI* fnSCardRemoveReaderFromGroupW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName); + +typedef LONG(WINAPI* fnSCardIntroduceCardTypeA)(SCARDCONTEXT hContext, LPCSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen); +typedef LONG(WINAPI* fnSCardIntroduceCardTypeW)(SCARDCONTEXT hContext, LPCWSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen); + +typedef LONG(WINAPI* fnSCardSetCardTypeProviderNameA)(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, LPCSTR szProvider); +typedef LONG(WINAPI* fnSCardSetCardTypeProviderNameW)(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, LPCWSTR szProvider); + +typedef LONG(WINAPI* fnSCardForgetCardTypeA)(SCARDCONTEXT hContext, LPCSTR szCardName); +typedef LONG(WINAPI* fnSCardForgetCardTypeW)(SCARDCONTEXT hContext, LPCWSTR szCardName); + +typedef LONG(WINAPI* fnSCardFreeMemory)(SCARDCONTEXT hContext, LPVOID pvMem); + +typedef HANDLE(WINAPI* fnSCardAccessStartedEvent)(void); + +typedef void(WINAPI* fnSCardReleaseStartedEvent)(void); + +typedef LONG(WINAPI* fnSCardLocateCardsA)(SCARDCONTEXT hContext, LPCSTR mszCards, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders); +typedef LONG(WINAPI* fnSCardLocateCardsW)(SCARDCONTEXT hContext, LPCWSTR mszCards, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders); + +typedef LONG(WINAPI* fnSCardLocateCardsByATRA)(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders); +typedef LONG(WINAPI* fnSCardLocateCardsByATRW)(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders); + +typedef LONG(WINAPI* fnSCardGetStatusChangeA)(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders); +typedef LONG(WINAPI* fnSCardGetStatusChangeW)(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders); + +typedef LONG(WINAPI* fnSCardCancel)(SCARDCONTEXT hContext); + +typedef LONG(WINAPI* fnSCardConnectA)(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol); +typedef LONG(WINAPI* fnSCardConnectW)(SCARDCONTEXT hContext, LPCWSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol); + +typedef LONG(WINAPI* fnSCardReconnect)(SCARDHANDLE hCard, DWORD dwShareMode, + DWORD dwPreferredProtocols, DWORD dwInitialization, + LPDWORD pdwActiveProtocol); + +typedef LONG(WINAPI* fnSCardDisconnect)(SCARDHANDLE hCard, DWORD dwDisposition); + +typedef LONG(WINAPI* fnSCardBeginTransaction)(SCARDHANDLE hCard); + +typedef LONG(WINAPI* fnSCardEndTransaction)(SCARDHANDLE hCard, DWORD dwDisposition); + +typedef LONG(WINAPI* fnSCardCancelTransaction)(SCARDHANDLE hCard); + +typedef LONG(WINAPI* fnSCardState)(SCARDHANDLE hCard, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen); + +typedef LONG(WINAPI* fnSCardStatusA)(SCARDHANDLE hCard, LPSTR mszReaderNames, LPDWORD pcchReaderLen, + LPDWORD pdwState, LPDWORD pdwProtocol, LPBYTE pbAtr, + LPDWORD pcbAtrLen); +typedef LONG(WINAPI* fnSCardStatusW)(SCARDHANDLE hCard, LPWSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen); + +typedef LONG(WINAPI* fnSCardTransmit)(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, + LPCBYTE pbSendBuffer, DWORD cbSendLength, + LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, + LPDWORD pcbRecvLength); + +typedef LONG(WINAPI* fnSCardGetTransmitCount)(SCARDHANDLE hCard, LPDWORD pcTransmitCount); + +typedef LONG(WINAPI* fnSCardControl)(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID lpInBuffer, + DWORD cbInBufferSize, LPVOID lpOutBuffer, + DWORD cbOutBufferSize, LPDWORD lpBytesReturned); + +typedef LONG(WINAPI* fnSCardGetAttrib)(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen); + +typedef LONG(WINAPI* fnSCardSetAttrib)(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr, + DWORD cbAttrLen); + +typedef LONG(WINAPI* fnSCardUIDlgSelectCardA)(LPOPENCARDNAMEA_EX pDlgStruc); +typedef LONG(WINAPI* fnSCardUIDlgSelectCardW)(LPOPENCARDNAMEW_EX pDlgStruc); + +typedef LONG(WINAPI* fnGetOpenCardNameA)(LPOPENCARDNAMEA pDlgStruc); +typedef LONG(WINAPI* fnGetOpenCardNameW)(LPOPENCARDNAMEW pDlgStruc); + +typedef LONG(WINAPI* fnSCardDlgExtendedError)(void); + +typedef LONG(WINAPI* fnSCardReadCacheA)(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD* DataLen); +typedef LONG(WINAPI* fnSCardReadCacheW)(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD* DataLen); + +typedef LONG(WINAPI* fnSCardWriteCacheA)(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD DataLen); +typedef LONG(WINAPI* fnSCardWriteCacheW)(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD DataLen); + +typedef LONG(WINAPI* fnSCardGetReaderIconA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon); +typedef LONG(WINAPI* fnSCardGetReaderIconW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon); + +typedef LONG(WINAPI* fnSCardGetDeviceTypeIdA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPDWORD pdwDeviceTypeId); +typedef LONG(WINAPI* fnSCardGetDeviceTypeIdW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPDWORD pdwDeviceTypeId); + +typedef LONG(WINAPI* fnSCardGetReaderDeviceInstanceIdA)(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId); +typedef LONG(WINAPI* fnSCardGetReaderDeviceInstanceIdW)(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPWSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId); + +typedef LONG(WINAPI* fnSCardListReadersWithDeviceInstanceIdA)(SCARDCONTEXT hContext, + LPCSTR szDeviceInstanceId, + LPSTR mszReaders, + LPDWORD pcchReaders); +typedef LONG(WINAPI* fnSCardListReadersWithDeviceInstanceIdW)(SCARDCONTEXT hContext, + LPCWSTR szDeviceInstanceId, + LPWSTR mszReaders, + LPDWORD pcchReaders); + +typedef LONG(WINAPI* fnSCardAudit)(SCARDCONTEXT hContext, DWORD dwEvent); + +typedef struct +{ + DWORD dwVersion; + DWORD dwFlags; + + fnSCardEstablishContext pfnSCardEstablishContext; + fnSCardReleaseContext pfnSCardReleaseContext; + fnSCardIsValidContext pfnSCardIsValidContext; + fnSCardListReaderGroupsA pfnSCardListReaderGroupsA; + fnSCardListReaderGroupsW pfnSCardListReaderGroupsW; + fnSCardListReadersA pfnSCardListReadersA; + fnSCardListReadersW pfnSCardListReadersW; + fnSCardListCardsA pfnSCardListCardsA; + fnSCardListCardsW pfnSCardListCardsW; + fnSCardListInterfacesA pfnSCardListInterfacesA; + fnSCardListInterfacesW pfnSCardListInterfacesW; + fnSCardGetProviderIdA pfnSCardGetProviderIdA; + fnSCardGetProviderIdW pfnSCardGetProviderIdW; + fnSCardGetCardTypeProviderNameA pfnSCardGetCardTypeProviderNameA; + fnSCardGetCardTypeProviderNameW pfnSCardGetCardTypeProviderNameW; + fnSCardIntroduceReaderGroupA pfnSCardIntroduceReaderGroupA; + fnSCardIntroduceReaderGroupW pfnSCardIntroduceReaderGroupW; + fnSCardForgetReaderGroupA pfnSCardForgetReaderGroupA; + fnSCardForgetReaderGroupW pfnSCardForgetReaderGroupW; + fnSCardIntroduceReaderA pfnSCardIntroduceReaderA; + fnSCardIntroduceReaderW pfnSCardIntroduceReaderW; + fnSCardForgetReaderA pfnSCardForgetReaderA; + fnSCardForgetReaderW pfnSCardForgetReaderW; + fnSCardAddReaderToGroupA pfnSCardAddReaderToGroupA; + fnSCardAddReaderToGroupW pfnSCardAddReaderToGroupW; + fnSCardRemoveReaderFromGroupA pfnSCardRemoveReaderFromGroupA; + fnSCardRemoveReaderFromGroupW pfnSCardRemoveReaderFromGroupW; + fnSCardIntroduceCardTypeA pfnSCardIntroduceCardTypeA; + fnSCardIntroduceCardTypeW pfnSCardIntroduceCardTypeW; + fnSCardSetCardTypeProviderNameA pfnSCardSetCardTypeProviderNameA; + fnSCardSetCardTypeProviderNameW pfnSCardSetCardTypeProviderNameW; + fnSCardForgetCardTypeA pfnSCardForgetCardTypeA; + fnSCardForgetCardTypeW pfnSCardForgetCardTypeW; + fnSCardFreeMemory pfnSCardFreeMemory; + fnSCardAccessStartedEvent pfnSCardAccessStartedEvent; + fnSCardReleaseStartedEvent pfnSCardReleaseStartedEvent; + fnSCardLocateCardsA pfnSCardLocateCardsA; + fnSCardLocateCardsW pfnSCardLocateCardsW; + fnSCardLocateCardsByATRA pfnSCardLocateCardsByATRA; + fnSCardLocateCardsByATRW pfnSCardLocateCardsByATRW; + fnSCardGetStatusChangeA pfnSCardGetStatusChangeA; + fnSCardGetStatusChangeW pfnSCardGetStatusChangeW; + fnSCardCancel pfnSCardCancel; + fnSCardConnectA pfnSCardConnectA; + fnSCardConnectW pfnSCardConnectW; + fnSCardReconnect pfnSCardReconnect; + fnSCardDisconnect pfnSCardDisconnect; + fnSCardBeginTransaction pfnSCardBeginTransaction; + fnSCardEndTransaction pfnSCardEndTransaction; + fnSCardCancelTransaction pfnSCardCancelTransaction; + fnSCardState pfnSCardState; + fnSCardStatusA pfnSCardStatusA; + fnSCardStatusW pfnSCardStatusW; + fnSCardTransmit pfnSCardTransmit; + fnSCardGetTransmitCount pfnSCardGetTransmitCount; + fnSCardControl pfnSCardControl; + fnSCardGetAttrib pfnSCardGetAttrib; + fnSCardSetAttrib pfnSCardSetAttrib; + fnSCardUIDlgSelectCardA pfnSCardUIDlgSelectCardA; + fnSCardUIDlgSelectCardW pfnSCardUIDlgSelectCardW; + fnGetOpenCardNameA pfnGetOpenCardNameA; + fnGetOpenCardNameW pfnGetOpenCardNameW; + fnSCardDlgExtendedError pfnSCardDlgExtendedError; + fnSCardReadCacheA pfnSCardReadCacheA; + fnSCardReadCacheW pfnSCardReadCacheW; + fnSCardWriteCacheA pfnSCardWriteCacheA; + fnSCardWriteCacheW pfnSCardWriteCacheW; + fnSCardGetReaderIconA pfnSCardGetReaderIconA; + fnSCardGetReaderIconW pfnSCardGetReaderIconW; + fnSCardGetDeviceTypeIdA pfnSCardGetDeviceTypeIdA; + fnSCardGetDeviceTypeIdW pfnSCardGetDeviceTypeIdW; + fnSCardGetReaderDeviceInstanceIdA pfnSCardGetReaderDeviceInstanceIdA; + fnSCardGetReaderDeviceInstanceIdW pfnSCardGetReaderDeviceInstanceIdW; + fnSCardListReadersWithDeviceInstanceIdA pfnSCardListReadersWithDeviceInstanceIdA; + fnSCardListReadersWithDeviceInstanceIdW pfnSCardListReadersWithDeviceInstanceIdW; + fnSCardAudit pfnSCardAudit; +} SCardApiFunctionTable; +typedef SCardApiFunctionTable* PSCardApiFunctionTable; + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINSCARDAPI const char* WINAPI SCardGetErrorString(LONG errorCode); + WINSCARDAPI const char* WINAPI SCardGetAttributeString(DWORD dwAttrId); + WINSCARDAPI const char* WINAPI SCardGetProtocolString(DWORD dwProtocols); + WINSCARDAPI const char* WINAPI SCardGetShareModeString(DWORD dwShareMode); + WINSCARDAPI const char* WINAPI SCardGetDispositionString(DWORD dwDisposition); + WINSCARDAPI const char* WINAPI SCardGetScopeString(DWORD dwScope); + WINSCARDAPI const char* WINAPI SCardGetCardStateString(DWORD dwCardState); + WINSCARDAPI char* WINAPI SCardGetReaderStateString(DWORD dwReaderState); + + WINPR_API BOOL WinSCard_LoadApiTableFunctions(PSCardApiFunctionTable pWinSCardApiTable, + HMODULE hWinSCardLibrary); + WINPR_API const SCardApiFunctionTable* WinPR_GetSCardApiFunctionTable(void); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_SMARTCARD_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/spec.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/spec.h new file mode 100644 index 0000000000000000000000000000000000000000..b37f2c948a1651eaf0044c6614155d3c39a03cc2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/spec.h @@ -0,0 +1,1004 @@ +/** + * WinPR: Windows Portable Runtime + * Compiler Specification Strings + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_SPEC_H +#define WINPR_SPEC_H + +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER + +#ifdef _WIN32 + +#include +#ifndef _COM_Outptr_ +#define _COM_Outptr_ +#endif + +#else + +#if defined(NONAMELESSUNION) +#define DUMMYUNIONNAME u +#define DUMMYUNIONNAME1 u1 +#define DUMMYUNIONNAME2 u2 +#define DUMMYUNIONNAME3 u3 +#define DUMMYUNIONNAME4 u4 +#define DUMMYUNIONNAME5 u5 +#define DUMMYUNIONNAME6 u6 +#define DUMMYUNIONNAME7 u7 +#define DUMMYUNIONNAME8 u8 + +#define DUMMYSTRUCTNAME s +#define DUMMYSTRUCTNAME1 s1 +#define DUMMYSTRUCTNAME2 s2 +#define DUMMYSTRUCTNAME3 s3 +#define DUMMYSTRUCTNAME4 s4 +#define DUMMYSTRUCTNAME5 s5 +#else +#define DUMMYUNIONNAME +#define DUMMYUNIONNAME1 +#define DUMMYUNIONNAME2 +#define DUMMYUNIONNAME3 +#define DUMMYUNIONNAME4 +#define DUMMYUNIONNAME5 +#define DUMMYUNIONNAME6 +#define DUMMYUNIONNAME7 +#define DUMMYUNIONNAME8 + +#define DUMMYSTRUCTNAME +#define DUMMYSTRUCTNAME1 +#define DUMMYSTRUCTNAME2 +#define DUMMYSTRUCTNAME3 +#define DUMMYSTRUCTNAME4 +#define DUMMYSTRUCTNAME5 +#endif + +#if (defined(_M_AMD64) || defined(_M_ARM)) && !defined(_WIN32) +#define _UNALIGNED __unaligned +#else +#define _UNALIGNED +#endif + +#ifndef DECLSPEC_ALIGN +#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(MIDL_PASS) +#define DECLSPEC_ALIGN(x) __declspec(align(x)) +#elif defined(__GNUC__) +#define DECLSPEC_ALIGN(x) __attribute__((__aligned__(x))) +#else +#define DECLSPEC_ALIGN(x) +#endif +#endif /* DECLSPEC_ALIGN */ + +#ifdef _M_AMD64 +#define MEMORY_ALLOCATION_ALIGNMENT 16 +#else +#define MEMORY_ALLOCATION_ALIGNMENT 8 +#endif + +#ifdef __GNUC__ +#ifndef __declspec +#define __declspec(e) __attribute__((e)) +#endif +#endif + +#ifndef DECLSPEC_NORETURN +#if (defined(__GNUC__) || defined(_MSC_VER) || defined(__clang__)) +#define DECLSPEC_NORETURN __declspec(noreturn) +#else +#define DECLSPEC_NORETURN +#endif +#endif /* DECLSPEC_NORETURN */ + +/** + * Header Annotations: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa383701/ + */ + +#define __field_bcount(size) __notnull __byte_writableTo(size) +#define __field_ecount(size) __notnull __elem_writableTo(size) +#define __post_invalid _Post_ __notvalid + +#define __deref_in +#define __deref_in_ecount(size) +#define __deref_in_bcount(size) +#define __deref_in_opt +#define __deref_in_ecount_opt(size) +#define __deref_in_bcount_opt(size) +#define __deref_opt_in +#define __deref_opt_in_ecount(size) +#define __deref_opt_in_bcount(size) +#define __deref_opt_in_opt +#define __deref_opt_in_ecount_opt(size) +#define __deref_opt_in_bcount_opt(size) +#define __out_awcount(expr, size) +#define __in_awcount(expr, size) +#define __nullnullterminated +#define __in_data_source(src_sym) +#define __kernel_entry +#define __out_data_source(src_sym) +#define __analysis_noreturn +#define _Check_return_opt_ +#define _Check_return_wat_ + +#define __inner_exceptthat +#define __inner_typefix(ctype) +#define _Always_(annos) +#define _Analysis_noreturn_ +#define _Analysis_assume_(expr) +#define _At_(target, annos) +#define _At_buffer_(target, iter, bound, annos) +#define _Check_return_ +#define _COM_Outptr_ +#define _COM_Outptr_opt_ +#define _COM_Outptr_opt_result_maybenull_ +#define _COM_Outptr_result_maybenull_ +#define _Const_ +#define _Deref_in_bound_ +#define _Deref_in_range_(lb, ub) +#define _Deref_inout_bound_ +#define _Deref_inout_z_ +#define _Deref_inout_z_bytecap_c_(size) +#define _Deref_inout_z_cap_c_(size) +#define _Deref_opt_out_ +#define _Deref_opt_out_opt_ +#define _Deref_opt_out_opt_z_ +#define _Deref_opt_out_z_ +#define _Deref_out_ +#define _Deref_out_bound_ +#define _Deref_out_opt_ +#define _Deref_out_opt_z_ +#define _Deref_out_range_(lb, ub) +#define _Deref_out_z_ +#define _Deref_out_z_bytecap_c_(size) +#define _Deref_out_z_cap_c_(size) +#define _Deref_post_bytecap_(size) +#define _Deref_post_bytecap_c_(size) +#define _Deref_post_bytecap_x_(size) +#define _Deref_post_bytecount_(size) +#define _Deref_post_bytecount_c_(size) +#define _Deref_post_bytecount_x_(size) +#define _Deref_post_cap_(size) +#define _Deref_post_cap_c_(size) +#define _Deref_post_cap_x_(size) +#define _Deref_post_count_(size) +#define _Deref_post_count_c_(size) +#define _Deref_post_count_x_(size) +#define _Deref_post_maybenull_ +#define _Deref_post_notnull_ +#define _Deref_post_null_ +#define _Deref_post_opt_bytecap_(size) +#define _Deref_post_opt_bytecap_c_(size) +#define _Deref_post_opt_bytecap_x_(size) +#define _Deref_post_opt_bytecount_(size) +#define _Deref_post_opt_bytecount_c_(size) +#define _Deref_post_opt_bytecount_x_(size) +#define _Deref_post_opt_cap_(size) +#define _Deref_post_opt_cap_c_(size) +#define _Deref_post_opt_cap_x_(size) +#define _Deref_post_opt_count_(size) +#define _Deref_post_opt_count_c_(size) +#define _Deref_post_opt_count_x_(size) +#define _Deref_post_opt_valid_ +#define _Deref_post_opt_valid_bytecap_(size) +#define _Deref_post_opt_valid_bytecap_c_(size) +#define _Deref_post_opt_valid_bytecap_x_(size) +#define _Deref_post_opt_valid_cap_(size) +#define _Deref_post_opt_valid_cap_c_(size) +#define _Deref_post_opt_valid_cap_x_(size) +#define _Deref_post_opt_z_ +#define _Deref_post_opt_z_bytecap_(size) +#define _Deref_post_opt_z_bytecap_c_(size) +#define _Deref_post_opt_z_bytecap_x_(size) +#define _Deref_post_opt_z_cap_(size) +#define _Deref_post_opt_z_cap_c_(size) +#define _Deref_post_opt_z_cap_x_(size) +#define _Deref_post_valid_ +#define _Deref_post_valid_bytecap_(size) +#define _Deref_post_valid_bytecap_c_(size) +#define _Deref_post_valid_bytecap_x_(size) +#define _Deref_post_valid_cap_(size) +#define _Deref_post_valid_cap_c_(size) +#define _Deref_post_valid_cap_x_(size) +#define _Deref_post_z_ +#define _Deref_post_z_bytecap_(size) +#define _Deref_post_z_bytecap_c_(size) +#define _Deref_post_z_bytecap_x_(size) +#define _Deref_post_z_cap_(size) +#define _Deref_post_z_cap_c_(size) +#define _Deref_post_z_cap_x_(size) +#define _Deref_pre_bytecap_(size) +#define _Deref_pre_bytecap_c_(size) +#define _Deref_pre_bytecap_x_(size) +#define _Deref_pre_bytecount_(size) +#define _Deref_pre_bytecount_c_(size) +#define _Deref_pre_bytecount_x_(size) +#define _Deref_pre_cap_(size) +#define _Deref_pre_cap_c_(size) +#define _Deref_pre_cap_x_(size) +#define _Deref_pre_count_(size) +#define _Deref_pre_count_c_(size) +#define _Deref_pre_count_x_(size) +#define _Deref_pre_invalid_ +#define _Deref_pre_maybenull_ +#define _Deref_pre_notnull_ +#define _Deref_pre_null_ +#define _Deref_pre_opt_bytecap_(size) +#define _Deref_pre_opt_bytecap_c_(size) +#define _Deref_pre_opt_bytecap_x_(size) +#define _Deref_pre_opt_bytecount_(size) +#define _Deref_pre_opt_bytecount_c_(size) +#define _Deref_pre_opt_bytecount_x_(size) +#define _Deref_pre_opt_cap_(size) +#define _Deref_pre_opt_cap_c_(size) +#define _Deref_pre_opt_cap_x_(size) +#define _Deref_pre_opt_count_(size) +#define _Deref_pre_opt_count_c_(size) +#define _Deref_pre_opt_count_x_(size) +#define _Deref_pre_opt_valid_ +#define _Deref_pre_opt_valid_bytecap_(size) +#define _Deref_pre_opt_valid_bytecap_c_(size) +#define _Deref_pre_opt_valid_bytecap_x_(size) +#define _Deref_pre_opt_valid_cap_(size) +#define _Deref_pre_opt_valid_cap_c_(size) +#define _Deref_pre_opt_valid_cap_x_(size) +#define _Deref_pre_opt_z_ +#define _Deref_pre_opt_z_bytecap_(size) +#define _Deref_pre_opt_z_bytecap_c_(size) +#define _Deref_pre_opt_z_bytecap_x_(size) +#define _Deref_pre_opt_z_cap_(size) +#define _Deref_pre_opt_z_cap_c_(size) +#define _Deref_pre_opt_z_cap_x_(size) +#define _Deref_pre_readonly_ +#define _Deref_pre_valid_ +#define _Deref_pre_valid_bytecap_(size) +#define _Deref_pre_valid_bytecap_c_(size) +#define _Deref_pre_valid_bytecap_x_(size) +#define _Deref_pre_valid_cap_(size) +#define _Deref_pre_valid_cap_c_(size) +#define _Deref_pre_valid_cap_x_(size) +#define _Deref_pre_writeonly_ +#define _Deref_pre_z_ +#define _Deref_pre_z_bytecap_(size) +#define _Deref_pre_z_bytecap_c_(size) +#define _Deref_pre_z_bytecap_x_(size) +#define _Deref_pre_z_cap_(size) +#define _Deref_pre_z_cap_c_(size) +#define _Deref_pre_z_cap_x_(size) +#define _Deref_prepost_bytecap_(size) +#define _Deref_prepost_bytecap_x_(size) +#define _Deref_prepost_bytecount_(size) +#define _Deref_prepost_bytecount_x_(size) +#define _Deref_prepost_cap_(size) +#define _Deref_prepost_cap_x_(size) +#define _Deref_prepost_count_(size) +#define _Deref_prepost_count_x_(size) +#define _Deref_prepost_opt_bytecap_(size) +#define _Deref_prepost_opt_bytecap_x_(size) +#define _Deref_prepost_opt_bytecount_(size) +#define _Deref_prepost_opt_bytecount_x_(size) +#define _Deref_prepost_opt_cap_(size) +#define _Deref_prepost_opt_cap_x_(size) +#define _Deref_prepost_opt_count_(size) +#define _Deref_prepost_opt_count_x_(size) +#define _Deref_prepost_opt_valid_ +#define _Deref_prepost_opt_valid_bytecap_(size) +#define _Deref_prepost_opt_valid_bytecap_x_(size) +#define _Deref_prepost_opt_valid_cap_(size) +#define _Deref_prepost_opt_valid_cap_x_(size) +#define _Deref_prepost_opt_z_ +#define _Deref_prepost_opt_z_bytecap_(size) +#define _Deref_prepost_opt_z_cap_(size) +#define _Deref_prepost_valid_ +#define _Deref_prepost_valid_bytecap_(size) +#define _Deref_prepost_valid_bytecap_x_(size) +#define _Deref_prepost_valid_cap_(size) +#define _Deref_prepost_valid_cap_x_(size) +#define _Deref_prepost_z_ +#define _Deref_prepost_z_bytecap_(size) +#define _Deref_prepost_z_cap_(size) +#define _Deref_ret_bound_ +#define _Deref_ret_opt_z_ +#define _Deref_ret_range_(lb, ub) +#define _Deref_ret_z_ +#define _Deref2_pre_readonly_ +#define _Field_range_(min, max) +#define _Field_size_(size) +#define _Field_size_bytes_(size) +#define _Field_size_bytes_full_(size) +#define _Field_size_bytes_full_opt_(size) +#define _Field_size_bytes_opt_(size) +#define _Field_size_bytes_part_(size, count) +#define _Field_size_bytes_part_opt_(size, count) +#define _Field_size_full_(size) +#define _Field_size_full_opt_(size) +#define _Field_size_opt_(size) +#define _Field_size_part_(size, count) +#define _Field_size_part_opt_(size, count) +#define _Field_z_ +#define _Function_class_(x) +#define _Group_(annos) +#define _In_ +#define _In_bound_ +#define _In_bytecount_(size) +#define _In_bytecount_c_(size) +#define _In_bytecount_x_(size) +#define _In_count_(size) +#define _In_count_c_(size) +#define _In_count_x_(size) +#define _In_defensive_(annotates) +#define _In_opt_ +#define _In_opt_bytecount_(size) +#define _In_opt_bytecount_c_(size) +#define _In_opt_bytecount_x_(size) +#define _In_opt_count_(size) +#define _In_opt_count_c_(size) +#define _In_opt_count_x_(size) +#define _In_opt_ptrdiff_count_(size) +#define _In_opt_z_ +#define _In_opt_z_bytecount_(size) +#define _In_opt_z_bytecount_c_(size) +#define _In_opt_z_count_(size) +#define _In_opt_z_count_c_(size) +#define _In_ptrdiff_count_(size) +#define _In_range_(lb, ub) +#define _In_reads_(size) +#define _In_reads_bytes_(size) +#define _In_reads_bytes_opt_(size) +#define _In_reads_opt_(size) +#define _In_reads_opt_z_(size) +#define _In_reads_or_z_(size) +#define _In_reads_to_ptr_(ptr) +#define _In_reads_to_ptr_opt_(ptr) +#define _In_reads_to_ptr_opt_z_(ptr) +#define _In_reads_to_ptr_z_(ptr) +#define _In_reads_z_(size) +#define _In_z_ +#define _In_z_bytecount_(size) +#define _In_z_bytecount_c_(size) +#define _In_z_count_(size) +#define _In_z_count_c_(size) +#define _Inout_ +#define _Inout_bytecap_(size) +#define _Inout_bytecap_c_(size) +#define _Inout_bytecap_x_(size) +#define _Inout_bytecount_(size) +#define _Inout_bytecount_c_(size) +#define _Inout_bytecount_x_(size) +#define _Inout_cap_(size) +#define _Inout_cap_c_(size) +#define _Inout_cap_x_(size) +#define _Inout_count_(size) +#define _Inout_count_c_(size) +#define _Inout_count_x_(size) +#define _Inout_defensive_(annotates) +#define _Inout_opt_ +#define _Inout_opt_bytecap_(size) +#define _Inout_opt_bytecap_c_(size) +#define _Inout_opt_bytecap_x_(size) +#define _Inout_opt_bytecount_(size) +#define _Inout_opt_bytecount_c_(size) +#define _Inout_opt_bytecount_x_(size) +#define _Inout_opt_cap_(size) +#define _Inout_opt_cap_c_(size) +#define _Inout_opt_cap_x_(size) +#define _Inout_opt_count_(size) +#define _Inout_opt_count_c_(size) +#define _Inout_opt_count_x_(size) +#define _Inout_opt_ptrdiff_count_(size) +#define _Inout_opt_z_ +#define _Inout_opt_z_bytecap_(size) +#define _Inout_opt_z_bytecap_c_(size) +#define _Inout_opt_z_bytecap_x_(size) +#define _Inout_opt_z_bytecount_(size) +#define _Inout_opt_z_bytecount_c_(size) +#define _Inout_opt_z_cap_(size) +#define _Inout_opt_z_cap_c_(size) +#define _Inout_opt_z_cap_x_(size) +#define _Inout_opt_z_count_(size) +#define _Inout_opt_z_count_c_(size) +#define _Inout_ptrdiff_count_(size) +#define _Inout_updates_(size) +#define _Inout_updates_all_(size) +#define _Inout_updates_all_opt_(size) +#define _Inout_updates_bytes_(size) +#define _Inout_updates_bytes_all_(size) +#define _Inout_updates_bytes_all_opt_(size) +#define _Inout_updates_bytes_opt_(size) +#define _Inout_updates_bytes_to_(size, count) +#define _Inout_updates_bytes_to_opt_(size, count) +#define _Inout_updates_opt_(size) +#define _Inout_updates_opt_z_(size) +#define _Inout_updates_to_(size, count) +#define _Inout_updates_to_opt_(size, count) +#define _Inout_updates_z_(size) +#define _Inout_z_ +#define _Inout_z_bytecap_(size) +#define _Inout_z_bytecap_c_(size) +#define _Inout_z_bytecap_x_(size) +#define _Inout_z_bytecount_(size) +#define _Inout_z_bytecount_c_(size) +#define _Inout_z_cap_(size) +#define _Inout_z_cap_c_(size) +#define _Inout_z_cap_x_(size) +#define _Inout_z_count_(size) +#define _Inout_z_count_c_(size) +#define _Interlocked_operand_ +#define _Literal_ +#define _Maybenull_ +#define _Maybevalid_ +#define _Maybe_raises_SEH_exception +#define _Must_inspect_result_ +#define _Notliteral_ +#define _Notnull_ +#define _Notref_ +#define _Notvalid_ +#define _Null_ +#define _Null_terminated_ +#define _NullNull_terminated_ +#define _On_failure_(annos) +#define _Out_ +#define _Out_bound_ +#define _Out_bytecap_(size) +#define _Out_bytecap_c_(size) +#define _Out_bytecap_post_bytecount_(cap, count) +#define _Out_bytecap_x_(size) +#define _Out_bytecapcount_(capcount) +#define _Out_bytecapcount_x_(capcount) +#define _Out_cap_(size) +#define _Out_cap_c_(size) +#define _Out_cap_m_(mult, size) +#define _Out_cap_post_count_(cap, count) +#define _Out_cap_x_(size) +#define _Out_capcount_(capcount) +#define _Out_capcount_x_(capcount) +#define _Out_defensive_(annotates) +#define _Out_opt_ +#define _Out_opt_bytecap_(size) +#define _Out_opt_bytecap_c_(size) +#define _Out_opt_bytecap_post_bytecount_(cap, count) +#define _Out_opt_bytecap_x_(size) +#define _Out_opt_bytecapcount_(capcount) +#define _Out_opt_bytecapcount_x_(capcount) +#define _Out_opt_cap_(size) +#define _Out_opt_cap_c_(size) +#define _Out_opt_cap_m_(mult, size) +#define _Out_opt_cap_post_count_(cap, count) +#define _Out_opt_cap_x_(size) +#define _Out_opt_capcount_(capcount) +#define _Out_opt_capcount_x_(capcount) +#define _Out_opt_ptrdiff_cap_(size) +#define _Out_opt_z_bytecap_(size) +#define _Out_opt_z_bytecap_c_(size) +#define _Out_opt_z_bytecap_post_bytecount_(cap, count) +#define _Out_opt_z_bytecap_x_(size) +#define _Out_opt_z_bytecapcount_(capcount) +#define _Out_opt_z_cap_(size) +#define _Out_opt_z_cap_c_(size) +#define _Out_opt_z_cap_m_(mult, size) +#define _Out_opt_z_cap_post_count_(cap, count) +#define _Out_opt_z_cap_x_(size) +#define _Out_opt_z_capcount_(capcount) +#define _Out_ptrdiff_cap_(size) +#define _Out_range_(lb, ub) +#define _Out_writes_(size) +#define _Out_writes_all_(size) +#define _Out_writes_all_opt_(size) +#define _Out_writes_bytes_(size) +#define _Out_writes_bytes_all_(size) +#define _Out_writes_bytes_all_opt_(size) +#define _Out_writes_bytes_opt_(size) +#define _Out_writes_bytes_to_(size, count) +#define _Out_writes_bytes_to_opt_(size, count) +#define _Out_writes_opt_(size) +#define _Out_writes_opt_z_(size) +#define _Out_writes_to_(size, count) +#define _Out_writes_to_opt_(size, count) +#define _Out_writes_to_ptr_(ptr) +#define _Out_writes_to_ptr_opt_(ptr) +#define _Out_writes_to_ptr_opt_z_(ptr) +#define _Out_writes_to_ptr_z_(ptr) +#define _Out_writes_z_(size) +#define _Out_z_bytecap_(size) +#define _Out_z_bytecap_c_(size) +#define _Out_z_bytecap_post_bytecount_(cap, count) +#define _Out_z_bytecap_x_(size) +#define _Out_z_bytecapcount_(capcount) +#define _Out_z_cap_(size) +#define _Out_z_cap_c_(size) +#define _Out_z_cap_m_(mult, size) +#define _Out_z_cap_post_count_(cap, count) +#define _Out_z_cap_x_(size) +#define _Out_z_capcount_(capcount) +#define _Outptr_ +#define _Outptr_opt_ +#define _Outptr_opt_result_buffer_(size) +#define _Outptr_opt_result_buffer_all_(size) +#define _Outptr_opt_result_buffer_all_maybenull_(size) +#define _Outptr_opt_result_buffer_maybenull_(size) +#define _Outptr_opt_result_buffer_to_(size, count) +#define _Outptr_opt_result_buffer_to_maybenull_(size, count) +#define _Outptr_opt_result_bytebuffer_(size) +#define _Outptr_opt_result_bytebuffer_all_(size) +#define _Outptr_opt_result_bytebuffer_all_maybenull_(size) +#define _Outptr_opt_result_bytebuffer_maybenull_(size) +#define _Outptr_opt_result_bytebuffer_to_(size, count) +#define _Outptr_opt_result_bytebuffer_to_maybenull_(size, count) +#define _Outptr_opt_result_maybenull_ +#define _Outptr_opt_result_maybenull_z_ +#define _Outptr_opt_result_nullonfailure_ +#define _Outptr_opt_result_z_ +#define _Outptr_result_buffer_(size) +#define _Outptr_result_buffer_all_(size) +#define _Outptr_result_buffer_all_maybenull_(size) +#define _Outptr_result_buffer_maybenull_(size) +#define _Outptr_result_buffer_to_(size, count) +#define _Outptr_result_buffer_to_maybenull_(size, count) +#define _Outptr_result_bytebuffer_(size) +#define _Outptr_result_bytebuffer_all_(size) +#define _Outptr_result_bytebuffer_all_maybenull_(size) +#define _Outptr_result_bytebuffer_maybenull_(size) +#define _Outptr_result_bytebuffer_to_(size, count) +#define _Outptr_result_bytebuffer_to_maybenull_(size, count) +#define _Outptr_result_maybenull_ +#define _Outptr_result_maybenull_z_ +#define _Outptr_result_nullonfailure_ +#define _Outptr_result_z_ +#define _Outref_ +#define _Outref_result_buffer_(size) +#define _Outref_result_buffer_all_(size) +#define _Outref_result_buffer_all_maybenull_(size) +#define _Outref_result_buffer_maybenull_(size) +#define _Outref_result_buffer_to_(size, count) +#define _Outref_result_buffer_to_maybenull_(size, count) +#define _Outref_result_bytebuffer_(size) +#define _Outref_result_bytebuffer_all_(size) +#define _Outref_result_bytebuffer_all_maybenull_(size) +#define _Outref_result_bytebuffer_maybenull_(size) +#define _Outref_result_bytebuffer_to_(size, count) +#define _Outref_result_bytebuffer_to_maybenull_(size, count) +#define _Outref_result_maybenull_ +#define _Outref_result_nullonfailure_ +#define _Points_to_data_ +#define _Post_ +#define _Post_bytecap_(size) +#define _Post_bytecount_(size) +#define _Post_bytecount_c_(size) +#define _Post_bytecount_x_(size) +#define _Post_cap_(size) +#define _Post_count_(size) +#define _Post_count_c_(size) +#define _Post_count_x_(size) +#define _Post_defensive_ +#define _Post_equal_to_(expr) +#define _Post_invalid_ +#define _Post_maybenull_ +#define _Post_maybez_ +#define _Post_notnull_ +#define _Post_null_ +#define _Post_ptr_invalid_ +#define _Post_readable_byte_size_(size) +#define _Post_readable_size_(size) +#define _Post_satisfies_(cond) +#define _Post_valid_ +#define _Post_writable_byte_size_(size) +#define _Post_writable_size_(size) +#define _Post_z_ +#define _Post_z_bytecount_(size) +#define _Post_z_bytecount_c_(size) +#define _Post_z_bytecount_x_(size) +#define _Post_z_count_(size) +#define _Post_z_count_c_(size) +#define _Post_z_count_x_(size) +#define _Pre_ +#define _Pre_bytecap_(size) +#define _Pre_bytecap_c_(size) +#define _Pre_bytecap_x_(size) +#define _Pre_bytecount_(size) +#define _Pre_bytecount_c_(size) +#define _Pre_bytecount_x_(size) +#define _Pre_cap_(size) +#define _Pre_cap_c_(size) +#define _Pre_cap_c_one_ +#define _Pre_cap_for_(param) +#define _Pre_cap_m_(mult, size) +#define _Pre_cap_x_(size) +#define _Pre_count_(size) +#define _Pre_count_c_(size) +#define _Pre_count_x_(size) +#define _Pre_defensive_ +#define _Pre_equal_to_(expr) +#define _Pre_invalid_ +#define _Pre_maybenull_ +#define _Pre_notnull_ +#define _Pre_null_ +#define _Pre_opt_bytecap_(size) +#define _Pre_opt_bytecap_c_(size) +#define _Pre_opt_bytecap_x_(size) +#define _Pre_opt_bytecount_(size) +#define _Pre_opt_bytecount_c_(size) +#define _Pre_opt_bytecount_x_(size) +#define _Pre_opt_cap_(size) +#define _Pre_opt_cap_c_(size) +#define _Pre_opt_cap_c_one_ +#define _Pre_opt_cap_for_(param) +#define _Pre_opt_cap_m_(mult, size) +#define _Pre_opt_cap_x_(size) +#define _Pre_opt_count_(size) +#define _Pre_opt_count_c_(size) +#define _Pre_opt_count_x_(size) +#define _Pre_opt_ptrdiff_cap_(ptr) +#define _Pre_opt_ptrdiff_count_(ptr) +#define _Pre_opt_valid_ +#define _Pre_opt_valid_bytecap_(size) +#define _Pre_opt_valid_bytecap_c_(size) +#define _Pre_opt_valid_bytecap_x_(size) +#define _Pre_opt_valid_cap_(size) +#define _Pre_opt_valid_cap_c_(size) +#define _Pre_opt_valid_cap_x_(size) +#define _Pre_opt_z_ +#define _Pre_opt_z_bytecap_(size) +#define _Pre_opt_z_bytecap_c_(size) +#define _Pre_opt_z_bytecap_x_(size) +#define _Pre_opt_z_cap_(size) +#define _Pre_opt_z_cap_c_(size) +#define _Pre_opt_z_cap_x_(size) +#define _Pre_ptrdiff_cap_(ptr) +#define _Pre_ptrdiff_count_(ptr) +#define _Pre_readable_byte_size_(size) +#define _Pre_readable_size_(size) +#define _Pre_readonly_ +#define _Pre_satisfies_(cond) +#define _Pre_unknown_ +#define _Pre_valid_ +#define _Pre_valid_bytecap_(size) +#define _Pre_valid_bytecap_c_(size) +#define _Pre_valid_bytecap_x_(size) +#define _Pre_valid_cap_(size) +#define _Pre_valid_cap_c_(size) +#define _Pre_valid_cap_x_(size) +#define _Pre_writable_byte_size_(size) +#define _Pre_writable_size_(size) +#define _Pre_writeonly_ +#define _Pre_z_ +#define _Pre_z_bytecap_(size) +#define _Pre_z_bytecap_c_(size) +#define _Pre_z_bytecap_x_(size) +#define _Pre_z_cap_(size) +#define _Pre_z_cap_c_(size) +#define _Pre_z_cap_x_(size) +#define _Prepost_bytecount_(size) +#define _Prepost_bytecount_c_(size) +#define _Prepost_bytecount_x_(size) +#define _Prepost_count_(size) +#define _Prepost_count_c_(size) +#define _Prepost_count_x_(size) +#define _Prepost_opt_bytecount_(size) +#define _Prepost_opt_bytecount_c_(size) +#define _Prepost_opt_bytecount_x_(size) +#define _Prepost_opt_count_(size) +#define _Prepost_opt_count_c_(size) +#define _Prepost_opt_count_x_(size) +#define _Prepost_opt_valid_ +#define _Prepost_opt_z_ +#define _Prepost_valid_ +#define _Prepost_z_ +#define _Printf_format_string_ +#define _Raises_SEH_exception_ +#define _Maybe_raises_SEH_exception_ +#define _Readable_bytes_(size) +#define _Readable_elements_(size) +#define _Reserved_ +#define _Result_nullonfailure_ +#define _Result_zeroonfailure_ +#define __inner_callback +#define _Ret_ +#define _Ret_bound_ +#define _Ret_bytecap_(size) +#define _Ret_bytecap_c_(size) +#define _Ret_bytecap_x_(size) +#define _Ret_bytecount_(size) +#define _Ret_bytecount_c_(size) +#define _Ret_bytecount_x_(size) +#define _Ret_cap_(size) +#define _Ret_cap_c_(size) +#define _Ret_cap_x_(size) +#define _Ret_count_(size) +#define _Ret_count_c_(size) +#define _Ret_count_x_(size) +#define _Ret_maybenull_ +#define _Ret_maybenull_z_ +#define _Ret_notnull_ +#define _Ret_null_ +#define _Ret_opt_ +#define _Ret_opt_bytecap_(size) +#define _Ret_opt_bytecap_c_(size) +#define _Ret_opt_bytecap_x_(size) +#define _Ret_opt_bytecount_(size) +#define _Ret_opt_bytecount_c_(size) +#define _Ret_opt_bytecount_x_(size) +#define _Ret_opt_cap_(size) +#define _Ret_opt_cap_c_(size) +#define _Ret_opt_cap_x_(size) +#define _Ret_opt_count_(size) +#define _Ret_opt_count_c_(size) +#define _Ret_opt_count_x_(size) +#define _Ret_opt_valid_ +#define _Ret_opt_z_ +#define _Ret_opt_z_bytecap_(size) +#define _Ret_opt_z_bytecount_(size) +#define _Ret_opt_z_cap_(size) +#define _Ret_opt_z_count_(size) +#define _Ret_range_(lb, ub) +#define _Ret_valid_ +#define _Ret_writes_(size) +#define _Ret_writes_bytes_(size) +#define _Ret_writes_bytes_maybenull_(size) +#define _Ret_writes_bytes_to_(size, count) +#define _Ret_writes_bytes_to_maybenull_(size, count) +#define _Ret_writes_maybenull_(size) +#define _Ret_writes_maybenull_z_(size) +#define _Ret_writes_to_(size, count) +#define _Ret_writes_to_maybenull_(size, count) +#define _Ret_writes_z_(size) +#define _Ret_z_ +#define _Ret_z_bytecap_(size) +#define _Ret_z_bytecount_(size) +#define _Ret_z_cap_(size) +#define _Ret_z_count_(size) +#define _Return_type_success_(expr) +#define _Scanf_format_string_ +#define _Scanf_s_format_string_ +#define _Struct_size_bytes_(size) +#define _Success_(expr) +#define _Unchanged_(e) +#define _Use_decl_annotations_ +#define _Valid_ +#define _When_(expr, annos) +#define _Writable_bytes_(size) +#define _Writable_elements_(size) + +#define __bcount(size) +#define __bcount_opt(size) +#define __deref_bcount(size) +#define __deref_bcount_opt(size) +#define __deref_ecount(size) +#define __deref_ecount_opt(size) +#define __deref_in +#define __deref_in_bcount(size) +#define __deref_in_bcount_opt(size) +#define __deref_in_ecount(size) +#define __deref_in_ecount_opt(size) +#define __deref_in_opt +#define __deref_inout +#define __deref_inout_bcount(size) +#define __deref_inout_bcount_full(size) +#define __deref_inout_bcount_full_opt(size) +#define __deref_inout_bcount_opt(size) +#define __deref_inout_bcount_part(size, length) +#define __deref_inout_bcount_part_opt(size, length) +#define __deref_inout_ecount(size) +#define __deref_inout_ecount_full(size) +#define __deref_inout_ecount_full_opt(size) +#define __deref_inout_ecount_opt(size) +#define __deref_inout_ecount_part(size, length) +#define __deref_inout_ecount_part_opt(size, length) +#define __deref_inout_opt +#define __deref_opt_bcount(size) +#define __deref_opt_bcount_opt(size) +#define __deref_opt_ecount(size) +#define __deref_opt_ecount_opt(size) +#define __deref_opt_in +#define __deref_opt_in_bcount(size) +#define __deref_opt_in_bcount_opt(size) +#define __deref_opt_in_ecount(size) +#define __deref_opt_in_ecount_opt(size) +#define __deref_opt_in_opt +#define __deref_opt_inout +#define __deref_opt_inout_bcount(size) +#define __deref_opt_inout_bcount_full(size) +#define __deref_opt_inout_bcount_full_opt(size) +#define __deref_opt_inout_bcount_opt(size) +#define __deref_opt_inout_bcount_part(size, length) +#define __deref_opt_inout_bcount_part_opt(size, length) +#define __deref_opt_inout_ecount(size) +#define __deref_opt_inout_ecount_full(size) +#define __deref_opt_inout_ecount_full_opt(size) +#define __deref_opt_inout_ecount_opt(size) +#define __deref_opt_inout_ecount_part(size, length) +#define __deref_opt_inout_ecount_part_opt(size, length) +#define __deref_opt_inout_opt +#define __deref_opt_out +#define __deref_opt_out_bcount(size) +#define __deref_opt_out_bcount_full(size) +#define __deref_opt_out_bcount_full_opt(size) +#define __deref_opt_out_bcount_opt(size) +#define __deref_opt_out_bcount_part(size, length) +#define __deref_opt_out_bcount_part_opt(size, length) +#define __deref_opt_out_ecount(size) +#define __deref_opt_out_ecount_full(size) +#define __deref_opt_out_ecount_full_opt(size) +#define __deref_opt_out_ecount_opt(size) +#define __deref_opt_out_ecount_part(size, length) +#define __deref_opt_out_ecount_part_opt(size, length) +#define __deref_opt_out_opt +#define __deref_out +#define __deref_out_bcount(size) +#define __deref_out_bcount_full(size) +#define __deref_out_bcount_full_opt(size) +#define __deref_out_bcount_opt(size) +#define __deref_out_bcount_part(size, length) +#define __deref_out_bcount_part_opt(size, length) +#define __deref_out_ecount(size) +#define __deref_out_ecount_full(size) +#define __deref_out_ecount_full_opt(size) +#define __deref_out_ecount_opt(size) +#define __deref_out_ecount_part(size, length) +#define __deref_out_ecount_part_opt(size, length) +#define __deref_out_opt +#define __ecount(size) +#define __ecount_opt(size) +//#define __in /* Conflicts with libstdc++ header macros */ +#define __in_bcount(size) +#define __in_bcount_opt(size) +#define __in_ecount(size) +#define __in_ecount_opt(size) +#define __in_opt +#define __inout +#define __inout_bcount(size) +#define __inout_bcount_full(size) +#define __inout_bcount_full_opt(size) +#define __inout_bcount_opt(size) +#define __inout_bcount_part(size, length) +#define __inout_bcount_part_opt(size, length) +#define __inout_ecount(size) +#define __inout_ecount_full(size) +#define __inout_ecount_full_opt(size) +#define __inout_ecount_opt(size) +#define __inout_ecount_part(size, length) +#define __inout_ecount_part_opt(size, length) +#define __inout_opt +//#define __out /* Conflicts with libstdc++ header macros */ +#define __out_bcount(size) +#define __out_bcount_full(size) +#define __out_bcount_full_opt(size) +#define __out_bcount_opt(size) +#define __out_bcount_part(size, length) +#define __out_bcount_part_opt(size, length) +#define __out_ecount(size) +#define __out_ecount_full(size) +#define __out_ecount_full_opt(size) +#define __out_ecount_opt(size) +#define __out_ecount_part(size, length) +#define __out_ecount_part_opt(size, length) +#define __out_opt + +#define __blocksOn(resource) +#define __callback +#define __checkReturn +#define __format_string +#define __in_awcount(expr, size) +#define __nullnullterminated +#define __nullterminated +#define __out_awcount(expr, size) +#define __override +//#define __reserved /* Conflicts with header included by CarbonCore.h on OS X */ +#define __success(expr) +#define __typefix(ctype) + +#ifndef _countof +#ifndef __cplusplus +#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0])) +#else +extern "C++" +{ + template + char (*__countof_helper(_CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray]; +#define _countof(_Array) sizeof(*__countof_helper(_Array)) +} +#endif +#endif + +/** + * RTL Definitions + */ + +#define MINCHAR 0x80 +#define MAXCHAR 0x7F + +#ifndef MINSHORT +#define MINSHORT 0x8000 +#endif + +#ifndef MAXSHORT +#define MAXSHORT 0x7FFF +#endif + +#define MINLONG 0x80000000 +#define MAXLONG 0x7FFFFFFF +#define MAXBYTE 0xFF +#define MAXWORD 0xFFFF +#define MAXDWORD 0xFFFFFFFF + +#define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR) & (((type*)0)->field)) + +#define RTL_FIELD_SIZE(type, field) (sizeof(((type*)0)->field)) + +#define RTL_SIZEOF_THROUGH_FIELD(type, field) \ + (FIELD_OFFSET(type, field) + RTL_FIELD_SIZE(type, field)) + +#define RTL_CONTAINS_FIELD(Struct, Size, Field) \ + ((((PCHAR)(&(Struct)->Field)) + sizeof((Struct)->Field)) <= (((PCHAR)(Struct)) + (Size))) + +#define RTL_NUMBER_OF_V1(A) (sizeof(A) / sizeof((A)[0])) +#define RTL_NUMBER_OF_V2(A) RTL_NUMBER_OF_V1(A) + +#define RTL_NUMBER_OF(A) RTL_NUMBER_OF_V1(A) + +#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) +#define _ARRAYSIZE(A) RTL_NUMBER_OF_V1(A) + +#define RTL_FIELD_TYPE(type, field) (((type*)0)->field) + +#define RTL_NUMBER_OF_FIELD(type, field) (RTL_NUMBER_OF(RTL_FIELD_TYPE(type, field))) + +#define RTL_PADDING_BETWEEN_FIELDS(T, F1, F2) \ + ((FIELD_OFFSET(T, F2) > FIELD_OFFSET(T, F1)) \ + ? (FIELD_OFFSET(T, F2) - FIELD_OFFSET(T, F1) - RTL_FIELD_SIZE(T, F1)) \ + : (FIELD_OFFSET(T, F1) - FIELD_OFFSET(T, F2) - RTL_FIELD_SIZE(T, F2))) + +#if defined(__cplusplus) +#define RTL_CONST_CAST(type) const_cast +#else +#define RTL_CONST_CAST(type) (type) +#endif + +#define RTL_BITS_OF(sizeOfArg) (sizeof(sizeOfArg) * 8) + +#define RTL_BITS_OF_FIELD(type, field) (RTL_BITS_OF(RTL_FIELD_TYPE(type, field))) + +#define CONTAINING_RECORD(address, type, field) \ + ((type*)((PCHAR)(address) - (ULONG_PTR)(&((type*)0)->field))) + +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +#ifdef __GNUC__ +#define DECLSPEC_EXPORT __attribute__((dllexport)) +#ifndef DECLSPEC_IMPORT +#define DECLSPEC_IMPORT __attribute__((dllimport)) +#endif /* DECLSPEC_IMPORT */ +#else +#define DECLSPEC_EXPORT __declspec(dllexport) +#define DECLSPEC_IMPORT __declspec(dllimport) +#endif /* __GNUC__ */ +#else +#if defined(__GNUC__) && __GNUC__ >= 4 +#define DECLSPEC_EXPORT __attribute__((visibility("default"))) +#define DECLSPEC_IMPORT +#else +#define DECLSPEC_EXPORT +#define DECLSPEC_IMPORT +#endif +#endif + +WINPR_PRAGMA_DIAG_POP + +#endif /* WINPR_SPEC_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ssl.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ssl.h new file mode 100644 index 0000000000000000000000000000000000000000..ff50097a00ec92fe9d42a81c12af8a36d394e7f7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/ssl.h @@ -0,0 +1,49 @@ +/** + * WinPR: Windows Portable Runtime + * OpenSSL Library Initialization + * + * Copyright 2014 Thincast Technologies GmbH + * Copyright 2014 Norbert Federa + * + * 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 +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspi.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspi.h new file mode 100644 index 0000000000000000000000000000000000000000..6150472ed77403a3123d6c944360cd524eb3a72c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspi.h @@ -0,0 +1,1439 @@ +/** + * WinPR: Windows Portable Runtime + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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_H +#define WINPR_SSPI_H + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + +#include +#include + +#define SECURITY_WIN32 +#include +#include + +#endif /* _WIN32 */ + +#if !defined(_WIN32) || defined(_UWP) + +#ifndef SEC_ENTRY +#define SEC_ENTRY +#endif /* SEC_ENTRY */ + +typedef CHAR SEC_CHAR; +typedef WCHAR SEC_WCHAR; + +typedef struct +{ + UINT32 LowPart; + INT32 HighPart; +} SECURITY_INTEGER; + +typedef SECURITY_INTEGER TimeStamp; +typedef SECURITY_INTEGER* PTimeStamp; + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#ifndef __SECSTATUS_DEFINED__ +typedef LONG SECURITY_STATUS; +#define __SECSTATUS_DEFINED__ +#endif /* __SECSTATUS_DEFINED__ */ + +WINPR_PRAGMA_DIAG_POP + +typedef struct +{ + UINT32 fCapabilities; + UINT16 wVersion; + UINT16 wRPCID; + UINT32 cbMaxToken; + SEC_CHAR* Name; + SEC_CHAR* Comment; +} SecPkgInfoA; +typedef SecPkgInfoA* PSecPkgInfoA; + +typedef struct +{ + UINT32 fCapabilities; + UINT16 wVersion; + UINT16 wRPCID; + UINT32 cbMaxToken; + SEC_WCHAR* Name; + SEC_WCHAR* Comment; +} SecPkgInfoW; +typedef SecPkgInfoW* PSecPkgInfoW; + +#ifdef UNICODE +#define SecPkgInfo SecPkgInfoW +#define PSecPkgInfo PSecPkgInfoW +#else +#define SecPkgInfo SecPkgInfoA +#define PSecPkgInfo PSecPkgInfoA +#endif /* UNICODE */ + +#endif /* !defined(_WIN32) || defined(_UWP) */ + +#define NTLM_SSP_NAME _T("NTLM") +#define KERBEROS_SSP_NAME _T("Kerberos") +#define NEGO_SSP_NAME _T("Negotiate") + +#define SECPKG_ID_NONE 0xFFFF + +#define SECPKG_FLAG_INTEGRITY 0x00000001 +#define SECPKG_FLAG_PRIVACY 0x00000002 +#define SECPKG_FLAG_TOKEN_ONLY 0x00000004 +#define SECPKG_FLAG_DATAGRAM 0x00000008 +#define SECPKG_FLAG_CONNECTION 0x00000010 +#define SECPKG_FLAG_MULTI_REQUIRED 0x00000020 +#define SECPKG_FLAG_CLIENT_ONLY 0x00000040 +#define SECPKG_FLAG_EXTENDED_ERROR 0x00000080 +#define SECPKG_FLAG_IMPERSONATION 0x00000100 +#define SECPKG_FLAG_ACCEPT_WIN32_NAME 0x00000200 +#define SECPKG_FLAG_STREAM 0x00000400 +#define SECPKG_FLAG_NEGOTIABLE 0x00000800 +#define SECPKG_FLAG_GSS_COMPATIBLE 0x00001000 +#define SECPKG_FLAG_LOGON 0x00002000 +#define SECPKG_FLAG_ASCII_BUFFERS 0x00004000 +#define SECPKG_FLAG_FRAGMENT 0x00008000 +#define SECPKG_FLAG_MUTUAL_AUTH 0x00010000 +#define SECPKG_FLAG_DELEGATION 0x00020000 +#define SECPKG_FLAG_READONLY_WITH_CHECKSUM 0x00040000 +#define SECPKG_FLAG_RESTRICTED_TOKENS 0x00080000 +#define SECPKG_FLAG_NEGO_EXTENDER 0x00100000 +#define SECPKG_FLAG_NEGOTIABLE2 0x00200000 + +#ifndef _WINERROR_ + +#define SEC_E_OK WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00000000) +#define SEC_E_INSUFFICIENT_MEMORY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090300) +#define SEC_E_INVALID_HANDLE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090301) +#define SEC_E_UNSUPPORTED_FUNCTION WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090302) +#define SEC_E_TARGET_UNKNOWN WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090303) +#define SEC_E_INTERNAL_ERROR WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090304) +#define SEC_E_SECPKG_NOT_FOUND WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090305) +#define SEC_E_NOT_OWNER WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090306) +#define SEC_E_CANNOT_INSTALL WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090307) +#define SEC_E_INVALID_TOKEN WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090308) +#define SEC_E_CANNOT_PACK WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090309) +#define SEC_E_QOP_NOT_SUPPORTED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030A) +#define SEC_E_NO_IMPERSONATION WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030B) +#define SEC_E_LOGON_DENIED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030C) +#define SEC_E_UNKNOWN_CREDENTIALS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030D) +#define SEC_E_NO_CREDENTIALS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030E) +#define SEC_E_MESSAGE_ALTERED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009030F) +#define SEC_E_OUT_OF_SEQUENCE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090310) +#define SEC_E_NO_AUTHENTICATING_AUTHORITY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090311) +#define SEC_E_BAD_PKGID WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090316) +#define SEC_E_CONTEXT_EXPIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090317) +#define SEC_E_INCOMPLETE_MESSAGE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090318) +#define SEC_E_INCOMPLETE_CREDENTIALS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090320) +#define SEC_E_BUFFER_TOO_SMALL WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090321) +#define SEC_E_WRONG_PRINCIPAL WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090322) +#define SEC_E_TIME_SKEW WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090324) +#define SEC_E_UNTRUSTED_ROOT WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090325) +#define SEC_E_ILLEGAL_MESSAGE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090326) +#define SEC_E_CERT_UNKNOWN WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090327) +#define SEC_E_CERT_EXPIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090328) +#define SEC_E_ENCRYPT_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090329) +#define SEC_E_DECRYPT_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090330) +#define SEC_E_ALGORITHM_MISMATCH WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090331) +#define SEC_E_SECURITY_QOS_FAILED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090332) +#define SEC_E_UNFINISHED_CONTEXT_DELETED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090333) +#define SEC_E_NO_TGT_REPLY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090334) +#define SEC_E_NO_IP_ADDRESSES WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090335) +#define SEC_E_WRONG_CREDENTIAL_HANDLE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090336) +#define SEC_E_CRYPTO_SYSTEM_INVALID WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090337) +#define SEC_E_MAX_REFERRALS_EXCEEDED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090338) +#define SEC_E_MUST_BE_KDC WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090339) +#define SEC_E_STRONG_CRYPTO_NOT_SUPPORTED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033A) +#define SEC_E_TOO_MANY_PRINCIPALS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033B) +#define SEC_E_NO_PA_DATA WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033C) +#define SEC_E_PKINIT_NAME_MISMATCH WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033D) +#define SEC_E_SMARTCARD_LOGON_REQUIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033E) +#define SEC_E_SHUTDOWN_IN_PROGRESS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009033F) +#define SEC_E_KDC_INVALID_REQUEST WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090340) +#define SEC_E_KDC_UNABLE_TO_REFER WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090341) +#define SEC_E_KDC_UNKNOWN_ETYPE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090342) +#define SEC_E_UNSUPPORTED_PREAUTH WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090343) +#define SEC_E_DELEGATION_REQUIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090345) +#define SEC_E_BAD_BINDINGS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090346) +#define SEC_E_MULTIPLE_ACCOUNTS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090347) +#define SEC_E_NO_KERB_KEY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090348) +#define SEC_E_CERT_WRONG_USAGE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090349) +#define SEC_E_DOWNGRADE_DETECTED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090350) +#define SEC_E_SMARTCARD_CERT_REVOKED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090351) +#define SEC_E_ISSUING_CA_UNTRUSTED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090352) +#define SEC_E_REVOCATION_OFFLINE_C WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090353) +#define SEC_E_PKINIT_CLIENT_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090354) +#define SEC_E_SMARTCARD_CERT_EXPIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090355) +#define SEC_E_NO_S4U_PROT_SUPPORT WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090356) +#define SEC_E_CROSSREALM_DELEGATION_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090357) +#define SEC_E_REVOCATION_OFFLINE_KDC WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090358) +#define SEC_E_ISSUING_CA_UNTRUSTED_KDC WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090359) +#define SEC_E_KDC_CERT_EXPIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035A) +#define SEC_E_KDC_CERT_REVOKED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035B) +#define SEC_E_INVALID_PARAMETER WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035D) +#define SEC_E_DELEGATION_POLICY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035E) +#define SEC_E_POLICY_NLTM_ONLY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035F) +#define SEC_E_NO_CONTEXT WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090361) +#define SEC_E_PKU2U_CERT_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090362) +#define SEC_E_MUTUAL_AUTH_FAILED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090363) + +#define SEC_I_CONTINUE_NEEDED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090312) +#define SEC_I_COMPLETE_NEEDED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090313) +#define SEC_I_COMPLETE_AND_CONTINUE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090314) +#define SEC_I_LOCAL_LOGON WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090315) +#define SEC_I_CONTEXT_EXPIRED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090317) +#define SEC_I_INCOMPLETE_CREDENTIALS WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090320) +#define SEC_I_RENEGOTIATE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090321) +#define SEC_I_NO_LSA_CONTEXT WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090323) +#define SEC_I_SIGNATURE_NEEDED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x0009035C) +#define SEC_I_NO_RENEGOTIATION WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090360) + +#endif /* _WINERROR_ */ + +/* ============== some definitions missing in mingw ========================*/ +#ifndef SEC_E_INVALID_PARAMETER +#define SEC_E_INVALID_PARAMETER WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035D) +#endif + +#ifndef SEC_E_DELEGATION_POLICY +#define SEC_E_DELEGATION_POLICY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035E) +#endif + +#ifndef SEC_E_POLICY_NLTM_ONLY +#define SEC_E_POLICY_NLTM_ONLY WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x8009035F) +#endif + +#ifndef SEC_E_NO_CONTEXT +#define SEC_E_NO_CONTEXT WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090361) +#endif + +#ifndef SEC_E_PKU2U_CERT_FAILURE +#define SEC_E_PKU2U_CERT_FAILURE WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090362) +#endif + +#ifndef SEC_E_MUTUAL_AUTH_FAILED +#define SEC_E_MUTUAL_AUTH_FAILED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x80090363) +#endif + +#ifndef SEC_I_SIGNATURE_NEEDED +#define SEC_I_SIGNATURE_NEEDED WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x0009035C) +#endif + +#ifndef SEC_I_NO_RENEGOTIATION +#define SEC_I_NO_RENEGOTIATION WINPR_CXX_COMPAT_CAST(SECURITY_STATUS, 0x00090360) +#endif + +/* ==================================================================================== */ + +#define SECURITY_NATIVE_DREP 0x00000010 +#define SECURITY_NETWORK_DREP 0x00000000 + +#define SECPKG_CRED_INBOUND 0x00000001 +#define SECPKG_CRED_OUTBOUND 0x00000002 +#define SECPKG_CRED_BOTH 0x00000003 +#define SECPKG_CRED_AUTOLOGON_RESTRICTED 0x00000010 +#define SECPKG_CRED_PROCESS_POLICY_ONLY 0x00000020 + +/* Security Context Attributes */ + +#define SECPKG_ATTR_SIZES 0 +#define SECPKG_ATTR_NAMES 1 +#define SECPKG_ATTR_LIFESPAN 2 +#define SECPKG_ATTR_DCE_INFO 3 +#define SECPKG_ATTR_STREAM_SIZES 4 +#define SECPKG_ATTR_KEY_INFO 5 +#define SECPKG_ATTR_AUTHORITY 6 +#define SECPKG_ATTR_PROTO_INFO 7 +#define SECPKG_ATTR_PASSWORD_EXPIRY 8 +#define SECPKG_ATTR_SESSION_KEY 9 +#define SECPKG_ATTR_PACKAGE_INFO 10 +#define SECPKG_ATTR_USER_FLAGS 11 +#define SECPKG_ATTR_NEGOTIATION_INFO 12 +#define SECPKG_ATTR_NATIVE_NAMES 13 +#define SECPKG_ATTR_FLAGS 14 +#define SECPKG_ATTR_USE_VALIDATED 15 +#define SECPKG_ATTR_CREDENTIAL_NAME 16 +#define SECPKG_ATTR_TARGET_INFORMATION 17 +#define SECPKG_ATTR_ACCESS_TOKEN 18 +#define SECPKG_ATTR_TARGET 19 +#define SECPKG_ATTR_AUTHENTICATION_ID 20 +#define SECPKG_ATTR_LOGOFF_TIME 21 +#define SECPKG_ATTR_NEGO_KEYS 22 +#define SECPKG_ATTR_PROMPTING_NEEDED 24 +#define SECPKG_ATTR_UNIQUE_BINDINGS 25 +#define SECPKG_ATTR_ENDPOINT_BINDINGS 26 +#define SECPKG_ATTR_CLIENT_SPECIFIED_TARGET 27 +#define SECPKG_ATTR_LAST_CLIENT_TOKEN_STATUS 30 +#define SECPKG_ATTR_NEGO_PKG_INFO 31 +#define SECPKG_ATTR_NEGO_STATUS 32 +#define SECPKG_ATTR_CONTEXT_DELETED 33 + +#if !defined(_WIN32) || defined(_UWP) + +typedef struct +{ + void* AccessToken; +} SecPkgContext_AccessToken; + +typedef struct +{ + UINT32 dwFlags; + UINT32 cbAppData; + BYTE* pbAppData; +} SecPkgContext_SessionAppData; + +typedef struct +{ + char* sAuthorityName; +} SecPkgContext_Authority; + +typedef struct +{ + char* sTargetName; +} SecPkgContext_ClientSpecifiedTarget; + +typedef UINT32 ALG_ID; + +typedef struct +{ + UINT32 dwProtocol; + ALG_ID aiCipher; + UINT32 dwCipherStrength; + ALG_ID aiHash; + UINT32 dwHashStrength; + ALG_ID aiExch; + UINT32 dwExchStrength; +} SecPkgContext_ConnectionInfo; + +typedef struct +{ + UINT32 AuthBufferLen; + BYTE* AuthBuffer; +} SecPkgContext_ClientCreds; + +typedef struct +{ + UINT32 AuthzSvc; + void* pPac; +} SecPkgContex_DceInfo; + +typedef struct +{ + UINT32 dwInitiatorAddrType; + UINT32 cbInitiatorLength; + UINT32 dwInitiatorOffset; + UINT32 dwAcceptorAddrType; + UINT32 cbAcceptorLength; + UINT32 dwAcceptorOffset; + UINT32 cbApplicationDataLength; + UINT32 dwApplicationDataOffset; +} SEC_CHANNEL_BINDINGS; + +typedef struct +{ + BYTE rgbKeys[128]; + BYTE rgbIVs[64]; +} SecPkgContext_EapKeyBlock; + +typedef struct +{ + UINT32 Flags; +} SecPkgContext_Flags; + +typedef struct +{ + char* sSignatureAlgorithmName; + char* sEncryptAlgorithmName; + UINT32 KeySize; + UINT32 SignatureAlgorithm; + UINT32 EncryptAlgorithm; +} SecPkgContext_KeyInfo; + +typedef struct +{ + TimeStamp tsStart; + TimeStamp tsExpiry; +} SecPkgContext_Lifespan; + +typedef struct +{ + char* sUserName; +} SecPkgContext_Names; + +typedef struct +{ + char* sClientName; + char* sServerName; +} SecPkgContext_NativeNames; + +typedef struct +{ + SecPkgInfo* PackageInfo; + UINT32 NegotiationState; +} SecPkgContext_NegotiationInfo; + +typedef struct +{ + SecPkgInfo* PackageInfo; +} SecPkgContext_PackageInfo; + +typedef struct +{ + TimeStamp tsPasswordExpires; +} SecPkgContext_PasswordExpiry; + +typedef struct +{ + UINT32 SessionKeyLength; + BYTE* SessionKey; +} SecPkgContext_SessionKey; + +typedef struct +{ + UINT32 dwFlags; + UINT32 cbSessionId; + BYTE rgbSessionId[32]; +} SecPkgContext_SessionInfo; + +typedef struct +{ + UINT32 cbMaxToken; + UINT32 cbMaxSignature; + UINT32 cbBlockSize; + UINT32 cbSecurityTrailer; +} SecPkgContext_Sizes; + +typedef struct +{ + UINT32 cbHeader; + UINT32 cbTrailer; + UINT32 cbMaximumMessage; + UINT32 cBuffers; + UINT32 cbBlockSize; +} SecPkgContext_StreamSizes; + +typedef struct +{ + void* AttributeInfo; +} SecPkgContext_SubjectAttributes; + +typedef struct +{ + UINT16 cSignatureAndHashAlgorithms; + UINT16* pSignatureAndHashAlgorithms; +} SecPkgContext_SupportedSignatures; + +typedef struct +{ + UINT32 MarshalledTargetInfoLength; + BYTE* MarshalledTargetInfo; +} SecPkgContext_TargetInformation; + +/* Security Credentials Attributes */ + +#define SECPKG_CRED_ATTR_NAMES 1 +#define SECPKG_CRED_ATTR_SSI_PROVIDER 2 +#define SECPKG_CRED_ATTR_CERT 4 +#define SECPKG_CRED_ATTR_PAC_BYPASS 5 + +typedef struct +{ + SEC_CHAR* sUserName; +} SecPkgCredentials_NamesA; +typedef SecPkgCredentials_NamesA* PSecPkgCredentials_NamesA; + +typedef struct +{ + SEC_WCHAR* sUserName; +} SecPkgCredentials_NamesW; +typedef SecPkgCredentials_NamesW* PSecPkgCredentials_NamesW; + +#ifdef UNICODE +#define SecPkgCredentials_Names SecPkgCredentials_NamesW +#define PSecPkgCredentials_Names PSecPkgCredentials_NamesW +#else +#define SecPkgCredentials_Names SecPkgCredentials_NamesA +#define PSecPkgCredentials_Names PSecPkgCredentials_NamesA +#endif + +typedef struct +{ + SEC_WCHAR* sProviderName; + unsigned long ProviderInfoLength; + char* ProviderInfo; +} SecPkgCredentials_SSIProviderW, *PSecPkgCredentials_SSIProviderW; + +typedef struct +{ + SEC_CHAR* sProviderName; + unsigned long ProviderInfoLength; + char* ProviderInfo; +} SecPkgCredentials_SSIProviderA, *PSecPkgCredentials_SSIProviderA; + +#ifdef UNICODE +#define SecPkgCredentials_SSIProvider SecPkgCredentials_SSIProviderW +#define PSecPkgCredentials_SSIProvider PSecPkgCredentials_SSIProviderW +#else +#define SecPkgCredentials_SSIProvider SecPkgCredentials_SSIProviderA +#define PSecPkgCredentials_SSIProvider PSecPkgCredentials_SSIProviderA +#endif + +typedef struct +{ + unsigned long EncodedCertSize; + unsigned char* EncodedCert; +} SecPkgCredentials_Cert, *PSecPkgCredentials_Cert; + +#endif /* !defined(_WIN32) || defined(_UWP) */ + +#if !defined(_WIN32) || defined(_UWP) || (defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 8)) + +#define SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS 3 + +#define KDC_PROXY_SETTINGS_V1 1 +#define KDC_PROXY_SETTINGS_FLAGS_FORCEPROXY 0x1 + +typedef struct +{ + ULONG Version; + ULONG Flags; + USHORT ProxyServerOffset; + USHORT ProxyServerLength; + USHORT ClientTlsCredOffset; + USHORT ClientTlsCredLength; +} SecPkgCredentials_KdcProxySettingsW, *PSecPkgCredentials_KdcProxySettingsW; + +typedef struct +{ + ULONG Version; + ULONG Flags; + USHORT ProxyServerOffset; + USHORT ProxyServerLength; + USHORT ClientTlsCredOffset; + USHORT ClientTlsCredLength; +} SecPkgCredentials_KdcProxySettingsA, *PSecPkgCredentials_KdcProxySettingsA; + +#ifdef UNICODE +#define SecPkgCredentials_KdcProxySettings SecPkgCredentials_KdcProxySettingsW +#define PSecPkgCredentials_KdcProxySettings PSecPkgCredentials_KdcProxySettingsW +#else +#define SecPkgCredentials_KdcProxySettings SecPkgCredentials_KdcProxySettingsA +#define PSecPkgCredentials_KdcProxySettings SecPkgCredentials_KdcProxySettingsA +#endif + +typedef struct +{ + UINT32 BindingsLength; + SEC_CHANNEL_BINDINGS* Bindings; +} SecPkgContext_Bindings; +#endif + +/* InitializeSecurityContext Flags */ + +#define ISC_REQ_DELEGATE 0x00000001 +#define ISC_REQ_MUTUAL_AUTH 0x00000002 +#define ISC_REQ_REPLAY_DETECT 0x00000004 +#define ISC_REQ_SEQUENCE_DETECT 0x00000008 +#define ISC_REQ_CONFIDENTIALITY 0x00000010 +#define ISC_REQ_USE_SESSION_KEY 0x00000020 +#define ISC_REQ_PROMPT_FOR_CREDS 0x00000040 +#define ISC_REQ_USE_SUPPLIED_CREDS 0x00000080 +#define ISC_REQ_ALLOCATE_MEMORY 0x00000100 +#define ISC_REQ_USE_DCE_STYLE 0x00000200 +#define ISC_REQ_DATAGRAM 0x00000400 +#define ISC_REQ_CONNECTION 0x00000800 +#define ISC_REQ_CALL_LEVEL 0x00001000 +#define ISC_REQ_FRAGMENT_SUPPLIED 0x00002000 +#define ISC_REQ_EXTENDED_ERROR 0x00004000 +#define ISC_REQ_STREAM 0x00008000 +#define ISC_REQ_INTEGRITY 0x00010000 +#define ISC_REQ_IDENTIFY 0x00020000 +#define ISC_REQ_NULL_SESSION 0x00040000 +#define ISC_REQ_MANUAL_CRED_VALIDATION 0x00080000 +#define ISC_REQ_RESERVED1 0x00100000 +#define ISC_REQ_FRAGMENT_TO_FIT 0x00200000 +#define ISC_REQ_FORWARD_CREDENTIALS 0x00400000 +#define ISC_REQ_NO_INTEGRITY 0x00800000 +#define ISC_REQ_USE_HTTP_STYLE 0x01000000 + +#define ISC_RET_DELEGATE 0x00000001 +#define ISC_RET_MUTUAL_AUTH 0x00000002 +#define ISC_RET_REPLAY_DETECT 0x00000004 +#define ISC_RET_SEQUENCE_DETECT 0x00000008 +#define ISC_RET_CONFIDENTIALITY 0x00000010 +#define ISC_RET_USE_SESSION_KEY 0x00000020 +#define ISC_RET_USED_COLLECTED_CREDS 0x00000040 +#define ISC_RET_USED_SUPPLIED_CREDS 0x00000080 +#define ISC_RET_ALLOCATED_MEMORY 0x00000100 +#define ISC_RET_USED_DCE_STYLE 0x00000200 +#define ISC_RET_DATAGRAM 0x00000400 +#define ISC_RET_CONNECTION 0x00000800 +#define ISC_RET_INTERMEDIATE_RETURN 0x00001000 +#define ISC_RET_CALL_LEVEL 0x00002000 +#define ISC_RET_EXTENDED_ERROR 0x00004000 +#define ISC_RET_STREAM 0x00008000 +#define ISC_RET_INTEGRITY 0x00010000 +#define ISC_RET_IDENTIFY 0x00020000 +#define ISC_RET_NULL_SESSION 0x00040000 +#define ISC_RET_MANUAL_CRED_VALIDATION 0x00080000 +#define ISC_RET_RESERVED1 0x00100000 +#define ISC_RET_FRAGMENT_ONLY 0x00200000 +#define ISC_RET_FORWARD_CREDENTIALS 0x00400000 +#define ISC_RET_USED_HTTP_STYLE 0x01000000 + +/* AcceptSecurityContext Flags */ + +#define ASC_REQ_DELEGATE 0x00000001 +#define ASC_REQ_MUTUAL_AUTH 0x00000002 +#define ASC_REQ_REPLAY_DETECT 0x00000004 +#define ASC_REQ_SEQUENCE_DETECT 0x00000008 +#define ASC_REQ_CONFIDENTIALITY 0x00000010 +#define ASC_REQ_USE_SESSION_KEY 0x00000020 +#define ASC_REQ_ALLOCATE_MEMORY 0x00000100 +#define ASC_REQ_USE_DCE_STYLE 0x00000200 +#define ASC_REQ_DATAGRAM 0x00000400 +#define ASC_REQ_CONNECTION 0x00000800 +#define ASC_REQ_CALL_LEVEL 0x00001000 +#define ASC_REQ_EXTENDED_ERROR 0x00008000 +#define ASC_REQ_STREAM 0x00010000 +#define ASC_REQ_INTEGRITY 0x00020000 +#define ASC_REQ_LICENSING 0x00040000 +#define ASC_REQ_IDENTIFY 0x00080000 +#define ASC_REQ_ALLOW_NULL_SESSION 0x00100000 +#define ASC_REQ_ALLOW_NON_USER_LOGONS 0x00200000 +#define ASC_REQ_ALLOW_CONTEXT_REPLAY 0x00400000 +#define ASC_REQ_FRAGMENT_TO_FIT 0x00800000 +#define ASC_REQ_FRAGMENT_SUPPLIED 0x00002000 +#define ASC_REQ_NO_TOKEN 0x01000000 +#define ASC_REQ_PROXY_BINDINGS 0x04000000 +#define ASC_REQ_ALLOW_MISSING_BINDINGS 0x10000000 + +#define ASC_RET_DELEGATE 0x00000001 +#define ASC_RET_MUTUAL_AUTH 0x00000002 +#define ASC_RET_REPLAY_DETECT 0x00000004 +#define ASC_RET_SEQUENCE_DETECT 0x00000008 +#define ASC_RET_CONFIDENTIALITY 0x00000010 +#define ASC_RET_USE_SESSION_KEY 0x00000020 +#define ASC_RET_ALLOCATED_MEMORY 0x00000100 +#define ASC_RET_USED_DCE_STYLE 0x00000200 +#define ASC_RET_DATAGRAM 0x00000400 +#define ASC_RET_CONNECTION 0x00000800 +#define ASC_RET_CALL_LEVEL 0x00002000 +#define ASC_RET_THIRD_LEG_FAILED 0x00004000 +#define ASC_RET_EXTENDED_ERROR 0x00008000 +#define ASC_RET_STREAM 0x00010000 +#define ASC_RET_INTEGRITY 0x00020000 +#define ASC_RET_LICENSING 0x00040000 +#define ASC_RET_IDENTIFY 0x00080000 +#define ASC_RET_NULL_SESSION 0x00100000 +#define ASC_RET_ALLOW_NON_USER_LOGONS 0x00200000 +#define ASC_RET_FRAGMENT_ONLY 0x00800000 +#define ASC_RET_NO_TOKEN 0x01000000 +#define ASC_RET_NO_PROXY_BINDINGS 0x04000000 +#define ASC_RET_MISSING_BINDINGS 0x10000000 + +#define SEC_WINNT_AUTH_IDENTITY_ANSI 0x1 +#define SEC_WINNT_AUTH_IDENTITY_UNICODE 0x2 +#define SEC_WINNT_AUTH_IDENTITY_MARSHALLED 0x4 +#define SEC_WINNT_AUTH_IDENTITY_ONLY 0x8 +#define SEC_WINNT_AUTH_IDENTITY_EXTENDED 0x100 + +#if !defined(_WIN32) || defined(_UWP) || defined(__MINGW32__) + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#ifndef _AUTH_IDENTITY_DEFINED +#define _AUTH_IDENTITY_DEFINED + +typedef struct +{ + UINT16* User; + ULONG UserLength; + UINT16* Domain; + ULONG DomainLength; + UINT16* Password; + ULONG PasswordLength; + UINT32 Flags; +} SEC_WINNT_AUTH_IDENTITY_W, *PSEC_WINNT_AUTH_IDENTITY_W; + +typedef struct +{ + BYTE* User; + ULONG UserLength; + BYTE* Domain; + ULONG DomainLength; + BYTE* Password; + ULONG PasswordLength; + UINT32 Flags; +} SEC_WINNT_AUTH_IDENTITY_A, *PSEC_WINNT_AUTH_IDENTITY_A; + +// Always define SEC_WINNT_AUTH_IDENTITY to SEC_WINNT_AUTH_IDENTITY_W + +#ifdef UNICODE +#define SEC_WINNT_AUTH_IDENTITY SEC_WINNT_AUTH_IDENTITY_W +#define PSEC_WINNT_AUTH_IDENTITY PSEC_WINNT_AUTH_IDENTITY_W +#else +#define SEC_WINNT_AUTH_IDENTITY SEC_WINNT_AUTH_IDENTITY_W +#define PSEC_WINNT_AUTH_IDENTITY PSEC_WINNT_AUTH_IDENTITY_W +#endif + +#endif /* _AUTH_IDENTITY_DEFINED */ + +#ifndef SEC_WINNT_AUTH_IDENTITY_VERSION +#define SEC_WINNT_AUTH_IDENTITY_VERSION 0x200 + +typedef struct +{ + UINT32 Version; + UINT32 Length; + UINT16* User; + UINT32 UserLength; + UINT16* Domain; + UINT32 DomainLength; + UINT16* Password; + UINT32 PasswordLength; + UINT32 Flags; + UINT16* PackageList; + UINT32 PackageListLength; +} SEC_WINNT_AUTH_IDENTITY_EXW, *PSEC_WINNT_AUTH_IDENTITY_EXW; + +typedef struct +{ + UINT32 Version; + UINT32 Length; + BYTE* User; + UINT32 UserLength; + BYTE* Domain; + UINT32 DomainLength; + BYTE* Password; + UINT32 PasswordLength; + UINT32 Flags; + BYTE* PackageList; + UINT32 PackageListLength; +} SEC_WINNT_AUTH_IDENTITY_EXA, *PSEC_WINNT_AUTH_IDENTITY_EXA; + +#ifdef UNICODE +#define SEC_WINNT_AUTH_IDENTITY_EX SEC_WINNT_AUTH_IDENTITY_EXW +#define PSEC_WINNT_AUTH_IDENTITY_EX PSEC_WINNT_AUTH_IDENTITY_EXW +#else +#define SEC_WINNT_AUTH_IDENTITY_EX SEC_WINNT_AUTH_IDENTITY_EXA +#define PSEC_WINNT_AUTH_IDENTITY_EX PSEC_WINNT_AUTH_IDENTITY_EXA +#endif + +#endif /* SEC_WINNT_AUTH_IDENTITY_VERSION */ + +#ifndef SEC_WINNT_AUTH_IDENTITY_VERSION_2 +#define SEC_WINNT_AUTH_IDENTITY_VERSION_2 0x201 + +typedef struct +{ + UINT32 Version; + UINT16 cbHeaderLength; + UINT32 cbStructureLength; + UINT32 UserOffset; + UINT16 UserLength; + UINT32 DomainOffset; + UINT16 DomainLength; + UINT32 PackedCredentialsOffset; + UINT16 PackedCredentialsLength; + UINT32 Flags; + UINT32 PackageListOffset; + UINT16 PackageListLength; +} SEC_WINNT_AUTH_IDENTITY_EX2, *PSEC_WINNT_AUTH_IDENTITY_EX2; + +#endif /* SEC_WINNT_AUTH_IDENTITY_VERSION_2 */ + +#ifndef _AUTH_IDENTITY_INFO_DEFINED +#define _AUTH_IDENTITY_INFO_DEFINED + +// https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-sec_winnt_auth_identity_info + +typedef union +{ + SEC_WINNT_AUTH_IDENTITY_EXW AuthIdExw; + SEC_WINNT_AUTH_IDENTITY_EXA AuthIdExa; + SEC_WINNT_AUTH_IDENTITY_A AuthId_a; + SEC_WINNT_AUTH_IDENTITY_W AuthId_w; + SEC_WINNT_AUTH_IDENTITY_EX2 AuthIdEx2; +} SEC_WINNT_AUTH_IDENTITY_INFO, *PSEC_WINNT_AUTH_IDENTITY_INFO; + +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_PROCESS_ENCRYPTED 0x10 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SYSTEM_PROTECTED 0x20 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_USER_PROTECTED 0x40 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SYSTEM_ENCRYPTED 0x80 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_RESERVED 0x10000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_NULL_USER 0x20000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_NULL_DOMAIN 0x40000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_ID_PROVIDER 0x80000 + +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_USE_MASK 0xFF000000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_CREDPROV_DO_NOT_SAVE 0x80000000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_SAVE_CRED_CHECKED 0x40000000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_NO_CHECKBOX 0x20000000 +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_CREDPROV_DO_NOT_LOAD 0x10000000 + +#define SEC_WINNT_AUTH_IDENTITY_FLAGS_VALID_SSPIPFC_FLAGS \ + (SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_CREDPROV_DO_NOT_SAVE | \ + SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_SAVE_CRED_CHECKED | \ + SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_NO_CHECKBOX | \ + SEC_WINNT_AUTH_IDENTITY_FLAGS_SSPIPFC_CREDPROV_DO_NOT_LOAD) + +#endif /* _AUTH_IDENTITY_INFO_DEFINED */ + +WINPR_PRAGMA_DIAG_POP + +#if !defined(__MINGW32__) +typedef struct +{ + ULONG_PTR dwLower; + ULONG_PTR dwUpper; +} SecHandle; +typedef SecHandle* PSecHandle; + +typedef SecHandle CredHandle; +typedef CredHandle* PCredHandle; +typedef SecHandle CtxtHandle; +typedef CtxtHandle* PCtxtHandle; + +#define SecInvalidateHandle(x) \ + ((PSecHandle)(x))->dwLower = ((PSecHandle)(x))->dwUpper = ((ULONG_PTR)((INT_PTR)-1)) + +#define SecIsValidHandle(x) \ + ((((PSecHandle)(x))->dwLower != ((ULONG_PTR)((INT_PTR)-1))) && \ + (((PSecHandle)(x))->dwUpper != ((ULONG_PTR)((INT_PTR)-1)))) + +typedef struct +{ + ULONG cbBuffer; + ULONG BufferType; + void* pvBuffer; +} SecBuffer; +typedef SecBuffer* PSecBuffer; + +typedef struct +{ + ULONG ulVersion; + ULONG cBuffers; + PSecBuffer pBuffers; +} SecBufferDesc; +typedef SecBufferDesc* PSecBufferDesc; + +#endif /* __MINGW32__ */ + +#endif /* !defined(_WIN32) || defined(_UWP) || defined(__MINGW32__) */ + +typedef SECURITY_STATUS (*psSspiNtlmHashCallback)(void* client, + const SEC_WINNT_AUTH_IDENTITY* authIdentity, + const SecBuffer* ntproofvalue, + const BYTE* randkey, const BYTE* mic, + const SecBuffer* micvalue, BYTE* ntlmhash); + +typedef struct +{ + char* samFile; + psSspiNtlmHashCallback hashCallback; + void* hashCallbackArg; +} SEC_WINPR_NTLM_SETTINGS; + +typedef struct +{ + char* kdcUrl; + char* keytab; + char* cache; + char* armorCache; + char* pkinitX509Anchors; + char* pkinitX509Identity; + BOOL withPac; + INT32 startTime; + INT32 renewLifeTime; + INT32 lifeTime; + BYTE certSha1[20]; +} SEC_WINPR_KERBEROS_SETTINGS; + +typedef struct +{ + SEC_WINNT_AUTH_IDENTITY_EXW identity; + SEC_WINPR_NTLM_SETTINGS* ntlmSettings; + SEC_WINPR_KERBEROS_SETTINGS* kerberosSettings; +} SEC_WINNT_AUTH_IDENTITY_WINPR; + +#define SECBUFFER_VERSION 0 + +/* Buffer Types */ +#define SECBUFFER_EMPTY 0 +#define SECBUFFER_DATA 1 +#define SECBUFFER_TOKEN 2 +#define SECBUFFER_PKG_PARAMS 3 +#define SECBUFFER_MISSING 4 +#define SECBUFFER_EXTRA 5 +#define SECBUFFER_STREAM_TRAILER 6 +#define SECBUFFER_STREAM_HEADER 7 +#define SECBUFFER_NEGOTIATION_INFO 8 +#define SECBUFFER_PADDING 9 +#define SECBUFFER_STREAM 10 +#define SECBUFFER_MECHLIST 11 +#define SECBUFFER_MECHLIST_SIGNATURE 12 +#define SECBUFFER_TARGET 13 +#define SECBUFFER_CHANNEL_BINDINGS 14 +#define SECBUFFER_CHANGE_PASS_RESPONSE 15 +#define SECBUFFER_TARGET_HOST 16 +#define SECBUFFER_ALERT 17 + +/* Security Buffer Flags */ +#define SECBUFFER_ATTRMASK 0xF0000000 +#define SECBUFFER_READONLY 0x80000000 +#define SECBUFFER_READONLY_WITH_CHECKSUM 0x10000000 +#define SECBUFFER_RESERVED 0x60000000 + +#if !defined(_WIN32) || defined(_UWP) + +typedef void(SEC_ENTRY* SEC_GET_KEY_FN)(void* Arg, void* Principal, UINT32 KeyVer, void** Key, + SECURITY_STATUS* pStatus); + +typedef SECURITY_STATUS(SEC_ENTRY* ENUMERATE_SECURITY_PACKAGES_FN_A)(ULONG* pcPackages, + PSecPkgInfoA* ppPackageInfo); +typedef SECURITY_STATUS(SEC_ENTRY* ENUMERATE_SECURITY_PACKAGES_FN_W)(ULONG* pcPackages, + PSecPkgInfoW* ppPackageInfo); + +#ifdef UNICODE +#define EnumerateSecurityPackages EnumerateSecurityPackagesW +#define ENUMERATE_SECURITY_PACKAGES_FN ENUMERATE_SECURITY_PACKAGES_FN_W +#else +#define EnumerateSecurityPackages EnumerateSecurityPackagesA +#define ENUMERATE_SECURITY_PACKAGES_FN ENUMERATE_SECURITY_PACKAGES_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_CREDENTIALS_ATTRIBUTES_FN_A)(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer); +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_CREDENTIALS_ATTRIBUTES_FN_W)(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer); + +#ifdef UNICODE +#define QueryCredentialsAttributes QueryCredentialsAttributesW +#define QUERY_CREDENTIALS_ATTRIBUTES_FN QUERY_CREDENTIALS_ATTRIBUTES_FN_W +#else +#define QueryCredentialsAttributes QueryCredentialsAttributesA +#define QUERY_CREDENTIALS_ATTRIBUTES_FN QUERY_CREDENTIALS_ATTRIBUTES_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* ACQUIRE_CREDENTIALS_HANDLE_FN_A)( + LPSTR pszPrincipal, LPSTR pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, + SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry); +typedef SECURITY_STATUS(SEC_ENTRY* ACQUIRE_CREDENTIALS_HANDLE_FN_W)( + LPWSTR pszPrincipal, LPWSTR pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, + SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry); + +#ifdef UNICODE +#define AcquireCredentialsHandle AcquireCredentialsHandleW +#define ACQUIRE_CREDENTIALS_HANDLE_FN ACQUIRE_CREDENTIALS_HANDLE_FN_W +#else +#define AcquireCredentialsHandle AcquireCredentialsHandleA +#define ACQUIRE_CREDENTIALS_HANDLE_FN ACQUIRE_CREDENTIALS_HANDLE_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* FREE_CREDENTIALS_HANDLE_FN)(PCredHandle phCredential); + +typedef SECURITY_STATUS(SEC_ENTRY* INITIALIZE_SECURITY_CONTEXT_FN_A)( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry); +typedef SECURITY_STATUS(SEC_ENTRY* INITIALIZE_SECURITY_CONTEXT_FN_W)( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry); + +#ifdef UNICODE +#define InitializeSecurityContext InitializeSecurityContextW +#define INITIALIZE_SECURITY_CONTEXT_FN INITIALIZE_SECURITY_CONTEXT_FN_W +#else +#define InitializeSecurityContext InitializeSecurityContextA +#define INITIALIZE_SECURITY_CONTEXT_FN INITIALIZE_SECURITY_CONTEXT_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* ACCEPT_SECURITY_CONTEXT_FN)( + PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq, + ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsTimeStamp); + +typedef SECURITY_STATUS(SEC_ENTRY* COMPLETE_AUTH_TOKEN_FN)(PCtxtHandle phContext, + PSecBufferDesc pToken); + +typedef SECURITY_STATUS(SEC_ENTRY* DELETE_SECURITY_CONTEXT_FN)(PCtxtHandle phContext); + +typedef SECURITY_STATUS(SEC_ENTRY* APPLY_CONTROL_TOKEN_FN)(PCtxtHandle phContext, + PSecBufferDesc pInput); + +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_CONTEXT_ATTRIBUTES_FN_A)(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer); +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_CONTEXT_ATTRIBUTES_FN_W)(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer); + +#ifdef UNICODE +#define QueryContextAttributes QueryContextAttributesW +#define QUERY_CONTEXT_ATTRIBUTES_FN QUERY_CONTEXT_ATTRIBUTES_FN_W +#else +#define QueryContextAttributes QueryContextAttributesA +#define QUERY_CONTEXT_ATTRIBUTES_FN QUERY_CONTEXT_ATTRIBUTES_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* IMPERSONATE_SECURITY_CONTEXT_FN)(PCtxtHandle phContext); + +typedef SECURITY_STATUS(SEC_ENTRY* REVERT_SECURITY_CONTEXT_FN)(PCtxtHandle phContext); + +typedef SECURITY_STATUS(SEC_ENTRY* MAKE_SIGNATURE_FN)(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo); + +typedef SECURITY_STATUS(SEC_ENTRY* VERIFY_SIGNATURE_FN)(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP); + +typedef SECURITY_STATUS(SEC_ENTRY* FREE_CONTEXT_BUFFER_FN)(void* pvContextBuffer); + +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_SECURITY_PACKAGE_INFO_FN_A)(SEC_CHAR* pszPackageName, + PSecPkgInfoA* ppPackageInfo); +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_SECURITY_PACKAGE_INFO_FN_W)(SEC_WCHAR* pszPackageName, + PSecPkgInfoW* ppPackageInfo); + +#ifdef UNICODE +#define QuerySecurityPackageInfo QuerySecurityPackageInfoW +#define QUERY_SECURITY_PACKAGE_INFO_FN QUERY_SECURITY_PACKAGE_INFO_FN_W +#else +#define QuerySecurityPackageInfo QuerySecurityPackageInfoA +#define QUERY_SECURITY_PACKAGE_INFO_FN QUERY_SECURITY_PACKAGE_INFO_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* EXPORT_SECURITY_CONTEXT_FN)(PCtxtHandle phContext, ULONG fFlags, + PSecBuffer pPackedContext, + HANDLE* pToken); + +typedef SECURITY_STATUS(SEC_ENTRY* IMPORT_SECURITY_CONTEXT_FN_A)(SEC_CHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, + PCtxtHandle phContext); +typedef SECURITY_STATUS(SEC_ENTRY* IMPORT_SECURITY_CONTEXT_FN_W)(SEC_WCHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, + PCtxtHandle phContext); + +#ifdef UNICODE +#define ImportSecurityContext ImportSecurityContextW +#define IMPORT_SECURITY_CONTEXT_FN IMPORT_SECURITY_CONTEXT_FN_W +#else +#define ImportSecurityContext ImportSecurityContextA +#define IMPORT_SECURITY_CONTEXT_FN IMPORT_SECURITY_CONTEXT_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* ADD_CREDENTIALS_FN_A)( + PCredHandle hCredentials, SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, UINT32 fCredentialUse, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PTimeStamp ptsExpiry); +typedef SECURITY_STATUS(SEC_ENTRY* ADD_CREDENTIALS_FN_W)( + PCredHandle hCredentials, SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, UINT32 fCredentialUse, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PTimeStamp ptsExpiry); + +#ifdef UNICODE +#define AddCredentials AddCredentialsW +#define ADD_CREDENTIALS_FN ADD_CREDENTIALS_FN_W +#else +#define AddCredentials AddCredentialsA +#define ADD_CREDENTIALS_FN ADD_CREDENTIALS_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* QUERY_SECURITY_CONTEXT_TOKEN_FN)(PCtxtHandle phContext, + HANDLE* phToken); + +typedef SECURITY_STATUS(SEC_ENTRY* ENCRYPT_MESSAGE_FN)(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo); + +typedef SECURITY_STATUS(SEC_ENTRY* DECRYPT_MESSAGE_FN)(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP); + +typedef SECURITY_STATUS(SEC_ENTRY* SET_CONTEXT_ATTRIBUTES_FN_A)(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer); +typedef SECURITY_STATUS(SEC_ENTRY* SET_CONTEXT_ATTRIBUTES_FN_W)(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer); + +#ifdef UNICODE +#define SetContextAttributes SetContextAttributesW +#define SET_CONTEXT_ATTRIBUTES_FN SET_CONTEXT_ATTRIBUTES_FN_W +#else +#define SetContextAttributes SetContextAttributesA +#define SET_CONTEXT_ATTRIBUTES_FN SET_CONTEXT_ATTRIBUTES_FN_A +#endif + +typedef SECURITY_STATUS(SEC_ENTRY* SET_CREDENTIALS_ATTRIBUTES_FN_A)(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer); + +typedef SECURITY_STATUS(SEC_ENTRY* SET_CREDENTIALS_ATTRIBUTES_FN_W)(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer); + +#ifdef UNICODE +#define SetCredentialsAttributes SetCredentialsAttributesW +#define SET_CREDENTIALS_ATTRIBUTES_FN SET_CREDENTIALS_ATTRIBUTES_FN_W +#else +#define SetCredentialsAttributes SetCredentialsAttributesA +#define SET_CREDENTIALS_ATTRIBUTES_FN SET_CREDENTIALS_ATTRIBUTES_FN_A +#endif + +#define SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION \ + 1 /* Interface has all routines through DecryptMessage */ +#define SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2 \ + 2 /* Interface has all routines through SetContextAttributes */ +#define SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_3 \ + 3 /* Interface has all routines through SetCredentialsAttributes */ +#define SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_4 \ + 4 /* Interface has all routines through ChangeAccountPassword */ + +typedef struct +{ + UINT32 dwVersion; + ENUMERATE_SECURITY_PACKAGES_FN_A EnumerateSecurityPackagesA; + QUERY_CREDENTIALS_ATTRIBUTES_FN_A QueryCredentialsAttributesA; + ACQUIRE_CREDENTIALS_HANDLE_FN_A AcquireCredentialsHandleA; + FREE_CREDENTIALS_HANDLE_FN FreeCredentialsHandle; + void* Reserved2; + INITIALIZE_SECURITY_CONTEXT_FN_A InitializeSecurityContextA; + ACCEPT_SECURITY_CONTEXT_FN AcceptSecurityContext; + COMPLETE_AUTH_TOKEN_FN CompleteAuthToken; + DELETE_SECURITY_CONTEXT_FN DeleteSecurityContext; + APPLY_CONTROL_TOKEN_FN ApplyControlToken; + QUERY_CONTEXT_ATTRIBUTES_FN_A QueryContextAttributesA; + IMPERSONATE_SECURITY_CONTEXT_FN ImpersonateSecurityContext; + REVERT_SECURITY_CONTEXT_FN RevertSecurityContext; + MAKE_SIGNATURE_FN MakeSignature; + VERIFY_SIGNATURE_FN VerifySignature; + FREE_CONTEXT_BUFFER_FN FreeContextBuffer; + QUERY_SECURITY_PACKAGE_INFO_FN_A QuerySecurityPackageInfoA; + void* Reserved3; + void* Reserved4; + EXPORT_SECURITY_CONTEXT_FN ExportSecurityContext; + IMPORT_SECURITY_CONTEXT_FN_A ImportSecurityContextA; + ADD_CREDENTIALS_FN_A AddCredentialsA; + void* Reserved8; + QUERY_SECURITY_CONTEXT_TOKEN_FN QuerySecurityContextToken; + ENCRYPT_MESSAGE_FN EncryptMessage; + DECRYPT_MESSAGE_FN DecryptMessage; + SET_CONTEXT_ATTRIBUTES_FN_A SetContextAttributesA; + SET_CREDENTIALS_ATTRIBUTES_FN_A SetCredentialsAttributesA; +} SecurityFunctionTableA; +typedef SecurityFunctionTableA* PSecurityFunctionTableA; + +typedef struct +{ + UINT32 dwVersion; + ENUMERATE_SECURITY_PACKAGES_FN_W EnumerateSecurityPackagesW; + QUERY_CREDENTIALS_ATTRIBUTES_FN_W QueryCredentialsAttributesW; + ACQUIRE_CREDENTIALS_HANDLE_FN_W AcquireCredentialsHandleW; + FREE_CREDENTIALS_HANDLE_FN FreeCredentialsHandle; + void* Reserved2; + INITIALIZE_SECURITY_CONTEXT_FN_W InitializeSecurityContextW; + ACCEPT_SECURITY_CONTEXT_FN AcceptSecurityContext; + COMPLETE_AUTH_TOKEN_FN CompleteAuthToken; + DELETE_SECURITY_CONTEXT_FN DeleteSecurityContext; + APPLY_CONTROL_TOKEN_FN ApplyControlToken; + QUERY_CONTEXT_ATTRIBUTES_FN_W QueryContextAttributesW; + IMPERSONATE_SECURITY_CONTEXT_FN ImpersonateSecurityContext; + REVERT_SECURITY_CONTEXT_FN RevertSecurityContext; + MAKE_SIGNATURE_FN MakeSignature; + VERIFY_SIGNATURE_FN VerifySignature; + FREE_CONTEXT_BUFFER_FN FreeContextBuffer; + QUERY_SECURITY_PACKAGE_INFO_FN_W QuerySecurityPackageInfoW; + void* Reserved3; + void* Reserved4; + EXPORT_SECURITY_CONTEXT_FN ExportSecurityContext; + IMPORT_SECURITY_CONTEXT_FN_W ImportSecurityContextW; + ADD_CREDENTIALS_FN_W AddCredentialsW; + void* Reserved8; + QUERY_SECURITY_CONTEXT_TOKEN_FN QuerySecurityContextToken; + ENCRYPT_MESSAGE_FN EncryptMessage; + DECRYPT_MESSAGE_FN DecryptMessage; + SET_CONTEXT_ATTRIBUTES_FN_W SetContextAttributesW; + SET_CREDENTIALS_ATTRIBUTES_FN_W SetCredentialsAttributesW; +} SecurityFunctionTableW; +typedef SecurityFunctionTableW* PSecurityFunctionTableW; + +typedef PSecurityFunctionTableA(SEC_ENTRY* INIT_SECURITY_INTERFACE_A)(void); +typedef PSecurityFunctionTableW(SEC_ENTRY* INIT_SECURITY_INTERFACE_W)(void); + +#ifdef UNICODE +#define InitSecurityInterface InitSecurityInterfaceW +#define SecurityFunctionTable SecurityFunctionTableW +#define PSecurityFunctionTable PSecurityFunctionTableW +#define INIT_SECURITY_INTERFACE INIT_SECURITY_INTERFACE_W +#else +#define InitSecurityInterface InitSecurityInterfaceA +#define SecurityFunctionTable SecurityFunctionTableA +#define PSecurityFunctionTable PSecurityFunctionTableA +#define INIT_SECURITY_INTERFACE INIT_SECURITY_INTERFACE_A +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef SSPI_DLL + + /* Package Management */ + + WINPR_API SECURITY_STATUS SEC_ENTRY EnumerateSecurityPackagesA(ULONG* pcPackages, + PSecPkgInfoA* ppPackageInfo); + WINPR_API SECURITY_STATUS SEC_ENTRY EnumerateSecurityPackagesW(ULONG* pcPackages, + PSecPkgInfoW* ppPackageInfo); + + WINPR_API PSecurityFunctionTableA SEC_ENTRY InitSecurityInterfaceA(void); + WINPR_API PSecurityFunctionTableW SEC_ENTRY InitSecurityInterfaceW(void); + + WINPR_API SECURITY_STATUS SEC_ENTRY QuerySecurityPackageInfoA(SEC_CHAR* pszPackageName, + PSecPkgInfoA* ppPackageInfo); + WINPR_API SECURITY_STATUS SEC_ENTRY QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, + PSecPkgInfoW* ppPackageInfo); + + /* Credential Management */ + + WINPR_API SECURITY_STATUS SEC_ENTRY AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry); + WINPR_API SECURITY_STATUS SEC_ENTRY AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry); + + WINPR_API SECURITY_STATUS SEC_ENTRY ExportSecurityContext(PCtxtHandle phContext, ULONG fFlags, + PSecBuffer pPackedContext, + HANDLE* pToken); + WINPR_API SECURITY_STATUS SEC_ENTRY FreeCredentialsHandle(PCredHandle phCredential); + + WINPR_API SECURITY_STATUS SEC_ENTRY ImportSecurityContextA(SEC_CHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, + PCtxtHandle phContext); + WINPR_API SECURITY_STATUS SEC_ENTRY ImportSecurityContextW(SEC_WCHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, + PCtxtHandle phContext); + + WINPR_API SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer); + WINPR_API SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer); + + /* Context Management */ + + WINPR_API SECURITY_STATUS SEC_ENTRY + AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, + ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp); + + WINPR_API SECURITY_STATUS SEC_ENTRY ApplyControlToken(PCtxtHandle phContext, + PSecBufferDesc pInput); + WINPR_API SECURITY_STATUS SEC_ENTRY CompleteAuthToken(PCtxtHandle phContext, + PSecBufferDesc pToken); + WINPR_API SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext); + WINPR_API SECURITY_STATUS SEC_ENTRY FreeContextBuffer(void* pvContextBuffer); + WINPR_API SECURITY_STATUS SEC_ENTRY ImpersonateSecurityContext(PCtxtHandle phContext); + + WINPR_API SECURITY_STATUS SEC_ENTRY InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsExpiry); + WINPR_API SECURITY_STATUS SEC_ENTRY InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, + ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, + ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsExpiry); + + WINPR_API SECURITY_STATUS SEC_ENTRY QueryContextAttributes(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer); + WINPR_API SECURITY_STATUS SEC_ENTRY QuerySecurityContextToken(PCtxtHandle phContext, + HANDLE* phToken); + WINPR_API SECURITY_STATUS SEC_ENTRY SetContextAttributes(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer); + WINPR_API SECURITY_STATUS SEC_ENTRY RevertSecurityContext(PCtxtHandle phContext); + + /* Message Support */ + + WINPR_API SECURITY_STATUS SEC_ENTRY DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP); + WINPR_API SECURITY_STATUS SEC_ENTRY EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo); + WINPR_API SECURITY_STATUS SEC_ENTRY MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo); + WINPR_API SECURITY_STATUS SEC_ENTRY VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP); + +#endif /* SSPI_DLL */ + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* Custom API */ + +/* Extended SECPKG_ATTR IDs begin at 1000 */ +#define SECPKG_ATTR_AUTH_IDENTITY 1001 +#define SECPKG_ATTR_AUTH_PASSWORD 1002 +#define SECPKG_ATTR_AUTH_NTLM_HASH 1003 +#define SECPKG_ATTR_AUTH_NTLM_MESSAGE 1100 +#define SECPKG_ATTR_AUTH_NTLM_TIMESTAMP 1101 +#define SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE 1102 +#define SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE 1103 +#define SECPKG_ATTR_AUTH_NTLM_NTPROOF_VALUE 1104 +#define SECPKG_ATTR_AUTH_NTLM_RANDKEY 1105 +#define SECPKG_ATTR_AUTH_NTLM_MIC 1106 +#define SECPKG_ATTR_AUTH_NTLM_MIC_VALUE 1107 + +#define SECPKG_CRED_ATTR_TICKET_LOGON 1200 + + typedef struct + { + char User[256 + 1]; + char Domain[256 + 1]; + } SecPkgContext_AuthIdentity; + + typedef struct + { + char Password[256 + 1]; + } SecPkgContext_AuthPassword; + + typedef struct + { + int Version; + BYTE NtlmHash[16]; + } SecPkgContext_AuthNtlmHash; + + typedef struct + { + BYTE Timestamp[8]; + BOOL ChallengeOrResponse; + } SecPkgContext_AuthNtlmTimestamp; + + typedef struct + { + BYTE ClientChallenge[8]; + } SecPkgContext_AuthNtlmClientChallenge; + + typedef struct + { + BYTE ServerChallenge[8]; + } SecPkgContext_AuthNtlmServerChallenge; + + typedef struct + { + UINT32 type; + UINT32 length; + BYTE* buffer; + } SecPkgContext_AuthNtlmMessage; + +#define SSPI_INTERFACE_WINPR 0x00000001 +#define SSPI_INTERFACE_NATIVE 0x00000002 + + typedef PSecurityFunctionTableA(SEC_ENTRY* INIT_SECURITY_INTERFACE_EX_A)(DWORD flags); + typedef PSecurityFunctionTableW(SEC_ENTRY* INIT_SECURITY_INTERFACE_EX_W)(DWORD flags); + + WINPR_API void sspi_GlobalInit(void); + WINPR_API void sspi_GlobalFinish(void); + + WINPR_API void* sspi_SecBufferAlloc(PSecBuffer SecBuffer, ULONG size); + WINPR_API void sspi_SecBufferFree(PSecBuffer SecBuffer); + +#define sspi_SetAuthIdentity sspi_SetAuthIdentityA + WINPR_API int sspi_SetAuthIdentityA(SEC_WINNT_AUTH_IDENTITY* identity, const char* user, + const char* domain, const char* password); + WINPR_API int sspi_SetAuthIdentityW(SEC_WINNT_AUTH_IDENTITY* identity, const WCHAR* user, + const WCHAR* domain, const WCHAR* password); + WINPR_API int sspi_SetAuthIdentityWithLengthW(SEC_WINNT_AUTH_IDENTITY* identity, + const WCHAR* user, size_t userLen, + const WCHAR* domain, size_t domainLen, + const WCHAR* password, size_t passwordLen); + WINPR_API UINT32 sspi_GetAuthIdentityVersion(const void* identity); + WINPR_API UINT32 sspi_GetAuthIdentityFlags(const void* identity); + WINPR_API BOOL sspi_GetAuthIdentityUserDomainW(const void* identity, const WCHAR** pUser, + UINT32* pUserLength, const WCHAR** pDomain, + UINT32* pDomainLength); + WINPR_API BOOL sspi_GetAuthIdentityUserDomainA(const void* identity, const char** pUser, + UINT32* pUserLength, const char** pDomain, + UINT32* pDomainLength); + WINPR_API BOOL sspi_GetAuthIdentityPasswordW(const void* identity, const WCHAR** pPassword, + UINT32* pPasswordLength); + WINPR_API BOOL sspi_GetAuthIdentityPasswordA(const void* identity, const char** pPassword, + UINT32* pPasswordLength); + WINPR_API BOOL sspi_CopyAuthIdentityFieldsA(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, + char** pUser, char** pDomain, char** pPassword); + WINPR_API BOOL sspi_CopyAuthIdentityFieldsW(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, + WCHAR** pUser, WCHAR** pDomain, WCHAR** pPassword); + WINPR_API BOOL sspi_CopyAuthPackageListA(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, + char** pPackageList); + WINPR_API int sspi_CopyAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, + const SEC_WINNT_AUTH_IDENTITY_INFO* srcIdentity); + + WINPR_API void sspi_FreeAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity); + + WINPR_API const char* GetSecurityStatusString(SECURITY_STATUS status); + + WINPR_API SecurityFunctionTableW* SEC_ENTRY InitSecurityInterfaceExW(DWORD flags); + WINPR_API SecurityFunctionTableA* SEC_ENTRY InitSecurityInterfaceExA(DWORD flags); + +#ifdef UNICODE +#define InitSecurityInterfaceEx InitSecurityInterfaceExW +#define INIT_SECURITY_INTERFACE_EX INIT_SECURITY_INTERFACE_EX_W +#else +#define InitSecurityInterfaceEx InitSecurityInterfaceExA +#define INIT_SECURITY_INTERFACE_EX INIT_SECURITY_INTERFACE_EX_A +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_SSPI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspicli.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspicli.h new file mode 100644 index 0000000000000000000000000000000000000000..64727c30ad9d1443431ff2fd9f0d953323eab433 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sspicli.h @@ -0,0 +1,147 @@ +/** + * WinPR: Windows Portable Runtime + * Security Support Provider Interface + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/stream.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..aaf3a53791f60177e3e07c1c02a84bef8098b1f9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/stream.h @@ -0,0 +1,1414 @@ +/* + * WinPR: Windows Portable Runtime + * Stream Utils + * + * Copyright 2011 Vic Lee + * Copyright 2012 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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_STREAM_H +#define WINPR_UTILS_STREAM_H + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef struct s_wStreamPool wStreamPool; + + typedef struct + { + BYTE* buffer; + BYTE* pointer; + size_t length; + size_t capacity; + + DWORD count; + wStreamPool* pool; + BOOL isAllocatedStream; + BOOL isOwner; + } wStream; + + static INLINE size_t Stream_Capacity(const wStream* _s); + WINPR_API size_t Stream_GetRemainingCapacity(const wStream* _s); + WINPR_API size_t Stream_GetRemainingLength(const wStream* _s); + + WINPR_API BOOL Stream_EnsureCapacity(wStream* s, size_t size); + WINPR_API BOOL Stream_EnsureRemainingCapacity(wStream* s, size_t size); + +#define WINPR_STREAM_CAST(t, val) WINPR_CXX_COMPAT_CAST(t, val) + +#define Stream_CheckAndLogRequiredCapacityOfSize(tag, s, nmemb, size) \ + Stream_CheckAndLogRequiredCapacityEx(tag, WLOG_WARN, s, nmemb, size, "%s(%s:%" PRIuz ")", \ + __func__, __FILE__, (size_t)__LINE__) +#define Stream_CheckAndLogRequiredCapacity(tag, s, len) \ + Stream_CheckAndLogRequiredCapacityOfSize((tag), (s), (len), 1) + + WINPR_API BOOL Stream_CheckAndLogRequiredCapacityEx(const char* tag, DWORD level, wStream* s, + size_t nmemb, size_t size, const char* fmt, + ...); + WINPR_API BOOL Stream_CheckAndLogRequiredCapacityExVa(const char* tag, DWORD level, wStream* s, + size_t nmemb, size_t size, + const char* fmt, va_list args); + +#define Stream_CheckAndLogRequiredCapacityOfSizeWLog(log, s, nmemb, size) \ + Stream_CheckAndLogRequiredCapacityWLogEx(log, WLOG_WARN, s, nmemb, size, "%s(%s:%" PRIuz ")", \ + __func__, __FILE__, (size_t)__LINE__) + +#define Stream_CheckAndLogRequiredCapacityWLog(log, s, len) \ + Stream_CheckAndLogRequiredCapacityOfSizeWLog((log), (s), (len), 1) + + WINPR_API BOOL Stream_CheckAndLogRequiredCapacityWLogEx(wLog* log, DWORD level, wStream* s, + size_t nmemb, size_t size, + const char* fmt, ...); + WINPR_API BOOL Stream_CheckAndLogRequiredCapacityWLogExVa(wLog* log, DWORD level, wStream* s, + size_t nmemb, size_t size, + const char* fmt, va_list args); + + WINPR_API void Stream_Free(wStream* s, BOOL bFreeBuffer); + + WINPR_ATTR_MALLOC(Stream_Free, 1) + WINPR_API wStream* Stream_New(BYTE* buffer, size_t size); + WINPR_API wStream* Stream_StaticConstInit(wStream* s, const BYTE* buffer, size_t size); + WINPR_API wStream* Stream_StaticInit(wStream* s, BYTE* buffer, size_t size); + +#define Stream_CheckAndLogRequiredLengthOfSize(tag, s, nmemb, size) \ + Stream_CheckAndLogRequiredLengthEx(tag, WLOG_WARN, s, nmemb, size, "%s(%s:%" PRIuz ")", \ + __func__, __FILE__, (size_t)__LINE__) +#define Stream_CheckAndLogRequiredLength(tag, s, len) \ + Stream_CheckAndLogRequiredLengthOfSize(tag, s, len, 1) + + WINPR_API BOOL Stream_CheckAndLogRequiredLengthEx(const char* tag, DWORD level, wStream* s, + size_t nmemb, size_t size, const char* fmt, + ...); + WINPR_API BOOL Stream_CheckAndLogRequiredLengthExVa(const char* tag, DWORD level, wStream* s, + size_t nmemb, size_t size, const char* fmt, + va_list args); + +#define Stream_CheckAndLogRequiredLengthOfSizeWLog(log, s, nmemb, size) \ + Stream_CheckAndLogRequiredLengthWLogEx(log, WLOG_WARN, s, nmemb, size, "%s(%s:%" PRIuz ")", \ + __func__, __FILE__, (size_t)__LINE__) +#define Stream_CheckAndLogRequiredLengthWLog(log, s, len) \ + Stream_CheckAndLogRequiredLengthOfSizeWLog(log, s, len, 1) + + WINPR_API BOOL Stream_CheckAndLogRequiredLengthWLogEx(wLog* log, DWORD level, wStream* s, + size_t nmemb, size_t size, + const char* fmt, ...); + WINPR_API BOOL Stream_CheckAndLogRequiredLengthWLogExVa(wLog* log, DWORD level, wStream* s, + size_t nmemb, size_t size, + const char* fmt, va_list args); + + static INLINE void Stream_Seek(wStream* s, size_t _offset) + { + WINPR_ASSERT(s); + WINPR_ASSERT(Stream_GetRemainingCapacity(s) >= _offset); + s->pointer += (_offset); + } + + static INLINE void Stream_Rewind(wStream* s, size_t _offset) + { + size_t cur = 0; + WINPR_ASSERT(s); + WINPR_ASSERT(s->buffer <= s->pointer); + cur = WINPR_STREAM_CAST(size_t, s->pointer - s->buffer); + WINPR_ASSERT(cur >= _offset); + if (cur >= _offset) + s->pointer -= (_offset); + else + s->pointer = s->buffer; + } + + static INLINE UINT8 stream_read_u8(wStream* _s, BOOL seek) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= sizeof(UINT8)); + + const UINT8 v = winpr_Data_Get_UINT8(_s->pointer); + if (seek) + Stream_Seek(_s, sizeof(UINT8)); + return v; + } + + static INLINE INT8 stream_read_i8(wStream* _s, BOOL seek) + { + const INT8 v = winpr_Data_Get_INT8(_s->pointer); + if (seek) + Stream_Seek(_s, sizeof(INT8)); + return v; + } + + static INLINE UINT16 stream_read_u16_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT16); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT16 v = winpr_Data_Get_UINT16(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE UINT16 stream_read_u16_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT16); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT16 v = winpr_Data_Get_UINT16_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT16 stream_read_i16_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT16); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT16 v = winpr_Data_Get_INT16(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT16 stream_read_i16_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT16); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT16 v = winpr_Data_Get_INT16_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE UINT32 stream_read_u32_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT32); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT32 v = winpr_Data_Get_UINT32(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE UINT32 stream_read_u32_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT32); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT32 v = winpr_Data_Get_UINT32_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT32 stream_read_i32_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT32); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT32 v = winpr_Data_Get_INT32(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT32 stream_read_i32_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT32); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT32 v = winpr_Data_Get_INT32_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE UINT64 stream_read_u64_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT64); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT64 v = winpr_Data_Get_UINT64(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE UINT64 stream_read_u64_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(UINT64); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const UINT64 v = winpr_Data_Get_UINT64_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT64 stream_read_i64_le(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT64); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT64 v = winpr_Data_Get_INT64(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + static INLINE INT64 stream_read_i64_be(wStream* _s, BOOL seek) + { + const size_t typesize = sizeof(INT64); + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingLength(_s) >= typesize); + + const INT64 v = winpr_Data_Get_INT64_BE(_s->pointer); + if (seek) + Stream_Seek(_s, typesize); + return v; + } + + /** + * @brief Stream_Get_UINT8 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT8 Stream_Get_UINT8(wStream* _s) + { + return stream_read_u8(_s, TRUE); + } + + /** + * @brief Stream_Get_INT8 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT8 Stream_Get_INT8(wStream* _s) + { + return stream_read_i8(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT16 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT16 Stream_Get_UINT16(wStream* _s) + { + return stream_read_u16_le(_s, TRUE); + } + + /** + * @brief Stream_Get_INT16 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT16 Stream_Get_INT16(wStream* _s) + { + return stream_read_i16_le(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT16 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT16 Stream_Get_UINT16_BE(wStream* _s) + { + return stream_read_u16_be(_s, TRUE); + } + + /** + * @brief Stream_Get_INT16 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT16 Stream_Get_INT16_BE(wStream* _s) + { + return stream_read_i16_be(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT32 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT32 Stream_Get_UINT32(wStream* _s) + { + return stream_read_u32_le(_s, TRUE); + } + + /** + * @brief Stream_Get_INT32 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT32 Stream_Get_INT32(wStream* _s) + { + return stream_read_i32_le(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT32 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT32 Stream_Get_UINT32_BE(wStream* _s) + { + return stream_read_u32_be(_s, TRUE); + } + + /** + * @brief Stream_Get_INT32 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT32 Stream_Get_INT32_BE(wStream* _s) + { + return stream_read_i32_be(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT64 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT64 Stream_Get_UINT64(wStream* _s) + { + return stream_read_u64_le(_s, TRUE); + } + + /** + * @brief Stream_Get_INT64 + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT64 Stream_Get_INT64(wStream* _s) + { + return stream_read_i64_le(_s, TRUE); + } + + /** + * @brief Stream_Get_UINT64 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT64 Stream_Get_UINT64_BE(wStream* _s) + { + return stream_read_u64_be(_s, TRUE); + } + + /** + * @brief Stream_Get_INT64 big endian + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT64 Stream_Get_INT64_BE(wStream* _s) + { + return stream_read_i64_be(_s, TRUE); + } + + /** + * @brief Read a UINT8 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT8 Stream_Peek_Get_UINT8(wStream* _s) + { + return stream_read_u8(_s, FALSE); + } + + /** + * @brief Read a INT8 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT8 Stream_Peek_Get_INT8(wStream* _s) + { + return stream_read_i8(_s, FALSE); + } + + /** + * @brief Read a UINT16 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT16 Stream_Peek_Get_UINT16(wStream* _s) + { + return stream_read_u16_le(_s, FALSE); + } + + /** + * @brief Read a INT16 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT16 Stream_Peek_Get_INT16(wStream* _s) + { + return stream_read_i16_le(_s, FALSE); + } + + /** + * @brief Read a UINT16 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT16 Stream_Peek_Get_UINT16_BE(wStream* _s) + { + return stream_read_u16_be(_s, FALSE); + } + + /** + * @brief Read a INT16 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT16 Stream_Peek_Get_INT16_BE(wStream* _s) + { + return stream_read_i16_be(_s, FALSE); + } + + /** + * @brief Read a UINT32 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT32 Stream_Peek_Get_UINT32(wStream* _s) + { + return stream_read_u32_le(_s, FALSE); + } + + /** + * @brief Read a INT32 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT32 Stream_Peek_Get_INT32(wStream* _s) + { + return stream_read_i32_le(_s, FALSE); + } + + /** + * @brief Read a UINT32 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT32 Stream_Peek_Get_UINT32_BE(wStream* _s) + { + return stream_read_u32_be(_s, FALSE); + } + + /** + * @brief Read a INT32 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT32 Stream_Peek_Get_INT32_BE(wStream* _s) + { + return stream_read_i32_be(_s, FALSE); + } + + /** + * @brief Read a UINT64 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT64 Stream_Peek_Get_UINT64(wStream* _s) + { + return stream_read_u64_le(_s, FALSE); + } + + /** + * @brief Read a INT64 from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT64 Stream_Peek_Get_INT64(wStream* _s) + { + return stream_read_i64_le(_s, FALSE); + } + + /** + * @brief Read a UINT64 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE UINT64 Stream_Peek_Get_UINT64_BE(wStream* _s) + { + return stream_read_u64_be(_s, FALSE); + } + + /** + * @brief Read a INT64 big endian from the stream, do not increment stream position + * @param _s The stream to read from + * @return an integer + * @since version 3.9.0 + */ + static INLINE INT64 Stream_Peek_Get_INT64_BE(wStream* _s) + { + return stream_read_i64_be(_s, FALSE); + } + +#define Stream_Read_UINT8(_s, _v) \ + do \ + { \ + _v = stream_read_u8(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT8(_s, _v) \ + do \ + { \ + _v = stream_read_i8(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT16(_s, _v) \ + do \ + { \ + _v = stream_read_u16_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT16(_s, _v) \ + do \ + { \ + _v = stream_read_i16_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT16_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u16_be(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT16_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i16_be(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT32(_s, _v) \ + do \ + { \ + _v = stream_read_u32_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT32(_s, _v) \ + do \ + { \ + _v = stream_read_i32_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT32_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u32_be(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT32_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i32_be(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT64(_s, _v) \ + do \ + { \ + _v = stream_read_u64_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT64(_s, _v) \ + do \ + { \ + _v = stream_read_i64_le(_s, TRUE); \ + } while (0) + +#define Stream_Read_UINT64_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u64_be(_s, TRUE); \ + } while (0) + +#define Stream_Read_INT64_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i64_be(_s, TRUE); \ + } while (0) + + static INLINE void Stream_Read(wStream* _s, void* _b, size_t _n) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_b || (_n == 0)); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= _n); + memcpy(_b, (_s->pointer), (_n)); + Stream_Seek(_s, _n); + } + +#define Stream_Peek_UINT8(_s, _v) \ + do \ + { \ + _v = stream_read_u8(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT8(_s, _v) \ + do \ + { \ + _v = stream_read_i8(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT16(_s, _v) \ + do \ + { \ + _v = stream_read_u16_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT16(_s, _v) \ + do \ + { \ + _v = stream_read_i16_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT16_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u16_be(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT16_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i16_be(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT32(_s, _v) \ + do \ + { \ + _v = stream_read_u32_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT32(_s, _v) \ + do \ + { \ + _v = stream_read_i32_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT32_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u32_be(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT32_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i32_be(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT64(_s, _v) \ + do \ + { \ + _v = stream_read_u64_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT64(_s, _v) \ + do \ + { \ + _v = stream_read_i64_le(_s, FALSE); \ + } while (0) + +#define Stream_Peek_UINT64_BE(_s, _v) \ + do \ + { \ + _v = stream_read_u64_be(_s, FALSE); \ + } while (0) + +#define Stream_Peek_INT64_BE(_s, _v) \ + do \ + { \ + _v = stream_read_i64_be(_s, FALSE); \ + } while (0) + + static INLINE void Stream_Peek(const wStream* _s, void* _b, size_t _n) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_b || (_n == 0)); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= _n); + memcpy(_b, (_s->pointer), (_n)); + } + +#define Stream_Write_INT8(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= INT8_MAX); \ + WINPR_ASSERT((v) >= INT8_MIN); \ + Stream_Write_INT8_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b INT8 to a \b wStream. The stream must be large enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_INT8 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_INT8_unchecked(wStream* _s, INT8 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 1); + + winpr_Data_Write_INT8(_s->pointer, _v); + _s->pointer += 1; + } + +#define Stream_Write_UINT8(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= UINT8_MAX); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT8_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT8 to a \b wStream. The stream must be large enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT8 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT8_unchecked(wStream* _s, UINT8 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 1); + + winpr_Data_Write_UINT8(_s->pointer, _v); + _s->pointer += 1; + } + +#define Stream_Write_INT16(s, v) \ + do \ + { \ + WINPR_ASSERT((v) >= INT16_MIN); \ + WINPR_ASSERT((v) <= INT16_MAX); \ + Stream_Write_INT16_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b INT16 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_INT16 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_INT16_unchecked(wStream* _s, INT16 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 2); + + winpr_Data_Write_INT16(_s->pointer, _v); + _s->pointer += 2; + } + +#define Stream_Write_UINT16(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= UINT16_MAX); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT16_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT16 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT16 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT16_unchecked(wStream* _s, UINT16 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 2); + + winpr_Data_Write_UINT16(_s->pointer, _v); + _s->pointer += 2; + } + +#define Stream_Write_UINT16_BE(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= UINT16_MAX); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT16_BE_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT16 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT16_BE instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT16_BE_unchecked(wStream* _s, UINT16 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 2); + + winpr_Data_Write_UINT16_BE(_s->pointer, _v); + _s->pointer += 2; + } + +#define Stream_Write_INT16_BE(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= INT16_MAX); \ + WINPR_ASSERT((v) >= INT16_MIN); \ + Stream_Write_INT16_BE_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT16 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT16_BE instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + * + * @since version 3.10.0 + */ + static INLINE void Stream_Write_INT16_BE_unchecked(wStream* _s, INT16 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 2); + + winpr_Data_Write_INT16_BE(_s->pointer, _v); + _s->pointer += 2; + } + +#define Stream_Write_UINT24_BE(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= 0xFFFFFF); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT24_BE_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT24 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT24_BE instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT24_BE_unchecked(wStream* _s, UINT32 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(_v <= 0x00FFFFFF); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 3); + + *_s->pointer++ = ((_v) >> 16) & 0xFF; + *_s->pointer++ = ((_v) >> 8) & 0xFF; + *_s->pointer++ = (_v) & 0xFF; + } + +#define Stream_Write_INT32(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= INT32_MAX); \ + WINPR_ASSERT((v) >= INT32_MIN); \ + Stream_Write_INT32_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b INT32 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_INT32 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_INT32_unchecked(wStream* _s, INT32 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 4); + + winpr_Data_Write_INT32(_s->pointer, _v); + _s->pointer += 4; + } + +#define Stream_Write_INT32_BE(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= INT32_MAX); \ + WINPR_ASSERT((v) >= INT32_MIN); \ + Stream_Write_INT32_BE_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b INT32 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_INT32 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + * + * @since version 3.10.0 + */ + static INLINE void Stream_Write_INT32_BE_unchecked(wStream* _s, INT32 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 4); + + winpr_Data_Write_INT32_BE(_s->pointer, _v); + _s->pointer += 4; + } + +#define Stream_Write_UINT32(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= UINT32_MAX); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT32_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT32 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT32 instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT32_unchecked(wStream* _s, UINT32 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 4); + + winpr_Data_Write_UINT32(_s->pointer, _v); + _s->pointer += 4; + } + +#define Stream_Write_UINT32_BE(s, v) \ + do \ + { \ + WINPR_ASSERT((v) <= UINT32_MAX); \ + WINPR_ASSERT((v) >= 0); \ + Stream_Write_UINT32_BE_unchecked((s), (v)); \ + } while (0) + + /** @brief writes a \b UINT32 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * Do not use directly, use the define @ref Stream_Write_UINT32_BE instead + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT32_BE_unchecked(wStream* _s, UINT32 _v) + { + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 4); + + winpr_Data_Write_UINT32_BE(_s->pointer, _v); + _s->pointer += 4; + } + + /** @brief writes a \b UINT64 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT64(wStream* _s, UINT64 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 8); + + winpr_Data_Write_UINT64(_s->pointer, _v); + _s->pointer += 8; + } + + /** @brief writes a \b UINT64 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + */ + static INLINE void Stream_Write_UINT64_BE(wStream* _s, UINT64 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 8); + + winpr_Data_Write_UINT64_BE(_s->pointer, _v); + _s->pointer += 8; + } + + /** @brief writes a \b INT64 as \b little endian to a \b wStream. The stream must be large + * enough to hold the data. + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + * \since version 3.10.0 + */ + static INLINE void Stream_Write_INT64(wStream* _s, INT64 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 8); + + winpr_Data_Write_INT64(_s->pointer, _v); + _s->pointer += 8; + } + + /** @brief writes a \b INT64 as \b big endian to a \b wStream. The stream must be large enough + * to hold the data. + * + * \param _s The stream to write to, must not be \b NULL + * \param _v The value to write + * \since version 3.10.0 + */ + static INLINE void Stream_Write_INT64_BE(wStream* _s, INT64 _v) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->pointer); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= 8); + + winpr_Data_Write_INT64_BE(_s->pointer, _v); + _s->pointer += 8; + } + + static INLINE void Stream_Write(wStream* _s, const void* _b, size_t _n) + { + if (_n > 0) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_b); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= _n); + memcpy(_s->pointer, (_b), (_n)); + Stream_Seek(_s, _n); + } + } + + static INLINE void Stream_Seek_UINT8(wStream* _s) + { + Stream_Seek(_s, sizeof(UINT8)); + } + static INLINE void Stream_Seek_UINT16(wStream* _s) + { + Stream_Seek(_s, sizeof(UINT16)); + } + static INLINE void Stream_Seek_UINT32(wStream* _s) + { + Stream_Seek(_s, sizeof(UINT32)); + } + static INLINE void Stream_Seek_UINT64(wStream* _s) + { + Stream_Seek(_s, sizeof(UINT64)); + } + + static INLINE void Stream_Rewind_UINT8(wStream* _s) + { + Stream_Rewind(_s, sizeof(UINT8)); + } + static INLINE void Stream_Rewind_UINT16(wStream* _s) + { + Stream_Rewind(_s, sizeof(UINT16)); + } + static INLINE void Stream_Rewind_UINT32(wStream* _s) + { + Stream_Rewind(_s, sizeof(UINT32)); + } + static INLINE void Stream_Rewind_UINT64(wStream* _s) + { + Stream_Rewind(_s, sizeof(UINT64)); + } + + static INLINE void Stream_Fill(wStream* _s, int _v, size_t _n) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(Stream_GetRemainingCapacity(_s) >= (_n)); + memset(_s->pointer, _v, (_n)); + Stream_Seek(_s, _n); + } + + static INLINE void Stream_Zero(wStream* _s, size_t _n) + { + Stream_Fill(_s, '\0', _n); + } + + static INLINE void Stream_Copy(wStream* _src, wStream* _dst, size_t _n) + { + WINPR_ASSERT(_src); + WINPR_ASSERT(_dst); + WINPR_ASSERT(Stream_GetRemainingCapacity(_src) >= (_n)); + WINPR_ASSERT(Stream_GetRemainingCapacity(_dst) >= (_n)); + + memcpy(_dst->pointer, _src->pointer, _n); + Stream_Seek(_dst, _n); + Stream_Seek(_src, _n); + } + +/** @brief Convenience macro to get a pointer to the stream buffer casted to a specific type + * + * @since version 3.9.0 + */ +#define Stream_BufferAs(s, type) WINPR_STREAM_CAST(type*, Stream_Buffer(s)) + + static INLINE BYTE* Stream_Buffer(wStream* _s) + { + WINPR_ASSERT(_s); + return _s->buffer; + } + +/** @brief Convenience macro to get a const pointer to the stream buffer casted to a specific type + * + * @since version 3.9.0 + */ +#define Stream_ConstBufferAs(s, type) WINPR_STREAM_CAST(type*, Stream_ConstBuffer(s)) + static INLINE const BYTE* Stream_ConstBuffer(const wStream* _s) + { + WINPR_ASSERT(_s); + return _s->buffer; + } + +#define Stream_GetBuffer(_s, _b) _b = Stream_Buffer(_s) + +/** @brief Convenience macro to get a pointer to the stream buffer casted to a specific type + * + * @since version 3.9.0 + */ +#define Stream_GetBufferAs(_s, _b) _b = Stream_BufferAs(_s, __typeof(_b)) + +#define Stream_PointerAs(s, type) WINPR_STREAM_CAST(type*, Stream_Pointer(s)) + + static INLINE void* Stream_Pointer(wStream* _s) + { + WINPR_ASSERT(_s); + return _s->pointer; + } + + static INLINE const void* Stream_ConstPointer(const wStream* _s) + { + WINPR_ASSERT(_s); + return _s->pointer; + } + +#define Stream_GetPointer(_s, _p) _p = Stream_Pointer(_s) + +/** @brief Convenience macro to get a pointer to the stream pointer casted to a specific type + * + * @since version 3.9.0 + */ +#define Stream_GetPointerAs(_s, _p) _p = Stream_PointerAs(_s, __typeof(_p)) + +#if defined(WITH_WINPR_DEPRECATED) + WINPR_API WINPR_DEPRECATED_VAR("Use Stream_SetPosition instead", + BOOL Stream_SetPointer(wStream* _s, BYTE* _p)); + WINPR_API WINPR_DEPRECATED_VAR("Use Stream_New(buffer, capacity) instead", + BOOL Stream_SetBuffer(wStream* _s, BYTE* _b)); + WINPR_API WINPR_DEPRECATED_VAR("Use Stream_New(buffer, capacity) instead", + void Stream_SetCapacity(wStream* _s, size_t capacity)); +#endif + + static INLINE size_t Stream_Length(const wStream* _s) + { + WINPR_ASSERT(_s); + return _s->length; + } + +#define Stream_GetLength(_s, _l) _l = Stream_Length(_s) + WINPR_API BOOL Stream_SetLength(wStream* _s, size_t _l); + + static INLINE size_t Stream_Capacity(const wStream* _s) + { + WINPR_ASSERT(_s); + return _s->capacity; + } + +#define Stream_GetCapacity(_s, _c) _c = Stream_Capacity(_s); + + static INLINE size_t Stream_GetPosition(const wStream* _s) + { + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->buffer <= _s->pointer); + return WINPR_STREAM_CAST(size_t, (_s->pointer - _s->buffer)); + } + + WINPR_API BOOL Stream_SetPosition(wStream* _s, size_t _p); + + WINPR_API void Stream_SealLength(wStream* _s); + + static INLINE void Stream_Clear(wStream* _s) + { + WINPR_ASSERT(_s); + memset(_s->buffer, 0, _s->capacity); + } + +#define Stream_SafeSeek(s, size) Stream_SafeSeekEx(s, size, __FILE__, __LINE__, __func__) + WINPR_API BOOL Stream_SafeSeekEx(wStream* s, size_t size, const char* file, size_t line, + const char* fkt); + + WINPR_API BOOL Stream_Read_UTF16_String(wStream* s, WCHAR* dst, size_t charLength); + WINPR_API BOOL Stream_Write_UTF16_String(wStream* s, const WCHAR* src, size_t charLength); + + /** \brief Reads a WCHAR string from a stream and converts it to UTF-8 and returns a newly + * allocated string + * + * \param s The stream to read data from + * \param wcharLength The number of WCHAR characters to read (NOT the size in bytes!) + * \param pUtfCharLength Ignored if \b NULL, otherwise will be set to the number of + * characters in the resulting UTF-8 string + * \return A '\0' terminated UTF-8 encoded string or NULL for any failure. + */ + WINPR_API char* Stream_Read_UTF16_String_As_UTF8(wStream* s, size_t wcharLength, + size_t* pUtfCharLength); + + /** \brief Reads a WCHAR string from a stream and converts it to UTF-8 and + * writes it to the supplied buffer + * + * \param s The stream to read data from + * \param wcharLength The number of WCHAR characters to read (NOT the size in bytes!) + * \param utfBuffer A pointer to a buffer holding the result string + * \param utfBufferCharLength The size of the result buffer + * \return The char length (strlen) of the result string or -1 for failure + */ + WINPR_API SSIZE_T Stream_Read_UTF16_String_As_UTF8_Buffer(wStream* s, size_t wcharLength, + char* utfBuffer, + size_t utfBufferCharLength); + + /** \brief Writes a UTF-8 string UTF16 encoded to the stream. If the UTF-8 + * string is short, the remaining characters are filled up with '\0' + * + * \param s The stream to write to + * \param wcharLength the length (in WCHAR characters) to write + * \param src The source data buffer with the UTF-8 data + * \param length The length in bytes of the UTF-8 buffer + * \param fill If \b TRUE fill the unused parts of the wcharLength with 0 + * + * \b return number of used characters for success, /b -1 for failure + */ + WINPR_API SSIZE_T Stream_Write_UTF16_String_From_UTF8(wStream* s, size_t wcharLength, + const char* src, size_t length, + BOOL fill); + + /* StreamPool */ + + WINPR_API void StreamPool_Return(wStreamPool* pool, wStream* s); + + WINPR_API void Stream_AddRef(wStream* s); + WINPR_API void Stream_Release(wStream* s); + + WINPR_ATTR_MALLOC(Stream_Release, 1) + WINPR_API wStream* StreamPool_Take(wStreamPool* pool, size_t size); + + WINPR_API wStream* StreamPool_Find(wStreamPool* pool, const BYTE* ptr); + + /** Return the number of streams still not returned to the pool + * + * @param pool The pool to query, must not be \b NULL + * + * @return the number of streams still in use + * + * @since version 3.10.0 + */ + WINPR_API size_t StreamPool_UsedCount(wStreamPool* pool); + + /** Wait up to \b timeoutMS milliseconds for streams to be returned to the pool. + * Use \b INFINITE for an infinite timeout + * + * @param pool The pool to query, must not be \b NULL + * @param timeoutMS Milliseconds to wait at most, use \b INFINITE for no timeout. + * + * @return \b TRUE in case all streams were returned, \b FALSE otherwise. + * + * @since version 3.10.0 + */ + WINPR_API BOOL StreamPool_WaitForReturn(wStreamPool* pool, UINT32 timeoutMS); + + WINPR_API void StreamPool_Clear(wStreamPool* pool); + + WINPR_API void StreamPool_Free(wStreamPool* pool); + + WINPR_ATTR_MALLOC(StreamPool_Free, 1) + WINPR_API wStreamPool* StreamPool_New(BOOL synchronized, size_t defaultSize); + + WINPR_API char* StreamPool_GetStatistics(wStreamPool* pool, char* buffer, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_UTILS_STREAM_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/string.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/string.h new file mode 100644 index 0000000000000000000000000000000000000000..c77f56529bc3aa27a219227d16716dd1d4569263 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/string.h @@ -0,0 +1,455 @@ +/** + * WinPR: Windows Portable Runtime + * String Manipulation (CRT) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2016 David PHAM-VAN + * + * 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 +#include +#include +#include +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER + +#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(NULL, 0, __VA_ARGS__) + +#define _scprintf(...) snprintf(NULL, 0, __VA_ARGS__) + + /* Unicode Conversion */ + +#if defined(WITH_WINPR_DEPRECATED) + WINPR_API WINPR_DEPRECATED_VAR("Use ConvertUtf8ToWChar instead", + int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, + LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar)); + + WINPR_API WINPR_DEPRECATED_VAR("Use ConvertWCharToUtf8 instead", + 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 NULL + * \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 NULL + * \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 NULL + * \param pUtfCharLength Ignored if NULL, otherwise receives the length of the result string in + * characters (strlen) + * + * \return An allocated zero terminated UTF-8 string or NULL 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 NULL, otherwise receives the length of the result string in + * characters (strlen) + * + * \return An allocated zero terminated UTF-8 string or NULL 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 NULL, otherwise receives the length of the result string in + * characters (including any '\0' character) + * + * \return An allocated double zero terminated UTF-8 string or NULL 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 NULL + * \param pSize Ignored if NULL, otherwise receives the length of the result string in + * characters (wcslen) + * + * \return An allocated zero terminated UTF-16 string or NULL 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 NULL, otherwise receives the length of the result string in + * characters (wcslen) + * + * \return An allocated zero terminated UTF-16 string or NULL 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 NULL, otherwise receives the length of the result string in + * characters (including any '\0' character) + * + * \return An allocated double zero terminated UTF-16 string or NULL 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_API WINPR_DEPRECATED_VAR("Use ConvertUtf8ToWChar functions instead", + int ConvertToUnicode(UINT CodePage, DWORD dwFlags, + LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR* lpWideCharStr, int cchWideChar)); + + WINPR_API WINPR_DEPRECATED_VAR("Use ConvertWCharToUtf8 functions instead", + 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_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_API WCHAR* wcsndup(const WCHAR* s, size_t n); + +#ifdef __cplusplus +} +#endif + +WINPR_PRAGMA_DIAG_POP + +#endif /* WINPR_CRT_STRING_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/strlst.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/strlst.h new file mode 100644 index 0000000000000000000000000000000000000000..4e49d8b72a758e870a21493ec03da5d6d737a231 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/strlst.h @@ -0,0 +1,41 @@ +/** + * String list Manipulation (UTILS) + * + * Copyright 2018 Pascal Bourguignon + * + * 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 + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API void string_list_free(char** string_list); + WINPR_API int string_list_length(const char** string_list); + WINPR_API char** string_list_copy(const char** string_list); + WINPR_API void string_list_print(FILE* out, const char** string_list); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_UTILS_STRLST_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/synch.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/synch.h new file mode 100644 index 0000000000000000000000000000000000000000..eb6289522ea0bafeeede543d3a8bbe3b9531e8e5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/synch.h @@ -0,0 +1,462 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Thincast Technologies GmbH + * Copyright 2014 Norbert Federa + * + * 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 +#include +#include + +#include +#include +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifndef _WIN32 + +/* Mutex */ +#define CREATE_MUTEX_INITIAL_OWNER 0x00000001 + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, + LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, + LPCWSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateMutexExA(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCSTR lpName, + DWORD dwFlags, DWORD dwDesiredAccess); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateMutexExW(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCWSTR lpName, + DWORD dwFlags, DWORD dwDesiredAccess); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE OpenMutexA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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_API HANDLE CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, + LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, + LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE OpenSemaphoreA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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_API HANDLE CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, + BOOL bInitialState, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, + BOOL bInitialState, LPCWSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateEventExA(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCSTR lpName, + DWORD dwFlags, DWORD dwDesiredAccess); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateEventExW(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCWSTR lpName, + DWORD dwFlags, DWORD dwDesiredAccess); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE OpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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_API HANDLE CreateWaitableTimerA(LPSECURITY_ATTRIBUTES lpTimerAttributes, + BOOL bManualReset, LPCSTR lpTimerName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateWaitableTimerW(LPSECURITY_ATTRIBUTES lpTimerAttributes, + BOOL bManualReset, LPCWSTR lpTimerName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateWaitableTimerExA(LPSECURITY_ATTRIBUTES lpTimerAttributes, + LPCSTR lpTimerName, DWORD dwFlags, + DWORD dwDesiredAccess); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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_API HANDLE OpenWaitableTimerA(DWORD dwDesiredAccess, BOOL bInheritHandle, + LPCSTR lpTimerName); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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_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 +#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_API HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, + BOOL bManualReset, BOOL bInitialState, + int FileDescriptor, ULONG mode); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + WINPR_API HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, + BOOL bManualReset, BOOL bInitialState, + int FileDescriptor, ULONG mode); + + WINPR_ATTR_MALLOC(CloseHandle, 1) + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sysinfo.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sysinfo.h new file mode 100644 index 0000000000000000000000000000000000000000..4a9095663cb6c9201c04b74ec9e96eaf28f1da53 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/sysinfo.h @@ -0,0 +1,392 @@ +/** + * WinPR: Windows Portable Runtime + * System Information + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef _WIN32 +#include +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tchar.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tchar.h new file mode 100644 index 0000000000000000000000000000000000000000..7bc613ca69e54e07eada9e99daa3de031be63507 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tchar.h @@ -0,0 +1,74 @@ +/** + * WinPR: Windows Portable Runtime + * TCHAR + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#ifdef _WIN32 + +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/thread.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/thread.h new file mode 100644 index 0000000000000000000000000000000000000000..5a9b77cc04206f638b730113b03066a3327fda5e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/thread.h @@ -0,0 +1,300 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include + +#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 + + 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_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_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 + 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/timezone.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/timezone.h new file mode 100644 index 0000000000000000000000000000000000000000..4f9d4141804d38231a4e86f2eecef6c58f1c1657 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/timezone.h @@ -0,0 +1,127 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +#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( + const DWORD dwIndex, PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation); + WINPR_API DWORD GetDynamicTimeZoneInformationEffectiveYears( + const PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation, LPDWORD FirstYear, + LPDWORD LastYear); + +#else +#pragma comment(lib, "advapi32") +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_TIMEZONE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tools/makecert.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tools/makecert.h new file mode 100644 index 0000000000000000000000000000000000000000..8a6d30fdbdca502dc0e8450c970add056926ddb6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/tools/makecert.h @@ -0,0 +1,50 @@ +/** + * WinPR: Windows Portable Runtime + * makecert replacement + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#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_API MAKECERT_CONTEXT* makecert_context_new(void); + +#ifdef __cplusplus +} +#endif + +#endif /* MAKECERT_TOOL_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/user.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/user.h new file mode 100644 index 0000000000000000000000000000000000000000..b85a81582269d7977e2ffd4fb13f6553168fad62 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/user.h @@ -0,0 +1,298 @@ +/** + * WinPR: Windows Portable Runtime + * User Environment + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +/** + * Standard Clipboard Formats + */ + +#ifdef _WIN32 +#include +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wincrypt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wincrypt.h new file mode 100644 index 0000000000000000000000000000000000000000..0a46e2a089bc54cb89fa3cb94befa1aa7293b1e0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wincrypt.h @@ -0,0 +1,738 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +#ifdef _WIN32 + +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/windows.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/windows.h new file mode 100644 index 0000000000000000000000000000000000000000..5bc6722c2d3193db424b37caa77a8d6425ad7689 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/windows.h @@ -0,0 +1,130 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Header Include Wrapper + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winpr.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winpr.h new file mode 100644 index 0000000000000000000000000000000000000000..f760476ec83e2e8983a2e3399f55a4b7001e3709 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winpr.h @@ -0,0 +1,39 @@ +/** + * WinPR: Windows Portable Runtime + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#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); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winsock.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winsock.h new file mode 100644 index 0000000000000000000000000000000000000000..95bcce6c221ff05820db31296fae86ecd710acab --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/winsock.h @@ -0,0 +1,376 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Sockets (Winsock) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include + +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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#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 + +#define _IFF_UP 0x00000001 +#define _IFF_BROADCAST 0x00000002 +#define _IFF_LOOPBACK 0x00000004 +#define _IFF_POINTTOPOINT 0x00000008 +#define _IFF_MULTICAST 0x00000010 + +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_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); + + 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); + +#ifdef __cplusplus +} +#endif + +#ifdef UNICODE +#define WSASocket WSASocketW +#else +#define WSASocket WSASocketA +#endif + +#endif /* _WIN32 */ + +WINPR_PRAGMA_DIAG_POP + +#endif /* WINPR_WINSOCK_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wlog.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wlog.h new file mode 100644 index 0000000000000000000000000000000000000000..5a12bf37bc877af7482b5ffd99cac3db42b827d1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wlog.h @@ -0,0 +1,246 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 Bernhard Miklautz + * + * + * 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 +#include +#include +#include +#include + +/** + * 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 + +/** + * 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 + + WINPR_API BOOL WLog_PrintMessage(wLog* log, DWORD type, DWORD level, size_t line, + const char* file, const char* function, ...); + 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 NULL + * @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_PrintMessage(_log, WLOG_MESSAGE_TEXT, _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 = NULL; \ + 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_PrintMessageVA(_log, WLOG_MESSAGE_TEXT, _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) + +#define WLog_LVL(tag, lvl, ...) WLog_Print_tag(tag, lvl, __VA_ARGS__) +#define WLog_VRB(tag, ...) WLog_Print_tag(tag, WLOG_TRACE, __VA_ARGS__) +#define WLog_DBG(tag, ...) WLog_Print_tag(tag, WLOG_DEBUG, __VA_ARGS__) +#define WLog_INFO(tag, ...) WLog_Print_tag(tag, WLOG_INFO, __VA_ARGS__) +#define WLog_WARN(tag, ...) WLog_Print_tag(tag, WLOG_WARN, __VA_ARGS__) +#define WLog_ERR(tag, ...) WLog_Print_tag(tag, WLOG_ERROR, __VA_ARGS__) +#define WLog_FATAL(tag, ...) WLog_Print_tag(tag, WLOG_FATAL, __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_API WINPR_DEPRECATED(BOOL WLog_Init(void)); + /** Deprecated */ + WINPR_API WINPR_DEPRECATED(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 + { + wLogCallbackData_t data; + wLogCallbackImage_t image; + wLogCallbackMessage_t message; + wLogCallbackPackage_t package; + } wLogCallbacks; + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_WLOG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtsapi.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtsapi.h new file mode 100644 index 0000000000000000000000000000000000000000..6bb64fc6c8cccdacf2ca8028456229289e53f736 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtsapi.h @@ -0,0 +1,1525 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Terminal Services API + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2015 Copyright 2015 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_WTSAPI_H +#define WINPR_WTSAPI_H + +#include +#include + +#include + +#define CHANNEL_CHUNK_MAX_LENGTH 16256 + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER + +#ifdef _WIN32 + +#define CurrentTime _CurrentTime /* Workaround for X11 "CurrentTime" header conflict */ + +#endif + +#if defined(_WIN32) && !defined(_UWP) + +#include + +#else + +/** + * Virtual Channel Protocol (pchannel.h) + */ + +#define CHANNEL_CHUNK_LENGTH 1600 + +#define CHANNEL_PDU_LENGTH (CHANNEL_CHUNK_LENGTH + sizeof(CHANNEL_PDU_HEADER)) + +#define CHANNEL_FLAG_FIRST 0x01 +#define CHANNEL_FLAG_LAST 0x02 +#define CHANNEL_FLAG_ONLY (CHANNEL_FLAG_FIRST | CHANNEL_FLAG_LAST) +#define CHANNEL_FLAG_MIDDLE 0 +#define CHANNEL_FLAG_FAIL 0x100 + +#define CHANNEL_OPTION_INITIALIZED 0x80000000 + +#define CHANNEL_OPTION_ENCRYPT_RDP 0x40000000 +#define CHANNEL_OPTION_ENCRYPT_SC 0x20000000 +#define CHANNEL_OPTION_ENCRYPT_CS 0x10000000 +#define CHANNEL_OPTION_PRI_HIGH 0x08000000 +#define CHANNEL_OPTION_PRI_MED 0x04000000 +#define CHANNEL_OPTION_PRI_LOW 0x02000000 +#define CHANNEL_OPTION_COMPRESS_RDP 0x00800000 +#define CHANNEL_OPTION_COMPRESS 0x00400000 +#define CHANNEL_OPTION_SHOW_PROTOCOL 0x00200000 +#define CHANNEL_OPTION_REMOTE_CONTROL_PERSISTENT 0x00100000 + +#define CHANNEL_MAX_COUNT 31 +#define CHANNEL_NAME_LEN 7 + +typedef struct tagCHANNEL_DEF +{ + char name[CHANNEL_NAME_LEN + 1]; + ULONG options; +} CHANNEL_DEF; +typedef CHANNEL_DEF* PCHANNEL_DEF; +typedef PCHANNEL_DEF* PPCHANNEL_DEF; + +typedef struct tagCHANNEL_PDU_HEADER +{ + UINT32 length; + UINT32 flags; +} CHANNEL_PDU_HEADER, *PCHANNEL_PDU_HEADER; + +#endif /* _WIN32 */ + +/** + * These channel flags are defined in some versions of pchannel.h only + */ + +#ifndef CHANNEL_FLAG_SHOW_PROTOCOL +#define CHANNEL_FLAG_SHOW_PROTOCOL 0x10 +#endif +#ifndef CHANNEL_FLAG_SUSPEND +#define CHANNEL_FLAG_SUSPEND 0x20 +#endif +#ifndef CHANNEL_FLAG_RESUME +#define CHANNEL_FLAG_RESUME 0x40 +#endif +#ifndef CHANNEL_FLAG_SHADOW_PERSISTENT +#define CHANNEL_FLAG_SHADOW_PERSISTENT 0x80 +#endif + +#if !defined(_WIN32) || !defined(H_CCHANNEL) + +/** + * Virtual Channel Client API (cchannel.h) + */ + +#ifdef _WIN32 +#define VCAPITYPE __stdcall +#define VCEXPORT +#else +#define VCAPITYPE CALLBACK +#define VCEXPORT __export +#endif + +typedef VOID VCAPITYPE CHANNEL_INIT_EVENT_FN(LPVOID pInitHandle, UINT event, LPVOID pData, + UINT dataLength); + +typedef CHANNEL_INIT_EVENT_FN* PCHANNEL_INIT_EVENT_FN; + +typedef VOID VCAPITYPE CHANNEL_INIT_EVENT_EX_FN(LPVOID lpUserParam, LPVOID pInitHandle, UINT event, + LPVOID pData, UINT dataLength); + +typedef CHANNEL_INIT_EVENT_EX_FN* PCHANNEL_INIT_EVENT_EX_FN; + +#define CHANNEL_EVENT_INITIALIZED 0 +#define CHANNEL_EVENT_CONNECTED 1 +#define CHANNEL_EVENT_V1_CONNECTED 2 +#define CHANNEL_EVENT_DISCONNECTED 3 +#define CHANNEL_EVENT_TERMINATED 4 +#define CHANNEL_EVENT_REMOTE_CONTROL_START 5 +#define CHANNEL_EVENT_REMOTE_CONTROL_STOP 6 +#define CHANNEL_EVENT_ATTACHED 7 +#define CHANNEL_EVENT_DETACHED 8 +#define CHANNEL_EVENT_DATA_RECEIVED 10 +#define CHANNEL_EVENT_WRITE_COMPLETE 11 +#define CHANNEL_EVENT_WRITE_CANCELLED 12 + +typedef VOID VCAPITYPE CHANNEL_OPEN_EVENT_FN(DWORD openHandle, UINT event, LPVOID pData, + UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags); + +typedef CHANNEL_OPEN_EVENT_FN* PCHANNEL_OPEN_EVENT_FN; + +typedef VOID VCAPITYPE CHANNEL_OPEN_EVENT_EX_FN(LPVOID lpUserParam, DWORD openHandle, UINT event, + LPVOID pData, UINT32 dataLength, UINT32 totalLength, + UINT32 dataFlags); + +typedef CHANNEL_OPEN_EVENT_EX_FN* PCHANNEL_OPEN_EVENT_EX_FN; + +#define CHANNEL_RC_OK 0 +#define CHANNEL_RC_ALREADY_INITIALIZED 1 +#define CHANNEL_RC_NOT_INITIALIZED 2 +#define CHANNEL_RC_ALREADY_CONNECTED 3 +#define CHANNEL_RC_NOT_CONNECTED 4 +#define CHANNEL_RC_TOO_MANY_CHANNELS 5 +#define CHANNEL_RC_BAD_CHANNEL 6 +#define CHANNEL_RC_BAD_CHANNEL_HANDLE 7 +#define CHANNEL_RC_NO_BUFFER 8 +#define CHANNEL_RC_BAD_INIT_HANDLE 9 +#define CHANNEL_RC_NOT_OPEN 10 +#define CHANNEL_RC_BAD_PROC 11 +#define CHANNEL_RC_NO_MEMORY 12 +#define CHANNEL_RC_UNKNOWN_CHANNEL_NAME 13 +#define CHANNEL_RC_ALREADY_OPEN 14 +#define CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY 15 +#define CHANNEL_RC_NULL_DATA 16 +#define CHANNEL_RC_ZERO_LENGTH 17 +#define CHANNEL_RC_INVALID_INSTANCE 18 +#define CHANNEL_RC_UNSUPPORTED_VERSION 19 +#define CHANNEL_RC_INITIALIZATION_ERROR 20 + +#define VIRTUAL_CHANNEL_VERSION_WIN2000 1 + +typedef UINT VCAPITYPE VIRTUALCHANNELINIT(LPVOID* ppInitHandle, PCHANNEL_DEF pChannel, + INT channelCount, ULONG versionRequested, + PCHANNEL_INIT_EVENT_FN pChannelInitEventProc); + +typedef VIRTUALCHANNELINIT* PVIRTUALCHANNELINIT; + +typedef UINT VCAPITYPE VIRTUALCHANNELINITEX(LPVOID lpUserParam, LPVOID clientContext, + LPVOID pInitHandle, PCHANNEL_DEF pChannel, + INT channelCount, ULONG versionRequested, + PCHANNEL_INIT_EVENT_EX_FN pChannelInitEventProcEx); + +typedef VIRTUALCHANNELINITEX* PVIRTUALCHANNELINITEX; + +typedef UINT VCAPITYPE VIRTUALCHANNELOPEN(LPVOID pInitHandle, LPDWORD pOpenHandle, + PCHAR pChannelName, + PCHANNEL_OPEN_EVENT_FN pChannelOpenEventProc); + +typedef VIRTUALCHANNELOPEN* PVIRTUALCHANNELOPEN; + +typedef UINT VCAPITYPE VIRTUALCHANNELOPENEX(LPVOID pInitHandle, LPDWORD pOpenHandle, + PCHAR pChannelName, + PCHANNEL_OPEN_EVENT_EX_FN pChannelOpenEventProcEx); + +typedef VIRTUALCHANNELOPENEX* PVIRTUALCHANNELOPENEX; + +typedef UINT VCAPITYPE VIRTUALCHANNELCLOSE(DWORD openHandle); + +typedef VIRTUALCHANNELCLOSE* PVIRTUALCHANNELCLOSE; + +typedef UINT VCAPITYPE VIRTUALCHANNELCLOSEEX(LPVOID pInitHandle, DWORD openHandle); + +typedef VIRTUALCHANNELCLOSEEX* PVIRTUALCHANNELCLOSEEX; + +typedef UINT VCAPITYPE VIRTUALCHANNELWRITE(DWORD openHandle, LPVOID pData, ULONG dataLength, + LPVOID pUserData); + +typedef VIRTUALCHANNELWRITE* PVIRTUALCHANNELWRITE; + +typedef UINT VCAPITYPE VIRTUALCHANNELWRITEEX(LPVOID pInitHandle, DWORD openHandle, LPVOID pData, + ULONG dataLength, LPVOID pUserData); + +typedef VIRTUALCHANNELWRITEEX* PVIRTUALCHANNELWRITEEX; + +typedef struct tagCHANNEL_ENTRY_POINTS +{ + DWORD cbSize; + DWORD protocolVersion; + PVIRTUALCHANNELINIT pVirtualChannelInit; + PVIRTUALCHANNELOPEN pVirtualChannelOpen; + PVIRTUALCHANNELCLOSE pVirtualChannelClose; + PVIRTUALCHANNELWRITE pVirtualChannelWrite; +} CHANNEL_ENTRY_POINTS, *PCHANNEL_ENTRY_POINTS; + +typedef struct tagCHANNEL_ENTRY_POINTS_EX +{ + DWORD cbSize; + DWORD protocolVersion; + PVIRTUALCHANNELINITEX pVirtualChannelInitEx; + PVIRTUALCHANNELOPENEX pVirtualChannelOpenEx; + PVIRTUALCHANNELCLOSEEX pVirtualChannelCloseEx; + PVIRTUALCHANNELWRITEEX pVirtualChannelWriteEx; +} CHANNEL_ENTRY_POINTS_EX, *PCHANNEL_ENTRY_POINTS_EX; + +typedef BOOL VCAPITYPE VIRTUALCHANNELENTRY(PCHANNEL_ENTRY_POINTS pEntryPoints); + +typedef VIRTUALCHANNELENTRY* PVIRTUALCHANNELENTRY; + +typedef BOOL VCAPITYPE VIRTUALCHANNELENTRYEX(PCHANNEL_ENTRY_POINTS_EX pEntryPointsEx, + PVOID pInitHandle); + +typedef VIRTUALCHANNELENTRYEX* PVIRTUALCHANNELENTRYEX; + +typedef HRESULT(VCAPITYPE* PFNVCAPIGETINSTANCE)(REFIID refiid, PULONG pNumObjs, PVOID* ppObjArray); + +#endif + +#if !defined(_WIN32) || !defined(_INC_WTSAPI) + +/** + * Windows Terminal Services API (wtsapi32.h) + */ + +#define WTS_CURRENT_SERVER ((HANDLE)NULL) +#define WTS_CURRENT_SERVER_HANDLE ((HANDLE)NULL) +#define WTS_CURRENT_SERVER_NAME (NULL) + +#define WTS_CURRENT_SESSION ((DWORD)-1) + +#define WTS_ANY_SESSION ((DWORD)-2) + +#define IDTIMEOUT 32000 +#define IDASYNC 32001 + +#define USERNAME_LENGTH 20 +#define CLIENTNAME_LENGTH 20 +#define CLIENTADDRESS_LENGTH 30 + +#define WTS_WSD_LOGOFF 0x00000001 +#define WTS_WSD_SHUTDOWN 0x00000002 +#define WTS_WSD_REBOOT 0x00000004 +#define WTS_WSD_POWEROFF 0x00000008 +#define WTS_WSD_FASTREBOOT 0x00000010 + +#define MAX_ELAPSED_TIME_LENGTH 15 +#define MAX_DATE_TIME_LENGTH 56 +#define WINSTATIONNAME_LENGTH 32 +#define DOMAIN_LENGTH 17 + +#define WTS_DRIVE_LENGTH 3 +#define WTS_LISTENER_NAME_LENGTH 32 +#define WTS_COMMENT_LENGTH 60 + +#define WTS_LISTENER_CREATE 0x00000001 +#define WTS_LISTENER_UPDATE 0x00000010 + +#define WTS_SECURITY_QUERY_INFORMATION 0x00000001 +#define WTS_SECURITY_SET_INFORMATION 0x00000002 +#define WTS_SECURITY_RESET 0x00000004 +#define WTS_SECURITY_VIRTUAL_CHANNELS 0x00000008 +#define WTS_SECURITY_REMOTE_CONTROL 0x00000010 +#define WTS_SECURITY_LOGON 0x00000020 +#define WTS_SECURITY_LOGOFF 0x00000040 +#define WTS_SECURITY_MESSAGE 0x00000080 +#define WTS_SECURITY_CONNECT 0x00000100 +#define WTS_SECURITY_DISCONNECT 0x00000200 + +#define WTS_SECURITY_GUEST_ACCESS (WTS_SECURITY_LOGON) + +#define WTS_SECURITY_CURRENT_GUEST_ACCESS (WTS_SECURITY_VIRTUAL_CHANNELS | WTS_SECURITY_LOGOFF) + +#define WTS_SECURITY_USER_ACCESS \ + (WTS_SECURITY_CURRENT_GUEST_ACCESS | WTS_SECURITY_QUERY_INFORMATION | WTS_SECURITY_CONNECT) + +#define WTS_SECURITY_CURRENT_USER_ACCESS \ + (WTS_SECURITY_SET_INFORMATION | WTS_SECURITY_RESET WTS_SECURITY_VIRTUAL_CHANNELS | \ + WTS_SECURITY_LOGOFF WTS_SECURITY_DISCONNECT) + +#define WTS_SECURITY_ALL_ACCESS \ + (STANDARD_RIGHTS_REQUIRED | WTS_SECURITY_QUERY_INFORMATION | WTS_SECURITY_SET_INFORMATION | \ + WTS_SECURITY_RESET | WTS_SECURITY_VIRTUAL_CHANNELS | WTS_SECURITY_REMOTE_CONTROL | \ + WTS_SECURITY_LOGON | WTS_SECURITY_MESSAGE | WTS_SECURITY_CONNECT | WTS_SECURITY_DISCONNECT) + +typedef enum +{ + WTSActive, + WTSConnected, + WTSConnectQuery, + WTSShadow, + WTSDisconnected, + WTSIdle, + WTSListen, + WTSReset, + WTSDown, + WTSInit +} WTS_CONNECTSTATE_CLASS; + +typedef struct +{ + LPWSTR pServerName; +} WTS_SERVER_INFOW, *PWTS_SERVER_INFOW; + +typedef struct +{ + LPSTR pServerName; +} WTS_SERVER_INFOA, *PWTS_SERVER_INFOA; + +typedef struct +{ + DWORD SessionId; + LPWSTR pWinStationName; + WTS_CONNECTSTATE_CLASS State; +} WTS_SESSION_INFOW, *PWTS_SESSION_INFOW; + +typedef struct +{ + DWORD SessionId; + LPSTR pWinStationName; + WTS_CONNECTSTATE_CLASS State; +} WTS_SESSION_INFOA, *PWTS_SESSION_INFOA; + +typedef struct +{ + DWORD ExecEnvId; + WTS_CONNECTSTATE_CLASS State; + DWORD SessionId; + LPWSTR pSessionName; + LPWSTR pHostName; + LPWSTR pUserName; + LPWSTR pDomainName; + LPWSTR pFarmName; +} WTS_SESSION_INFO_1W, *PWTS_SESSION_INFO_1W; + +typedef struct +{ + DWORD ExecEnvId; + WTS_CONNECTSTATE_CLASS State; + DWORD SessionId; + LPSTR pSessionName; + LPSTR pHostName; + LPSTR pUserName; + LPSTR pDomainName; + LPSTR pFarmName; +} WTS_SESSION_INFO_1A, *PWTS_SESSION_INFO_1A; + +typedef struct +{ + DWORD SessionId; + DWORD ProcessId; + LPWSTR pProcessName; + PSID pUserSid; +} WTS_PROCESS_INFOW, *PWTS_PROCESS_INFOW; + +typedef struct +{ + DWORD SessionId; + DWORD ProcessId; + LPSTR pProcessName; + PSID pUserSid; +} WTS_PROCESS_INFOA, *PWTS_PROCESS_INFOA; + +#define WTS_PROTOCOL_TYPE_CONSOLE 0 +#define WTS_PROTOCOL_TYPE_ICA 1 +#define WTS_PROTOCOL_TYPE_RDP 2 + +typedef enum +{ + WTSInitialProgram, + WTSApplicationName, + WTSWorkingDirectory, + WTSOEMId, + WTSSessionId, + WTSUserName, + WTSWinStationName, + WTSDomainName, + WTSConnectState, + WTSClientBuildNumber, + WTSClientName, + WTSClientDirectory, + WTSClientProductId, + WTSClientHardwareId, + WTSClientAddress, + WTSClientDisplay, + WTSClientProtocolType, + WTSIdleTime, + WTSLogonTime, + WTSIncomingBytes, + WTSOutgoingBytes, + WTSIncomingFrames, + WTSOutgoingFrames, + WTSClientInfo, + WTSSessionInfo, + WTSSessionInfoEx, + WTSConfigInfo, + WTSValidationInfo, + WTSSessionAddressV4, + WTSIsRemoteSession +} WTS_INFO_CLASS; + +typedef struct +{ + ULONG version; + ULONG fConnectClientDrivesAtLogon; + ULONG fConnectPrinterAtLogon; + ULONG fDisablePrinterRedirection; + ULONG fDisableDefaultMainClientPrinter; + ULONG ShadowSettings; + WCHAR LogonUserName[USERNAME_LENGTH + 1]; + WCHAR LogonDomain[DOMAIN_LENGTH + 1]; + WCHAR WorkDirectory[MAX_PATH + 1]; + WCHAR InitialProgram[MAX_PATH + 1]; + WCHAR ApplicationName[MAX_PATH + 1]; +} WTSCONFIGINFOW, *PWTSCONFIGINFOW; + +typedef struct +{ + ULONG version; + ULONG fConnectClientDrivesAtLogon; + ULONG fConnectPrinterAtLogon; + ULONG fDisablePrinterRedirection; + ULONG fDisableDefaultMainClientPrinter; + ULONG ShadowSettings; + CHAR LogonUserName[USERNAME_LENGTH + 1]; + CHAR LogonDomain[DOMAIN_LENGTH + 1]; + CHAR WorkDirectory[MAX_PATH + 1]; + CHAR InitialProgram[MAX_PATH + 1]; + CHAR ApplicationName[MAX_PATH + 1]; +} WTSCONFIGINFOA, *PWTSCONFIGINFOA; + +typedef struct +{ + WTS_CONNECTSTATE_CLASS State; + DWORD SessionId; + DWORD IncomingBytes; + DWORD OutgoingBytes; + DWORD IncomingFrames; + DWORD OutgoingFrames; + DWORD IncomingCompressedBytes; + DWORD OutgoingCompressedBytes; + WCHAR WinStationName[WINSTATIONNAME_LENGTH]; + WCHAR Domain[DOMAIN_LENGTH]; + WCHAR UserName[USERNAME_LENGTH + 1]; + LARGE_INTEGER ConnectTime; + LARGE_INTEGER DisconnectTime; + LARGE_INTEGER LastInputTime; + LARGE_INTEGER LogonTime; + LARGE_INTEGER _CurrentTime; /* Conflicts with X11 headers */ +} WTSINFOW, *PWTSINFOW; + +typedef struct +{ + WTS_CONNECTSTATE_CLASS State; + DWORD SessionId; + DWORD IncomingBytes; + DWORD OutgoingBytes; + DWORD IncomingFrames; + DWORD OutgoingFrames; + DWORD IncomingCompressedBytes; + DWORD OutgoingCompressedBy; + CHAR WinStationName[WINSTATIONNAME_LENGTH]; + CHAR Domain[DOMAIN_LENGTH]; + CHAR UserName[USERNAME_LENGTH + 1]; + LARGE_INTEGER ConnectTime; + LARGE_INTEGER DisconnectTime; + LARGE_INTEGER LastInputTime; + LARGE_INTEGER LogonTime; + LARGE_INTEGER _CurrentTime; /* Conflicts with X11 headers */ +} WTSINFOA, *PWTSINFOA; + +#define WTS_SESSIONSTATE_UNKNOWN 0xFFFFFFFF +#define WTS_SESSIONSTATE_LOCK 0x00000000 +#define WTS_SESSIONSTATE_UNLOCK 0x00000001 + +typedef struct +{ + ULONG SessionId; + WTS_CONNECTSTATE_CLASS SessionState; + LONG SessionFlags; + WCHAR WinStationName[WINSTATIONNAME_LENGTH + 1]; + WCHAR UserName[USERNAME_LENGTH + 1]; + WCHAR DomainName[DOMAIN_LENGTH + 1]; + LARGE_INTEGER LogonTime; + LARGE_INTEGER ConnectTime; + LARGE_INTEGER DisconnectTime; + LARGE_INTEGER LastInputTime; + LARGE_INTEGER _CurrentTime; /* Conflicts with X11 headers */ + DWORD IncomingBytes; + DWORD OutgoingBytes; + DWORD IncomingFrames; + DWORD OutgoingFrames; + DWORD IncomingCompressedBytes; + DWORD OutgoingCompressedBytes; +} WTSINFOEX_LEVEL1_W, *PWTSINFOEX_LEVEL1_W; + +typedef struct +{ + ULONG SessionId; + WTS_CONNECTSTATE_CLASS SessionState; + LONG SessionFlags; + CHAR WinStationName[WINSTATIONNAME_LENGTH + 1]; + CHAR UserName[USERNAME_LENGTH + 1]; + CHAR DomainName[DOMAIN_LENGTH + 1]; + LARGE_INTEGER LogonTime; + LARGE_INTEGER ConnectTime; + LARGE_INTEGER DisconnectTime; + LARGE_INTEGER LastInputTime; + LARGE_INTEGER _CurrentTime; /* Conflicts with X11 headers */ + DWORD IncomingBytes; + DWORD OutgoingBytes; + DWORD IncomingFrames; + DWORD OutgoingFrames; + DWORD IncomingCompressedBytes; + DWORD OutgoingCompressedBytes; +} WTSINFOEX_LEVEL1_A, *PWTSINFOEX_LEVEL1_A; + +typedef union +{ + WTSINFOEX_LEVEL1_W WTSInfoExLevel1; +} WTSINFOEX_LEVEL_W, *PWTSINFOEX_LEVEL_W; + +typedef union +{ + WTSINFOEX_LEVEL1_A WTSInfoExLevel1; +} WTSINFOEX_LEVEL_A, *PWTSINFOEX_LEVEL_A; + +typedef struct +{ + DWORD Level; + WTSINFOEX_LEVEL_W Data; +} WTSINFOEXW, *PWTSINFOEXW; + +typedef struct +{ + DWORD Level; + WTSINFOEX_LEVEL_A Data; +} WTSINFOEXA, *PWTSINFOEXA; + +typedef struct +{ + WCHAR ClientName[CLIENTNAME_LENGTH + 1]; + WCHAR Domain[DOMAIN_LENGTH + 1]; + WCHAR UserName[USERNAME_LENGTH + 1]; + WCHAR WorkDirectory[MAX_PATH + 1]; + WCHAR InitialProgram[MAX_PATH + 1]; + BYTE EncryptionLevel; + ULONG ClientAddressFamily; + USHORT ClientAddress[CLIENTADDRESS_LENGTH + 1]; + USHORT HRes; + USHORT VRes; + USHORT ColorDepth; + WCHAR ClientDirectory[MAX_PATH + 1]; + ULONG ClientBuildNumber; + ULONG ClientHardwareId; + USHORT ClientProductId; + USHORT OutBufCountHost; + USHORT OutBufCountClient; + USHORT OutBufLength; + WCHAR DeviceId[MAX_PATH + 1]; +} WTSCLIENTW, *PWTSCLIENTW; + +typedef struct +{ + CHAR ClientName[CLIENTNAME_LENGTH + 1]; + CHAR Domain[DOMAIN_LENGTH + 1]; + CHAR UserName[USERNAME_LENGTH + 1]; + CHAR WorkDirectory[MAX_PATH + 1]; + CHAR InitialProgram[MAX_PATH + 1]; + BYTE EncryptionLevel; + ULONG ClientAddressFamily; + USHORT ClientAddress[CLIENTADDRESS_LENGTH + 1]; + USHORT HRes; + USHORT VRes; + USHORT ColorDepth; + CHAR ClientDirectory[MAX_PATH + 1]; + ULONG ClientBuildNumber; + ULONG ClientHardwareId; + USHORT ClientProductId; + USHORT OutBufCountHost; + USHORT OutBufCountClient; + USHORT OutBufLength; + CHAR DeviceId[MAX_PATH + 1]; +} WTSCLIENTA, *PWTSCLIENTA; + +#define PRODUCTINFO_COMPANYNAME_LENGTH 256 +#define PRODUCTINFO_PRODUCTID_LENGTH 4 + +typedef struct +{ + CHAR CompanyName[PRODUCTINFO_COMPANYNAME_LENGTH]; + CHAR ProductID[PRODUCTINFO_PRODUCTID_LENGTH]; +} PRODUCT_INFOA; + +typedef struct +{ + WCHAR CompanyName[PRODUCTINFO_COMPANYNAME_LENGTH]; + WCHAR ProductID[PRODUCTINFO_PRODUCTID_LENGTH]; +} PRODUCT_INFOW; + +#define VALIDATIONINFORMATION_LICENSE_LENGTH 16384 +#define VALIDATIONINFORMATION_HARDWAREID_LENGTH 20 + +typedef struct +{ + PRODUCT_INFOA ProductInfo; + BYTE License[VALIDATIONINFORMATION_LICENSE_LENGTH]; + DWORD LicenseLength; + BYTE HardwareID[VALIDATIONINFORMATION_HARDWAREID_LENGTH]; + DWORD HardwareIDLength; +} WTS_VALIDATION_INFORMATIONA, *PWTS_VALIDATION_INFORMATIONA; + +typedef struct +{ + PRODUCT_INFOW ProductInfo; + BYTE License[VALIDATIONINFORMATION_LICENSE_LENGTH]; + DWORD LicenseLength; + BYTE HardwareID[VALIDATIONINFORMATION_HARDWAREID_LENGTH]; + DWORD HardwareIDLength; +} WTS_VALIDATION_INFORMATIONW, *PWTS_VALIDATION_INFORMATIONW; + +typedef struct +{ + DWORD AddressFamily; + BYTE Address[20]; +} WTS_CLIENT_ADDRESS, *PWTS_CLIENT_ADDRESS; + +typedef struct +{ + DWORD HorizontalResolution; + DWORD VerticalResolution; + DWORD ColorDepth; +} WTS_CLIENT_DISPLAY, *PWTS_CLIENT_DISPLAY; + +typedef enum +{ + WTSUserConfigInitialProgram, + WTSUserConfigWorkingDirectory, + WTSUserConfigfInheritInitialProgram, + WTSUserConfigfAllowLogonTerminalServer, + WTSUserConfigTimeoutSettingsConnections, + WTSUserConfigTimeoutSettingsDisconnections, + WTSUserConfigTimeoutSettingsIdle, + WTSUserConfigfDeviceClientDrives, + WTSUserConfigfDeviceClientPrinters, + WTSUserConfigfDeviceClientDefaultPrinter, + WTSUserConfigBrokenTimeoutSettings, + WTSUserConfigReconnectSettings, + WTSUserConfigModemCallbackSettings, + WTSUserConfigModemCallbackPhoneNumber, + WTSUserConfigShadowingSettings, + WTSUserConfigTerminalServerProfilePath, + WTSUserConfigTerminalServerHomeDir, + WTSUserConfigTerminalServerHomeDirDrive, + WTSUserConfigfTerminalServerRemoteHomeDir, + WTSUserConfigUser +} WTS_CONFIG_CLASS; + +typedef enum +{ + WTSUserConfigSourceSAM +} WTS_CONFIG_SOURCE; + +typedef struct +{ + DWORD Source; + DWORD InheritInitialProgram; + DWORD AllowLogonTerminalServer; + DWORD TimeoutSettingsConnections; + DWORD TimeoutSettingsDisconnections; + DWORD TimeoutSettingsIdle; + DWORD DeviceClientDrives; + DWORD DeviceClientPrinters; + DWORD ClientDefaultPrinter; + DWORD BrokenTimeoutSettings; + DWORD ReconnectSettings; + DWORD ShadowingSettings; + DWORD TerminalServerRemoteHomeDir; + CHAR InitialProgram[MAX_PATH + 1]; + CHAR WorkDirectory[MAX_PATH + 1]; + CHAR TerminalServerProfilePath[MAX_PATH + 1]; + CHAR TerminalServerHomeDir[MAX_PATH + 1]; + CHAR TerminalServerHomeDirDrive[WTS_DRIVE_LENGTH + 1]; +} WTSUSERCONFIGA, *PWTSUSERCONFIGA; + +typedef struct +{ + DWORD Source; + DWORD InheritInitialProgram; + DWORD AllowLogonTerminalServer; + DWORD TimeoutSettingsConnections; + DWORD TimeoutSettingsDisconnections; + DWORD TimeoutSettingsIdle; + DWORD DeviceClientDrives; + DWORD DeviceClientPrinters; + DWORD ClientDefaultPrinter; + DWORD BrokenTimeoutSettings; + DWORD ReconnectSettings; + DWORD ShadowingSettings; + DWORD TerminalServerRemoteHomeDir; + WCHAR InitialProgram[MAX_PATH + 1]; + WCHAR WorkDirectory[MAX_PATH + 1]; + WCHAR TerminalServerProfilePath[MAX_PATH + 1]; + WCHAR TerminalServerHomeDir[MAX_PATH + 1]; + WCHAR TerminalServerHomeDirDrive[WTS_DRIVE_LENGTH + 1]; +} WTSUSERCONFIGW, *PWTSUSERCONFIGW; + +#define WTS_EVENT_NONE 0x00000000 +#define WTS_EVENT_CREATE 0x00000001 +#define WTS_EVENT_DELETE 0x00000002 +#define WTS_EVENT_RENAME 0x00000004 +#define WTS_EVENT_CONNECT 0x00000008 +#define WTS_EVENT_DISCONNECT 0x00000010 +#define WTS_EVENT_LOGON 0x00000020 +#define WTS_EVENT_LOGOFF 0x00000040 +#define WTS_EVENT_STATECHANGE 0x00000080 +#define WTS_EVENT_LICENSE 0x00000100 +#define WTS_EVENT_ALL 0x7FFFFFFF +#define WTS_EVENT_FLUSH 0x80000000 + +#define REMOTECONTROL_KBDSHIFT_HOTKEY 0x1 +#define REMOTECONTROL_KBDCTRL_HOTKEY 0x2 +#define REMOTECONTROL_KBDALT_HOTKEY 0x4 + +typedef enum +{ + WTSVirtualClientData, + WTSVirtualFileHandle, + WTSVirtualEventHandle, /* Extended */ + WTSVirtualChannelReady, /* Extended */ + WTSVirtualChannelOpenStatus /* Extended */ +} WTS_VIRTUAL_CLASS; + +typedef struct +{ + DWORD AddressFamily; + BYTE Address[20]; +} WTS_SESSION_ADDRESS, *PWTS_SESSION_ADDRESS; + +#define WTS_CHANNEL_OPTION_DYNAMIC 0x00000001 +#define WTS_CHANNEL_OPTION_DYNAMIC_PRI_LOW 0x00000000 +#define WTS_CHANNEL_OPTION_DYNAMIC_PRI_MED 0x00000002 +#define WTS_CHANNEL_OPTION_DYNAMIC_PRI_HIGH 0x00000004 +#define WTS_CHANNEL_OPTION_DYNAMIC_PRI_REAL 0x00000006 +#define WTS_CHANNEL_OPTION_DYNAMIC_NO_COMPRESS 0x00000008 + +#define NOTIFY_FOR_ALL_SESSIONS 1 +#define NOTIFY_FOR_THIS_SESSION 0 + +#define WTS_PROCESS_INFO_LEVEL_0 0 +#define WTS_PROCESS_INFO_LEVEL_1 1 + +typedef struct +{ + DWORD SessionId; + DWORD ProcessId; + LPWSTR pProcessName; + PSID pUserSid; + DWORD NumberOfThreads; + DWORD HandleCount; + DWORD PagefileUsage; + DWORD PeakPagefileUsage; + DWORD WorkingSetSize; + DWORD PeakWorkingSetSize; + LARGE_INTEGER UserTime; + LARGE_INTEGER KernelTime; +} WTS_PROCESS_INFO_EXW, *PWTS_PROCESS_INFO_EXW; + +typedef struct +{ + DWORD SessionId; + DWORD ProcessId; + LPSTR pProcessName; + PSID pUserSid; + DWORD NumberOfThreads; + DWORD HandleCount; + DWORD PagefileUsage; + DWORD PeakPagefileUsage; + DWORD WorkingSetSize; + DWORD PeakWorkingSetSize; + LARGE_INTEGER UserTime; + LARGE_INTEGER KernelTime; +} WTS_PROCESS_INFO_EXA, *PWTS_PROCESS_INFO_EXA; + +typedef enum +{ + WTSTypeProcessInfoLevel0, + WTSTypeProcessInfoLevel1, + WTSTypeSessionInfoLevel1 +} WTS_TYPE_CLASS; + +typedef WCHAR WTSLISTENERNAMEW[WTS_LISTENER_NAME_LENGTH + 1]; +typedef WTSLISTENERNAMEW* PWTSLISTENERNAMEW; +typedef CHAR WTSLISTENERNAMEA[WTS_LISTENER_NAME_LENGTH + 1]; +typedef WTSLISTENERNAMEA* PWTSLISTENERNAMEA; + +typedef struct +{ + ULONG version; + ULONG fEnableListener; + ULONG MaxConnectionCount; + ULONG fPromptForPassword; + ULONG fInheritColorDepth; + ULONG ColorDepth; + ULONG fInheritBrokenTimeoutSettings; + ULONG BrokenTimeoutSettings; + ULONG fDisablePrinterRedirection; + ULONG fDisableDriveRedirection; + ULONG fDisableComPortRedirection; + ULONG fDisableLPTPortRedirection; + ULONG fDisableClipboardRedirection; + ULONG fDisableAudioRedirection; + ULONG fDisablePNPRedirection; + ULONG fDisableDefaultMainClientPrinter; + ULONG LanAdapter; + ULONG PortNumber; + ULONG fInheritShadowSettings; + ULONG ShadowSettings; + ULONG TimeoutSettingsConnection; + ULONG TimeoutSettingsDisconnection; + ULONG TimeoutSettingsIdle; + ULONG SecurityLayer; + ULONG MinEncryptionLevel; + ULONG UserAuthentication; + WCHAR Comment[WTS_COMMENT_LENGTH + 1]; + WCHAR LogonUserName[USERNAME_LENGTH + 1]; + WCHAR LogonDomain[DOMAIN_LENGTH + 1]; + WCHAR WorkDirectory[MAX_PATH + 1]; + WCHAR InitialProgram[MAX_PATH + 1]; +} WTSLISTENERCONFIGW, *PWTSLISTENERCONFIGW; + +typedef struct +{ + ULONG version; + ULONG fEnableListener; + ULONG MaxConnectionCount; + ULONG fPromptForPassword; + ULONG fInheritColorDepth; + ULONG ColorDepth; + ULONG fInheritBrokenTimeoutSettings; + ULONG BrokenTimeoutSettings; + ULONG fDisablePrinterRedirection; + ULONG fDisableDriveRedirection; + ULONG fDisableComPortRedirection; + ULONG fDisableLPTPortRedirection; + ULONG fDisableClipboardRedirection; + ULONG fDisableAudioRedirection; + ULONG fDisablePNPRedirection; + ULONG fDisableDefaultMainClientPrinter; + ULONG LanAdapter; + ULONG PortNumber; + ULONG fInheritShadowSettings; + ULONG ShadowSettings; + ULONG TimeoutSettingsConnection; + ULONG TimeoutSettingsDisconnection; + ULONG TimeoutSettingsIdle; + ULONG SecurityLayer; + ULONG MinEncryptionLevel; + ULONG UserAuthentication; + CHAR Comment[WTS_COMMENT_LENGTH + 1]; + CHAR LogonUserName[USERNAME_LENGTH + 1]; + CHAR LogonDomain[DOMAIN_LENGTH + 1]; + CHAR WorkDirectory[MAX_PATH + 1]; + CHAR InitialProgram[MAX_PATH + 1]; +} WTSLISTENERCONFIGA, *PWTSLISTENERCONFIGA; + +#ifdef UNICODE +#define WTS_SERVER_INFO WTS_SERVER_INFOW +#define PWTS_SERVER_INFO PWTS_SERVER_INFOW +#define WTS_SESSION_INFO WTS_SESSION_INFOW +#define PWTS_SESSION_INFO PWTS_SESSION_INFOW +#define WTS_SESSION_INFO_1 WTS_SESSION_INFO_1W +#define PWTS_SESSION_INFO_1 PWTS_SESSION_INFO_1W +#define WTS_PROCESS_INFO WTS_PROCESS_INFOW +#define PWTS_PROCESS_INFO PWTS_PROCESS_INFOW +#define WTSCONFIGINFO WTSCONFIGINFOW +#define PWTSCONFIGINFO PWTSCONFIGINFOW +#define WTSINFO WTSINFOW +#define PWTSINFO PWTSINFOW +#define WTSINFOEX WTSINFOEXW +#define PWTSINFOEX PWTSINFOEXW +#define WTSINFOEX_LEVEL WTSINFOEX_LEVEL_W +#define PWTSINFOEX_LEVEL PWTSINFOEX_LEVEL_W +#define WTSINFOEX_LEVEL1 WTSINFOEX_LEVEL1_W +#define PWTSINFOEX_LEVEL1 PWTSINFOEX_LEVEL1_W +#define WTSCLIENT WTSCLIENTW +#define PWTSCLIENT PWTSCLIENTW +#define PRODUCT_INFO PRODUCT_INFOW +#define WTS_VALIDATION_INFORMATION WTS_VALIDATION_INFORMATIONW +#define PWTS_VALIDATION_INFORMATION PWTS_VALIDATION_INFORMATIONW +#define WTSUSERCONFIG WTSUSERCONFIGW +#define PWTSUSERCONFIG PWTSUSERCONFIGW +#define WTS_PROCESS_INFO_EX WTS_PROCESS_INFO_EXW +#define PWTS_PROCESS_INFO_EX PWTS_PROCESS_INFO_EXW +#define WTSLISTENERNAME WTSLISTENERNAMEW +#define PWTSLISTENERNAME PWTSLISTENERNAMEW +#define WTSLISTENERCONFIG WTSLISTENERCONFIGW +#define PWTSLISTENERCONFIG PWTSLISTENERCONFIGW +#else +#define WTS_SERVER_INFO WTS_SERVER_INFOA +#define PWTS_SERVER_INFO PWTS_SERVER_INFOA +#define WTS_SESSION_INFO WTS_SESSION_INFOA +#define PWTS_SESSION_INFO PWTS_SESSION_INFOA +#define WTS_SESSION_INFO_1 WTS_SESSION_INFO_1A +#define PWTS_SESSION_INFO_1 PWTS_SESSION_INFO_1A +#define WTS_PROCESS_INFO WTS_PROCESS_INFOA +#define PWTS_PROCESS_INFO PWTS_PROCESS_INFOA +#define WTSCONFIGINFO WTSCONFIGINFOA +#define PWTSCONFIGINFO PWTSCONFIGINFOA +#define WTSINFO WTSINFOA +#define PWTSINFO PWTSINFOA +#define WTSINFOEX WTSINFOEXA +#define PWTSINFOEX PWTSINFOEXA +#define WTSINFOEX_LEVEL WTSINFOEX_LEVEL_A +#define PWTSINFOEX_LEVEL PWTSINFOEX_LEVEL_A +#define WTSINFOEX_LEVEL1 WTSINFOEX_LEVEL1_A +#define PWTSINFOEX_LEVEL1 PWTSINFOEX_LEVEL1_A +#define WTSCLIENT WTSCLIENTA +#define PWTSCLIENT PWTSCLIENTA +#define PRODUCT_INFO PRODUCT_INFOA +#define WTS_VALIDATION_INFORMATION WTS_VALIDATION_INFORMATIONA +#define PWTS_VALIDATION_INFORMATION PWTS_VALIDATION_INFORMATIONA +#define WTSUSERCONFIG WTSUSERCONFIGA +#define PWTSUSERCONFIG PWTSUSERCONFIGA +#define WTS_PROCESS_INFO_EX WTS_PROCESS_INFO_EXA +#define PWTS_PROCESS_INFO_EX PWTS_PROCESS_INFO_EXA +#define WTSLISTENERNAME WTSLISTENERNAMEA +#define PWTSLISTENERNAME PWTSLISTENERNAMEA +#define WTSLISTENERCONFIG WTSLISTENERCONFIGA +#define PWTSLISTENERCONFIG PWTSLISTENERCONFIGA +#endif + +#define REMOTECONTROL_FLAG_DISABLE_KEYBOARD 0x00000001 +#define REMOTECONTROL_FLAG_DISABLE_MOUSE 0x00000002 +#define REMOTECONTROL_FLAG_DISABLE_INPUT \ + REMOTECONTROL_FLAG_DISABLE_KEYBOARD | REMOTECONTROL_FLAG_DISABLE_MOUSE + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API BOOL WINAPI WTSStopRemoteControlSession(ULONG LogonId); + + WINPR_API BOOL WINAPI WTSStartRemoteControlSessionW(LPWSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers); + WINPR_API BOOL WINAPI WTSStartRemoteControlSessionA(LPSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers); + + WINPR_API BOOL WINAPI WTSStartRemoteControlSessionExW(LPWSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers, DWORD flags); + WINPR_API BOOL WINAPI WTSStartRemoteControlSessionExA(LPSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers, DWORD flags); + + WINPR_API BOOL WINAPI WTSConnectSessionW(ULONG LogonId, ULONG TargetLogonId, PWSTR pPassword, + BOOL bWait); + WINPR_API BOOL WINAPI WTSConnectSessionA(ULONG LogonId, ULONG TargetLogonId, PSTR pPassword, + BOOL bWait); + + WINPR_API BOOL WINAPI WTSEnumerateServersW(LPWSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOW* ppServerInfo, DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateServersA(LPSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOA* ppServerInfo, DWORD* pCount); + + WINPR_API VOID WINAPI WTSCloseServer(HANDLE hServer); + + WINPR_ATTR_MALLOC(WTSCloseServer, 1) + WINPR_API HANDLE WINAPI WTSOpenServerW(LPWSTR pServerName); + + WINPR_ATTR_MALLOC(WTSCloseServer, 1) + WINPR_API HANDLE WINAPI WTSOpenServerA(LPSTR pServerName); + + WINPR_ATTR_MALLOC(WTSCloseServer, 1) + WINPR_API HANDLE WINAPI WTSOpenServerExW(LPWSTR pServerName); + + WINPR_ATTR_MALLOC(WTSCloseServer, 1) + WINPR_API HANDLE WINAPI WTSOpenServerExA(LPSTR pServerName); + + WINPR_API BOOL WINAPI WTSEnumerateSessionsW(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOW* ppSessionInfo, DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateSessionsA(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOA* ppSessionInfo, DWORD* pCount); + + WINPR_API BOOL WINAPI WTSEnumerateSessionsExW(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1W* ppSessionInfo, + DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateSessionsExA(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1A* ppSessionInfo, + DWORD* pCount); + + WINPR_API BOOL WINAPI WTSEnumerateProcessesW(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOW* ppProcessInfo, DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateProcessesA(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOA* ppProcessInfo, DWORD* pCount); + + WINPR_API BOOL WINAPI WTSTerminateProcess(HANDLE hServer, DWORD ProcessId, DWORD ExitCode); + + WINPR_API BOOL WINAPI WTSQuerySessionInformationW(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, LPWSTR* ppBuffer, + DWORD* pBytesReturned); + WINPR_API BOOL WINAPI WTSQuerySessionInformationA(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, LPSTR* ppBuffer, + DWORD* pBytesReturned); + + WINPR_API BOOL WINAPI WTSQueryUserConfigW(LPWSTR pServerName, LPWSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPWSTR* ppBuffer, + DWORD* pBytesReturned); + WINPR_API BOOL WINAPI WTSQueryUserConfigA(LPSTR pServerName, LPSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPSTR* ppBuffer, + DWORD* pBytesReturned); + + WINPR_API BOOL WINAPI WTSSetUserConfigW(LPWSTR pServerName, LPWSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPWSTR pBuffer, + DWORD DataLength); + WINPR_API BOOL WINAPI WTSSetUserConfigA(LPSTR pServerName, LPSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPSTR pBuffer, + DWORD DataLength); + + WINPR_API BOOL WINAPI WTSSendMessageW(HANDLE hServer, DWORD SessionId, LPWSTR pTitle, + DWORD TitleLength, LPWSTR pMessage, DWORD MessageLength, + DWORD Style, DWORD Timeout, DWORD* pResponse, BOOL bWait); + WINPR_API BOOL WINAPI WTSSendMessageA(HANDLE hServer, DWORD SessionId, LPSTR pTitle, + DWORD TitleLength, LPSTR pMessage, DWORD MessageLength, + DWORD Style, DWORD Timeout, DWORD* pResponse, BOOL bWait); + + WINPR_API BOOL WINAPI WTSDisconnectSession(HANDLE hServer, DWORD SessionId, BOOL bWait); + + WINPR_API BOOL WINAPI WTSLogoffSession(HANDLE hServer, DWORD SessionId, BOOL bWait); + + WINPR_API BOOL WINAPI WTSShutdownSystem(HANDLE hServer, DWORD ShutdownFlag); + + WINPR_API BOOL WINAPI WTSWaitSystemEvent(HANDLE hServer, DWORD EventMask, DWORD* pEventFlags); + + WINPR_API BOOL WINAPI WTSVirtualChannelClose(HANDLE hChannelHandle); + + WINPR_ATTR_MALLOC(WTSVirtualChannelClose, 1) + WINPR_API HANDLE WINAPI WTSVirtualChannelOpen(HANDLE hServer, DWORD SessionId, + LPSTR pVirtualName); + + WINPR_ATTR_MALLOC(WTSVirtualChannelClose, 1) + WINPR_API HANDLE WINAPI WTSVirtualChannelOpenEx(DWORD SessionId, LPSTR pVirtualName, + DWORD flags); + + WINPR_API BOOL WINAPI WTSVirtualChannelRead(HANDLE hChannelHandle, ULONG TimeOut, PCHAR Buffer, + ULONG BufferSize, PULONG pBytesRead); + + WINPR_API BOOL WINAPI WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, ULONG Length, + PULONG pBytesWritten); + + WINPR_API BOOL WINAPI WTSVirtualChannelPurgeInput(HANDLE hChannelHandle); + + WINPR_API BOOL WINAPI WTSVirtualChannelPurgeOutput(HANDLE hChannelHandle); + + WINPR_API BOOL WINAPI WTSVirtualChannelQuery(HANDLE hChannelHandle, + WTS_VIRTUAL_CLASS WtsVirtualClass, PVOID* ppBuffer, + DWORD* pBytesReturned); + + WINPR_API VOID WINAPI WTSFreeMemory(PVOID pMemory); + + WINPR_API BOOL WINAPI WTSRegisterSessionNotification(HWND hWnd, DWORD dwFlags); + + WINPR_API BOOL WINAPI WTSUnRegisterSessionNotification(HWND hWnd); + + WINPR_API BOOL WINAPI WTSRegisterSessionNotificationEx(HANDLE hServer, HWND hWnd, + DWORD dwFlags); + + WINPR_API BOOL WINAPI WTSUnRegisterSessionNotificationEx(HANDLE hServer, HWND hWnd); + + WINPR_API BOOL WINAPI WTSQueryUserToken(ULONG SessionId, PHANDLE phToken); + + WINPR_API BOOL WINAPI WTSFreeMemoryExW(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries); + WINPR_API BOOL WINAPI WTSFreeMemoryExA(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries); + + WINPR_API BOOL WINAPI WTSEnumerateProcessesExW(HANDLE hServer, DWORD* pLevel, DWORD SessionId, + LPWSTR* ppProcessInfo, DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateProcessesExA(HANDLE hServer, DWORD* pLevel, DWORD SessionId, + LPSTR* ppProcessInfo, DWORD* pCount); + + WINPR_API BOOL WINAPI WTSEnumerateListenersW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEW pListeners, DWORD* pCount); + WINPR_API BOOL WINAPI WTSEnumerateListenersA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEA pListeners, DWORD* pCount); + + WINPR_API BOOL WINAPI WTSQueryListenerConfigW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, + PWTSLISTENERCONFIGW pBuffer); + WINPR_API BOOL WINAPI WTSQueryListenerConfigA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, PWTSLISTENERCONFIGA pBuffer); + + WINPR_API BOOL WINAPI WTSCreateListenerW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, PWTSLISTENERCONFIGW pBuffer, + DWORD flag); + WINPR_API BOOL WINAPI WTSCreateListenerA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, PWTSLISTENERCONFIGA pBuffer, + DWORD flag); + + WINPR_API BOOL WINAPI WTSSetListenerSecurityW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor); + WINPR_API BOOL WINAPI WTSSetListenerSecurityA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor); + + WINPR_API BOOL WINAPI WTSGetListenerSecurityW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, + DWORD nLength, LPDWORD lpnLengthNeeded); + WINPR_API BOOL WINAPI WTSGetListenerSecurityA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, + DWORD nLength, LPDWORD lpnLengthNeeded); + + /** + * WTSEnableChildSessions, WTSIsChildSessionsEnabled and WTSGetChildSessionId + * are not explicitly declared as WINAPI like other WTSAPI functions. + * Since they are declared as extern "C", we explicitly declare them as CDECL. + */ + + WINPR_API BOOL CDECL WTSEnableChildSessions(BOOL bEnable); + + WINPR_API BOOL CDECL WTSIsChildSessionsEnabled(PBOOL pbEnabled); + + WINPR_API BOOL CDECL WTSGetChildSessionId(PULONG pSessionId); + + WINPR_API BOOL CDECL WTSLogonUser(HANDLE hServer, LPCSTR username, LPCSTR password, + LPCSTR domain); + + WINPR_API BOOL CDECL WTSLogoffUser(HANDLE hServer); + +#ifdef __cplusplus +} +#endif + +#ifdef UNICODE +#define WTSStartRemoteControlSession WTSStartRemoteControlSessionW +#define WTSStartRemoteControlSessionEx WTSStartRemoteControlSessionExW +#define WTSConnectSession WTSConnectSessionW +#define WTSEnumerateServers WTSEnumerateServersW +#define WTSOpenServer WTSOpenServerW +#define WTSOpenServerEx WTSOpenServerExW +#define WTSEnumerateSessions WTSEnumerateSessionsW +#define WTSEnumerateSessionsEx WTSEnumerateSessionsExW +#define WTSEnumerateProcesses WTSEnumerateProcessesW +#define WTSQuerySessionInformation WTSQuerySessionInformationW +#define WTSQueryUserConfig WTSQueryUserConfigW +#define WTSSetUserConfig WTSSetUserConfigW +#define WTSSendMessage WTSSendMessageW +#define WTSFreeMemoryEx WTSFreeMemoryExW +#define WTSEnumerateProcessesEx WTSEnumerateProcessesExW +#define WTSEnumerateListeners WTSEnumerateListenersW +#define WTSQueryListenerConfig WTSQueryListenerConfigW +#define WTSCreateListener WTSCreateListenerW +#define WTSSetListenerSecurity WTSSetListenerSecurityW +#define WTSGetListenerSecurity WTSGetListenerSecurityW +#else +#define WTSStartRemoteControlSession WTSStartRemoteControlSessionA +#define WTSStartRemoteControlSessionEx WTSStartRemoteControlSessionExA +#define WTSConnectSession WTSConnectSessionA +#define WTSEnumerateServers WTSEnumerateServersA +#define WTSOpenServer WTSOpenServerA +#define WTSOpenServerEx WTSOpenServerExA +#define WTSEnumerateSessions WTSEnumerateSessionsA +#define WTSEnumerateSessionsEx WTSEnumerateSessionsExA +#define WTSEnumerateProcesses WTSEnumerateProcessesA +#define WTSQuerySessionInformation WTSQuerySessionInformationA +#define WTSQueryUserConfig WTSQueryUserConfigA +#define WTSSetUserConfig WTSSetUserConfigA +#define WTSSendMessage WTSSendMessageA +#define WTSFreeMemoryEx WTSFreeMemoryExA +#define WTSEnumerateProcessesEx WTSEnumerateProcessesExA +#define WTSEnumerateListeners WTSEnumerateListenersA +#define WTSQueryListenerConfig WTSQueryListenerConfigA +#define WTSCreateListener WTSCreateListenerA +#define WTSSetListenerSecurity WTSSetListenerSecurityA +#define WTSGetListenerSecurity WTSGetListenerSecurityA +#endif + +#endif + +#ifndef _WIN32 + +/** + * WTSGetActiveConsoleSessionId is declared in WinBase.h + * and exported by kernel32.dll, so we have to treat it separately. + */ + +WINPR_API DWORD WINAPI WTSGetActiveConsoleSessionId(void); + +#endif + +typedef BOOL(WINAPI* WTS_STOP_REMOTE_CONTROL_SESSION_FN)(ULONG LogonId); + +typedef BOOL(WINAPI* WTS_START_REMOTE_CONTROL_SESSION_FN_W)(LPWSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers); +typedef BOOL(WINAPI* WTS_START_REMOTE_CONTROL_SESSION_FN_A)(LPSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers); + +typedef BOOL(WINAPI* WTS_START_REMOTE_CONTROL_SESSION_EX_FN_W)(LPWSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers, DWORD flags); +typedef BOOL(WINAPI* WTS_START_REMOTE_CONTROL_SESSION_EX_FN_A)(LPSTR pTargetServerName, + ULONG TargetLogonId, BYTE HotkeyVk, + USHORT HotkeyModifiers, DWORD flags); + +typedef BOOL(WINAPI* WTS_CONNECT_SESSION_FN_W)(ULONG LogonId, ULONG TargetLogonId, PWSTR pPassword, + BOOL bWait); +typedef BOOL(WINAPI* WTS_CONNECT_SESSION_FN_A)(ULONG LogonId, ULONG TargetLogonId, PSTR pPassword, + BOOL bWait); + +typedef BOOL(WINAPI* WTS_ENUMERATE_SERVERS_FN_W)(LPWSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOW* ppServerInfo, DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_SERVERS_FN_A)(LPSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOA* ppServerInfo, DWORD* pCount); + +typedef HANDLE(WINAPI* WTS_OPEN_SERVER_FN_W)(LPWSTR pServerName); +typedef HANDLE(WINAPI* WTS_OPEN_SERVER_FN_A)(LPSTR pServerName); + +typedef HANDLE(WINAPI* WTS_OPEN_SERVER_EX_FN_W)(LPWSTR pServerName); +typedef HANDLE(WINAPI* WTS_OPEN_SERVER_EX_FN_A)(LPSTR pServerName); + +typedef VOID(WINAPI* WTS_CLOSE_SERVER_FN)(HANDLE hServer); + +typedef BOOL(WINAPI* WTS_ENUMERATE_SESSIONS_FN_W)(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOW* ppSessionInfo, DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_SESSIONS_FN_A)(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOA* ppSessionInfo, DWORD* pCount); + +typedef BOOL(WINAPI* WTS_ENUMERATE_SESSIONS_EX_FN_W)(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1W* ppSessionInfo, + DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_SESSIONS_EX_FN_A)(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1A* ppSessionInfo, + DWORD* pCount); + +typedef BOOL(WINAPI* WTS_ENUMERATE_PROCESSES_FN_W)(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOW* ppProcessInfo, + DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_PROCESSES_FN_A)(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOA* ppProcessInfo, + DWORD* pCount); + +typedef BOOL(WINAPI* WTS_TERMINATE_PROCESS_FN)(HANDLE hServer, DWORD ProcessId, DWORD ExitCode); + +typedef BOOL(WINAPI* WTS_QUERY_SESSION_INFORMATION_FN_W)(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, + LPWSTR* ppBuffer, DWORD* pBytesReturned); +typedef BOOL(WINAPI* WTS_QUERY_SESSION_INFORMATION_FN_A)(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, + LPSTR* ppBuffer, DWORD* pBytesReturned); + +typedef BOOL(WINAPI* WTS_QUERY_USER_CONFIG_FN_W)(LPWSTR pServerName, LPWSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPWSTR* ppBuffer, + DWORD* pBytesReturned); +typedef BOOL(WINAPI* WTS_QUERY_USER_CONFIG_FN_A)(LPSTR pServerName, LPSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPSTR* ppBuffer, + DWORD* pBytesReturned); + +typedef BOOL(WINAPI* WTS_SET_USER_CONFIG_FN_W)(LPWSTR pServerName, LPWSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPWSTR pBuffer, + DWORD DataLength); +typedef BOOL(WINAPI* WTS_SET_USER_CONFIG_FN_A)(LPSTR pServerName, LPSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPSTR pBuffer, + DWORD DataLength); + +typedef BOOL(WINAPI* WTS_SEND_MESSAGE_FN_W)(HANDLE hServer, DWORD SessionId, LPWSTR pTitle, + DWORD TitleLength, LPWSTR pMessage, DWORD MessageLength, + DWORD Style, DWORD Timeout, DWORD* pResponse, + BOOL bWait); +typedef BOOL(WINAPI* WTS_SEND_MESSAGE_FN_A)(HANDLE hServer, DWORD SessionId, LPSTR pTitle, + DWORD TitleLength, LPSTR pMessage, DWORD MessageLength, + DWORD Style, DWORD Timeout, DWORD* pResponse, + BOOL bWait); + +typedef BOOL(WINAPI* WTS_DISCONNECT_SESSION_FN)(HANDLE hServer, DWORD SessionId, BOOL bWait); + +typedef BOOL(WINAPI* WTS_LOGOFF_SESSION_FN)(HANDLE hServer, DWORD SessionId, BOOL bWait); + +typedef BOOL(WINAPI* WTS_SHUTDOWN_SYSTEM_FN)(HANDLE hServer, DWORD ShutdownFlag); + +typedef BOOL(WINAPI* WTS_WAIT_SYSTEM_EVENT_FN)(HANDLE hServer, DWORD EventMask, DWORD* pEventFlags); + +typedef HANDLE(WINAPI* WTS_VIRTUAL_CHANNEL_OPEN_FN)(HANDLE hServer, DWORD SessionId, + LPSTR pVirtualName); + +typedef HANDLE(WINAPI* WTS_VIRTUAL_CHANNEL_OPEN_EX_FN)(DWORD SessionId, LPSTR pVirtualName, + DWORD flags); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_CLOSE_FN)(HANDLE hChannelHandle); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_READ_FN)(HANDLE hChannelHandle, ULONG TimeOut, + PCHAR Buffer, ULONG BufferSize, + PULONG pBytesRead); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_WRITE_FN)(HANDLE hChannelHandle, PCHAR Buffer, + ULONG Length, PULONG pBytesWritten); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_PURGE_INPUT_FN)(HANDLE hChannelHandle); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_PURGE_OUTPUT_FN)(HANDLE hChannelHandle); + +typedef BOOL(WINAPI* WTS_VIRTUAL_CHANNEL_QUERY_FN)(HANDLE hChannelHandle, + WTS_VIRTUAL_CLASS WtsVirtualClass, + PVOID* ppBuffer, DWORD* pBytesReturned); + +typedef VOID(WINAPI* WTS_FREE_MEMORY_FN)(PVOID pMemory); + +typedef BOOL(WINAPI* WTS_REGISTER_SESSION_NOTIFICATION_FN)(HWND hWnd, DWORD dwFlags); + +typedef BOOL(WINAPI* WTS_UNREGISTER_SESSION_NOTIFICATION_FN)(HWND hWnd); + +typedef BOOL(WINAPI* WTS_REGISTER_SESSION_NOTIFICATION_EX_FN)(HANDLE hServer, HWND hWnd, + DWORD dwFlags); + +typedef BOOL(WINAPI* WTS_UNREGISTER_SESSION_NOTIFICATION_EX_FN)(HANDLE hServer, HWND hWnd); + +typedef BOOL(WINAPI* WTS_QUERY_USER_TOKEN_FN)(ULONG SessionId, PHANDLE phToken); + +typedef BOOL(WINAPI* WTS_FREE_MEMORY_EX_FN_W)(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries); +typedef BOOL(WINAPI* WTS_FREE_MEMORY_EX_FN_A)(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries); + +typedef BOOL(WINAPI* WTS_ENUMERATE_PROCESSES_EX_FN_W)(HANDLE hServer, DWORD* pLevel, + DWORD SessionId, LPWSTR* ppProcessInfo, + DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_PROCESSES_EX_FN_A)(HANDLE hServer, DWORD* pLevel, + DWORD SessionId, LPSTR* ppProcessInfo, + DWORD* pCount); + +typedef BOOL(WINAPI* WTS_ENUMERATE_LISTENERS_FN_W)(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEW pListeners, DWORD* pCount); +typedef BOOL(WINAPI* WTS_ENUMERATE_LISTENERS_FN_A)(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEA pListeners, DWORD* pCount); + +typedef BOOL(WINAPI* WTS_QUERY_LISTENER_CONFIG_FN_W)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPWSTR pListenerName, + PWTSLISTENERCONFIGW pBuffer); +typedef BOOL(WINAPI* WTS_QUERY_LISTENER_CONFIG_FN_A)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPSTR pListenerName, + PWTSLISTENERCONFIGA pBuffer); + +typedef BOOL(WINAPI* WTS_CREATE_LISTENER_FN_W)(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, PWTSLISTENERCONFIGW pBuffer, + DWORD flag); +typedef BOOL(WINAPI* WTS_CREATE_LISTENER_FN_A)(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, PWTSLISTENERCONFIGA pBuffer, + DWORD flag); + +typedef BOOL(WINAPI* WTS_SET_LISTENER_SECURITY_FN_W)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPWSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor); +typedef BOOL(WINAPI* WTS_SET_LISTENER_SECURITY_FN_A)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor); + +typedef BOOL(WINAPI* WTS_GET_LISTENER_SECURITY_FN_W)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPWSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, + DWORD nLength, LPDWORD lpnLengthNeeded); +typedef BOOL(WINAPI* WTS_GET_LISTENER_SECURITY_FN_A)(HANDLE hServer, PVOID pReserved, + DWORD Reserved, LPSTR pListenerName, + SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, + DWORD nLength, LPDWORD lpnLengthNeeded); + +typedef BOOL(CDECL* WTS_ENABLE_CHILD_SESSIONS_FN)(BOOL bEnable); + +typedef BOOL(CDECL* WTS_IS_CHILD_SESSIONS_ENABLED_FN)(PBOOL pbEnabled); + +typedef BOOL(CDECL* WTS_GET_CHILD_SESSION_ID_FN)(PULONG pSessionId); + +typedef DWORD(WINAPI* WTS_GET_ACTIVE_CONSOLE_SESSION_ID_FN)(void); + +typedef BOOL(WINAPI* WTS_LOGON_USER_FN)(HANDLE hServer, LPCSTR username, LPCSTR password, + LPCSTR domain); + +typedef BOOL(WINAPI* WTS_LOGOFF_USER_FN)(HANDLE hServer); + +typedef struct +{ + DWORD dwVersion; + DWORD dwFlags; + + WTS_STOP_REMOTE_CONTROL_SESSION_FN pStopRemoteControlSession; + WTS_START_REMOTE_CONTROL_SESSION_FN_W pStartRemoteControlSessionW; + WTS_START_REMOTE_CONTROL_SESSION_FN_A pStartRemoteControlSessionA; + WTS_CONNECT_SESSION_FN_W pConnectSessionW; + WTS_CONNECT_SESSION_FN_A pConnectSessionA; + WTS_ENUMERATE_SERVERS_FN_W pEnumerateServersW; + WTS_ENUMERATE_SERVERS_FN_A pEnumerateServersA; + WTS_OPEN_SERVER_FN_W pOpenServerW; + WTS_OPEN_SERVER_FN_A pOpenServerA; + WTS_OPEN_SERVER_EX_FN_W pOpenServerExW; + WTS_OPEN_SERVER_EX_FN_A pOpenServerExA; + WTS_CLOSE_SERVER_FN pCloseServer; + WTS_ENUMERATE_SESSIONS_FN_W pEnumerateSessionsW; + WTS_ENUMERATE_SESSIONS_FN_A pEnumerateSessionsA; + WTS_ENUMERATE_SESSIONS_EX_FN_W pEnumerateSessionsExW; + WTS_ENUMERATE_SESSIONS_EX_FN_A pEnumerateSessionsExA; + WTS_ENUMERATE_PROCESSES_FN_W pEnumerateProcessesW; + WTS_ENUMERATE_PROCESSES_FN_A pEnumerateProcessesA; + WTS_TERMINATE_PROCESS_FN pTerminateProcess; + WTS_QUERY_SESSION_INFORMATION_FN_W pQuerySessionInformationW; + WTS_QUERY_SESSION_INFORMATION_FN_A pQuerySessionInformationA; + WTS_QUERY_USER_CONFIG_FN_W pQueryUserConfigW; + WTS_QUERY_USER_CONFIG_FN_A pQueryUserConfigA; + WTS_SET_USER_CONFIG_FN_W pSetUserConfigW; + WTS_SET_USER_CONFIG_FN_A pSetUserConfigA; + WTS_SEND_MESSAGE_FN_W pSendMessageW; + WTS_SEND_MESSAGE_FN_A pSendMessageA; + WTS_DISCONNECT_SESSION_FN pDisconnectSession; + WTS_LOGOFF_SESSION_FN pLogoffSession; + WTS_SHUTDOWN_SYSTEM_FN pShutdownSystem; + WTS_WAIT_SYSTEM_EVENT_FN pWaitSystemEvent; + WTS_VIRTUAL_CHANNEL_OPEN_FN pVirtualChannelOpen; + WTS_VIRTUAL_CHANNEL_OPEN_EX_FN pVirtualChannelOpenEx; + WTS_VIRTUAL_CHANNEL_CLOSE_FN pVirtualChannelClose; + WTS_VIRTUAL_CHANNEL_READ_FN pVirtualChannelRead; + WTS_VIRTUAL_CHANNEL_WRITE_FN pVirtualChannelWrite; + WTS_VIRTUAL_CHANNEL_PURGE_INPUT_FN pVirtualChannelPurgeInput; + WTS_VIRTUAL_CHANNEL_PURGE_OUTPUT_FN pVirtualChannelPurgeOutput; + WTS_VIRTUAL_CHANNEL_QUERY_FN pVirtualChannelQuery; + WTS_FREE_MEMORY_FN pFreeMemory; + WTS_REGISTER_SESSION_NOTIFICATION_FN pRegisterSessionNotification; + WTS_UNREGISTER_SESSION_NOTIFICATION_FN pUnRegisterSessionNotification; + WTS_REGISTER_SESSION_NOTIFICATION_EX_FN pRegisterSessionNotificationEx; + WTS_UNREGISTER_SESSION_NOTIFICATION_EX_FN pUnRegisterSessionNotificationEx; + WTS_QUERY_USER_TOKEN_FN pQueryUserToken; + WTS_FREE_MEMORY_EX_FN_W pFreeMemoryExW; + WTS_FREE_MEMORY_EX_FN_A pFreeMemoryExA; + WTS_ENUMERATE_PROCESSES_EX_FN_W pEnumerateProcessesExW; + WTS_ENUMERATE_PROCESSES_EX_FN_A pEnumerateProcessesExA; + WTS_ENUMERATE_LISTENERS_FN_W pEnumerateListenersW; + WTS_ENUMERATE_LISTENERS_FN_A pEnumerateListenersA; + WTS_QUERY_LISTENER_CONFIG_FN_W pQueryListenerConfigW; + WTS_QUERY_LISTENER_CONFIG_FN_A pQueryListenerConfigA; + WTS_CREATE_LISTENER_FN_W pCreateListenerW; + WTS_CREATE_LISTENER_FN_A pCreateListenerA; + WTS_SET_LISTENER_SECURITY_FN_W pSetListenerSecurityW; + WTS_SET_LISTENER_SECURITY_FN_A pSetListenerSecurityA; + WTS_GET_LISTENER_SECURITY_FN_W pGetListenerSecurityW; + WTS_GET_LISTENER_SECURITY_FN_A pGetListenerSecurityA; + WTS_ENABLE_CHILD_SESSIONS_FN pEnableChildSessions; + WTS_IS_CHILD_SESSIONS_ENABLED_FN pIsChildSessionsEnabled; + WTS_GET_CHILD_SESSION_ID_FN pGetChildSessionId; + WTS_GET_ACTIVE_CONSOLE_SESSION_ID_FN pGetActiveConsoleSessionId; + WTS_LOGON_USER_FN pLogonUser; + WTS_LOGOFF_USER_FN pLogoffUser; + WTS_START_REMOTE_CONTROL_SESSION_EX_FN_W pStartRemoteControlSessionExW; + WTS_START_REMOTE_CONTROL_SESSION_EX_FN_A pStartRemoteControlSessionExA; +} WtsApiFunctionTable; +typedef WtsApiFunctionTable* PWtsApiFunctionTable; + +typedef const WtsApiFunctionTable*(CDECL* INIT_WTSAPI_FN)(void); + +#ifdef __cplusplus +extern "C" +{ +#endif + + WINPR_API BOOL WTSRegisterWtsApiFunctionTable(const WtsApiFunctionTable* table); + WINPR_API const CHAR* WTSErrorToString(UINT error); + WINPR_API const CHAR* WTSSessionStateToString(WTS_CONNECTSTATE_CLASS state); + +#ifdef __cplusplus +} +#endif + +WINPR_PRAGMA_DIAG_POP + +#endif /* WINPR_WTSAPI_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtypes.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtypes.h new file mode 100644 index 0000000000000000000000000000000000000000..d00932920c77fdcded20a758e04454c155974a7e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/include/winpr/wtypes.h @@ -0,0 +1,499 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Data Types + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2024 Armin Novak + * 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 + +#include +#include + +/* 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 +#include + +#include + +#include +#include +#include + +#include + +#if defined(_WIN32) || defined(__MINGW32__) +#include + +/* 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 +#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 + +/* ensure compatibility with objc libraries */ +#if (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0) && defined(__LP64__)) || \ + (defined(TARGET_OS_WATCH) && (TARGET_OS_WATCH != 0)) +typedef bool BOOL; +#else +typedef signed char BOOL; +#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 +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 + +#ifndef _WIN32 +#include + +// 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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dacb79d24093d0526d1c4677dce8f49a17692a0b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/CMakeLists.txt @@ -0,0 +1,252 @@ +# WinPR: Windows Portable Runtime +# winpr cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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") +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 + 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 $) +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}) +install(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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..037ce1842621480d85f5bdb1693b31638601b2d5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-bcrypt cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3edec7e9f22bfdd44e852a0c9fafa32a613e847b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/ModuleOptions.cmake @@ -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}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/bcrypt.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/bcrypt.c new file mode 100644 index 0000000000000000000000000000000000000000..0ec86aca221661fd676cc6c92cde63922328c203 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/bcrypt.c @@ -0,0 +1,114 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API: Next Generation + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#ifndef _WIN32 +#include + +/** + * Cryptography API: Next Generation: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa376210/ + */ + +NTSTATUS BCryptOpenAlgorithmProvider(BCRYPT_ALG_HANDLE* phAlgorithm, LPCWSTR pszAlgId, + LPCWSTR pszImplementation, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptCloseAlgorithmProvider(BCRYPT_ALG_HANDLE hAlgorithm, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptGetProperty(BCRYPT_HANDLE hObject, LPCWSTR pszProperty, PUCHAR pbOutput, + ULONG cbOutput, ULONG* pcbResult, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptCreateHash(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_HASH_HANDLE* phHash, + PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret, ULONG cbSecret, + ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptDestroyHash(BCRYPT_HASH_HANDLE hHash) +{ + return 0; +} + +NTSTATUS BCryptHashData(BCRYPT_HASH_HANDLE hHash, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptFinishHash(BCRYPT_HASH_HANDLE hHash, PUCHAR pbOutput, ULONG cbOutput, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptGenRandom(BCRYPT_ALG_HANDLE hAlgorithm, PUCHAR pbBuffer, ULONG cbBuffer, + ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptGenerateSymmetricKey(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE* phKey, + PUCHAR pbKeyObject, ULONG cbKeyObject, PUCHAR pbSecret, + ULONG cbSecret, ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptGenerateKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE* phKey, + ULONG dwLength, ULONG dwFlags) +{ + return 0; +} + +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) +{ + return 0; +} + +NTSTATUS BCryptDestroyKey(BCRYPT_KEY_HANDLE hKey) +{ + return 0; +} + +NTSTATUS BCryptEncrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, VOID* pPaddingInfo, + PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG* pcbResult, + ULONG dwFlags) +{ + return 0; +} + +NTSTATUS BCryptDecrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, VOID* pPaddingInfo, + PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG* pcbResult, + ULONG dwFlags) +{ + return 0; +} + +#endif /* _WIN32 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6915b2dd7add818287573ac39f7b988479d930bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/CMakeLists.txt @@ -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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/TestBCryptDefine.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/TestBCryptDefine.c new file mode 100644 index 0000000000000000000000000000000000000000..778db572e565827c67775ba1ec303f099663cf82 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/bcrypt/test/TestBCryptDefine.c @@ -0,0 +1,129 @@ +#include + +#include +#include + +#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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..acf01b42bd7e2274223272b609a5d915d224fd04 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-clipboard cmake build script +# +# Copyright 2014 Marc-Andre Moreau +# +# 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() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..b0ed4025b55f26b6a8589e3077fbdc158398d6f6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/ModuleOptions.cmake @@ -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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.c new file mode 100644 index 0000000000000000000000000000000000000000..6702855d54f072a969f3a34ea2979cdf00031b91 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.c @@ -0,0 +1,757 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include + +#include "clipboard.h" + +#include "synthetic_file.h" + +#include "../log.h" +#define TAG WINPR_TAG("clipboard") + +const char* 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 = NULL; + + if (!clipboard) + return NULL; + + 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 NULL; + + 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 NULL; + + for (UINT32 index = 0; index < format->numSynthesizers; index++) + { + wClipboardSynthesizer* synthesizer = &(format->synthesizers[index]); + + if (formatId == synthesizer->syntheticId) + return synthesizer; + } + + return NULL; +} + +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 = NULL; + } + + 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 = NULL; + wClipboardFormat* format = NULL; + + 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 = NULL; + + 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 = NULL; + 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 = NULL; + wClipboardSynthesizer* synthesizer = NULL; + + if (!clipboard) + return FALSE; + + format = ClipboardFindFormat(clipboard, formatId, NULL); + + if (!format) + return FALSE; + + if (format->formatId == syntheticId) + return FALSE; + + synthesizer = ClipboardFindSynthesizer(format, formatId); + + if (!synthesizer) + { + wClipboardSynthesizer* tmpSynthesizer = NULL; + 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 = NULL; + + if (!clipboard) + return 0; + + format = ClipboardFindFormat(clipboard, clipboard->formatId, NULL); + + if (!format) + return 0; + + count = 1 + format->numSynthesizers; + return count; +} + +UINT32 ClipboardGetFormatIds(wClipboard* clipboard, UINT32** ppFormatIds) +{ + UINT32 count = 0; + UINT32* pFormatIds = NULL; + wClipboardFormat* format = NULL; + wClipboardSynthesizer* synthesizer = NULL; + + if (!clipboard) + return 0; + + format = ClipboardFindFormat(clipboard, clipboard->formatId, NULL); + + 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 = NULL; + format->synthesizers = NULL; + } +} + +static BOOL ClipboardInitFormats(wClipboard* clipboard) +{ + UINT32 formatId = 0; + wClipboardFormat* format = NULL; + + 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 = NULL; + + 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 = NULL; + + if (!clipboard) + return NULL; + + format = ClipboardFindFormat(clipboard, formatId, NULL); + + if (!format) + return NULL; + + return format->formatName; +} + +void* ClipboardGetData(wClipboard* clipboard, UINT32 formatId, UINT32* pSize) +{ + UINT32 SrcSize = 0; + UINT32 DstSize = 0; + void* pSrcData = NULL; + void* pDstData = NULL; + wClipboardFormat* format = NULL; + wClipboardSynthesizer* synthesizer = NULL; + + if (!clipboard) + return NULL; + + if (!pSize) + return NULL; + + *pSize = 0; + format = ClipboardFindFormat(clipboard, clipboard->formatId, NULL); + + if (!format) + return NULL; + + SrcSize = clipboard->size; + pSrcData = clipboard->data; + + if (formatId == format->formatId) + { + DstSize = SrcSize; + pDstData = malloc(DstSize); + + if (!pDstData) + return NULL; + + CopyMemory(pDstData, pSrcData, SrcSize); + *pSize = DstSize; + } + else + { + synthesizer = ClipboardFindSynthesizer(format, formatId); + + if (!synthesizer || !synthesizer->pfnSynthesize) + return NULL; + + DstSize = SrcSize; + pDstData = synthesizer->pfnSynthesize(clipboard, format->formatId, pSrcData, &DstSize); + if (pDstData) + *pSize = DstSize; + } + + return pDstData; +} + +BOOL ClipboardSetData(wClipboard* clipboard, UINT32 formatId, const void* data, UINT32 size) +{ + wClipboardFormat* format = NULL; + + if (!clipboard) + return FALSE; + + format = ClipboardFindFormat(clipboard, formatId, NULL); + + 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 NULL; + + 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 NULL; + + 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 NULL; +} + +void ClipboardDestroy(wClipboard* clipboard) +{ + if (!clipboard) + return; + + ArrayList_Free(clipboard->localFiles); + clipboard->localFiles = NULL; + + ClipboardUninitFormats(clipboard); + + free(clipboard->data); + clipboard->data = NULL; + 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 = NULL; + size_t localLen = 0; + char* buffer = NULL; + 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", uri_len, uri); + + if ((uri_len <= prefixLen) || strncmp(uri, prefix, prefixLen) != 0) + { + WLog_ERR(TAG, "non-'file:' URI schemes are not supported"); + return NULL; + } + + 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 NULL; + } + } + + /* + * - 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 NULL; + } + + localName = &uri[prefixTraditionalLen]; + localLen = uri_len - prefixTraditionalLen; + + if (localLen < 1) + { + WLog_ERR(TAG, "empty 'file:' URI schemes are not supported"); + return NULL; + } + + /* + * "file:///c:/path/to/file" + * "file:///c|/path/to/file" + */ + if (localName[0] != '/') + { + WLog_ERR(TAG, "URI format are not supported: %s", uri); + return NULL; + } + + 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 NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.h new file mode 100644 index 0000000000000000000000000000000000000000..b3dc4d07e309b628c616a218ab052fc6d6395ac4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/clipboard.h @@ -0,0 +1,77 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include + +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* mime_text_plain; + +#endif /* WINPR_CLIPBOARD_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic.c new file mode 100644 index 0000000000000000000000000000000000000000..496462c7a4ce776349cec8a6d34b2baa52660d32 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic.c @@ -0,0 +1,850 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "../utils/image.h" +#include "clipboard.h" + +static const char* mime_bitmap[] = { "image/bmp", "image/x-bmp", "image/x-MS-bmp", + "image/x-win-bitmap" }; + +#if defined(WINPR_UTILS_IMAGE_WEBP) +static const char mime_webp[] = "image/webp"; +#endif +#if defined(WINPR_UTILS_IMAGE_PNG) +static const char mime_png[] = "image/png"; +#endif +#if defined(WINPR_UTILS_IMAGE_JPEG) +static const char mime_jpeg[] = "image/jpeg"; +#endif +/** + * Standard Clipboard Formats: + * http://msdn.microsoft.com/en-us/library/windows/desktop/ff729168/ + */ + +/** + * "CF_TEXT": + * + * Null-terminated ANSI text with CR/LF line endings. + */ + +static void* clipboard_synthesize_cf_text(wClipboard* clipboard, UINT32 formatId, const void* data, + UINT32* pSize) +{ + size_t size = 0; + char* pDstData = NULL; + + if (formatId == CF_UNICODETEXT) + { + char* str = ConvertWCharNToUtf8Alloc(data, *pSize / sizeof(WCHAR), &size); + + if (!str || (size > UINT32_MAX)) + { + free(str); + return NULL; + } + + pDstData = ConvertLineEndingToCRLF(str, &size); + free(str); + *pSize = (UINT32)size; + return pDstData; + } + else if ((formatId == CF_TEXT) || (formatId == CF_OEMTEXT) || + (formatId == ClipboardGetFormatId(clipboard, mime_text_plain))) + { + size = *pSize; + pDstData = ConvertLineEndingToCRLF(data, &size); + + if (!pDstData || (size > *pSize)) + { + free(pDstData); + return NULL; + } + + *pSize = (UINT32)size; + return pDstData; + } + + return NULL; +} + +/** + * "CF_OEMTEXT": + * + * Null-terminated OEM text with CR/LF line endings. + */ + +static void* clipboard_synthesize_cf_oemtext(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_cf_text(clipboard, formatId, data, pSize); +} + +/** + * "CF_LOCALE": + * + * System locale identifier associated with CF_TEXT + */ + +static void* clipboard_synthesize_cf_locale(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + UINT32* pDstData = NULL; + pDstData = (UINT32*)malloc(sizeof(UINT32)); + + if (!pDstData) + return NULL; + + *pDstData = 0x0409; /* English - United States */ + return (void*)pDstData; +} + +/** + * "CF_UNICODETEXT": + * + * Null-terminated UTF-16 text with CR/LF line endings. + */ + +static void* clipboard_synthesize_cf_unicodetext(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + size_t size = 0; + char* crlfStr = NULL; + WCHAR* pDstData = NULL; + + if ((formatId == CF_TEXT) || (formatId == CF_OEMTEXT) || + (formatId == ClipboardGetFormatId(clipboard, mime_text_plain))) + { + size_t len = 0; + if (!pSize || (*pSize > INT32_MAX)) + return NULL; + + size = *pSize; + crlfStr = ConvertLineEndingToCRLF((const char*)data, &size); + + if (!crlfStr) + return NULL; + + pDstData = ConvertUtf8NToWCharAlloc(crlfStr, size, &len); + free(crlfStr); + + if ((len < 1) || ((len + 1) > UINT32_MAX / sizeof(WCHAR))) + { + free(pDstData); + return NULL; + } + + const size_t slen = (len + 1) * sizeof(WCHAR); + *pSize = (UINT32)slen; + } + + return (void*)pDstData; +} + +/** + * mime_utf8_string: + * + * Null-terminated UTF-8 string with LF line endings. + */ + +static void* clipboard_synthesize_utf8_string(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + if (formatId == CF_UNICODETEXT) + { + size_t size = 0; + char* pDstData = ConvertWCharNToUtf8Alloc(data, *pSize / sizeof(WCHAR), &size); + + if (!pDstData) + return NULL; + + const size_t rc = ConvertLineEndingToLF(pDstData, size); + WINPR_ASSERT(rc <= UINT32_MAX); + *pSize = (UINT32)rc; + return pDstData; + } + else if ((formatId == CF_TEXT) || (formatId == CF_OEMTEXT) || + (formatId == ClipboardGetFormatId(clipboard, mime_text_plain))) + { + const size_t size = *pSize; + char* pDstData = calloc(size + 1, sizeof(char)); + + if (!pDstData) + return NULL; + + CopyMemory(pDstData, data, size); + const size_t rc = ConvertLineEndingToLF(pDstData, size); + WINPR_ASSERT(rc <= UINT32_MAX); + *pSize = (UINT32)rc; + return pDstData; + } + + return NULL; +} + +static BOOL is_format_bitmap(wClipboard* clipboard, UINT32 formatId) +{ + for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++) + { + const char* mime = mime_bitmap[x]; + const UINT32 altFormatId = ClipboardGetFormatId(clipboard, mime); + if (altFormatId == formatId) + return TRUE; + } + + return FALSE; +} + +/** + * "CF_DIB": + * + * BITMAPINFO structure followed by the bitmap bits. + */ + +static void* clipboard_synthesize_cf_dib(wClipboard* clipboard, UINT32 formatId, const void* data, + UINT32* pSize) +{ + UINT32 SrcSize = 0; + UINT32 DstSize = 0; + BYTE* pDstData = NULL; + SrcSize = *pSize; + + if (formatId == CF_DIBV5) + { + } + else if (is_format_bitmap(clipboard, formatId)) + { + WINPR_BITMAP_FILE_HEADER pFileHeader = { 0 }; + wStream sbuffer = { 0 }; + wStream* s = Stream_StaticConstInit(&sbuffer, data, SrcSize); + if (!readBitmapFileHeader(s, &pFileHeader)) + return NULL; + + DstSize = SrcSize - sizeof(BITMAPFILEHEADER); + pDstData = (BYTE*)malloc(DstSize); + + if (!pDstData) + return NULL; + + data = (const void*)&((const BYTE*)data)[sizeof(BITMAPFILEHEADER)]; + CopyMemory(pDstData, data, DstSize); + *pSize = DstSize; + return pDstData; + } + + return NULL; +} + +/** + * "CF_DIBV5": + * + * BITMAPV5HEADER structure followed by the bitmap color space information and the bitmap bits. + */ + +static void* clipboard_synthesize_cf_dibv5(wClipboard* clipboard, UINT32 formatId, const void* data, + UINT32* pSize) +{ + if (formatId == CF_DIB) + { + } + else if (is_format_bitmap(clipboard, formatId)) + { + } + + return NULL; +} + +static void* clipboard_prepend_bmp_header(const WINPR_BITMAP_INFO_HEADER* pInfoHeader, + const void* data, size_t size, UINT32* pSize) +{ + WINPR_ASSERT(pInfoHeader); + WINPR_ASSERT(pSize); + + *pSize = 0; + if ((pInfoHeader->biBitCount < 1) || (pInfoHeader->biBitCount > 32)) + return NULL; + + const size_t DstSize = sizeof(WINPR_BITMAP_FILE_HEADER) + size; + if (DstSize > UINT32_MAX) + return NULL; + + wStream* s = Stream_New(NULL, DstSize); + if (!s) + return NULL; + + WINPR_BITMAP_FILE_HEADER fileHeader = { 0 }; + fileHeader.bfType[0] = 'B'; + fileHeader.bfType[1] = 'M'; + fileHeader.bfSize = (UINT32)DstSize; + fileHeader.bfOffBits = sizeof(WINPR_BITMAP_FILE_HEADER) + sizeof(WINPR_BITMAP_INFO_HEADER); + if (!writeBitmapFileHeader(s, &fileHeader)) + goto fail; + + if (!Stream_EnsureRemainingCapacity(s, size)) + goto fail; + Stream_Write(s, data, size); + const size_t len = Stream_GetPosition(s); + if (len != DstSize) + goto fail; + *pSize = (UINT32)DstSize; + + BYTE* dst = Stream_Buffer(s); + Stream_Free(s, FALSE); + return dst; + +fail: + Stream_Free(s, TRUE); + return NULL; +} + +/** + * "image/bmp": + * + * Bitmap file format. + */ + +static void* clipboard_synthesize_image_bmp(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + UINT32 SrcSize = *pSize; + + if (formatId == CF_DIB) + { + if (SrcSize < sizeof(BITMAPINFOHEADER)) + return NULL; + + wStream sbuffer = { 0 }; + size_t offset = 0; + WINPR_BITMAP_INFO_HEADER header = { 0 }; + wStream* s = Stream_StaticConstInit(&sbuffer, data, SrcSize); + if (!readBitmapInfoHeader(s, &header, &offset)) + return NULL; + + return clipboard_prepend_bmp_header(&header, data, SrcSize, pSize); + } + else if (formatId == CF_DIBV5) + { + } + + return NULL; +} + +#if defined(WINPR_UTILS_IMAGE_PNG) || defined(WINPR_UTILS_IMAGE_WEBP) || \ + defined(WINPR_UTILS_IMAGE_JPEG) +static void* clipboard_synthesize_image_bmp_to_format(wClipboard* clipboard, UINT32 formatId, + UINT32 bmpFormat, const void* data, + UINT32* pSize) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(data); + WINPR_ASSERT(pSize); + + size_t dsize = 0; + void* result = NULL; + + wImage* img = winpr_image_new(); + void* bmp = clipboard_synthesize_image_bmp(clipboard, formatId, data, pSize); + const UINT32 SrcSize = *pSize; + *pSize = 0; + + if (!bmp || !img) + goto fail; + + if (winpr_image_read_buffer(img, bmp, SrcSize) <= 0) + goto fail; + + result = winpr_image_write_buffer(img, bmpFormat, &dsize); + if (result) + { + if (dsize <= UINT32_MAX) + *pSize = (UINT32)dsize; + else + { + free(result); + result = NULL; + } + } + +fail: + free(bmp); + winpr_image_free(img, TRUE); + return result; +} +#endif + +#if defined(WINPR_UTILS_IMAGE_PNG) +static void* clipboard_synthesize_image_bmp_to_png(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_bmp_to_format(clipboard, formatId, WINPR_IMAGE_PNG, data, + pSize); +} + +static void* clipboard_synthesize_image_format_to_bmp(wClipboard* clipboard, UINT32 srcFormatId, + const void* data, UINT32* pSize) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(data); + WINPR_ASSERT(pSize); + + BYTE* dst = NULL; + const UINT32 SrcSize = *pSize; + size_t size = 0; + wImage* image = winpr_image_new(); + if (!image) + goto fail; + + const int res = winpr_image_read_buffer(image, data, SrcSize); + if (res <= 0) + goto fail; + + dst = winpr_image_write_buffer(image, WINPR_IMAGE_BITMAP, &size); + if ((size < sizeof(WINPR_BITMAP_FILE_HEADER)) || (size > UINT32_MAX)) + { + free(dst); + dst = NULL; + goto fail; + } + *pSize = (UINT32)size; + +fail: + winpr_image_free(image, TRUE); + + if (dst) + memmove(dst, &dst[sizeof(WINPR_BITMAP_FILE_HEADER)], + size - sizeof(WINPR_BITMAP_FILE_HEADER)); + return dst; +} + +static void* clipboard_synthesize_image_png_to_bmp(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_format_to_bmp(clipboard, formatId, data, pSize); +} +#endif + +#if defined(WINPR_UTILS_IMAGE_WEBP) +static void* clipboard_synthesize_image_bmp_to_webp(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_bmp_to_format(clipboard, formatId, WINPR_IMAGE_WEBP, data, + pSize); +} + +static void* clipboard_synthesize_image_webp_to_bmp(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_format_to_bmp(clipboard, formatId, data, pSize); +} +#endif + +#if defined(WINPR_UTILS_IMAGE_JPEG) +static void* clipboard_synthesize_image_bmp_to_jpeg(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_bmp_to_format(clipboard, formatId, WINPR_IMAGE_JPEG, data, + pSize); +} + +static void* clipboard_synthesize_image_jpeg_to_bmp(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return clipboard_synthesize_image_format_to_bmp(clipboard, formatId, data, pSize); +} +#endif + +/** + * "HTML Format": + * + * HTML clipboard format: msdn.microsoft.com/en-us/library/windows/desktop/ms649015/ + */ + +static void* clipboard_synthesize_html_format(wClipboard* clipboard, UINT32 formatId, + const void* pData, UINT32* pSize) +{ + union + { + const void* cpv; + const char* cpc; + const BYTE* cpb; + WCHAR* pv; + } pSrcData; + char* pDstData = NULL; + + pSrcData.cpv = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(pSize); + + if (formatId == ClipboardGetFormatId(clipboard, "text/html")) + { + const size_t SrcSize = (size_t)*pSize; + const size_t DstSize = SrcSize + 200; + char* body = NULL; + char num[20] = { 0 }; + + /* Create a copy, we modify the input data */ + pSrcData.pv = calloc(1, SrcSize + 1); + if (!pSrcData.pv) + goto fail; + memcpy(pSrcData.pv, pData, SrcSize); + + if (SrcSize > 2) + { + if (SrcSize > INT_MAX) + goto fail; + + /* Check the BOM (Byte Order Mark) */ + if ((pSrcData.cpb[0] == 0xFE) && (pSrcData.cpb[1] == 0xFF)) + ByteSwapUnicode(pSrcData.pv, (SrcSize / 2)); + + /* Check if we have WCHAR, convert to UTF-8 */ + if ((pSrcData.cpb[0] == 0xFF) && (pSrcData.cpb[1] == 0xFE)) + { + char* utfString = + ConvertWCharNToUtf8Alloc(&pSrcData.pv[1], SrcSize / sizeof(WCHAR), NULL); + free(pSrcData.pv); + pSrcData.cpc = utfString; + if (!utfString) + goto fail; + } + } + + pDstData = (char*)calloc(1, DstSize); + + if (!pDstData) + goto fail; + + (void)sprintf_s(pDstData, DstSize, + "Version:0.9\r\n" + "StartHTML:0000000000\r\n" + "EndHTML:0000000000\r\n" + "StartFragment:0000000000\r\n" + "EndFragment:0000000000\r\n"); + body = strstr(pSrcData.cpc, "", pDstData, DstSize, NULL)) + goto fail; + } + + if (!winpr_str_append("", pDstData, DstSize, NULL)) + goto fail; + + /* StartFragment */ + (void)sprintf_s(num, sizeof(num), "%010" PRIuz "", strnlen(pDstData, SrcSize + 200)); + CopyMemory(&pDstData[69], num, 10); + + if (!winpr_str_append(pSrcData.cpc, pDstData, DstSize, NULL)) + goto fail; + + /* EndFragment */ + (void)sprintf_s(num, sizeof(num), "%010" PRIuz "", strnlen(pDstData, SrcSize + 200)); + CopyMemory(&pDstData[93], num, 10); + + if (!winpr_str_append("", pDstData, DstSize, NULL)) + goto fail; + + if (!body) + { + if (!winpr_str_append("", pDstData, DstSize, NULL)) + goto fail; + } + + /* EndHTML */ + (void)sprintf_s(num, sizeof(num), "%010" PRIuz "", strnlen(pDstData, DstSize)); + CopyMemory(&pDstData[43], num, 10); + *pSize = (UINT32)strnlen(pDstData, DstSize) + 1; + } +fail: + free(pSrcData.pv); + return pDstData; +} + +/** + * "text/html": + * + * HTML text format. + */ + +static void* clipboard_synthesize_text_html(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + char* pDstData = NULL; + + if (formatId == ClipboardGetFormatId(clipboard, "HTML Format")) + { + const char* str = (const char*)data; + const size_t SrcSize = *pSize; + const char* begStr = strstr(str, "StartHTML:"); + const char* endStr = strstr(str, "EndHTML:"); + + if (!begStr || !endStr) + return NULL; + + errno = 0; + const long beg = strtol(&begStr[10], NULL, 10); + + if (errno != 0) + return NULL; + + const long end = strtol(&endStr[8], NULL, 10); + + if ((beg < 0) || (end < 0) || ((size_t)beg > SrcSize) || ((size_t)end > SrcSize) || + (beg >= end) || (errno != 0)) + return NULL; + + const size_t DstSize = (size_t)(end - beg); + pDstData = calloc(DstSize + 1, sizeof(char)); + + if (!pDstData) + return NULL; + + CopyMemory(pDstData, &str[beg], DstSize); + const size_t rc = ConvertLineEndingToLF(pDstData, DstSize); + WINPR_ASSERT(rc <= UINT32_MAX); + *pSize = (UINT32)rc; + } + + return pDstData; +} + +BOOL ClipboardInitSynthesizers(wClipboard* clipboard) +{ + /** + * CF_TEXT + */ + { + ClipboardRegisterSynthesizer(clipboard, CF_TEXT, CF_OEMTEXT, + clipboard_synthesize_cf_oemtext); + ClipboardRegisterSynthesizer(clipboard, CF_TEXT, CF_UNICODETEXT, + clipboard_synthesize_cf_unicodetext); + ClipboardRegisterSynthesizer(clipboard, CF_TEXT, CF_LOCALE, clipboard_synthesize_cf_locale); + + UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_text_plain); + ClipboardRegisterSynthesizer(clipboard, CF_TEXT, altFormatId, + clipboard_synthesize_utf8_string); + } + /** + * CF_OEMTEXT + */ + { + ClipboardRegisterSynthesizer(clipboard, CF_OEMTEXT, CF_TEXT, clipboard_synthesize_cf_text); + ClipboardRegisterSynthesizer(clipboard, CF_OEMTEXT, CF_UNICODETEXT, + clipboard_synthesize_cf_unicodetext); + ClipboardRegisterSynthesizer(clipboard, CF_OEMTEXT, CF_LOCALE, + clipboard_synthesize_cf_locale); + UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_text_plain); + ClipboardRegisterSynthesizer(clipboard, CF_OEMTEXT, altFormatId, + clipboard_synthesize_utf8_string); + } + /** + * CF_UNICODETEXT + */ + { + ClipboardRegisterSynthesizer(clipboard, CF_UNICODETEXT, CF_TEXT, + clipboard_synthesize_cf_text); + ClipboardRegisterSynthesizer(clipboard, CF_UNICODETEXT, CF_OEMTEXT, + clipboard_synthesize_cf_oemtext); + ClipboardRegisterSynthesizer(clipboard, CF_UNICODETEXT, CF_LOCALE, + clipboard_synthesize_cf_locale); + UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_text_plain); + ClipboardRegisterSynthesizer(clipboard, CF_UNICODETEXT, altFormatId, + clipboard_synthesize_utf8_string); + } + /** + * UTF8_STRING + */ + { + UINT32 formatId = ClipboardRegisterFormat(clipboard, mime_text_plain); + + if (formatId) + { + ClipboardRegisterSynthesizer(clipboard, formatId, CF_TEXT, + clipboard_synthesize_cf_text); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_OEMTEXT, + clipboard_synthesize_cf_oemtext); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_UNICODETEXT, + clipboard_synthesize_cf_unicodetext); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_LOCALE, + clipboard_synthesize_cf_locale); + } + } + /** + * text/plain + */ + { + UINT32 formatId = ClipboardRegisterFormat(clipboard, mime_text_plain); + + if (formatId) + { + ClipboardRegisterSynthesizer(clipboard, formatId, CF_TEXT, + clipboard_synthesize_cf_text); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_OEMTEXT, + clipboard_synthesize_cf_oemtext); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_UNICODETEXT, + clipboard_synthesize_cf_unicodetext); + ClipboardRegisterSynthesizer(clipboard, formatId, CF_LOCALE, + clipboard_synthesize_cf_locale); + } + } + /** + * CF_DIB + */ + { + ClipboardRegisterSynthesizer(clipboard, CF_DIB, CF_DIBV5, clipboard_synthesize_cf_dibv5); + for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++) + { + const char* mime = mime_bitmap[x]; + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime); + if (altFormatId == 0) + continue; + ClipboardRegisterSynthesizer(clipboard, CF_DIB, altFormatId, + clipboard_synthesize_image_bmp); + } + } + + /** + * CF_DIBV5 + */ + + if (0) + { + ClipboardRegisterSynthesizer(clipboard, CF_DIBV5, CF_DIB, clipboard_synthesize_cf_dib); + + for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++) + { + const char* mime = mime_bitmap[x]; + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime); + if (altFormatId == 0) + continue; + ClipboardRegisterSynthesizer(clipboard, CF_DIBV5, altFormatId, + clipboard_synthesize_image_bmp); + } + } + + /** + * image/bmp + */ + for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++) + { + const char* mime = mime_bitmap[x]; + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime); + if (altFormatId == 0) + continue; + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIB, clipboard_synthesize_cf_dib); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIBV5, + clipboard_synthesize_cf_dibv5); + } + + /** + * image/png + */ +#if defined(WINPR_UTILS_IMAGE_PNG) + { + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_png); + ClipboardRegisterSynthesizer(clipboard, CF_DIB, altFormatId, + clipboard_synthesize_image_bmp_to_png); + ClipboardRegisterSynthesizer(clipboard, CF_DIBV5, altFormatId, + clipboard_synthesize_image_bmp_to_png); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIB, + clipboard_synthesize_image_png_to_bmp); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIBV5, + clipboard_synthesize_image_png_to_bmp); + } +#endif + + /** + * image/webp + */ +#if defined(WINPR_UTILS_IMAGE_WEBP) + { + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_webp); + ClipboardRegisterSynthesizer(clipboard, CF_DIB, altFormatId, + clipboard_synthesize_image_bmp_to_webp); + ClipboardRegisterSynthesizer(clipboard, CF_DIBV5, altFormatId, + clipboard_synthesize_image_webp_to_bmp); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIB, + clipboard_synthesize_image_bmp_to_webp); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIBV5, + clipboard_synthesize_image_webp_to_bmp); + } +#endif + + /** + * image/jpeg + */ +#if defined(WINPR_UTILS_IMAGE_JPEG) + { + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, mime_jpeg); + ClipboardRegisterSynthesizer(clipboard, CF_DIB, altFormatId, + clipboard_synthesize_image_bmp_to_jpeg); + ClipboardRegisterSynthesizer(clipboard, CF_DIBV5, altFormatId, + clipboard_synthesize_image_jpeg_to_bmp); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIB, + clipboard_synthesize_image_bmp_to_jpeg); + ClipboardRegisterSynthesizer(clipboard, altFormatId, CF_DIBV5, + clipboard_synthesize_image_jpeg_to_bmp); + } +#endif + + /** + * HTML Format + */ + { + UINT32 formatId = ClipboardRegisterFormat(clipboard, "HTML Format"); + + if (formatId) + { + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, "text/html"); + ClipboardRegisterSynthesizer(clipboard, formatId, altFormatId, + clipboard_synthesize_text_html); + } + } + + /** + * text/html + */ + { + UINT32 formatId = ClipboardRegisterFormat(clipboard, "text/html"); + + if (formatId) + { + const UINT32 altFormatId = ClipboardRegisterFormat(clipboard, "HTML Format"); + ClipboardRegisterSynthesizer(clipboard, formatId, altFormatId, + clipboard_synthesize_html_format); + } + } + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.c new file mode 100644 index 0000000000000000000000000000000000000000..915a126a2b83d12a07319f973a2645d9b7cd880e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.c @@ -0,0 +1,1267 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions: POSIX file handling + * + * Copyright 2017 Alexei Lozovsky + * + * 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 +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO +WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO + +#define _FILE_OFFSET_BITS 64 // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +WINPR_PRAGMA_DIAG_POP + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "clipboard.h" +#include "synthetic_file.h" + +#include "../log.h" +#define TAG WINPR_TAG("clipboard.synthetic.file") + +static const char* mime_uri_list = "text/uri-list"; +static const char* mime_FileGroupDescriptorW = "FileGroupDescriptorW"; +static const char* mime_gnome_copied_files = "x-special/gnome-copied-files"; +static const char* mime_mate_copied_files = "x-special/mate-copied-files"; + +struct synthetic_file +{ + WCHAR* local_name; + WCHAR* remote_name; + + HANDLE fd; + INT64 offset; + + DWORD dwFileAttributes; + FILETIME ftCreationTime; + FILETIME ftLastAccessTime; + FILETIME ftLastWriteTime; + DWORD nFileSizeHigh; + DWORD nFileSizeLow; +}; + +void free_synthetic_file(struct synthetic_file* file); + +static struct synthetic_file* make_synthetic_file(const WCHAR* local_name, const WCHAR* remote_name) +{ + struct synthetic_file* file = NULL; + WIN32_FIND_DATAW fd = { 0 }; + HANDLE hFind = NULL; + + WINPR_ASSERT(local_name); + WINPR_ASSERT(remote_name); + + hFind = FindFirstFileW(local_name, &fd); + if (INVALID_HANDLE_VALUE == hFind) + { + WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError()); + return NULL; + } + FindClose(hFind); + + file = calloc(1, sizeof(*file)); + if (!file) + return NULL; + + file->fd = INVALID_HANDLE_VALUE; + file->offset = 0; + file->local_name = _wcsdup(local_name); + if (!file->local_name) + goto fail; + + file->remote_name = _wcsdup(remote_name); + if (!file->remote_name) + goto fail; + + const size_t len = _wcslen(file->remote_name); + PathCchConvertStyleW(file->remote_name, len, PATH_STYLE_WINDOWS); + + file->dwFileAttributes = fd.dwFileAttributes; + file->ftCreationTime = fd.ftCreationTime; + file->ftLastWriteTime = fd.ftLastWriteTime; + file->ftLastAccessTime = fd.ftLastAccessTime; + file->nFileSizeHigh = fd.nFileSizeHigh; + file->nFileSizeLow = fd.nFileSizeLow; + + return file; +fail: + free_synthetic_file(file); + return NULL; +} + +static UINT synthetic_file_read_close(struct synthetic_file* file, BOOL force); + +void free_synthetic_file(struct synthetic_file* file) +{ + if (!file) + return; + + synthetic_file_read_close(file, TRUE); + + free(file->local_name); + free(file->remote_name); + free(file); +} + +/* + * Note that the function converts a single file name component, + * it does not take care of component separators. + */ +static WCHAR* convert_local_name_component_to_remote(wClipboard* clipboard, const WCHAR* local_name) +{ + wClipboardDelegate* delegate = ClipboardGetDelegate(clipboard); + WCHAR* remote_name = NULL; + + WINPR_ASSERT(delegate); + + remote_name = _wcsdup(local_name); + + /* + * Some file names are not valid on Windows. Check for these now + * so that we won't get ourselves into a trouble later as such names + * are known to crash some Windows shells when pasted via clipboard. + * + * The IsFileNameComponentValid callback can be overridden by the API + * user, if it is known, that the connected peer is not on the + * Windows platform. + */ + if (!delegate->IsFileNameComponentValid(remote_name)) + { + WLog_ERR(TAG, "invalid file name component: %s", local_name); + goto error; + } + + return remote_name; +error: + free(remote_name); + return NULL; +} + +static WCHAR* concat_file_name(const WCHAR* dir, const WCHAR* file) +{ + size_t len_dir = 0; + size_t len_file = 0; + const WCHAR slash = '/'; + WCHAR* buffer = NULL; + + WINPR_ASSERT(dir); + WINPR_ASSERT(file); + + len_dir = _wcslen(dir); + len_file = _wcslen(file); + buffer = calloc(len_dir + 1 + len_file + 2, sizeof(WCHAR)); + + if (!buffer) + return NULL; + + memcpy(buffer, dir, len_dir * sizeof(WCHAR)); + buffer[len_dir] = slash; + memcpy(buffer + len_dir + 1, file, len_file * sizeof(WCHAR)); + return buffer; +} + +static BOOL add_file_to_list(wClipboard* clipboard, const WCHAR* local_name, + const WCHAR* remote_name, wArrayList* files); + +static BOOL add_directory_entry_to_list(wClipboard* clipboard, const WCHAR* local_dir_name, + const WCHAR* remote_dir_name, + const LPWIN32_FIND_DATAW pFileData, wArrayList* files) +{ + BOOL result = FALSE; + WCHAR* local_name = NULL; + WCHAR* remote_name = NULL; + WCHAR* remote_base_name = NULL; + + WCHAR dotbuffer[6] = { 0 }; + WCHAR dotdotbuffer[6] = { 0 }; + const WCHAR* dot = InitializeConstWCharFromUtf8(".", dotbuffer, ARRAYSIZE(dotbuffer)); + const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer)); + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(local_dir_name); + WINPR_ASSERT(remote_dir_name); + WINPR_ASSERT(pFileData); + WINPR_ASSERT(files); + + /* Skip special directory entries. */ + + if ((_wcscmp(pFileData->cFileName, dot) == 0) || (_wcscmp(pFileData->cFileName, dotdot) == 0)) + return TRUE; + + remote_base_name = convert_local_name_component_to_remote(clipboard, pFileData->cFileName); + + if (!remote_base_name) + return FALSE; + + local_name = concat_file_name(local_dir_name, pFileData->cFileName); + remote_name = concat_file_name(remote_dir_name, remote_base_name); + + if (local_name && remote_name) + result = add_file_to_list(clipboard, local_name, remote_name, files); + + free(remote_base_name); + free(remote_name); + free(local_name); + return result; +} + +static BOOL do_add_directory_contents_to_list(wClipboard* clipboard, const WCHAR* local_name, + const WCHAR* remote_name, WCHAR* namebuf, + wArrayList* files) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(local_name); + WINPR_ASSERT(remote_name); + WINPR_ASSERT(files); + WINPR_ASSERT(namebuf); + + WIN32_FIND_DATAW FindData = { 0 }; + HANDLE hFind = FindFirstFileW(namebuf, &FindData); + if (INVALID_HANDLE_VALUE == hFind) + { + WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError()); + return FALSE; + } + while (TRUE) + { + if (!add_directory_entry_to_list(clipboard, local_name, remote_name, &FindData, files)) + { + FindClose(hFind); + return FALSE; + } + + BOOL bRet = FindNextFileW(hFind, &FindData); + if (!bRet) + { + FindClose(hFind); + if (ERROR_NO_MORE_FILES == GetLastError()) + return TRUE; + WLog_WARN(TAG, "FindNextFile failed (%" PRIu32 ")", GetLastError()); + return FALSE; + } + } + + return TRUE; +} + +static BOOL add_directory_contents_to_list(wClipboard* clipboard, const WCHAR* local_name, + const WCHAR* remote_name, wArrayList* files) +{ + BOOL result = FALSE; + union + { + const char* c; + const WCHAR* w; + } wildcard; + const char buffer[6] = "/\0*\0\0\0"; + wildcard.c = buffer; + const size_t wildcardLen = ARRAYSIZE(buffer) / sizeof(WCHAR); + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(local_name); + WINPR_ASSERT(remote_name); + WINPR_ASSERT(files); + + size_t len = _wcslen(local_name); + WCHAR* namebuf = calloc(len + wildcardLen, sizeof(WCHAR)); + if (!namebuf) + return FALSE; + + _wcsncat(namebuf, local_name, len); + _wcsncat(namebuf, wildcard.w, wildcardLen); + + result = do_add_directory_contents_to_list(clipboard, local_name, remote_name, namebuf, files); + + free(namebuf); + return result; +} + +static BOOL add_file_to_list(wClipboard* clipboard, const WCHAR* local_name, + const WCHAR* remote_name, wArrayList* files) +{ + struct synthetic_file* file = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(local_name); + WINPR_ASSERT(remote_name); + WINPR_ASSERT(files); + + file = make_synthetic_file(local_name, remote_name); + + if (!file) + return FALSE; + + if (!ArrayList_Append(files, file)) + { + free_synthetic_file(file); + return FALSE; + } + + if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + /* + * This is effectively a recursive call, but we do not track + * recursion depth, thus filesystem loops can cause a crash. + */ + if (!add_directory_contents_to_list(clipboard, local_name, remote_name, files)) + return FALSE; + } + + return TRUE; +} + +static const WCHAR* get_basename(const WCHAR* name) +{ + const WCHAR* c = name; + const WCHAR* last_name = name; + const WCHAR slash = '/'; + + WINPR_ASSERT(name); + + while (*c++) + { + if (*c == slash) + last_name = c + 1; + } + + return last_name; +} + +static BOOL process_file_name(wClipboard* clipboard, const WCHAR* local_name, wArrayList* files) +{ + BOOL result = FALSE; + const WCHAR* base_name = NULL; + WCHAR* remote_name = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(local_name); + WINPR_ASSERT(files); + + /* + * Start with the base name of the file. text/uri-list contains the + * exact files selected by the user, and we want the remote files + * to have names relative to that selection. + */ + base_name = get_basename(local_name); + remote_name = convert_local_name_component_to_remote(clipboard, base_name); + + if (!remote_name) + return FALSE; + + result = add_file_to_list(clipboard, local_name, remote_name, files); + free(remote_name); + return result; +} + +static BOOL process_uri(wClipboard* clipboard, const char* uri, size_t uri_len) +{ + // URI is specified by RFC 8089: https://datatracker.ietf.org/doc/html/rfc8089 + BOOL result = FALSE; + char* name = NULL; + + WINPR_ASSERT(clipboard); + + name = parse_uri_to_local_file(uri, uri_len); + if (name) + { + WCHAR* wname = NULL; + /* + * Note that local file names are not actually guaranteed to be + * encoded in UTF-8. Filesystems and users can use whatever they + * want. The OS does not care, aside from special treatment of + * '\0' and '/' bytes. But we need to make some decision here. + * Assuming UTF-8 is currently the most sane thing. + */ + wname = ConvertUtf8ToWCharAlloc(name, NULL); + if (wname) + result = process_file_name(clipboard, wname, clipboard->localFiles); + + free(name); + free(wname); + } + + return result; +} + +static BOOL process_uri_list(wClipboard* clipboard, const char* data, size_t length) +{ + const char* cur = data; + const char* lim = data + length; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(data); + + WLog_VRB(TAG, "processing URI list:\n%.*s", length, data); + ArrayList_Clear(clipboard->localFiles); + + /* + * The "text/uri-list" Internet Media Type is specified by RFC 2483. + * + * While the RFCs 2046 and 2483 require the lines of text/... formats + * to be terminated by CRLF sequence, be prepared for those who don't + * read the spec, use plain LFs, and don't leave the trailing CRLF. + */ + + while (cur < lim) + { + BOOL comment = (*cur == '#'); + const char* start = cur; + const char* stop = cur; + + for (; stop < lim; stop++) + { + if (*stop == '\r') + { + if ((stop + 1 < lim) && (*(stop + 1) == '\n')) + cur = stop + 2; + else + cur = stop + 1; + + break; + } + + if (*stop == '\n') + { + cur = stop + 1; + break; + } + } + + if (stop == lim) + { + if (strnlen(start, WINPR_ASSERTING_INT_CAST(size_t, stop - start)) < 1) + return TRUE; + cur = lim; + } + + if (comment) + continue; + + if (!process_uri(clipboard, start, WINPR_ASSERTING_INT_CAST(size_t, stop - start))) + return FALSE; + } + + return TRUE; +} + +static BOOL convert_local_file_to_filedescriptor(const struct synthetic_file* file, + FILEDESCRIPTORW* descriptor) +{ + size_t remote_len = 0; + + WINPR_ASSERT(file); + WINPR_ASSERT(descriptor); + + descriptor->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI; + + if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + descriptor->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY; + descriptor->nFileSizeLow = 0; + descriptor->nFileSizeHigh = 0; + } + else + { + descriptor->dwFileAttributes = FILE_ATTRIBUTE_NORMAL; + descriptor->nFileSizeLow = file->nFileSizeLow; + descriptor->nFileSizeHigh = file->nFileSizeHigh; + } + + descriptor->ftLastWriteTime = file->ftLastWriteTime; + + remote_len = _wcsnlen(file->remote_name, ARRAYSIZE(descriptor->cFileName)); + + if (remote_len >= ARRAYSIZE(descriptor->cFileName)) + { + WLog_ERR(TAG, "file name too long (%" PRIuz " characters)", remote_len); + return FALSE; + } + + memcpy(descriptor->cFileName, file->remote_name, remote_len * sizeof(WCHAR)); + return TRUE; +} + +static FILEDESCRIPTORW* convert_local_file_list_to_filedescriptors(wArrayList* files) +{ + size_t count = 0; + FILEDESCRIPTORW* descriptors = NULL; + + count = ArrayList_Count(files); + + descriptors = calloc(count, sizeof(FILEDESCRIPTORW)); + + if (!descriptors) + goto error; + + for (size_t i = 0; i < count; i++) + { + const struct synthetic_file* file = ArrayList_GetItem(files, i); + + if (!convert_local_file_to_filedescriptor(file, &descriptors[i])) + goto error; + } + + return descriptors; +error: + free(descriptors); + return NULL; +} + +static void* convert_any_uri_list_to_filedescriptors(wClipboard* clipboard, UINT32 formatId, + UINT32* pSize) +{ + FILEDESCRIPTORW* descriptors = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(pSize); + + descriptors = convert_local_file_list_to_filedescriptors(clipboard->localFiles); + *pSize = 0; + if (!descriptors) + return NULL; + + *pSize = (UINT32)ArrayList_Count(clipboard->localFiles) * sizeof(FILEDESCRIPTORW); + clipboard->fileListSequenceNumber = clipboard->sequenceNumber; + return descriptors; +} + +static void* convert_uri_list_to_filedescriptors(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + const UINT32 expected = ClipboardGetFormatId(clipboard, mime_uri_list); + if (formatId != expected) + return NULL; + if (!process_uri_list(clipboard, (const char*)data, *pSize)) + return NULL; + return convert_any_uri_list_to_filedescriptors(clipboard, formatId, pSize); +} + +static BOOL process_files(wClipboard* clipboard, const char* data, UINT32 pSize, const char* prefix) +{ + WINPR_ASSERT(prefix); + + const size_t prefix_len = strlen(prefix); + + WINPR_ASSERT(clipboard); + + ArrayList_Clear(clipboard->localFiles); + + if (!data || (pSize < prefix_len)) + return FALSE; + if (strncmp(data, prefix, prefix_len) != 0) + return FALSE; + data += prefix_len; + pSize -= prefix_len; + + BOOL rc = FALSE; + char* copy = strndup(data, pSize); + if (!copy) + goto fail; + + char* endptr = NULL; + char* tok = strtok_s(copy, "\n", &endptr); + while (tok) + { + size_t tok_len = strnlen(tok, pSize); + if (!process_uri(clipboard, tok, tok_len)) + goto fail; + pSize -= tok_len; + tok = strtok_s(NULL, "\n", &endptr); + } + rc = TRUE; + +fail: + free(copy); + return rc; +} + +static BOOL process_gnome_copied_files(wClipboard* clipboard, const char* data, UINT32 pSize) +{ + return process_files(clipboard, data, pSize, "copy\n"); +} + +static BOOL process_mate_copied_files(wClipboard* clipboard, const char* data, UINT32 pSize) +{ + return process_files(clipboard, data, pSize, "copy\n"); +} + +static BOOL process_nautilus_clipboard(wClipboard* clipboard, const char* data, UINT32 pSize) +{ + return process_files(clipboard, data, pSize, "x-special/nautilus-clipboard\ncopy\n"); +} + +static void* convert_nautilus_clipboard_to_filedescriptors(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + const UINT32 expected = ClipboardGetFormatId(clipboard, mime_gnome_copied_files); + if (formatId != expected) + return NULL; + if (!process_nautilus_clipboard(clipboard, (const char*)data, *pSize)) + return NULL; + return convert_any_uri_list_to_filedescriptors(clipboard, formatId, pSize); +} + +static void* convert_gnome_copied_files_to_filedescriptors(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + const UINT32 expected = ClipboardGetFormatId(clipboard, mime_gnome_copied_files); + if (formatId != expected) + return NULL; + if (!process_gnome_copied_files(clipboard, (const char*)data, *pSize)) + return NULL; + return convert_any_uri_list_to_filedescriptors(clipboard, formatId, pSize); +} + +static void* convert_mate_copied_files_to_filedescriptors(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + const UINT32 expected = ClipboardGetFormatId(clipboard, mime_mate_copied_files); + if (formatId != expected) + return NULL; + + if (!process_mate_copied_files(clipboard, (const char*)data, *pSize)) + return NULL; + + return convert_any_uri_list_to_filedescriptors(clipboard, formatId, pSize); +} + +static size_t count_special_chars(const WCHAR* str) +{ + size_t count = 0; + const WCHAR* start = str; + + WINPR_ASSERT(str); + while (*start) + { + const WCHAR sharp = '#'; + const WCHAR questionmark = '?'; + const WCHAR star = '*'; + const WCHAR exclamationmark = '!'; + const WCHAR percent = '%'; + + if ((*start == sharp) || (*start == questionmark) || (*start == star) || + (*start == exclamationmark) || (*start == percent)) + { + count++; + } + start++; + } + return count; +} + +static const char* stop_at_special_chars(const char* str) +{ + const char* start = str; + WINPR_ASSERT(str); + + while (*start) + { + if (*start == '#' || *start == '?' || *start == '*' || *start == '!' || *start == '%') + { + return start; + } + start++; + } + return NULL; +} + +/* The universal converter from filedescriptors to different file lists */ +static void* convert_filedescriptors_to_file_list(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize, + const char* header, const char* lineprefix, + const char* lineending, BOOL skip_last_lineending) +{ + union + { + char c[2]; + WCHAR w; + } backslash; + backslash.c[0] = '\\'; + backslash.c[1] = '\0'; + + const FILEDESCRIPTORW* descriptors = NULL; + UINT32 nrDescriptors = 0; + size_t count = 0; + size_t alloc = 0; + size_t pos = 0; + size_t baseLength = 0; + char* dst = NULL; + size_t header_len = strlen(header); + size_t lineprefix_len = strlen(lineprefix); + size_t lineending_len = strlen(lineending); + size_t decoration_len = 0; + + if (!clipboard || !data || !pSize) + return NULL; + + if (*pSize < sizeof(UINT32)) + return NULL; + + if (clipboard->delegate.basePath) + baseLength = strnlen(clipboard->delegate.basePath, MAX_PATH); + + if (baseLength < 1) + return NULL; + + wStream sbuffer = { 0 }; + wStream* s = Stream_StaticConstInit(&sbuffer, data, *pSize); + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return NULL; + + Stream_Read_UINT32(s, nrDescriptors); + + count = (*pSize - 4) / sizeof(FILEDESCRIPTORW); + + if ((count < 1) || (count != nrDescriptors)) + return NULL; + + descriptors = Stream_ConstPointer(s); + + if (formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW)) + return NULL; + + /* Plus 1 for '/' between basepath and filename*/ + decoration_len = lineprefix_len + lineending_len + baseLength + 1; + alloc = header_len; + + /* Get total size of file/folder names under first level folder only */ + for (size_t x = 0; x < count; x++) + { + const FILEDESCRIPTORW* dsc = &descriptors[x]; + + if (_wcschr(dsc->cFileName, backslash.w) == NULL) + { + alloc += ARRAYSIZE(dsc->cFileName) * + 8; /* Overallocate, just take the biggest value the result path can have */ + /* # (1 char) -> %23 (3 chars) , the first char is replaced inplace */ + alloc += count_special_chars(dsc->cFileName) * 2; + alloc += decoration_len; + } + } + + /* Append a prefix file:// and postfix \n for each file */ + /* We need to keep last \n since snprintf is null terminated!! */ + alloc++; + dst = calloc(alloc, sizeof(char)); + + if (!dst) + return NULL; + + (void)_snprintf(&dst[0], alloc, "%s", header); + + pos = header_len; + + for (size_t x = 0; x < count; x++) + { + const FILEDESCRIPTORW* dsc = &descriptors[x]; + BOOL fail = TRUE; + if (_wcschr(dsc->cFileName, backslash.w) != NULL) + { + continue; + } + int rc = -1; + char curName[520] = { 0 }; + const char* stop_at = NULL; + const char* previous_at = NULL; + + if (ConvertWCharNToUtf8(dsc->cFileName, ARRAYSIZE(dsc->cFileName), curName, + ARRAYSIZE(curName)) < 0) + goto loop_fail; + + rc = _snprintf(&dst[pos], alloc - pos, "%s%s/", lineprefix, clipboard->delegate.basePath); + + if (rc < 0) + goto loop_fail; + + pos += (size_t)rc; + + previous_at = curName; + while ((stop_at = stop_at_special_chars(previous_at)) != NULL) + { + char* tmp = + strndup(previous_at, WINPR_ASSERTING_INT_CAST(size_t, stop_at - previous_at)); + if (!tmp) + goto loop_fail; + + rc = _snprintf(&dst[pos], WINPR_ASSERTING_INT_CAST(size_t, stop_at - previous_at + 1), + "%s", tmp); + free(tmp); + if (rc < 0) + goto loop_fail; + + pos += (size_t)rc; + rc = _snprintf(&dst[pos], 4, "%%%x", *stop_at); + if (rc < 0) + goto loop_fail; + + pos += (size_t)rc; + previous_at = stop_at + 1; + } + + rc = _snprintf(&dst[pos], alloc - pos, "%s%s", previous_at, lineending); + + fail = FALSE; + loop_fail: + if ((rc < 0) || fail) + { + free(dst); + return NULL; + } + + pos += (size_t)rc; + } + + if (skip_last_lineending) + { + const size_t endlen = strlen(lineending); + if (alloc > endlen) + { + const size_t len = strnlen(dst, alloc); + if (len < endlen) + { + free(dst); + return NULL; + } + + if (memcmp(&dst[len - endlen], lineending, endlen) == 0) + { + memset(&dst[len - endlen], 0, endlen); + alloc -= endlen; + } + } + } + + alloc = strnlen(dst, alloc) + 1; + *pSize = (UINT32)alloc; + clipboard->fileListSequenceNumber = clipboard->sequenceNumber; + return dst; +} + +/* Prepend header of kde dolphin format to file list + * See: + * GTK: https://docs.gtk.org/glib/struct.Uri.html + * uri syntax: https://www.rfc-editor.org/rfc/rfc3986#section-3 + * uri-lists format: https://www.rfc-editor.org/rfc/rfc2483#section-5 + */ +static void* convert_filedescriptors_to_uri_list(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return convert_filedescriptors_to_file_list(clipboard, formatId, data, pSize, "", "file://", + "\r\n", FALSE); +} + +/* Prepend header of common gnome format to file list*/ +static void* convert_filedescriptors_to_gnome_copied_files(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + return convert_filedescriptors_to_file_list(clipboard, formatId, data, pSize, "copy\n", + "file://", "\n", TRUE); +} + +/* Prepend header of nautilus based filemanager's format to file list*/ +static void* convert_filedescriptors_to_nautilus_clipboard(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + /* Here Nemo (and Caja) have different behavior. They encounter error with the last \n . but + nautilus needs it. So user have to skip Nemo's error dialog to continue. Caja has different + TARGET , so it's easy to fix. see convert_filedescriptors_to_mate_copied_files + + The text based "x-special/nautilus-clipboard" type was introduced with GNOME 3.30 and + was necessary for the desktop icons extension, as gnome-shell at that time only + supported text based mime types for gnome extensions. With GNOME 3.38, gnome-shell got + support for non-text based mime types for gnome extensions. With GNOME 40, nautilus reverted + the mime type change to "x-special/gnome-copied-files" and removed support for the text based + mime type. So, in the near future, change this behaviour in favor for Nemo and Caja. + */ + /* see nautilus/src/nautilus-clipboard.c:convert_selection_data_to_str_list + see nemo/libnemo-private/nemo-clipboard.c:nemo_clipboard_get_uri_list_from_selection_data + */ + + return convert_filedescriptors_to_file_list(clipboard, formatId, data, pSize, + "x-special/nautilus-clipboard\ncopy\n", "file://", + "\n", FALSE); +} + +static void* convert_filedescriptors_to_mate_copied_files(wClipboard* clipboard, UINT32 formatId, + const void* data, UINT32* pSize) +{ + + char* pDstData = convert_filedescriptors_to_file_list(clipboard, formatId, data, pSize, + "copy\n", "file://", "\n", TRUE); + if (!pDstData) + { + return pDstData; + } + /* Replace last \n with \0 + see + mate-desktop/caja/libcaja-private/caja-clipboard.c:caja_clipboard_get_uri_list_from_selection_data + */ + + pDstData[*pSize - 1] = '\0'; + *pSize = *pSize - 1; + return pDstData; +} + +static void array_free_synthetic_file(void* the_file) +{ + struct synthetic_file* file = the_file; + free_synthetic_file(file); +} + +static BOOL register_file_formats_and_synthesizers(wClipboard* clipboard) +{ + wObject* obj = NULL; + + /* + 1. Gnome Nautilus based file manager (Nautilus only with version >= 3.30 AND < 40): + TARGET: UTF8_STRING + format: x-special/nautilus-clipboard\copy\n\file://path\n\0 + 2. Kde Dolpin and Qt: + TARGET: text/uri-list + format: file:path\r\n\0 + See: + GTK: https://docs.gtk.org/glib/struct.Uri.html + uri syntax: https://www.rfc-editor.org/rfc/rfc3986#section-3 + uri-lists format: https://www.rfc-editor.org/rfc/rfc2483#section-5 + 3. Gnome and others (Unity/XFCE/Nautilus < 3.30/Nautilus >= 40): + TARGET: x-special/gnome-copied-files + format: copy\nfile://path\n\0 + 4. Mate Caja: + TARGET: x-special/mate-copied-files + format: copy\nfile://path\n + + TODO: other file managers do not use previous targets and formats. + */ + + const UINT32 local_gnome_file_format_id = + ClipboardRegisterFormat(clipboard, mime_gnome_copied_files); + const UINT32 local_mate_file_format_id = + ClipboardRegisterFormat(clipboard, mime_mate_copied_files); + const UINT32 file_group_format_id = + ClipboardRegisterFormat(clipboard, mime_FileGroupDescriptorW); + const UINT32 local_file_format_id = ClipboardRegisterFormat(clipboard, mime_uri_list); + + if (!file_group_format_id || !local_file_format_id || !local_gnome_file_format_id || + !local_mate_file_format_id) + goto error; + + clipboard->localFiles = ArrayList_New(FALSE); + + if (!clipboard->localFiles) + goto error; + + obj = ArrayList_Object(clipboard->localFiles); + obj->fnObjectFree = array_free_synthetic_file; + + if (!ClipboardRegisterSynthesizer(clipboard, local_file_format_id, file_group_format_id, + convert_uri_list_to_filedescriptors)) + goto error_free_local_files; + + if (!ClipboardRegisterSynthesizer(clipboard, file_group_format_id, local_file_format_id, + convert_filedescriptors_to_uri_list)) + goto error_free_local_files; + + if (!ClipboardRegisterSynthesizer(clipboard, local_gnome_file_format_id, file_group_format_id, + convert_gnome_copied_files_to_filedescriptors)) + goto error_free_local_files; + + if (!ClipboardRegisterSynthesizer(clipboard, file_group_format_id, local_gnome_file_format_id, + convert_filedescriptors_to_gnome_copied_files)) + goto error_free_local_files; + + if (!ClipboardRegisterSynthesizer(clipboard, local_mate_file_format_id, file_group_format_id, + convert_mate_copied_files_to_filedescriptors)) + goto error_free_local_files; + + if (!ClipboardRegisterSynthesizer(clipboard, file_group_format_id, local_mate_file_format_id, + convert_filedescriptors_to_mate_copied_files)) + goto error_free_local_files; + + return TRUE; +error_free_local_files: + ArrayList_Free(clipboard->localFiles); + clipboard->localFiles = NULL; +error: + return FALSE; +} + +static int32_t file_get_size(const struct synthetic_file* file, UINT64* size) +{ + UINT64 s = 0; + + if (!file || !size) + return E_INVALIDARG; + + s = file->nFileSizeHigh; + s <<= 32; + s |= file->nFileSizeLow; + *size = s; + return NO_ERROR; +} + +static UINT delegate_file_request_size(wClipboardDelegate* delegate, + const wClipboardFileSizeRequest* request) +{ + UINT64 size = 0; + + if (!delegate || !delegate->clipboard || !request) + return ERROR_BAD_ARGUMENTS; + + if (delegate->clipboard->sequenceNumber != delegate->clipboard->fileListSequenceNumber) + return ERROR_INVALID_STATE; + + struct synthetic_file* file = + ArrayList_GetItem(delegate->clipboard->localFiles, request->listIndex); + + if (!file) + return ERROR_INDEX_ABSENT; + + const int32_t s = file_get_size(file, &size); + uint32_t error = 0; + if (error) + error = delegate->ClipboardFileSizeFailure(delegate, request, (UINT)s); + else + error = delegate->ClipboardFileSizeSuccess(delegate, request, size); + + if (error) + WLog_WARN(TAG, "failed to report file size result: 0x%08X", error); + + return NO_ERROR; +} + +UINT synthetic_file_read_close(struct synthetic_file* file, BOOL force) +{ + if (!file || INVALID_HANDLE_VALUE == file->fd) + return NO_ERROR; + + /* Always force close the file. Clipboard might open hundreds of files + * so avoid caching to prevent running out of available file descriptors */ + UINT64 size = 0; + file_get_size(file, &size); + if ((file->offset < 0) || ((UINT64)file->offset >= size) || force) + { + WLog_VRB(TAG, "close file %d", file->fd); + if (!CloseHandle(file->fd)) + { + WLog_WARN(TAG, "failed to close fd %d: %" PRIu32, file->fd, GetLastError()); + } + + file->fd = INVALID_HANDLE_VALUE; + } + + return NO_ERROR; +} + +static UINT file_get_range(struct synthetic_file* file, UINT64 offset, UINT32 size, + BYTE** actual_data, UINT32* actual_size) +{ + UINT error = NO_ERROR; + DWORD dwLow = 0; + DWORD dwHigh = 0; + + WINPR_ASSERT(file); + WINPR_ASSERT(actual_data); + WINPR_ASSERT(actual_size); + + if (INVALID_HANDLE_VALUE == file->fd) + { + BY_HANDLE_FILE_INFORMATION FileInfo = { 0 }; + + file->fd = CreateFileW(file->local_name, GENERIC_READ, 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (INVALID_HANDLE_VALUE == file->fd) + { + error = GetLastError(); + WLog_ERR(TAG, "failed to open file %s: 0x%08" PRIx32, file->local_name, error); + return error; + } + + if (!GetFileInformationByHandle(file->fd, &FileInfo)) + { + (void)CloseHandle(file->fd); + file->fd = INVALID_HANDLE_VALUE; + error = GetLastError(); + WLog_ERR(TAG, "Get file [%s] information fail: 0x%08" PRIx32, file->local_name, error); + return error; + } + + file->offset = 0; + file->nFileSizeHigh = FileInfo.nFileSizeHigh; + file->nFileSizeLow = FileInfo.nFileSizeLow; + + /* + { + UINT64 s = 0; + file_get_size(file, &s); + WLog_DBG(TAG, "open file %d -> %s", file->fd, file->local_name); + WLog_DBG(TAG, "file %d size: %" PRIu64 " bytes", file->fd, s); + } //*/ + } + + do + { + /* + * We should avoid seeking when possible as some filesystems (e.g., + * an FTP server mapped via FUSE) may not support seeking. We keep + * an accurate account of the current file offset and do not call + * lseek() if the client requests file content sequentially. + */ + if (offset > INT64_MAX) + { + WLog_ERR(TAG, "offset [%" PRIu64 "] > INT64_MAX", offset); + error = ERROR_SEEK; + break; + } + + if (file->offset != (INT64)offset) + { + WLog_DBG(TAG, "file %d force seeking to %" PRIu64 ", current %" PRIu64, file->fd, + offset, file->offset); + + dwHigh = offset >> 32; + dwLow = offset & 0xFFFFFFFF; + if (INVALID_SET_FILE_POINTER == SetFilePointer(file->fd, + WINPR_ASSERTING_INT_CAST(LONG, dwLow), + (PLONG)&dwHigh, FILE_BEGIN)) + { + error = GetLastError(); + break; + } + } + + BYTE* buffer = malloc(size); + if (!buffer) + { + error = ERROR_NOT_ENOUGH_MEMORY; + break; + } + if (!ReadFile(file->fd, buffer, size, (LPDWORD)actual_size, NULL)) + { + free(buffer); + error = GetLastError(); + break; + } + + *actual_data = buffer; + file->offset += *actual_size; + WLog_VRB(TAG, "file %d actual read %" PRIu32 " bytes (offset %" PRIu64 ")", file->fd, + *actual_size, file->offset); + } while (0); + + synthetic_file_read_close(file, TRUE /* (error != NO_ERROR) && (size > 0) */); + return error; +} + +static UINT delegate_file_request_range(wClipboardDelegate* delegate, + const wClipboardFileRangeRequest* request) +{ + UINT error = 0; + BYTE* data = NULL; + UINT32 size = 0; + UINT64 offset = 0; + struct synthetic_file* file = NULL; + + if (!delegate || !delegate->clipboard || !request) + return ERROR_BAD_ARGUMENTS; + + if (delegate->clipboard->sequenceNumber != delegate->clipboard->fileListSequenceNumber) + return ERROR_INVALID_STATE; + + file = ArrayList_GetItem(delegate->clipboard->localFiles, request->listIndex); + + if (!file) + return ERROR_INDEX_ABSENT; + + offset = (((UINT64)request->nPositionHigh) << 32) | ((UINT64)request->nPositionLow); + error = file_get_range(file, offset, request->cbRequested, &data, &size); + + if (error) + error = delegate->ClipboardFileRangeFailure(delegate, request, error); + else + error = delegate->ClipboardFileRangeSuccess(delegate, request, data, size); + + if (error) + WLog_WARN(TAG, "failed to report file range result: 0x%08X", error); + + free(data); + return NO_ERROR; +} + +static UINT dummy_file_size_success(wClipboardDelegate* delegate, + const wClipboardFileSizeRequest* request, UINT64 fileSize) +{ + return ERROR_NOT_SUPPORTED; +} + +static UINT dummy_file_size_failure(wClipboardDelegate* delegate, + const wClipboardFileSizeRequest* request, UINT errorCode) +{ + return ERROR_NOT_SUPPORTED; +} + +static UINT dummy_file_range_success(wClipboardDelegate* delegate, + const wClipboardFileRangeRequest* request, const BYTE* data, + UINT32 size) +{ + return ERROR_NOT_SUPPORTED; +} + +static UINT dummy_file_range_failure(wClipboardDelegate* delegate, + const wClipboardFileRangeRequest* request, UINT errorCode) +{ + return ERROR_NOT_SUPPORTED; +} + +static void setup_delegate(wClipboardDelegate* delegate) +{ + WINPR_ASSERT(delegate); + + delegate->ClientRequestFileSize = delegate_file_request_size; + delegate->ClipboardFileSizeSuccess = dummy_file_size_success; + delegate->ClipboardFileSizeFailure = dummy_file_size_failure; + delegate->ClientRequestFileRange = delegate_file_request_range; + delegate->ClipboardFileRangeSuccess = dummy_file_range_success; + delegate->ClipboardFileRangeFailure = dummy_file_range_failure; + delegate->IsFileNameComponentValid = ValidFileNameComponent; +} + +BOOL ClipboardInitSyntheticFileSubsystem(wClipboard* clipboard) +{ + if (!clipboard) + return FALSE; + + if (!register_file_formats_and_synthesizers(clipboard)) + return FALSE; + + setup_delegate(&clipboard->delegate); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.h new file mode 100644 index 0000000000000000000000000000000000000000..a92a5da292f06e9d61ec5a480013bbc1a87285a6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/synthetic_file.h @@ -0,0 +1,27 @@ +/** + * WinPR: Windows Portable Runtime + * Clipboard Functions: POSIX file handling + * + * Copyright 2017 Alexei Lozovsky + * + * 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 + +BOOL ClipboardInitSyntheticFileSubsystem(wClipboard* clipboard); + +#endif /* WINPR_CLIPBOARD_POSIX_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..963fc24311319177856f9a5d328bac6aa3e3bcf4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/CMakeLists.txt @@ -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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestClipboardFormats.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestClipboardFormats.c new file mode 100644 index 0000000000000000000000000000000000000000..cde602b4340c737cc892c9f70126948ebefbe332 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestClipboardFormats.c @@ -0,0 +1,227 @@ + +#include +#include +#include +#include + +int TestClipboardFormats(int argc, char* argv[]) +{ + int rc = -1; + UINT32 count = 0; + UINT32* pFormatIds = NULL; + const char* formatName = NULL; + wClipboard* clipboard = NULL; + 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 = NULL; + 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 = NULL; + + 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 = NULL; + WCHAR* pDstData = NULL; + DstSize = 0; + pDstData = (WCHAR*)ClipboardGetData(clipboard, CF_UNICODETEXT, &DstSize); + pSrcData = ConvertWCharNToUtf8Alloc(pDstData, DstSize / sizeof(WCHAR), NULL); + + (void)fprintf(stderr, "ClipboardGetData (synthetic): %s\n", pSrcData); + free(pDstData); + free(pSrcData); + } + + pFormatIds = NULL; + 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; + } + { + 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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestUri.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestUri.c new file mode 100644 index 0000000000000000000000000000000000000000..3f78f2e6fbf7088d10a724345129eed9e49344d9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/clipboard/test/TestUri.c @@ -0,0 +1,69 @@ + +#include +#include +#include +#include +#include +#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 NULL*/ + "file://root/a.txt", + NULL, + "file:a.txt", + NULL, + "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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5210587c604d10ec600504dacef577ff1e37f70f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/CMakeLists.txt @@ -0,0 +1,49 @@ +# WinPR: Windows Portable Runtime +# libwinpr-comm cmake build script +# +# Copyright 2014 Marc-Andre Moreau +# +# 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) + 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() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e7f57a7df2bc1070ebb5d8b9f4db3aac3ba810ad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/ModuleOptions.cmake @@ -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}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.c new file mode 100644 index 0000000000000000000000000000000000000000..f7115638e58b2fff8a619f8688db4e26720ff6f3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.c @@ -0,0 +1,1494 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 + +#include +#include +#include +#include +#include +#if defined(WINPR_HAVE_SYS_EVENTFD_H) +#include +#endif +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "comm_ioctl.h" + +#include "../log.h" +#define TAG WINPR_TAG("comm") + +/** + * Communication Resources: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363196/ + */ + +#include "comm.h" + +static wLog* sLog = NULL; + +struct comm_device +{ + LPTSTR name; + LPTSTR path; +}; + +typedef struct comm_device COMM_DEVICE; + +/* FIXME: get a clever data structure, see also io.h functions */ +/* _CommDevices is a NULL-terminated array with a maximum of COMM_DEVICE_MAX COMM_DEVICE */ +#define COMM_DEVICE_MAX 128 +static COMM_DEVICE** sCommDevices = NULL; +static CRITICAL_SECTION sCommDevicesLock = { 0 }; + +static pthread_once_t sCommInitialized = PTHREAD_ONCE_INIT; + +static const _SERIAL_IOCTL_NAME S_SERIAL_IOCTL_NAMES[] = { + { IOCTL_SERIAL_SET_BAUD_RATE, "IOCTL_SERIAL_SET_BAUD_RATE" }, + { IOCTL_SERIAL_GET_BAUD_RATE, "IOCTL_SERIAL_GET_BAUD_RATE" }, + { IOCTL_SERIAL_SET_LINE_CONTROL, "IOCTL_SERIAL_SET_LINE_CONTROL" }, + { IOCTL_SERIAL_GET_LINE_CONTROL, "IOCTL_SERIAL_GET_LINE_CONTROL" }, + { IOCTL_SERIAL_SET_TIMEOUTS, "IOCTL_SERIAL_SET_TIMEOUTS" }, + { IOCTL_SERIAL_GET_TIMEOUTS, "IOCTL_SERIAL_GET_TIMEOUTS" }, + { IOCTL_SERIAL_GET_CHARS, "IOCTL_SERIAL_GET_CHARS" }, + { IOCTL_SERIAL_SET_CHARS, "IOCTL_SERIAL_SET_CHARS" }, + { IOCTL_SERIAL_SET_DTR, "IOCTL_SERIAL_SET_DTR" }, + { IOCTL_SERIAL_CLR_DTR, "IOCTL_SERIAL_CLR_DTR" }, + { IOCTL_SERIAL_RESET_DEVICE, "IOCTL_SERIAL_RESET_DEVICE" }, + { IOCTL_SERIAL_SET_RTS, "IOCTL_SERIAL_SET_RTS" }, + { IOCTL_SERIAL_CLR_RTS, "IOCTL_SERIAL_CLR_RTS" }, + { IOCTL_SERIAL_SET_XOFF, "IOCTL_SERIAL_SET_XOFF" }, + { IOCTL_SERIAL_SET_XON, "IOCTL_SERIAL_SET_XON" }, + { IOCTL_SERIAL_SET_BREAK_ON, "IOCTL_SERIAL_SET_BREAK_ON" }, + { IOCTL_SERIAL_SET_BREAK_OFF, "IOCTL_SERIAL_SET_BREAK_OFF" }, + { IOCTL_SERIAL_SET_QUEUE_SIZE, "IOCTL_SERIAL_SET_QUEUE_SIZE" }, + { IOCTL_SERIAL_GET_WAIT_MASK, "IOCTL_SERIAL_GET_WAIT_MASK" }, + { IOCTL_SERIAL_SET_WAIT_MASK, "IOCTL_SERIAL_SET_WAIT_MASK" }, + { IOCTL_SERIAL_WAIT_ON_MASK, "IOCTL_SERIAL_WAIT_ON_MASK" }, + { IOCTL_SERIAL_IMMEDIATE_CHAR, "IOCTL_SERIAL_IMMEDIATE_CHAR" }, + { IOCTL_SERIAL_PURGE, "IOCTL_SERIAL_PURGE" }, + { IOCTL_SERIAL_GET_HANDFLOW, "IOCTL_SERIAL_GET_HANDFLOW" }, + { IOCTL_SERIAL_SET_HANDFLOW, "IOCTL_SERIAL_SET_HANDFLOW" }, + { IOCTL_SERIAL_GET_MODEMSTATUS, "IOCTL_SERIAL_GET_MODEMSTATUS" }, + { IOCTL_SERIAL_GET_DTRRTS, "IOCTL_SERIAL_GET_DTRRTS" }, + { IOCTL_SERIAL_GET_COMMSTATUS, "IOCTL_SERIAL_GET_COMMSTATUS" }, + { IOCTL_SERIAL_GET_PROPERTIES, "IOCTL_SERIAL_GET_PROPERTIES" }, + // {IOCTL_SERIAL_XOFF_COUNTER, "IOCTL_SERIAL_XOFF_COUNTER"}, + // {IOCTL_SERIAL_LSRMST_INSERT, "IOCTL_SERIAL_LSRMST_INSERT"}, + { IOCTL_SERIAL_CONFIG_SIZE, "IOCTL_SERIAL_CONFIG_SIZE" }, + // {IOCTL_SERIAL_GET_STATS, "IOCTL_SERIAL_GET_STATS"}, + // {IOCTL_SERIAL_CLEAR_STATS, "IOCTL_SERIAL_CLEAR_STATS"}, + // {IOCTL_SERIAL_GET_MODEM_CONTROL,"IOCTL_SERIAL_GET_MODEM_CONTROL"}, + // {IOCTL_SERIAL_SET_MODEM_CONTROL,"IOCTL_SERIAL_SET_MODEM_CONTROL"}, + // {IOCTL_SERIAL_SET_FIFO_CONTROL, "IOCTL_SERIAL_SET_FIFO_CONTROL"}, + + // {IOCTL_PAR_QUERY_INFORMATION, "IOCTL_PAR_QUERY_INFORMATION"}, + // {IOCTL_PAR_SET_INFORMATION, "IOCTL_PAR_SET_INFORMATION"}, + // {IOCTL_PAR_QUERY_DEVICE_ID, "IOCTL_PAR_QUERY_DEVICE_ID"}, + // {IOCTL_PAR_QUERY_DEVICE_ID_SIZE,"IOCTL_PAR_QUERY_DEVICE_ID_SIZE"}, + // {IOCTL_IEEE1284_GET_MODE, "IOCTL_IEEE1284_GET_MODE"}, + // {IOCTL_IEEE1284_NEGOTIATE, "IOCTL_IEEE1284_NEGOTIATE"}, + // {IOCTL_PAR_SET_WRITE_ADDRESS, "IOCTL_PAR_SET_WRITE_ADDRESS"}, + // {IOCTL_PAR_SET_READ_ADDRESS, "IOCTL_PAR_SET_READ_ADDRESS"}, + // {IOCTL_PAR_GET_DEVICE_CAPS, "IOCTL_PAR_GET_DEVICE_CAPS"}, + // {IOCTL_PAR_GET_DEFAULT_MODES, "IOCTL_PAR_GET_DEFAULT_MODES"}, + // {IOCTL_PAR_QUERY_RAW_DEVICE_ID, "IOCTL_PAR_QUERY_RAW_DEVICE_ID"}, + // {IOCTL_PAR_IS_PORT_FREE, "IOCTL_PAR_IS_PORT_FREE"}, + + { IOCTL_USBPRINT_GET_1284_ID, "IOCTL_USBPRINT_GET_1284_ID" } +}; +const char* _comm_serial_ioctl_name(ULONG number) +{ + for (size_t x = 0; x < ARRAYSIZE(S_SERIAL_IOCTL_NAMES); x++) + { + const _SERIAL_IOCTL_NAME* cur = &S_SERIAL_IOCTL_NAMES[x]; + if (cur->number == number) + return cur->name; + } + + return "(unknown ioctl name)"; +} + +static int CommGetFd(HANDLE handle) +{ + WINPR_COMM* comm = (WINPR_COMM*)handle; + + if (!CommIsHandled(handle)) + return -1; + + return comm->fd; +} + +const HANDLE_CREATOR* GetCommHandleCreator(void) +{ +#if defined(WINPR_HAVE_SERIAL_SUPPORT) + static const HANDLE_CREATOR sCommHandleCreator = { .IsHandled = IsCommDevice, + .CreateFileA = CommCreateFileA }; + return &sCommHandleCreator; +#else + return NULL; +#endif +} + +static void CommInit(void) +{ + /* NB: error management to be done outside of this function */ + WINPR_ASSERT(sLog == NULL); + WINPR_ASSERT(sCommDevices == NULL); + sCommDevices = (COMM_DEVICE**)calloc(COMM_DEVICE_MAX + 1, sizeof(COMM_DEVICE*)); + + if (!sCommDevices) + return; + + if (!InitializeCriticalSectionEx(&sCommDevicesLock, 0, 0)) + { + free((void*)sCommDevices); + sCommDevices = NULL; + return; + } + + sLog = WLog_Get(TAG); + WINPR_ASSERT(sLog != NULL); +} + +/** + * Returns TRUE when the comm module is correctly initialized, FALSE otherwise + * with ERROR_DLL_INIT_FAILED set as the last error. + */ +static BOOL CommInitialized(void) +{ + if (pthread_once(&sCommInitialized, CommInit) != 0) + { + SetLastError(ERROR_DLL_INIT_FAILED); + return FALSE; + } + + return TRUE; +} + +void CommLog_Print(DWORD level, ...) +{ + if (!CommInitialized()) + return; + + va_list ap = { 0 }; + va_start(ap, level); + WLog_PrintVA(sLog, level, ap); + va_end(ap); +} + +BOOL BuildCommDCBA(LPCSTR lpDef, LPDCB lpDCB) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL BuildCommDCBW(LPCWSTR lpDef, LPDCB lpDCB) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL BuildCommDCBAndTimeoutsA(LPCSTR lpDef, LPDCB lpDCB, LPCOMMTIMEOUTS lpCommTimeouts) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL BuildCommDCBAndTimeoutsW(LPCWSTR lpDef, LPDCB lpDCB, LPCOMMTIMEOUTS lpCommTimeouts) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CommConfigDialogA(LPCSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CommConfigDialogW(LPCWSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, LPDWORD lpdwSize) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hCommDev; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, DWORD dwSize) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hCommDev; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetCommMask(HANDLE hFile, PDWORD lpEvtMask) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetCommMask(HANDLE hFile, DWORD dwEvtMask) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetCommModemStatus(HANDLE hFile, PDWORD lpModemStat) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +/** + * ERRORS: + * ERROR_DLL_INIT_FAILED + * ERROR_INVALID_HANDLE + */ +BOOL GetCommProperties(HANDLE hFile, LPCOMMPROP lpCommProp) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_PROPERTIES, NULL, 0, lpCommProp, + sizeof(COMMPROP), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommProperties failure."); + return FALSE; + } + + return TRUE; +} + +/** + * + * + * ERRORS: + * ERROR_INVALID_HANDLE + * ERROR_INVALID_DATA + * ERROR_IO_DEVICE + * ERROR_OUTOFMEMORY + */ +BOOL GetCommState(HANDLE hFile, LPDCB lpDCB) +{ + DCB* lpLocalDcb = NULL; + struct termios currentState; + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + if (!lpDCB) + { + SetLastError(ERROR_INVALID_DATA); + return FALSE; + } + + if (lpDCB->DCBlength < sizeof(DCB)) + { + SetLastError(ERROR_INVALID_DATA); + return FALSE; + } + + if (tcgetattr(pComm->fd, ¤tState) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + lpLocalDcb = (DCB*)calloc(1, lpDCB->DCBlength); + + if (lpLocalDcb == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + + /* error_handle */ + lpLocalDcb->DCBlength = lpDCB->DCBlength; + SERIAL_BAUD_RATE baudRate; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_BAUD_RATE, NULL, 0, &baudRate, + sizeof(SERIAL_BAUD_RATE), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the baud rate."); + goto error_handle; + } + + lpLocalDcb->BaudRate = baudRate.BaudRate; + lpLocalDcb->fBinary = (currentState.c_cflag & ICANON) == 0; + + if (!lpLocalDcb->fBinary) + { + CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag."); + } + + lpLocalDcb->fParity = (currentState.c_iflag & INPCK) != 0; + SERIAL_HANDFLOW handflow; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_HANDFLOW, NULL, 0, &handflow, + sizeof(SERIAL_HANDFLOW), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the handflow settings."); + goto error_handle; + } + + lpLocalDcb->fOutxCtsFlow = (handflow.ControlHandShake & SERIAL_CTS_HANDSHAKE) != 0; + lpLocalDcb->fOutxDsrFlow = (handflow.ControlHandShake & SERIAL_DSR_HANDSHAKE) != 0; + + if (handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE) + { + lpLocalDcb->fDtrControl = DTR_CONTROL_HANDSHAKE; + } + else if (handflow.ControlHandShake & SERIAL_DTR_CONTROL) + { + lpLocalDcb->fDtrControl = DTR_CONTROL_ENABLE; + } + else + { + lpLocalDcb->fDtrControl = DTR_CONTROL_DISABLE; + } + + lpLocalDcb->fDsrSensitivity = (handflow.ControlHandShake & SERIAL_DSR_SENSITIVITY) != 0; + lpLocalDcb->fTXContinueOnXoff = (handflow.FlowReplace & SERIAL_XOFF_CONTINUE) != 0; + lpLocalDcb->fOutX = (handflow.FlowReplace & SERIAL_AUTO_TRANSMIT) != 0; + lpLocalDcb->fInX = (handflow.FlowReplace & SERIAL_AUTO_RECEIVE) != 0; + lpLocalDcb->fErrorChar = (handflow.FlowReplace & SERIAL_ERROR_CHAR) != 0; + lpLocalDcb->fNull = (handflow.FlowReplace & SERIAL_NULL_STRIPPING) != 0; + + if (handflow.FlowReplace & SERIAL_RTS_HANDSHAKE) + { + lpLocalDcb->fRtsControl = RTS_CONTROL_HANDSHAKE; + } + else if (handflow.FlowReplace & SERIAL_RTS_CONTROL) + { + lpLocalDcb->fRtsControl = RTS_CONTROL_ENABLE; + } + else + { + lpLocalDcb->fRtsControl = RTS_CONTROL_DISABLE; + } + + // FIXME: how to get the RTS_CONTROL_TOGGLE state? Does it match the UART 16750's Autoflow + // Control Enabled bit in its Modem Control Register (MCR) + lpLocalDcb->fAbortOnError = (handflow.ControlHandShake & SERIAL_ERROR_ABORT) != 0; + /* lpLocalDcb->fDummy2 not used */ + lpLocalDcb->wReserved = 0; /* must be zero */ + lpLocalDcb->XonLim = handflow.XonLimit; + lpLocalDcb->XoffLim = handflow.XoffLimit; + SERIAL_LINE_CONTROL lineControl = { 0 }; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_LINE_CONTROL, NULL, 0, &lineControl, + sizeof(SERIAL_LINE_CONTROL), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the control settings."); + goto error_handle; + } + + lpLocalDcb->ByteSize = lineControl.WordLength; + lpLocalDcb->Parity = lineControl.Parity; + lpLocalDcb->StopBits = lineControl.StopBits; + SERIAL_CHARS serialChars; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars, + sizeof(SERIAL_CHARS), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the serial chars."); + goto error_handle; + } + + lpLocalDcb->XonChar = serialChars.XonChar; + lpLocalDcb->XoffChar = serialChars.XoffChar; + lpLocalDcb->ErrorChar = serialChars.ErrorChar; + lpLocalDcb->EofChar = serialChars.EofChar; + lpLocalDcb->EvtChar = serialChars.EventChar; + memcpy(lpDCB, lpLocalDcb, lpDCB->DCBlength); + free(lpLocalDcb); + return TRUE; +error_handle: + free(lpLocalDcb); + return FALSE; +} + +/** + * @return TRUE on success, FALSE otherwise. + * + * As of today, SetCommState() can fail half-way with some settings + * applied and some others not. SetCommState() returns on the first + * failure met. FIXME: or is it correct? + * + * ERRORS: + * ERROR_INVALID_HANDLE + * ERROR_IO_DEVICE + */ +BOOL SetCommState(HANDLE hFile, LPDCB lpDCB) +{ + struct termios upcomingTermios = { 0 }; + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + /* FIXME: validate changes according GetCommProperties? */ + + if (!CommIsHandleValid(hFile)) + return FALSE; + + if (!lpDCB) + { + SetLastError(ERROR_INVALID_DATA); + return FALSE; + } + + /* NB: did the choice to call ioctls first when available and + then to setup upcomingTermios. Don't mix both stages. */ + /** ioctl calls stage **/ + SERIAL_BAUD_RATE baudRate; + baudRate.BaudRate = lpDCB->BaudRate; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_BAUD_RATE, &baudRate, sizeof(SERIAL_BAUD_RATE), + NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the baud rate."); + return FALSE; + } + + SERIAL_CHARS serialChars; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars, + sizeof(SERIAL_CHARS), &bytesReturned, + NULL)) /* as of today, required for BreakChar */ + { + CommLog_Print(WLOG_WARN, "SetCommState failure: could not get the initial serial chars."); + return FALSE; + } + + serialChars.XonChar = lpDCB->XonChar; + serialChars.XoffChar = lpDCB->XoffChar; + serialChars.ErrorChar = lpDCB->ErrorChar; + serialChars.EofChar = lpDCB->EofChar; + serialChars.EventChar = lpDCB->EvtChar; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_CHARS, &serialChars, sizeof(SERIAL_CHARS), + NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the serial chars."); + return FALSE; + } + + SERIAL_LINE_CONTROL lineControl; + lineControl.StopBits = lpDCB->StopBits; + lineControl.Parity = lpDCB->Parity; + lineControl.WordLength = lpDCB->ByteSize; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_LINE_CONTROL, &lineControl, + sizeof(SERIAL_LINE_CONTROL), NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the control settings."); + return FALSE; + } + + SERIAL_HANDFLOW handflow = { 0 }; + + if (lpDCB->fOutxCtsFlow) + { + handflow.ControlHandShake |= SERIAL_CTS_HANDSHAKE; + } + + if (lpDCB->fOutxDsrFlow) + { + handflow.ControlHandShake |= SERIAL_DSR_HANDSHAKE; + } + + switch (lpDCB->fDtrControl) + { + case SERIAL_DTR_HANDSHAKE: + handflow.ControlHandShake |= DTR_CONTROL_HANDSHAKE; + break; + + case SERIAL_DTR_CONTROL: + handflow.ControlHandShake |= DTR_CONTROL_ENABLE; + break; + + case DTR_CONTROL_DISABLE: + /* do nothing since handflow is init-zeroed */ + break; + + default: + CommLog_Print(WLOG_WARN, "Unexpected fDtrControl value: %" PRIu32 "\n", + lpDCB->fDtrControl); + return FALSE; + } + + if (lpDCB->fDsrSensitivity) + { + handflow.ControlHandShake |= SERIAL_DSR_SENSITIVITY; + } + + if (lpDCB->fTXContinueOnXoff) + { + handflow.FlowReplace |= SERIAL_XOFF_CONTINUE; + } + + if (lpDCB->fOutX) + { + handflow.FlowReplace |= SERIAL_AUTO_TRANSMIT; + } + + if (lpDCB->fInX) + { + handflow.FlowReplace |= SERIAL_AUTO_RECEIVE; + } + + if (lpDCB->fErrorChar) + { + handflow.FlowReplace |= SERIAL_ERROR_CHAR; + } + + if (lpDCB->fNull) + { + handflow.FlowReplace |= SERIAL_NULL_STRIPPING; + } + + switch (lpDCB->fRtsControl) + { + case RTS_CONTROL_TOGGLE: + CommLog_Print(WLOG_WARN, "Unsupported RTS_CONTROL_TOGGLE feature"); + // FIXME: see also GetCommState() + return FALSE; + + case RTS_CONTROL_HANDSHAKE: + handflow.FlowReplace |= SERIAL_RTS_HANDSHAKE; + break; + + case RTS_CONTROL_ENABLE: + handflow.FlowReplace |= SERIAL_RTS_CONTROL; + break; + + case RTS_CONTROL_DISABLE: + /* do nothing since handflow is init-zeroed */ + break; + + default: + CommLog_Print(WLOG_WARN, "Unexpected fRtsControl value: %" PRIu32 "\n", + lpDCB->fRtsControl); + return FALSE; + } + + if (lpDCB->fAbortOnError) + { + handflow.ControlHandShake |= SERIAL_ERROR_ABORT; + } + + /* lpDCB->fDummy2 not used */ + /* lpLocalDcb->wReserved ignored */ + handflow.XonLimit = lpDCB->XonLim; + handflow.XoffLimit = lpDCB->XoffLim; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_HANDFLOW, &handflow, sizeof(SERIAL_HANDFLOW), + NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the handflow settings."); + return FALSE; + } + + /** upcomingTermios stage **/ + + if (tcgetattr(pComm->fd, &upcomingTermios) < + 0) /* NB: preserves current settings not directly handled by the Communication Functions */ + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + if (lpDCB->fBinary) + { + upcomingTermios.c_lflag &= WINPR_ASSERTING_INT_CAST(tcflag_t, ~ICANON); + } + else + { + upcomingTermios.c_lflag |= ICANON; + CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag."); + } + + if (lpDCB->fParity) + { + upcomingTermios.c_iflag |= INPCK; + } + else + { + upcomingTermios.c_iflag &= WINPR_ASSERTING_INT_CAST(tcflag_t, ~INPCK); + } + + /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363423%28v=vs.85%29.aspx + * + * The SetCommState function reconfigures the communications + * resource, but it does not affect the internal output and + * input buffers of the specified driver. The buffers are not + * flushed, and pending read and write operations are not + * terminated prematurely. + * + * TCSANOW matches the best this definition + */ + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +/** + * ERRORS: + * ERROR_INVALID_HANDLE + */ +BOOL GetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */ + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, lpCommTimeouts, + sizeof(COMMTIMEOUTS), &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "GetCommTimeouts failure."); + return FALSE; + } + + return TRUE; +} + +/** + * ERRORS: + * ERROR_INVALID_HANDLE + */ +BOOL SetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */ + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_TIMEOUTS, lpCommTimeouts, sizeof(COMMTIMEOUTS), + NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommTimeouts failure."); + return FALSE; + } + + return TRUE; +} + +BOOL GetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize) +{ + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetCommBreak(HANDLE hFile) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL ClearCommBreak(HANDLE hFile) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL ClearCommError(HANDLE hFile, PDWORD lpErrors, LPCOMSTAT lpStat) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL PurgeComm(HANDLE hFile, DWORD dwFlags) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_PURGE, &dwFlags, sizeof(DWORD), NULL, 0, + &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "PurgeComm failure."); + return FALSE; + } + + return TRUE; +} + +BOOL SetupComm(HANDLE hFile, DWORD dwInQueue, DWORD dwOutQueue) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + SERIAL_QUEUE_SIZE queueSize; + DWORD bytesReturned = 0; + + if (!CommIsHandleValid(hFile)) + return FALSE; + + queueSize.InSize = dwInQueue; + queueSize.OutSize = dwOutQueue; + + if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_QUEUE_SIZE, &queueSize, + sizeof(SERIAL_QUEUE_SIZE), NULL, 0, &bytesReturned, NULL)) + { + CommLog_Print(WLOG_WARN, "SetCommTimeouts failure."); + return FALSE; + } + + return TRUE; +} + +BOOL EscapeCommFunction(HANDLE hFile, DWORD dwFunc) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL TransmitCommChar(HANDLE hFile, char cChar) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL WaitCommEvent(HANDLE hFile, PDWORD lpEvtMask, LPOVERLAPPED lpOverlapped) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hFile; + + if (!CommInitialized()) + return FALSE; + + /* TODO: not implemented */ + + if (!pComm) + return FALSE; + + CommLog_Print(WLOG_ERROR, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +/** + * Returns TRUE on success, FALSE otherwise. To get extended error + * information, call GetLastError. + * + * ERRORS: + * ERROR_DLL_INIT_FAILED + * ERROR_OUTOFMEMORY was not possible to get mappings. + * ERROR_INVALID_DATA was not possible to add the device. + */ +BOOL DefineCommDevice(/* DWORD dwFlags,*/ LPCTSTR lpDeviceName, LPCTSTR lpTargetPath) +{ + LPTSTR storedDeviceName = NULL; + LPTSTR storedTargetPath = NULL; + + if (!CommInitialized()) + return FALSE; + + EnterCriticalSection(&sCommDevicesLock); + + if (sCommDevices == NULL) + { + SetLastError(ERROR_DLL_INIT_FAILED); + goto error_handle; + } + + storedDeviceName = _tcsdup(lpDeviceName); + + if (storedDeviceName == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + goto error_handle; + } + + storedTargetPath = _tcsdup(lpTargetPath); + + if (storedTargetPath == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + goto error_handle; + } + + int i = 0; + for (; i < COMM_DEVICE_MAX; i++) + { + if (sCommDevices[i] != NULL) + { + if (_tcscmp(sCommDevices[i]->name, storedDeviceName) == 0) + { + /* take over the emplacement */ + free(sCommDevices[i]->name); + free(sCommDevices[i]->path); + sCommDevices[i]->name = storedDeviceName; + sCommDevices[i]->path = storedTargetPath; + break; + } + } + else + { + /* new emplacement */ + sCommDevices[i] = (COMM_DEVICE*)calloc(1, sizeof(COMM_DEVICE)); + + if (sCommDevices[i] == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + goto error_handle; + } + + sCommDevices[i]->name = storedDeviceName; + sCommDevices[i]->path = storedTargetPath; + break; + } + } + + if (i == COMM_DEVICE_MAX) + { + SetLastError(ERROR_OUTOFMEMORY); + goto error_handle; + } + + LeaveCriticalSection(&sCommDevicesLock); + return TRUE; +error_handle: + free(storedDeviceName); + free(storedTargetPath); + LeaveCriticalSection(&sCommDevicesLock); + return FALSE; +} + +/** + * Returns the number of target paths in the buffer pointed to by + * lpTargetPath. + * + * The current implementation returns in any case 0 and 1 target + * path. A NULL lpDeviceName is not supported yet to get all the + * paths. + * + * ERRORS: + * ERROR_SUCCESS + * ERROR_DLL_INIT_FAILED + * ERROR_OUTOFMEMORY was not possible to get mappings. + * ERROR_NOT_SUPPORTED equivalent QueryDosDevice feature not supported. + * ERROR_INVALID_DATA was not possible to retrieve any device information. + * ERROR_INSUFFICIENT_BUFFER too small lpTargetPath + */ +DWORD QueryCommDevice(LPCTSTR lpDeviceName, LPTSTR lpTargetPath, DWORD ucchMax) +{ + LPTSTR storedTargetPath = NULL; + SetLastError(ERROR_SUCCESS); + + if (!CommInitialized()) + return 0; + + if (sCommDevices == NULL) + { + SetLastError(ERROR_DLL_INIT_FAILED); + return 0; + } + + if (lpDeviceName == NULL || lpTargetPath == NULL) + { + SetLastError(ERROR_NOT_SUPPORTED); + return 0; + } + + EnterCriticalSection(&sCommDevicesLock); + storedTargetPath = NULL; + + for (int i = 0; i < COMM_DEVICE_MAX; i++) + { + if (sCommDevices[i] != NULL) + { + if (_tcscmp(sCommDevices[i]->name, lpDeviceName) == 0) + { + storedTargetPath = sCommDevices[i]->path; + break; + } + + continue; + } + + break; + } + + LeaveCriticalSection(&sCommDevicesLock); + + if (storedTargetPath == NULL) + { + SetLastError(ERROR_INVALID_DATA); + return 0; + } + + const size_t size = _tcsnlen(storedTargetPath, ucchMax); + if (size + 2 > ucchMax) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + + _tcsncpy(lpTargetPath, storedTargetPath, size + 1); + lpTargetPath[size + 2] = '\0'; /* 2nd final '\0' */ + return (DWORD)size + 2UL; +} + +/** + * Checks whether lpDeviceName is a valid and registered Communication device. + */ +BOOL IsCommDevice(LPCTSTR lpDeviceName) +{ + TCHAR lpTargetPath[MAX_PATH]; + + if (!CommInitialized()) + return FALSE; + + if (QueryCommDevice(lpDeviceName, lpTargetPath, MAX_PATH) > 0) + { + return TRUE; + } + + return FALSE; +} + +/** + * Sets + */ +void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID driverId) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_COMM* pComm = NULL; + + if (!CommInitialized()) + return; + + if (!winpr_Handle_GetInfo(hComm, &Type, &Object)) + { + CommLog_Print(WLOG_WARN, "_comm_setServerSerialDriver failure"); + return; + } + + pComm = (WINPR_COMM*)Object; + pComm->serverSerialDriverId = driverId; +} + +static HANDLE_OPS ops = { CommIsHandled, CommCloseHandle, + CommGetFd, NULL, /* CleanupHandle */ + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL, NULL, + NULL }; + +/** + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363198%28v=vs.85%29.aspx + * + * @param lpDeviceName e.g. COM1, ... + * + * @param dwDesiredAccess expects GENERIC_READ | GENERIC_WRITE, a + * warning message is printed otherwise. TODO: better support. + * + * @param dwShareMode must be zero, INVALID_HANDLE_VALUE is returned + * otherwise and GetLastError() should return ERROR_SHARING_VIOLATION. + * + * @param lpSecurityAttributes NULL expected, a warning message is printed + * otherwise. TODO: better support. + * + * @param dwCreationDisposition must be OPEN_EXISTING. If the + * communication device doesn't exist INVALID_HANDLE_VALUE is returned + * and GetLastError() returns ERROR_FILE_NOT_FOUND. + * + * @param dwFlagsAndAttributes zero expected, a warning message is + * printed otherwise. + * + * @param hTemplateFile must be NULL. + * + * @return INVALID_HANDLE_VALUE on error. + */ +HANDLE CommCreateFileA(LPCSTR lpDeviceName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + CHAR devicePath[MAX_PATH] = { 0 }; + struct stat deviceStat = { 0 }; + WINPR_COMM* pComm = NULL; + struct termios upcomingTermios = { 0 }; + + if (!CommInitialized()) + return INVALID_HANDLE_VALUE; + + if (dwDesiredAccess != (GENERIC_READ | GENERIC_WRITE)) + { + CommLog_Print(WLOG_WARN, "unexpected access to the device: 0x%08" PRIX32 "", + dwDesiredAccess); + } + + if (dwShareMode != 0) + { + SetLastError(ERROR_SHARING_VIOLATION); + return INVALID_HANDLE_VALUE; + } + + /* TODO: Prevents other processes from opening a file or + * device if they request delete, read, or write access. */ + + if (lpSecurityAttributes != NULL) + { + CommLog_Print(WLOG_WARN, "unexpected security attributes, nLength=%" PRIu32 "", + lpSecurityAttributes->nLength); + } + + if (dwCreationDisposition != OPEN_EXISTING) + { + SetLastError(ERROR_FILE_NOT_FOUND); /* FIXME: ERROR_NOT_SUPPORTED better? */ + return INVALID_HANDLE_VALUE; + } + + if (QueryCommDevice(lpDeviceName, devicePath, MAX_PATH) <= 0) + { + /* SetLastError(GetLastError()); */ + return INVALID_HANDLE_VALUE; + } + + if (stat(devicePath, &deviceStat) < 0) + { + CommLog_Print(WLOG_WARN, "device not found %s", devicePath); + SetLastError(ERROR_FILE_NOT_FOUND); + return INVALID_HANDLE_VALUE; + } + + if (!S_ISCHR(deviceStat.st_mode)) + { + CommLog_Print(WLOG_WARN, "bad device %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + return INVALID_HANDLE_VALUE; + } + + if (dwFlagsAndAttributes != 0) + { + CommLog_Print(WLOG_WARN, "unexpected flags and attributes: 0x%08" PRIX32 "", + dwFlagsAndAttributes); + } + + if (hTemplateFile != NULL) + { + SetLastError(ERROR_NOT_SUPPORTED); /* FIXME: other proper error? */ + return INVALID_HANDLE_VALUE; + } + + pComm = (WINPR_COMM*)calloc(1, sizeof(WINPR_COMM)); + + if (pComm == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + return INVALID_HANDLE_VALUE; + } + + WINPR_HANDLE_SET_TYPE_AND_MODE(pComm, HANDLE_TYPE_COMM, WINPR_FD_READ); + pComm->common.ops = &ops; + /* error_handle */ + pComm->fd = open(devicePath, O_RDWR | O_NOCTTY | O_NONBLOCK); + + if (pComm->fd < 0) + { + CommLog_Print(WLOG_WARN, "failed to open device %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + goto error_handle; + } + + pComm->fd_read = open(devicePath, O_RDONLY | O_NOCTTY | O_NONBLOCK); + + if (pComm->fd_read < 0) + { + CommLog_Print(WLOG_WARN, "failed to open fd_read, device: %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + goto error_handle; + } + +#if defined(WINPR_HAVE_SYS_EVENTFD_H) + pComm->fd_read_event = eventfd( + 0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */ +#endif + + if (pComm->fd_read_event < 0) + { + CommLog_Print(WLOG_WARN, "failed to open fd_read_event, device: %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + goto error_handle; + } + + InitializeCriticalSection(&pComm->ReadLock); + pComm->fd_write = open(devicePath, O_WRONLY | O_NOCTTY | O_NONBLOCK); + + if (pComm->fd_write < 0) + { + CommLog_Print(WLOG_WARN, "failed to open fd_write, device: %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + goto error_handle; + } + +#if defined(WINPR_HAVE_SYS_EVENTFD_H) + pComm->fd_write_event = eventfd( + 0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */ +#endif + + if (pComm->fd_write_event < 0) + { + CommLog_Print(WLOG_WARN, "failed to open fd_write_event, device: %s", devicePath); + SetLastError(ERROR_BAD_DEVICE); + goto error_handle; + } + + InitializeCriticalSection(&pComm->WriteLock); + /* can also be setup later on with _comm_setServerSerialDriver() */ + pComm->serverSerialDriverId = SerialDriverUnknown; + InitializeCriticalSection(&pComm->EventsLock); + +#if defined(WINPR_HAVE_COMM_COUNTERS) + if (ioctl(pComm->fd, TIOCGICOUNT, &(pComm->counters)) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TIOCGICOUNT ioctl failed, errno=[%d] %s.", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + CommLog_Print(WLOG_WARN, "could not read counters."); + /* could not initialize counters but keep on. + * + * Not all drivers, especially for USB to serial + * adapters (e.g. those based on pl2303), does support + * this call. + */ + ZeroMemory(&(pComm->counters), sizeof(struct serial_icounter_struct)); + } +#endif + + /* The binary/raw mode is required for the redirection but + * only flags that are not handle somewhere-else, except + * ICANON, are forced here. */ + ZeroMemory(&upcomingTermios, sizeof(struct termios)); + + if (tcgetattr(pComm->fd, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + goto error_handle; + } + + upcomingTermios.c_iflag &= WINPR_ASSERTING_INT_CAST( + tcflag_t, ~(/*IGNBRK |*/ BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL /*| IXON*/)); + upcomingTermios.c_oflag = 0; /* <=> &= ~OPOST */ + upcomingTermios.c_lflag = 0; /* <=> &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); */ + /* upcomingTermios.c_cflag &= ~(CSIZE | PARENB); */ + /* upcomingTermios.c_cflag |= CS8; */ + /* About missing flags recommended by termios(3): + * + * IGNBRK and IXON, see: IOCTL_SERIAL_SET_HANDFLOW + * CSIZE, PARENB and CS8, see: IOCTL_SERIAL_SET_LINE_CONTROL + */ + /* a few more settings required for the redirection */ + upcomingTermios.c_cflag |= CLOCAL | CREAD; + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + goto error_handle; + } + + return (HANDLE)pComm; +error_handle: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC(void) CloseHandle(pComm); + WINPR_PRAGMA_DIAG_POP + return INVALID_HANDLE_VALUE; +} + +BOOL CommIsHandled(HANDLE handle) +{ + if (!CommInitialized()) + return FALSE; + + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_COMM, TRUE); +} + +BOOL CommIsHandleValid(HANDLE handle) +{ + WINPR_COMM* pComm = (WINPR_COMM*)handle; + if (!CommIsHandled(handle)) + return FALSE; + if (pComm->fd <= 0) + { + SetLastError(ERROR_INVALID_HANDLE); + return FALSE; + } + return TRUE; +} + +BOOL CommCloseHandle(HANDLE handle) +{ + WINPR_COMM* pComm = (WINPR_COMM*)handle; + + if (!CommIsHandled(handle)) + return FALSE; + + DeleteCriticalSection(&pComm->ReadLock); + DeleteCriticalSection(&pComm->WriteLock); + DeleteCriticalSection(&pComm->EventsLock); + + if (pComm->fd > 0) + close(pComm->fd); + + if (pComm->fd_write > 0) + close(pComm->fd_write); + + if (pComm->fd_write_event > 0) + close(pComm->fd_write_event); + + if (pComm->fd_read > 0) + close(pComm->fd_read); + + if (pComm->fd_read_event > 0) + close(pComm->fd_read_event); + + free(pComm); + return TRUE; +} + +#if defined(WINPR_HAVE_SYS_EVENTFD_H) +#ifndef WITH_EVENTFD_READ_WRITE +int eventfd_read(int fd, eventfd_t* value) +{ + return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1; +} + +int eventfd_write(int fd, eventfd_t value) +{ + return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1; +} +#endif +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..4a561d969789d7f70739d646808d9b79f965d740 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm.h @@ -0,0 +1,117 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2014 Marc-Andre Moreau + * 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 +#endif + +#include + +#include "../handle/handle.h" +#include + +#if defined(WINPR_HAVE_SYS_EVENTFD_H) +#include +#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 */ +}; + +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 */ + +void CommLog_Print(DWORD wlog_level, ...); + +BOOL CommIsHandled(HANDLE handle); +BOOL CommIsHandleValid(HANDLE handle); +BOOL CommCloseHandle(HANDLE handle); +const HANDLE_CREATOR* GetCommHandleCreator(void); + +#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 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_io.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_io.c new file mode 100644 index 0000000000000000000000000000000000000000..fa953ba1afb372548ddc9701dbc0f9bfbbc588df --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_io.c @@ -0,0 +1,555 @@ +/** + * 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 + +#include +#include +#include +#include + +#include +#include +#include + +#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 = NULL; + UCHAR vmin = 0; + UCHAR vtime = 0; + LONGLONG Tmax = 0; + struct timeval tmaxTimeout; + struct timeval* pTmaxTimeout = NULL; + struct termios currentTermios; + EnterCriticalSection(&pComm->ReadLock); /* KISSer by the function's beginning */ + + if (!CommIsHandled(hDevice)) + goto return_false; + + if (lpOverlapped != NULL) + { + SetLastError(ERROR_NOT_SUPPORTED); + goto return_false; + } + + if (lpNumberOfBytesRead == NULL) + { + SetLastError(ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != NULL */ + goto return_false; + } + + *lpNumberOfBytesRead = 0; /* will be adjusted if required ... */ + + if (nNumberOfBytesToRead <= 0) /* N */ + { + goto return_true; /* FIXME: or FALSE? */ + } + + if (tcgetattr(pComm->fd, ¤tTermios) < 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 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 = NULL; + } + + 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, ¤tTermios) < 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 NULL */ + + if (pTmaxTimeout != NULL) + { + 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_read(pComm->fd_read_event, NULL); +#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, NULL, NULL, pTmaxTimeout); + + if (nbFds < 0) + { + char ebuffer[256] = { 0 }; + 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] = { 0 }; + 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] = { 0 }; + 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 = NULL; + EnterCriticalSection(&pComm->WriteLock); /* KISSer by the function's beginning */ + + if (!CommIsHandled(hDevice)) + goto return_false; + + if (lpOverlapped != NULL) + { + SetLastError(ERROR_NOT_SUPPORTED); + goto return_false; + } + + if (lpNumberOfBytesWritten == NULL) + { + SetLastError(ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != NULL */ + 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_read(pComm->fd_write_event, NULL); +#endif + + /* ms */ + 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 = NULL; + } + + /* 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, NULL, pTmaxTimeout); + + if (nbFds < 0) + { + char ebuffer[256] = { 0 }; + 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] = { 0 }; + 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; + nbWritten = write(pComm->fd_write, ((const BYTE*)lpBuffer) + (*lpNumberOfBytesWritten), + nNumberOfBytesToWrite - (*lpNumberOfBytesWritten)); + + if (nbWritten < 0) + { + char ebuffer[256] = { 0 }; + 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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.c new file mode 100644 index 0000000000000000000000000000000000000000..d60e21319765d4ab4876cba02b32ea3434b202cc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.c @@ -0,0 +1,717 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 + +#include +#include + +#include + +#include "comm.h" +#include "comm_ioctl.h" +#include "comm_serial_sys.h" +#include "comm_sercx_sys.h" +#include "comm_sercx2_sys.h" + +/* 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) +{ + WINPR_COMM* pComm = (WINPR_COMM*)hDevice; + const SERIAL_DRIVER* pServerSerialDriver = NULL; + + if (!CommIsHandleValid(hDevice)) + return FALSE; + + if (lpOverlapped) + { + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (lpBytesReturned == NULL) + { + SetLastError(ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != NULL */ + return FALSE; + } + + /* clear any previous last error */ + SetLastError(ERROR_SUCCESS); + + *lpBytesReturned = 0; /* will be adjusted if required ... */ + + CommLog_Print(WLOG_DEBUG, "CommDeviceIoControl: IoControlCode: 0x%0.8x", 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 (%d), using SerCx2.sys", + pComm->serverSerialDriverId); + pServerSerialDriver = SerCx2Sys_s(); + break; + } + + WINPR_ASSERT(pServerSerialDriver != NULL); + + 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; + + *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; + } + + return pServerSerialDriver->set_wait_mask(pComm, pWaitMask); + } + 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; + + *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; + } + + if (!pServerSerialDriver->wait_on_mask(pComm, pOutputMask)) + { + *lpBytesReturned = sizeof(ULONG); + return FALSE; + } + + *lpBytesReturned = sizeof(ULONG); + return TRUE; + } + 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, + "lpBytesReturned=%" PRIu32 " and nOutBufferSize=%" PRIu32 " are different!", + *lpBytesReturned, nOutBufferSize); + } + + if (pComm->permissive) + { + if (!result) + { + CommLog_Print( + WLOG_WARN, + "[permissive]: whereas it failed, made to succeed IoControlCode=[0x%08" PRIX32 + "] %s, last-error: 0x%08" PRIX32 "", + dwIoControlCode, _comm_serial_ioctl_name(dwIoControlCode), GetLastError()); + } + + return TRUE; /* always! */ + } + + return result; +} + +int _comm_ioctl_tcsetattr(int fd, int optional_actions, const struct termios* termios_p) +{ + int result = 0; + struct termios currentState = { 0 }; + + if ((result = tcsetattr(fd, optional_actions, termios_p)) < 0) + { + CommLog_Print(WLOG_WARN, "tcsetattr failure, errno: %d", errno); + return result; + } + + /* NB: tcsetattr() can succeed even if not all changes have been applied. */ + if ((result = tcgetattr(fd, ¤tState)) < 0) + { + CommLog_Print(WLOG_WARN, "tcgetattr failure, errno: %d", errno); + return result; + } + + // NOLINTNEXTLINE(bugprone-suspicious-memory-comparison,cert-exp42-c,cert-flp37-c) + if (memcmp(¤tState, termios_p, sizeof(struct termios)) != 0) + { + CommLog_Print(WLOG_DEBUG, + "all termios parameters are not set yet, doing a second attempt..."); + if ((result = tcsetattr(fd, optional_actions, termios_p)) < 0) + { + CommLog_Print(WLOG_WARN, "2nd tcsetattr failure, errno: %d", errno); + return result; + } + + ZeroMemory(¤tState, sizeof(struct termios)); + if ((result = tcgetattr(fd, ¤tState)) < 0) + { + CommLog_Print(WLOG_WARN, "tcgetattr failure, errno: %d", errno); + return result; + } + + // NOLINTNEXTLINE(bugprone-suspicious-memory-comparison,cert-exp42-c,cert-flp37-c) + if (memcmp(¤tState, termios_p, sizeof(struct termios)) != 0) + { + CommLog_Print(WLOG_WARN, + "Failure: all termios parameters are still not set on a second attempt"); + return -1; + } + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.h new file mode 100644 index 0000000000000000000000000000000000000000..9d46df5362bf63713cb16bee270993018f63f9f3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl.h @@ -0,0 +1,232 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * 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 + +#include +#include +#include + +#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; + WORD XonLimit; + WORD 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 NULL 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_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl_dummy.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl_dummy.c new file mode 100644 index 0000000000000000000000000000000000000000..3c9910c96bafaf8dfd79656b802a7c19e096b9c1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_ioctl_dummy.c @@ -0,0 +1,87 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API - Dummy implementation + * + * Copyright 2024 Armin Novak + * 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 + +#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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.c new file mode 100644 index 0000000000000000000000000000000000000000..5cb19f2373680a8c87f2489079e0d3d9fae38dc2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.c @@ -0,0 +1,209 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 +#include + +#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_COMM* pComm, const SERIAL_CHARS* pSerialChars) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pSerialChars); + + return TRUE; +} + +static BOOL get_serial_chars(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 = NULL, + .get_baud_rate = NULL, + .get_properties = NULL, + .set_serial_chars = set_serial_chars, + .get_serial_chars = get_serial_chars, + .set_line_control = NULL, + .get_line_control = NULL, + .set_handflow = NULL, + .get_handflow = NULL, + .set_timeouts = NULL, + .get_timeouts = NULL, + .set_dtr = NULL, + .clear_dtr = NULL, + .set_rts = NULL, + .clear_rts = NULL, + .get_modemstatus = NULL, + .set_wait_mask = set_wait_mask, + .get_wait_mask = NULL, + .wait_on_mask = NULL, + .set_queue_size = NULL, + .purge = purge, + .get_commstatus = NULL, + .set_break_on = NULL, + .set_break_off = NULL, + .set_xoff = NULL, /* not supported by SerCx2.sys */ + .set_xon = NULL, /* not supported by SerCx2.sys */ + .get_dtrrts = NULL, + .config_size = NULL, /* not supported by SerCx2.sys */ + .immediate_char = NULL, /* not supported by SerCx2.sys */ + .reset_device = NULL, /* 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 NULL; + + 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; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..e2feb2a2fccd0e52669c9fa5a0de9dcfed85489c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx2_sys.h @@ -0,0 +1,36 @@ +/** + * 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. + */ + +#ifndef COMM_SERCX2_SYS_H +#define COMM_SERCX2_SYS_H + +#include "comm_ioctl.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + const SERIAL_DRIVER* SerCx2Sys_s(void); + +#ifdef __cplusplus +} +#endif + +#endif /* COMM_SERCX2_SYS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.c new file mode 100644 index 0000000000000000000000000000000000000000..39843c1b3e32eda3c0262433c32b0e409773960f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.c @@ -0,0 +1,261 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 +#include + +#include + +#include "comm_serial_sys.h" +#include "comm_sercx_sys.h" + +static BOOL set_handflow(WINPR_COMM* pComm, const SERIAL_HANDFLOW* pHandflow) +{ + SERIAL_HANDFLOW SerCxHandflow; + BOOL result = TRUE; + const SERIAL_DRIVER* pSerialSys = SerialSys_s(); + + memcpy(&SerCxHandflow, pHandflow, sizeof(SERIAL_HANDFLOW)); + + /* filter out unsupported bits by SerCx.sys + * + * http://msdn.microsoft.com/en-us/library/windows/hardware/jj680685%28v=vs.85%29.aspx + */ + + SerCxHandflow.ControlHandShake = + pHandflow->ControlHandShake & + (SERIAL_DTR_CONTROL | SERIAL_DTR_HANDSHAKE | SERIAL_CTS_HANDSHAKE | SERIAL_DSR_HANDSHAKE); + SerCxHandflow.FlowReplace = + pHandflow->FlowReplace & (SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE); + + if (SerCxHandflow.ControlHandShake != pHandflow->ControlHandShake) + { + if (pHandflow->ControlHandShake & SERIAL_DCD_HANDSHAKE) + { + CommLog_Print(WLOG_WARN, + "SERIAL_DCD_HANDSHAKE not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_DSR_SENSITIVITY) + { + CommLog_Print(WLOG_WARN, + "SERIAL_DSR_SENSITIVITY not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_ERROR_ABORT) + { + CommLog_Print(WLOG_WARN, + "SERIAL_ERROR_ABORT not supposed to be implemented by SerCx.sys"); + } + + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + result = FALSE; + } + + if (SerCxHandflow.FlowReplace != pHandflow->FlowReplace) + { + if (pHandflow->ControlHandShake & SERIAL_AUTO_TRANSMIT) + { + CommLog_Print(WLOG_WARN, + "SERIAL_AUTO_TRANSMIT not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_AUTO_RECEIVE) + { + CommLog_Print(WLOG_WARN, + "SERIAL_AUTO_RECEIVE not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_ERROR_CHAR) + { + CommLog_Print(WLOG_WARN, + "SERIAL_ERROR_CHAR not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_NULL_STRIPPING) + { + CommLog_Print(WLOG_WARN, + "SERIAL_NULL_STRIPPING not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_BREAK_CHAR) + { + CommLog_Print(WLOG_WARN, + "SERIAL_BREAK_CHAR not supposed to be implemented by SerCx.sys"); + } + + if (pHandflow->ControlHandShake & SERIAL_XOFF_CONTINUE) + { + CommLog_Print(WLOG_WARN, + "SERIAL_XOFF_CONTINUE not supposed to be implemented by SerCx.sys"); + } + + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + result = FALSE; + } + + if (!pSerialSys->set_handflow(pComm, &SerCxHandflow)) + return FALSE; + + return result; +} + +static BOOL get_handflow(WINPR_COMM* pComm, SERIAL_HANDFLOW* pHandflow) +{ + const SERIAL_DRIVER* pSerialSys = SerialSys_s(); + + BOOL result = pSerialSys->get_handflow(pComm, pHandflow); + + /* filter out unsupported bits by SerCx.sys + * + * http://msdn.microsoft.com/en-us/library/windows/hardware/jj680685%28v=vs.85%29.aspx + */ + + pHandflow->ControlHandShake = + pHandflow->ControlHandShake & + (SERIAL_DTR_CONTROL | SERIAL_DTR_HANDSHAKE | SERIAL_CTS_HANDSHAKE | SERIAL_DSR_HANDSHAKE); + pHandflow->FlowReplace = pHandflow->FlowReplace & (SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE); + + return result; +} + +/* http://msdn.microsoft.com/en-us/library/windows/hardware/hh439605%28v=vs.85%29.aspx */ +static const ULONG SERCX_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*/ + ; + +static BOOL set_wait_mask(WINPR_COMM* pComm, const ULONG* pWaitMask) +{ + const SERIAL_DRIVER* pSerialSys = SerialSys_s(); + WINPR_ASSERT(pWaitMask); + + const ULONG possibleMask = *pWaitMask & SERCX_SYS_SUPPORTED_EV_MASK; + + if (possibleMask != *pWaitMask) + { + CommLog_Print(WLOG_WARN, + "Not all wait events supported (SerCx.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); +} + +/* specific functions only */ +static SERIAL_DRIVER SerCxSys = { + .id = SerialDriverSerCxSys, + .name = _T("SerCx.sys"), + .set_baud_rate = NULL, + .get_baud_rate = NULL, + .get_properties = NULL, + .set_serial_chars = NULL, + .get_serial_chars = NULL, + .set_line_control = NULL, + .get_line_control = NULL, + .set_handflow = set_handflow, + .get_handflow = get_handflow, + .set_timeouts = NULL, + .get_timeouts = NULL, + .set_dtr = NULL, + .clear_dtr = NULL, + .set_rts = NULL, + .clear_rts = NULL, + .get_modemstatus = NULL, + .set_wait_mask = set_wait_mask, + .get_wait_mask = NULL, + .wait_on_mask = NULL, + .set_queue_size = NULL, + .purge = NULL, + .get_commstatus = NULL, + .set_break_on = NULL, + .set_break_off = NULL, + .set_xoff = NULL, + .set_xon = NULL, + .get_dtrrts = NULL, + .config_size = NULL, /* not supported by SerCx.sys */ + .immediate_char = NULL, + .reset_device = NULL, /* not supported by SerCx.sys */ +}; + +const SERIAL_DRIVER* SerCxSys_s(void) +{ + /* _SerCxSys completed with inherited functions from SerialSys */ + const SERIAL_DRIVER* pSerialSys = SerialSys_s(); + if (!pSerialSys) + return NULL; + + SerCxSys.set_baud_rate = pSerialSys->set_baud_rate; + SerCxSys.get_baud_rate = pSerialSys->get_baud_rate; + + SerCxSys.get_properties = pSerialSys->get_properties; + + SerCxSys.set_serial_chars = pSerialSys->set_serial_chars; + SerCxSys.get_serial_chars = pSerialSys->get_serial_chars; + SerCxSys.set_line_control = pSerialSys->set_line_control; + SerCxSys.get_line_control = pSerialSys->get_line_control; + + SerCxSys.set_timeouts = pSerialSys->set_timeouts; + SerCxSys.get_timeouts = pSerialSys->get_timeouts; + + SerCxSys.set_dtr = pSerialSys->set_dtr; + SerCxSys.clear_dtr = pSerialSys->clear_dtr; + + SerCxSys.set_rts = pSerialSys->set_rts; + SerCxSys.clear_rts = pSerialSys->clear_rts; + + SerCxSys.get_modemstatus = pSerialSys->get_modemstatus; + + SerCxSys.set_wait_mask = pSerialSys->set_wait_mask; + SerCxSys.get_wait_mask = pSerialSys->get_wait_mask; + SerCxSys.wait_on_mask = pSerialSys->wait_on_mask; + + SerCxSys.set_queue_size = pSerialSys->set_queue_size; + + SerCxSys.purge = pSerialSys->purge; + + SerCxSys.get_commstatus = pSerialSys->get_commstatus; + + SerCxSys.set_break_on = pSerialSys->set_break_on; + SerCxSys.set_break_off = pSerialSys->set_break_off; + + SerCxSys.set_xoff = pSerialSys->set_xoff; + SerCxSys.set_xon = pSerialSys->set_xon; + + SerCxSys.get_dtrrts = pSerialSys->get_dtrrts; + + SerCxSys.immediate_char = pSerialSys->immediate_char; + + return &SerCxSys; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..0ab6f1738f182bf7d19beb148538c6b5885b2c74 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_sercx_sys.h @@ -0,0 +1,36 @@ +/** + * 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. + */ + +#ifndef COMM_SERCX_SYS_H +#define COMM_SERCX_SYS_H + +#include "comm_ioctl.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + const SERIAL_DRIVER* SerCxSys_s(void); + +#ifdef __cplusplus +} +#endif + +#endif /* COMM_SERCX_SYS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.c new file mode 100644 index 0000000000000000000000000000000000000000..16428e04144ccf36c5a53f9c57068cb020a0ad07 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.c @@ -0,0 +1,1687 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2011 O.S. Systems Software Ltda. + * Copyright 2011 Eduardo Fiss Beloni + * Copyright 2014 Marc-Andre Moreau + * 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 +#include +#include +#include +#include +#include + +#include "comm_serial_sys.h" +#include "comm.h" + +#include +#include + +/* Undocumented flag, not supported everywhere. + * Provide a sensible fallback to avoid compilation problems. */ +#ifndef CMSPAR +#define CMSPAR 010000000000 +#endif + +/* hard-coded in N_TTY */ +#define TTY_THRESHOLD_THROTTLE 128 /* now based on remaining room */ +#define TTY_THRESHOLD_UNTHROTTLE 128 +#define N_TTY_BUF_SIZE 4096 + +#define BAUD_TABLE_END 0010020 /* __MAX_BAUD + 1 */ + +/* 0: B* (Linux termios) + * 1: CBR_* or actual baud rate + * 2: BAUD_* (identical to SERIAL_BAUD_*) + */ +static const speed_t BAUD_TABLE[][3] = { +#ifdef B0 + { B0, 0, 0 }, /* hang up */ +#endif +#ifdef B50 + { B50, 50, 0 }, +#endif +#ifdef B75 + { B75, 75, BAUD_075 }, +#endif +#ifdef B110 + { B110, CBR_110, BAUD_110 }, +#endif +#ifdef B134 + { B134, 134, 0 /*BAUD_134_5*/ }, +#endif +#ifdef B150 + { B150, 150, BAUD_150 }, +#endif +#ifdef B200 + { B200, 200, 0 }, +#endif +#ifdef B300 + { B300, CBR_300, BAUD_300 }, +#endif +#ifdef B600 + { B600, CBR_600, BAUD_600 }, +#endif +#ifdef B1200 + { B1200, CBR_1200, BAUD_1200 }, +#endif +#ifdef B1800 + { B1800, 1800, BAUD_1800 }, +#endif +#ifdef B2400 + { B2400, CBR_2400, BAUD_2400 }, +#endif +#ifdef B4800 + { B4800, CBR_4800, BAUD_4800 }, +#endif +/* {, ,BAUD_7200} */ +#ifdef B9600 + { B9600, CBR_9600, BAUD_9600 }, +#endif +/* {, CBR_14400, BAUD_14400}, /\* unsupported on Linux *\/ */ +#ifdef B19200 + { B19200, CBR_19200, BAUD_19200 }, +#endif +#ifdef B38400 + { B38400, CBR_38400, BAUD_38400 }, +#endif +/* {, CBR_56000, BAUD_56K}, /\* unsupported on Linux *\/ */ +#ifdef B57600 + { B57600, CBR_57600, BAUD_57600 }, +#endif +#ifdef B115200 + { B115200, CBR_115200, BAUD_115200 }, +#endif +/* {, CBR_128000, BAUD_128K}, /\* unsupported on Linux *\/ */ +/* {, CBR_256000, BAUD_USER}, /\* unsupported on Linux *\/ */ +#ifdef B230400 + { B230400, 230400, BAUD_USER }, +#endif +#ifdef B460800 + { B460800, 460800, BAUD_USER }, +#endif +#ifdef B500000 + { B500000, 500000, BAUD_USER }, +#endif +#ifdef B576000 + { B576000, 576000, BAUD_USER }, +#endif +#ifdef B921600 + { B921600, 921600, BAUD_USER }, +#endif +#ifdef B1000000 + { B1000000, 1000000, BAUD_USER }, +#endif +#ifdef B1152000 + { B1152000, 1152000, BAUD_USER }, +#endif +#ifdef B1500000 + { B1500000, 1500000, BAUD_USER }, +#endif +#ifdef B2000000 + { B2000000, 2000000, BAUD_USER }, +#endif +#ifdef B2500000 + { B2500000, 2500000, BAUD_USER }, +#endif +#ifdef B3000000 + { B3000000, 3000000, BAUD_USER }, +#endif +#ifdef B3500000 + { B3500000, 3500000, BAUD_USER }, +#endif +#ifdef B4000000 + { B4000000, 4000000, BAUD_USER }, /* __MAX_BAUD */ +#endif + { BAUD_TABLE_END, 0, 0 } +}; + +static BOOL commstatus_error(WINPR_COMM* pComm, const char* ctrl); + +static BOOL get_properties(WINPR_COMM* pComm, COMMPROP* pProperties) +{ + WINPR_ASSERT(pComm); + /* http://msdn.microsoft.com/en-us/library/windows/hardware/jj680684%28v=vs.85%29.aspx + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363189%28v=vs.85%29.aspx + */ + + /* FIXME: properties should be better probed. The current + * implementation just relies on the Linux' implementation. + */ + WINPR_ASSERT(pProperties); + if (pProperties->dwProvSpec1 != COMMPROP_INITIALIZED) + { + ZeroMemory(pProperties, sizeof(COMMPROP)); + pProperties->wPacketLength = sizeof(COMMPROP); + } + + pProperties->wPacketVersion = 2; + + pProperties->dwServiceMask = SERIAL_SP_SERIALCOMM; + + /* pProperties->Reserved1; not used */ + + /* FIXME: could be implemented on top of N_TTY */ + pProperties->dwMaxTxQueue = N_TTY_BUF_SIZE; + pProperties->dwMaxRxQueue = N_TTY_BUF_SIZE; + + /* FIXME: to be probe on the device? */ + pProperties->dwMaxBaud = BAUD_USER; + + /* FIXME: what about PST_RS232? see also: serial_struct */ + pProperties->dwProvSubType = PST_UNSPECIFIED; + + /* TODO: to be finalized */ + pProperties->dwProvCapabilities = + /*PCF_16BITMODE |*/ PCF_DTRDSR | PCF_INTTIMEOUTS | PCF_PARITY_CHECK | /*PCF_RLSD |*/ + PCF_RTSCTS | PCF_SETXCHAR | /*PCF_SPECIALCHARS |*/ PCF_TOTALTIMEOUTS | PCF_XONXOFF; + + /* TODO: double check SP_RLSD */ + pProperties->dwSettableParams = SP_BAUD | SP_DATABITS | SP_HANDSHAKING | SP_PARITY | + SP_PARITY_CHECK | /*SP_RLSD |*/ SP_STOPBITS; + + pProperties->dwSettableBaud = 0; + for (int i = 0; BAUD_TABLE[i][0] < BAUD_TABLE_END; i++) + { + pProperties->dwSettableBaud |= BAUD_TABLE[i][2]; + } + + pProperties->wSettableData = + DATABITS_5 | DATABITS_6 | DATABITS_7 | DATABITS_8 /*| DATABITS_16 | DATABITS_16X*/; + + pProperties->wSettableStopParity = STOPBITS_10 | /*STOPBITS_15 |*/ STOPBITS_20 | PARITY_NONE | + PARITY_ODD | PARITY_EVEN | PARITY_MARK | PARITY_SPACE; + + /* FIXME: additional input and output buffers could be implemented on top of N_TTY */ + pProperties->dwCurrentTxQueue = N_TTY_BUF_SIZE; + pProperties->dwCurrentRxQueue = N_TTY_BUF_SIZE; + + /* pProperties->ProvSpec1; see above */ + /* pProperties->ProvSpec2; ignored */ + /* pProperties->ProvChar[1]; ignored */ + + return TRUE; +} + +static BOOL set_baud_rate(WINPR_COMM* pComm, const SERIAL_BAUD_RATE* pBaudRate) +{ + speed_t newSpeed = 0; + struct termios futureState = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pBaudRate); + + if (tcgetattr(pComm->fd, &futureState) < + 0) /* NB: preserves current settings not directly handled by the Communication Functions */ + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + for (int i = 0; BAUD_TABLE[i][0] < BAUD_TABLE_END; i++) + { + if (BAUD_TABLE[i][1] == pBaudRate->BaudRate) + { + newSpeed = BAUD_TABLE[i][0]; + if (cfsetspeed(&futureState, newSpeed) < 0) + { + CommLog_Print(WLOG_WARN, "failed to set speed 0x%x (%" PRIu32 ")", newSpeed, + pBaudRate->BaudRate); + return FALSE; + } + + WINPR_ASSERT(cfgetispeed(&futureState) == newSpeed); + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &futureState) < 0) + { + CommLog_Print(WLOG_WARN, "_comm_ioctl_tcsetattr failure: last-error: 0x%" PRIX32 "", + GetLastError()); + return FALSE; + } + + return TRUE; + } + } + + CommLog_Print(WLOG_WARN, "could not find a matching speed for the baud rate %" PRIu32 "", + pBaudRate->BaudRate); + SetLastError(ERROR_INVALID_DATA); + return FALSE; +} + +static BOOL get_baud_rate(WINPR_COMM* pComm, SERIAL_BAUD_RATE* pBaudRate) +{ + speed_t currentSpeed = 0; + struct termios currentState = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pBaudRate); + + if (tcgetattr(pComm->fd, ¤tState) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + currentSpeed = cfgetispeed(¤tState); + + for (int i = 0; BAUD_TABLE[i][0] < BAUD_TABLE_END; i++) + { + if (BAUD_TABLE[i][0] == currentSpeed) + { + pBaudRate->BaudRate = BAUD_TABLE[i][1]; + return TRUE; + } + } + + CommLog_Print(WLOG_WARN, "could not find a matching baud rate for the speed 0x%x", + currentSpeed); + SetLastError(ERROR_INVALID_DATA); + return FALSE; +} + +/** + * NOTE: Only XonChar and XoffChar are plenty supported with the Linux + * N_TTY line discipline. + * + * ERRORS: + * ERROR_IO_DEVICE + * ERROR_INVALID_PARAMETER when Xon and Xoff chars are the same; + * ERROR_NOT_SUPPORTED + */ +static BOOL set_serial_chars(WINPR_COMM* pComm, const SERIAL_CHARS* pSerialChars) +{ + BOOL result = TRUE; + struct termios upcomingTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pSerialChars); + + if (tcgetattr(pComm->fd, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + /* termios(3): (..) above symbolic subscript values are all + * different, except that VTIME, VMIN may have the same value + * as VEOL, VEOF, respectively. In noncanonical mode the + * special character meaning is replaced by the timeout + * meaning. + * + * EofChar and c_cc[VEOF] are not quite the same, prefer to + * don't use c_cc[VEOF] at all. + * + * FIXME: might be implemented during read/write I/O + */ + if (pSerialChars->EofChar != '\0') + { + CommLog_Print(WLOG_WARN, "EofChar %02" PRIX8 " cannot be set\n", pSerialChars->EofChar); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + /* According the Linux's n_tty discipline, characters with a + * parity error can only be let unchanged, replaced by \0 or + * get the prefix the prefix \377 \0 + */ + + /* FIXME: see also: set_handflow() */ + if (pSerialChars->ErrorChar != '\0') + { + CommLog_Print(WLOG_WARN, "ErrorChar 0x%02" PRIX8 " ('%c') cannot be set (unsupported).\n", + pSerialChars->ErrorChar, (char)pSerialChars->ErrorChar); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + /* FIXME: see also: set_handflow() */ + if (pSerialChars->BreakChar != '\0') + { + CommLog_Print(WLOG_WARN, "BreakChar 0x%02" PRIX8 " ('%c') cannot be set (unsupported).\n", + pSerialChars->BreakChar, (char)pSerialChars->BreakChar); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + if (pSerialChars->EventChar != '\0') + { + pComm->eventChar = pSerialChars->EventChar; + } + + upcomingTermios.c_cc[VSTART] = pSerialChars->XonChar; + + upcomingTermios.c_cc[VSTOP] = pSerialChars->XoffChar; + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0) + { + CommLog_Print(WLOG_WARN, "_comm_ioctl_tcsetattr failure: last-error: 0x%08" PRIX32 "", + GetLastError()); + return FALSE; + } + + return result; +} + +static BOOL get_serial_chars(WINPR_COMM* pComm, SERIAL_CHARS* pSerialChars) +{ + struct termios currentTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pSerialChars); + + if (tcgetattr(pComm->fd, ¤tTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + ZeroMemory(pSerialChars, sizeof(SERIAL_CHARS)); + + /* EofChar unsupported */ + + /* ErrorChar unsupported */ + + /* BreakChar unsupported */ + + /* FIXME: see also: set_serial_chars() */ + /* EventChar */ + + pSerialChars->XonChar = currentTermios.c_cc[VSTART]; + + pSerialChars->XoffChar = currentTermios.c_cc[VSTOP]; + + return TRUE; +} + +static BOOL set_line_control(WINPR_COMM* pComm, const SERIAL_LINE_CONTROL* pLineControl) +{ + BOOL result = TRUE; + struct termios upcomingTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pLineControl); + + /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363214%28v=vs.85%29.aspx + * + * The use of 5 data bits with 2 stop bits is an invalid + * combination, as is 6, 7, or 8 data bits with 1.5 stop bits. + * + * FIXME: preferred to let the underlying driver to deal with + * this issue. At least produce a warning message? + */ + + if (tcgetattr(pComm->fd, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + /* FIXME: use of a COMMPROP to validate new settings? */ + + switch (pLineControl->StopBits) + { + case STOP_BIT_1: + upcomingTermios.c_cflag &= (uint32_t)~CSTOPB; + break; + + case STOP_BITS_1_5: + CommLog_Print(WLOG_WARN, "Unsupported one and a half stop bits."); + break; + + case STOP_BITS_2: + upcomingTermios.c_cflag |= CSTOPB; + break; + + default: + CommLog_Print(WLOG_WARN, "unexpected number of stop bits: %" PRIu8 "\n", + pLineControl->StopBits); + result = FALSE; /* but keep on */ + break; + } + + switch (pLineControl->Parity) + { + case NO_PARITY: + upcomingTermios.c_cflag &= (uint32_t)~(PARENB | PARODD | CMSPAR); + break; + + case ODD_PARITY: + upcomingTermios.c_cflag &= (uint32_t)~CMSPAR; + upcomingTermios.c_cflag |= PARENB | PARODD; + break; + + case EVEN_PARITY: + upcomingTermios.c_cflag &= (uint32_t)~(PARODD | CMSPAR); + upcomingTermios.c_cflag |= PARENB; + break; + + case MARK_PARITY: + upcomingTermios.c_cflag |= PARENB | PARODD | CMSPAR; + break; + + case SPACE_PARITY: + upcomingTermios.c_cflag &= (uint32_t)~PARODD; + upcomingTermios.c_cflag |= PARENB | CMSPAR; + break; + + default: + CommLog_Print(WLOG_WARN, "unexpected type of parity: %" PRIu8 "\n", + pLineControl->Parity); + result = FALSE; /* but keep on */ + break; + } + + switch (pLineControl->WordLength) + { + case 5: + upcomingTermios.c_cflag &= (uint32_t)~CSIZE; + upcomingTermios.c_cflag |= CS5; + break; + + case 6: + upcomingTermios.c_cflag &= (uint32_t)~CSIZE; + upcomingTermios.c_cflag |= CS6; + break; + + case 7: + upcomingTermios.c_cflag &= (uint32_t)~CSIZE; + upcomingTermios.c_cflag |= CS7; + break; + + case 8: + upcomingTermios.c_cflag &= (uint32_t)~CSIZE; + upcomingTermios.c_cflag |= CS8; + break; + + default: + CommLog_Print(WLOG_WARN, "unexpected number od data bits per character: %" PRIu8 "\n", + pLineControl->WordLength); + result = FALSE; /* but keep on */ + break; + } + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0) + { + CommLog_Print(WLOG_WARN, "_comm_ioctl_tcsetattr failure: last-error: 0x%08" PRIX32 "", + GetLastError()); + return FALSE; + } + + return result; +} + +static BOOL get_line_control(WINPR_COMM* pComm, SERIAL_LINE_CONTROL* pLineControl) +{ + struct termios currentTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pLineControl); + + if (tcgetattr(pComm->fd, ¤tTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + pLineControl->StopBits = (currentTermios.c_cflag & CSTOPB) ? STOP_BITS_2 : STOP_BIT_1; + + if (!(currentTermios.c_cflag & PARENB)) + { + pLineControl->Parity = NO_PARITY; + } + else if (currentTermios.c_cflag & CMSPAR) + { + pLineControl->Parity = (currentTermios.c_cflag & PARODD) ? MARK_PARITY : SPACE_PARITY; + } + else + { + /* PARENB is set */ + pLineControl->Parity = (currentTermios.c_cflag & PARODD) ? ODD_PARITY : EVEN_PARITY; + } + + switch (currentTermios.c_cflag & CSIZE) + { + case CS5: + pLineControl->WordLength = 5; + break; + case CS6: + pLineControl->WordLength = 6; + break; + case CS7: + pLineControl->WordLength = 7; + break; + default: + pLineControl->WordLength = 8; + break; + } + + return TRUE; +} + +static BOOL set_handflow(WINPR_COMM* pComm, const SERIAL_HANDFLOW* pHandflow) +{ + BOOL result = TRUE; + struct termios upcomingTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pHandflow); + + if (tcgetattr(pComm->fd, &upcomingTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + /* HUPCL */ + + /* logical XOR */ + if ((!(pHandflow->ControlHandShake & SERIAL_DTR_CONTROL) && + (pHandflow->FlowReplace & SERIAL_RTS_CONTROL)) || + ((pHandflow->ControlHandShake & SERIAL_DTR_CONTROL) && + !(pHandflow->FlowReplace & SERIAL_RTS_CONTROL))) + { + CommLog_Print(WLOG_WARN, + "SERIAL_DTR_CONTROL:%s and SERIAL_RTS_CONTROL:%s cannot be different, HUPCL " + "will be set since it is claimed for one of the both lines.", + (pHandflow->ControlHandShake & SERIAL_DTR_CONTROL) ? "ON" : "OFF", + (pHandflow->FlowReplace & SERIAL_RTS_CONTROL) ? "ON" : "OFF"); + } + + if ((pHandflow->ControlHandShake & SERIAL_DTR_CONTROL) || + (pHandflow->FlowReplace & SERIAL_RTS_CONTROL)) + { + upcomingTermios.c_cflag |= HUPCL; + } + else + { + upcomingTermios.c_cflag &= (uint32_t)~HUPCL; + + /* FIXME: is the DTR line also needs to be forced to a disable state according + * SERIAL_DTR_CONTROL? */ + /* FIXME: is the RTS line also needs to be forced to a disable state according + * SERIAL_RTS_CONTROL? */ + } + + /* CRTSCTS */ + + /* logical XOR */ + if ((!(pHandflow->ControlHandShake & SERIAL_CTS_HANDSHAKE) && + (pHandflow->FlowReplace & SERIAL_RTS_HANDSHAKE)) || + ((pHandflow->ControlHandShake & SERIAL_CTS_HANDSHAKE) && + !(pHandflow->FlowReplace & SERIAL_RTS_HANDSHAKE))) + { + CommLog_Print(WLOG_WARN, + "SERIAL_CTS_HANDSHAKE:%s and SERIAL_RTS_HANDSHAKE:%s cannot be different, " + "CRTSCTS will be set since it is claimed for one of the both lines.", + (pHandflow->ControlHandShake & SERIAL_CTS_HANDSHAKE) ? "ON" : "OFF", + (pHandflow->FlowReplace & SERIAL_RTS_HANDSHAKE) ? "ON" : "OFF"); + } + + if ((pHandflow->ControlHandShake & SERIAL_CTS_HANDSHAKE) || + (pHandflow->FlowReplace & SERIAL_RTS_HANDSHAKE)) + { + upcomingTermios.c_cflag |= CRTSCTS; + } + else + { + upcomingTermios.c_cflag &= ~CRTSCTS; + } + + /* ControlHandShake */ + + if (pHandflow->ControlHandShake & SERIAL_DTR_HANDSHAKE) + { + /* DTR/DSR flow control not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_DTR_HANDSHAKE feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + if (pHandflow->ControlHandShake & SERIAL_DSR_HANDSHAKE) + { + /* DTR/DSR flow control not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_DSR_HANDSHAKE feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + if (pHandflow->ControlHandShake & SERIAL_DCD_HANDSHAKE) + { + /* DCD flow control not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_DCD_HANDSHAKE feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + // FIXME: could be implemented during read/write I/O + if (pHandflow->ControlHandShake & SERIAL_DSR_SENSITIVITY) + { + /* DSR line control not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_DSR_SENSITIVITY feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + // FIXME: could be implemented during read/write I/O + if (pHandflow->ControlHandShake & SERIAL_ERROR_ABORT) + { + /* Aborting operations on error not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_ERROR_ABORT feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + /* FlowReplace */ + + if (pHandflow->FlowReplace & SERIAL_AUTO_TRANSMIT) + { + upcomingTermios.c_iflag |= IXON; + } + else + { + upcomingTermios.c_iflag &= (uint32_t)~IXON; + } + + if (pHandflow->FlowReplace & SERIAL_AUTO_RECEIVE) + { + upcomingTermios.c_iflag |= IXOFF; + } + else + { + upcomingTermios.c_iflag &= (uint32_t)~IXOFF; + } + + // FIXME: could be implemented during read/write I/O, as of today ErrorChar is necessary '\0' + if (pHandflow->FlowReplace & SERIAL_ERROR_CHAR) + { + /* errors will be replaced by the character '\0'. */ + upcomingTermios.c_iflag &= (uint32_t)~IGNPAR; + } + else + { + upcomingTermios.c_iflag |= IGNPAR; + } + + if (pHandflow->FlowReplace & SERIAL_NULL_STRIPPING) + { + upcomingTermios.c_iflag |= IGNBRK; + } + else + { + upcomingTermios.c_iflag &= (uint32_t)~IGNBRK; + } + + // FIXME: could be implemented during read/write I/O + if (pHandflow->FlowReplace & SERIAL_BREAK_CHAR) + { + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_BREAK_CHAR feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + // FIXME: could be implemented during read/write I/O + if (pHandflow->FlowReplace & SERIAL_XOFF_CONTINUE) + { + /* not supported on Linux */ + CommLog_Print(WLOG_WARN, "Attempt to use the unsupported SERIAL_XOFF_CONTINUE feature."); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + /* XonLimit */ + + // FIXME: could be implemented during read/write I/O + if (pHandflow->XonLimit != TTY_THRESHOLD_UNTHROTTLE) + { + CommLog_Print(WLOG_WARN, "Attempt to set XonLimit with an unsupported value: %" PRId32 "", + pHandflow->XonLimit); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + /* XoffChar */ + + // FIXME: could be implemented during read/write I/O + if (pHandflow->XoffLimit != TTY_THRESHOLD_THROTTLE) + { + CommLog_Print(WLOG_WARN, "Attempt to set XoffLimit with an unsupported value: %" PRId32 "", + pHandflow->XoffLimit); + SetLastError(ERROR_NOT_SUPPORTED); + result = FALSE; /* but keep on */ + } + + if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0) + { + CommLog_Print(WLOG_WARN, "_comm_ioctl_tcsetattr failure: last-error: 0x%" PRIX32 "", + GetLastError()); + return FALSE; + } + + return result; +} + +static BOOL get_handflow(WINPR_COMM* pComm, SERIAL_HANDFLOW* pHandflow) +{ + struct termios currentTermios = { 0 }; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pHandflow); + + if (tcgetattr(pComm->fd, ¤tTermios) < 0) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + /* ControlHandShake */ + + pHandflow->ControlHandShake = 0; + + if (currentTermios.c_cflag & HUPCL) + pHandflow->ControlHandShake |= SERIAL_DTR_CONTROL; + + /* SERIAL_DTR_HANDSHAKE unsupported */ + + if (currentTermios.c_cflag & CRTSCTS) + pHandflow->ControlHandShake |= SERIAL_CTS_HANDSHAKE; + + /* SERIAL_DSR_HANDSHAKE unsupported */ + + /* SERIAL_DCD_HANDSHAKE unsupported */ + + /* SERIAL_DSR_SENSITIVITY unsupported */ + + /* SERIAL_ERROR_ABORT unsupported */ + + /* FlowReplace */ + + pHandflow->FlowReplace = 0; + + if (currentTermios.c_iflag & IXON) + pHandflow->FlowReplace |= SERIAL_AUTO_TRANSMIT; + + if (currentTermios.c_iflag & IXOFF) + pHandflow->FlowReplace |= SERIAL_AUTO_RECEIVE; + + if (!(currentTermios.c_iflag & IGNPAR)) + pHandflow->FlowReplace |= SERIAL_ERROR_CHAR; + + if (currentTermios.c_iflag & IGNBRK) + pHandflow->FlowReplace |= SERIAL_NULL_STRIPPING; + + /* SERIAL_BREAK_CHAR unsupported */ + + if (currentTermios.c_cflag & HUPCL) + pHandflow->FlowReplace |= SERIAL_RTS_CONTROL; + + if (currentTermios.c_cflag & CRTSCTS) + pHandflow->FlowReplace |= SERIAL_RTS_HANDSHAKE; + + /* SERIAL_XOFF_CONTINUE unsupported */ + + /* XonLimit */ + + pHandflow->XonLimit = TTY_THRESHOLD_UNTHROTTLE; + + /* XoffLimit */ + + pHandflow->XoffLimit = TTY_THRESHOLD_THROTTLE; + + return TRUE; +} + +static BOOL set_timeouts(WINPR_COMM* pComm, const SERIAL_TIMEOUTS* pTimeouts) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pTimeouts); + + /* NB: timeouts are applied on system during read/write I/O */ + + /* http://msdn.microsoft.com/en-us/library/windows/hardware/hh439614%28v=vs.85%29.aspx */ + if ((pTimeouts->ReadIntervalTimeout == MAXULONG) && + (pTimeouts->ReadTotalTimeoutConstant == MAXULONG)) + { + CommLog_Print( + WLOG_WARN, + "ReadIntervalTimeout and ReadTotalTimeoutConstant cannot be both set to MAXULONG"); + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + pComm->timeouts.ReadIntervalTimeout = pTimeouts->ReadIntervalTimeout; + pComm->timeouts.ReadTotalTimeoutMultiplier = pTimeouts->ReadTotalTimeoutMultiplier; + pComm->timeouts.ReadTotalTimeoutConstant = pTimeouts->ReadTotalTimeoutConstant; + pComm->timeouts.WriteTotalTimeoutMultiplier = pTimeouts->WriteTotalTimeoutMultiplier; + pComm->timeouts.WriteTotalTimeoutConstant = pTimeouts->WriteTotalTimeoutConstant; + + CommLog_Print(WLOG_DEBUG, "ReadIntervalTimeout %" PRIu32 "", + pComm->timeouts.ReadIntervalTimeout); + CommLog_Print(WLOG_DEBUG, "ReadTotalTimeoutMultiplier %" PRIu32 "", + pComm->timeouts.ReadTotalTimeoutMultiplier); + CommLog_Print(WLOG_DEBUG, "ReadTotalTimeoutConstant %" PRIu32 "", + pComm->timeouts.ReadTotalTimeoutConstant); + CommLog_Print(WLOG_DEBUG, "WriteTotalTimeoutMultiplier %" PRIu32 "", + pComm->timeouts.WriteTotalTimeoutMultiplier); + CommLog_Print(WLOG_DEBUG, "WriteTotalTimeoutConstant %" PRIu32 "", + pComm->timeouts.WriteTotalTimeoutConstant); + + return TRUE; +} + +static BOOL get_timeouts(WINPR_COMM* pComm, SERIAL_TIMEOUTS* pTimeouts) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pTimeouts); + + pTimeouts->ReadIntervalTimeout = pComm->timeouts.ReadIntervalTimeout; + pTimeouts->ReadTotalTimeoutMultiplier = pComm->timeouts.ReadTotalTimeoutMultiplier; + pTimeouts->ReadTotalTimeoutConstant = pComm->timeouts.ReadTotalTimeoutConstant; + pTimeouts->WriteTotalTimeoutMultiplier = pComm->timeouts.WriteTotalTimeoutMultiplier; + pTimeouts->WriteTotalTimeoutConstant = pComm->timeouts.WriteTotalTimeoutConstant; + + return TRUE; +} + +static BOOL set_lines(WINPR_COMM* pComm, UINT32 lines) +{ + WINPR_ASSERT(pComm); + + if (ioctl(pComm->fd, TIOCMBIS, &lines) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TIOCMBIS ioctl failed, lines=0x%" PRIX32 ", errno=[%d] %s", lines, + errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL clear_lines(WINPR_COMM* pComm, UINT32 lines) +{ + WINPR_ASSERT(pComm); + + if (ioctl(pComm->fd, TIOCMBIC, &lines) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TIOCMBIC ioctl failed, lines=0x%" PRIX32 ", errno=[%d] %s", lines, + errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL set_dtr(WINPR_COMM* pComm) +{ + SERIAL_HANDFLOW handflow = { 0 }; + WINPR_ASSERT(pComm); + + if (!get_handflow(pComm, &handflow)) + return FALSE; + + /* SERIAL_DTR_HANDSHAKE not supported as of today */ + WINPR_ASSERT((handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE) == 0); + + if (handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + return set_lines(pComm, TIOCM_DTR); +} + +static BOOL clear_dtr(WINPR_COMM* pComm) +{ + SERIAL_HANDFLOW handflow = { 0 }; + WINPR_ASSERT(pComm); + + if (!get_handflow(pComm, &handflow)) + return FALSE; + + /* SERIAL_DTR_HANDSHAKE not supported as of today */ + WINPR_ASSERT((handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE) == 0); + + if (handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + return clear_lines(pComm, TIOCM_DTR); +} + +static BOOL set_rts(WINPR_COMM* pComm) +{ + SERIAL_HANDFLOW handflow = { 0 }; + WINPR_ASSERT(pComm); + + if (!get_handflow(pComm, &handflow)) + return FALSE; + + if (handflow.FlowReplace & SERIAL_RTS_HANDSHAKE) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + return set_lines(pComm, TIOCM_RTS); +} + +static BOOL clear_rts(WINPR_COMM* pComm) +{ + SERIAL_HANDFLOW handflow = { 0 }; + WINPR_ASSERT(pComm); + if (!get_handflow(pComm, &handflow)) + return FALSE; + + if (handflow.FlowReplace & SERIAL_RTS_HANDSHAKE) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + return clear_lines(pComm, TIOCM_RTS); +} + +static BOOL get_modemstatus(WINPR_COMM* pComm, ULONG* pRegister) +{ + UINT32 lines = 0; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pRegister); + + *pRegister = 0; + if (ioctl(pComm->fd, TIOCMGET, &lines) < 0) + { + if (!commstatus_error(pComm, "TIOCMGET")) + return FALSE; + } + + if (lines & TIOCM_CTS) + *pRegister |= SERIAL_MSR_CTS; + if (lines & TIOCM_DSR) + *pRegister |= SERIAL_MSR_DSR; + if (lines & TIOCM_RI) + *pRegister |= SERIAL_MSR_RI; + if (lines & TIOCM_CD) + *pRegister |= SERIAL_MSR_DCD; + + return TRUE; +} + +/* http://msdn.microsoft.com/en-us/library/windows/hardware/hh439605%28v=vs.85%29.aspx */ +static const ULONG SERIAL_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*/ + ; + +static BOOL is_wait_set(WINPR_COMM* pComm) +{ + WINPR_ASSERT(pComm); + + EnterCriticalSection(&pComm->EventsLock); + const BOOL isWaiting = (pComm->PendingEvents & SERIAL_EV_WINPR_WAITING) != 0; + LeaveCriticalSection(&pComm->EventsLock); + return isWaiting; +} + +static BOOL set_wait_mask(WINPR_COMM* pComm, const ULONG* pWaitMask) +{ + ULONG possibleMask = 0; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pWaitMask); + + /* Stops pending IOCTL_SERIAL_WAIT_ON_MASK + * http://msdn.microsoft.com/en-us/library/ff546805%28v=vs.85%29.aspx + */ + if (is_wait_set(pComm)) + { + /* FIXME: any doubt on reading PendingEvents out of a critical section? */ + + EnterCriticalSection(&pComm->EventsLock); + pComm->PendingEvents |= SERIAL_EV_WINPR_STOP; + LeaveCriticalSection(&pComm->EventsLock); + + /* waiting the end of the pending wait_on_mask() */ + while (is_wait_set(pComm)) + Sleep(10); /* 10ms */ + + EnterCriticalSection(&pComm->EventsLock); + pComm->PendingEvents &= (uint32_t)~SERIAL_EV_WINPR_STOP; + LeaveCriticalSection(&pComm->EventsLock); + } + + /* NB: ensure to leave the critical section before to return */ + EnterCriticalSection(&pComm->EventsLock); + + if (*pWaitMask == 0) + { + /* clearing pending events */ +#if defined(WINPR_HAVE_COMM_COUNTERS) + if (ioctl(pComm->fd, TIOCGICOUNT, &(pComm->counters)) < 0) + { + if (!commstatus_error(pComm, "TIOCGICOUNT")) + { + LeaveCriticalSection(&pComm->EventsLock); + return FALSE; + } + ZeroMemory(&(pComm->counters), sizeof(struct serial_icounter_struct)); + } +#endif + pComm->PendingEvents = 0; + } + + possibleMask = *pWaitMask & SERIAL_SYS_SUPPORTED_EV_MASK; + + if (possibleMask != *pWaitMask) + { + CommLog_Print(WLOG_WARN, + "Not all wait events supported (Serial.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; + + LeaveCriticalSection(&pComm->EventsLock); + return FALSE; + } + + pComm->WaitEventMask = possibleMask; + + LeaveCriticalSection(&pComm->EventsLock); + return TRUE; +} + +static BOOL get_wait_mask(WINPR_COMM* pComm, ULONG* pWaitMask) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pWaitMask); + + *pWaitMask = pComm->WaitEventMask; + return TRUE; +} + +static BOOL set_queue_size(WINPR_COMM* pComm, const SERIAL_QUEUE_SIZE* pQueueSize) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pQueueSize); + + if ((pQueueSize->InSize <= N_TTY_BUF_SIZE) && (pQueueSize->OutSize <= N_TTY_BUF_SIZE)) + return TRUE; /* nothing to do */ + + /* FIXME: could be implemented on top of N_TTY */ + + if (pQueueSize->InSize > N_TTY_BUF_SIZE) + CommLog_Print(WLOG_WARN, + "Requested an incompatible input buffer size: %" PRIu32 + ", keeping on with a %" PRIu32 " bytes buffer.", + pQueueSize->InSize, N_TTY_BUF_SIZE); + + if (pQueueSize->OutSize > N_TTY_BUF_SIZE) + CommLog_Print(WLOG_WARN, + "Requested an incompatible output buffer size: %" PRIu32 + ", keeping on with a %" PRIu32 " bytes buffer.", + pQueueSize->OutSize, N_TTY_BUF_SIZE); + + SetLastError(ERROR_CANCELLED); + return FALSE; +} + +static BOOL purge(WINPR_COMM* pComm, const ULONG* pPurgeMask) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pPurgeMask); + + if ((*pPurgeMask & (uint32_t)~(SERIAL_PURGE_TXABORT | SERIAL_PURGE_RXABORT | + SERIAL_PURGE_TXCLEAR | SERIAL_PURGE_RXCLEAR)) > 0) + { + CommLog_Print(WLOG_WARN, "Invalid purge mask: 0x%" PRIX32 "\n", *pPurgeMask); + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + /* FIXME: currently relying too much on the fact the server + * sends a single IRP_MJ_WRITE or IRP_MJ_READ at a time + * (taking care though that one IRP_MJ_WRITE and one + * IRP_MJ_READ can be sent simultaneously) */ + + if (*pPurgeMask & SERIAL_PURGE_TXABORT) + { + /* Purges all write (IRP_MJ_WRITE) requests. */ +#if defined(WINPR_HAVE_SYS_EVENTFD_H) + if (eventfd_write(pComm->fd_write_event, WINPR_PURGE_TXABORT) < 0) + { + if (errno != EAGAIN) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "eventfd_write failed, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + } + + WINPR_ASSERT(errno == EAGAIN); /* no reader <=> no pending IRP_MJ_WRITE */ + } +#endif + } + + if (*pPurgeMask & SERIAL_PURGE_RXABORT) + { + /* Purges all read (IRP_MJ_READ) requests. */ +#if defined(WINPR_HAVE_SYS_EVENTFD_H) + if (eventfd_write(pComm->fd_read_event, WINPR_PURGE_RXABORT) < 0) + { + if (errno != EAGAIN) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "eventfd_write failed, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + } + + WINPR_ASSERT(errno == EAGAIN); /* no reader <=> no pending IRP_MJ_READ */ + } +#endif + } + + if (*pPurgeMask & SERIAL_PURGE_TXCLEAR) + { + /* Purges the transmit buffer, if one exists. */ + + if (tcflush(pComm->fd, TCOFLUSH) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "tcflush(TCOFLUSH) failure, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_CANCELLED); + return FALSE; + } + } + + if (*pPurgeMask & SERIAL_PURGE_RXCLEAR) + { + /* Purges the receive buffer, if one exists. */ + + if (tcflush(pComm->fd, TCIFLUSH) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "tcflush(TCIFLUSH) failure, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_CANCELLED); + return FALSE; + } + } + + return TRUE; +} + +BOOL commstatus_error(WINPR_COMM* pComm, const char* ctrl) +{ + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "%s ioctl failed, errno=[%d] %s.", ctrl, errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + + if (!pComm->permissive) + { + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + return TRUE; +} + +/* NB: get_commstatus also produces most of the events consumed by wait_on_mask(). Exceptions: + * - SERIAL_EV_RXFLAG: FIXME: once EventChar supported + * + */ +static BOOL get_commstatus(WINPR_COMM* pComm, SERIAL_STATUS* pCommstatus) +{ + BOOL rc = FALSE; + /* http://msdn.microsoft.com/en-us/library/jj673022%28v=vs.85%29.aspx */ +#if defined(WINPR_HAVE_COMM_COUNTERS) + struct serial_icounter_struct currentCounters = { 0 }; +#endif + WINPR_ASSERT(pComm); + WINPR_ASSERT(pCommstatus); + + /* NB: ensure to leave the critical section before to return */ + EnterCriticalSection(&pComm->EventsLock); + + ZeroMemory(pCommstatus, sizeof(SERIAL_STATUS)); + + ULONG status = 0; + if (!get_modemstatus(pComm, &status)) + { + if (!commstatus_error(pComm, "TIOCGICOUNT")) + goto fail; + /* Errors and events based on counters could not be + * detected but keep on. + */ + SetLastError(0); + status = 0; + } + +#if defined(WINPR_HAVE_COMM_COUNTERS) + if (ioctl(pComm->fd, TIOCGICOUNT, ¤tCounters) < 0) + { + if (!commstatus_error(pComm, "TIOCGICOUNT")) + goto fail; + ZeroMemory(¤tCounters, sizeof(struct serial_icounter_struct)); + } + + /* NB: preferred below (currentCounters.* != pComm->counters.*) over (currentCounters.* > + * pComm->counters.*) thinking the counters can loop */ + + /* Errors */ + + if (currentCounters.buf_overrun != pComm->counters.buf_overrun) + { + pCommstatus->Errors |= SERIAL_ERROR_QUEUEOVERRUN; + } + + if (currentCounters.overrun != pComm->counters.overrun) + { + pCommstatus->Errors |= SERIAL_ERROR_OVERRUN; + pComm->PendingEvents |= SERIAL_EV_ERR; + } + + if (currentCounters.brk != pComm->counters.brk) + { + pCommstatus->Errors |= SERIAL_ERROR_BREAK; + pComm->PendingEvents |= SERIAL_EV_BREAK; + } + + if (currentCounters.parity != pComm->counters.parity) + { + pCommstatus->Errors |= SERIAL_ERROR_PARITY; + pComm->PendingEvents |= SERIAL_EV_ERR; + } + + if (currentCounters.frame != pComm->counters.frame) + { + pCommstatus->Errors |= SERIAL_ERROR_FRAMING; + pComm->PendingEvents |= SERIAL_EV_ERR; + } +#endif + + /* HoldReasons */ + + /* TODO: SERIAL_TX_WAITING_FOR_CTS */ + + /* TODO: SERIAL_TX_WAITING_FOR_DSR */ + + /* TODO: SERIAL_TX_WAITING_FOR_DCD */ + + /* TODO: SERIAL_TX_WAITING_FOR_XON */ + + /* TODO: SERIAL_TX_WAITING_ON_BREAK, see LCR's bit 6 */ + + /* TODO: SERIAL_TX_WAITING_XOFF_SENT */ + + /* AmountInInQueue */ + +#if defined(__linux__) + if (ioctl(pComm->fd, TIOCINQ, &(pCommstatus->AmountInInQueue)) < 0) + { + if (!commstatus_error(pComm, "TIOCINQ")) + goto fail; + } +#endif + + /* AmountInOutQueue */ + + if (ioctl(pComm->fd, TIOCOUTQ, &(pCommstatus->AmountInOutQueue)) < 0) + { + if (!commstatus_error(pComm, "TIOCOUTQ")) + goto fail; + } + + /* BOOLEAN EofReceived; FIXME: once EofChar supported */ + + /* BOOLEAN WaitForImmediate; TODO: once IOCTL_SERIAL_IMMEDIATE_CHAR fully supported */ + + /* other events based on counters */ +#if defined(WINPR_HAVE_COMM_COUNTERS) + if (currentCounters.rx != pComm->counters.rx) + { + pComm->PendingEvents |= SERIAL_EV_RXFLAG | SERIAL_EV_RXCHAR; + } + + if ((currentCounters.tx != pComm->counters.tx) && /* at least a transmission occurred AND ...*/ + (pCommstatus->AmountInOutQueue == 0)) /* output buffer is now empty */ + { + pComm->PendingEvents |= SERIAL_EV_TXEMPTY; + } + else + { + /* FIXME: "now empty" from the specs is ambiguous, need to track previous completed + * transmission? */ + pComm->PendingEvents &= (uint32_t)~SERIAL_EV_TXEMPTY; + } + + if (currentCounters.cts != pComm->counters.cts) + { + pComm->PendingEvents |= SERIAL_EV_CTS; + } + + if (currentCounters.dsr != pComm->counters.dsr) + { + pComm->PendingEvents |= SERIAL_EV_DSR; + } + + if (currentCounters.dcd != pComm->counters.dcd) + { + pComm->PendingEvents |= SERIAL_EV_RLSD; + } + + if (currentCounters.rng != pComm->counters.rng) + { + pComm->PendingEvents |= SERIAL_EV_RING; + } + + pComm->counters = currentCounters; +#endif + + if (pCommstatus->AmountInInQueue > (0.8 * N_TTY_BUF_SIZE)) + { + pComm->PendingEvents |= SERIAL_EV_RX80FULL; + } + else + { + /* FIXME: "is 80 percent full" from the specs is ambiguous, need to track when it previously + * * occurred? */ + pComm->PendingEvents &= (uint32_t)~SERIAL_EV_RX80FULL; + } + + rc = TRUE; +fail: + LeaveCriticalSection(&pComm->EventsLock); + return rc; +} + +static BOOL refresh_PendingEvents(WINPR_COMM* pComm) +{ + SERIAL_STATUS serialStatus = { 0 }; + + WINPR_ASSERT(pComm); + + /* NB: also ensures PendingEvents to be up to date */ + if (!get_commstatus(pComm, &serialStatus)) + { + return FALSE; + } + + return TRUE; +} + +static void consume_event(WINPR_COMM* pComm, ULONG* pOutputMask, ULONG event) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pOutputMask); + + if ((pComm->WaitEventMask & event) && (pComm->PendingEvents & event)) + { + pComm->PendingEvents &= ~event; /* consumed */ + *pOutputMask |= event; + } +} + +static BOOL unlock_return(WINPR_COMM* pComm, BOOL res) +{ + EnterCriticalSection(&pComm->EventsLock); + pComm->PendingEvents &= (uint32_t)~SERIAL_EV_WINPR_WAITING; + LeaveCriticalSection(&pComm->EventsLock); + return res; +} + +/* + * NB: see also: set_wait_mask() + */ +static BOOL wait_on_mask(WINPR_COMM* pComm, ULONG* pOutputMask) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(*pOutputMask == 0); + + EnterCriticalSection(&pComm->EventsLock); + pComm->PendingEvents |= SERIAL_EV_WINPR_WAITING; + LeaveCriticalSection(&pComm->EventsLock); + + while (TRUE) + { + /* NB: EventsLock also used by refresh_PendingEvents() */ + if (!refresh_PendingEvents(pComm)) + return unlock_return(pComm, FALSE); + + /* NB: ensure to leave the critical section before to return */ + EnterCriticalSection(&pComm->EventsLock); + + if (pComm->PendingEvents & SERIAL_EV_WINPR_STOP) + { + /* pOutputMask must remain empty but should + * not have been modified. + * + * http://msdn.microsoft.com/en-us/library/ff546805%28v=vs.85%29.aspx + */ + WINPR_ASSERT(*pOutputMask == 0); + + LeaveCriticalSection(&pComm->EventsLock); + break; + } + + consume_event(pComm, pOutputMask, SERIAL_EV_RXCHAR); + consume_event(pComm, pOutputMask, SERIAL_EV_RXFLAG); + consume_event(pComm, pOutputMask, SERIAL_EV_TXEMPTY); + consume_event(pComm, pOutputMask, SERIAL_EV_CTS); + consume_event(pComm, pOutputMask, SERIAL_EV_DSR); + consume_event(pComm, pOutputMask, SERIAL_EV_RLSD); + consume_event(pComm, pOutputMask, SERIAL_EV_BREAK); + consume_event(pComm, pOutputMask, SERIAL_EV_ERR); + consume_event(pComm, pOutputMask, SERIAL_EV_RING); + consume_event(pComm, pOutputMask, SERIAL_EV_RX80FULL); + + LeaveCriticalSection(&pComm->EventsLock); + + /* NOTE: PendingEvents can be modified from now on but + * not pOutputMask */ + + if (*pOutputMask != 0) + break; + + /* waiting for a modification of PendingEvents. + * + * NOTE: previously used a semaphore but used + * sem_timedwait() anyway. Finally preferred a simpler + * solution with Sleep() without the burden of the + * semaphore initialization and destroying. + */ + + Sleep(100); /* 100 ms */ + } + + return unlock_return(pComm, TRUE); +} + +static BOOL set_break_on(WINPR_COMM* pComm) +{ + WINPR_ASSERT(pComm); + if (ioctl(pComm->fd, TIOCSBRK, NULL) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TIOCSBRK ioctl failed, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL set_break_off(WINPR_COMM* pComm) +{ + WINPR_ASSERT(pComm); + if (ioctl(pComm->fd, TIOCCBRK, NULL) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TIOCSBRK ioctl failed, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL set_xoff(WINPR_COMM* pComm) +{ + WINPR_ASSERT(pComm); + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (tcflow(pComm->fd, TCIOFF) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TCIOFF failure, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL set_xon(WINPR_COMM* pComm) +{ + WINPR_ASSERT(pComm); + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (tcflow(pComm->fd, TCION) < 0) + { + char ebuffer[256] = { 0 }; + CommLog_Print(WLOG_WARN, "TCION failure, errno=[%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_IO_DEVICE); + return FALSE; + } + + return TRUE; +} + +static BOOL get_dtrrts(WINPR_COMM* pComm, ULONG* pMask) +{ + UINT32 lines = 0; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pMask); + + if (!get_modemstatus(pComm, &lines)) + return FALSE; + + *pMask = 0; + + if (!(lines & TIOCM_DTR)) + *pMask |= SERIAL_DTR_STATE; + if (!(lines & TIOCM_RTS)) + *pMask |= SERIAL_RTS_STATE; + + return TRUE; +} + +static BOOL config_size(WINPR_COMM* pComm, ULONG* pSize) +{ + WINPR_ASSERT(pComm); + WINPR_ASSERT(pSize); + + /* http://msdn.microsoft.com/en-us/library/ff546548%28v=vs.85%29.aspx */ + if (!pSize) + return FALSE; + + *pSize = 0; + return TRUE; +} + +static BOOL immediate_char(WINPR_COMM* pComm, const UCHAR* pChar) +{ + BOOL result = 0; + DWORD nbBytesWritten = 0; + + WINPR_ASSERT(pComm); + WINPR_ASSERT(pChar); + + /* FIXME: CommWriteFile uses a critical section, shall it be + * interrupted? + * + * FIXME: see also get_commstatus()'s WaitForImmediate boolean + */ + + result = CommWriteFile(pComm, pChar, 1, &nbBytesWritten, NULL); + + WINPR_ASSERT(nbBytesWritten == 1); + + return result; +} + +static BOOL reset_device(WINPR_COMM* pComm) +{ + /* http://msdn.microsoft.com/en-us/library/dn265347%28v=vs.85%29.aspx */ + return TRUE; +} + +static const SERIAL_DRIVER SerialSys = { + .id = SerialDriverSerialSys, + .name = _T("Serial.sys"), + .set_baud_rate = set_baud_rate, + .get_baud_rate = get_baud_rate, + .get_properties = get_properties, + .set_serial_chars = set_serial_chars, + .get_serial_chars = get_serial_chars, + .set_line_control = set_line_control, + .get_line_control = get_line_control, + .set_handflow = set_handflow, + .get_handflow = get_handflow, + .set_timeouts = set_timeouts, + .get_timeouts = get_timeouts, + .set_dtr = set_dtr, + .clear_dtr = clear_dtr, + .set_rts = set_rts, + .clear_rts = clear_rts, + .get_modemstatus = get_modemstatus, + .set_wait_mask = set_wait_mask, + .get_wait_mask = get_wait_mask, + .wait_on_mask = wait_on_mask, + .set_queue_size = set_queue_size, + .purge = purge, + .get_commstatus = get_commstatus, + .set_break_on = set_break_on, + .set_break_off = set_break_off, + .set_xoff = set_xoff, + .set_xon = set_xon, + .get_dtrrts = get_dtrrts, + .config_size = config_size, + .immediate_char = immediate_char, + .reset_device = reset_device, +}; + +const SERIAL_DRIVER* SerialSys_s(void) +{ + return &SerialSys; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..52b17fb20a23850368e278203cff667b656cb987 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/comm_serial_sys.h @@ -0,0 +1,36 @@ +/** + * 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. + */ + +#ifndef COMM_SERIAL_SYS_H +#define COMM_SERIAL_SYS_H + +#include "comm_ioctl.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + const SERIAL_DRIVER* SerialSys_s(void); + +#ifdef __cplusplus +} +#endif + +#endif /* COMM_SERIAL_SYS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..816f6e64b05a653c1712c3e967f1fae735819e41 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/CMakeLists.txt @@ -0,0 +1,34 @@ +set(MODULE_NAME "TestComm") +set(MODULE_PREFIX "TEST_COMM") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS + TestCommDevice.c + TestCommConfig.c + TestGetCommState.c + TestSetCommState.c + TestSerialChars.c + TestControlSettings.c + TestHandflow.c + TestTimeouts.c + TestCommMonitor.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_TESTS}) + get_filename_component(TestName ${test} NAME_WE) + add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName}) + set_tests_properties(${TestName} PROPERTIES LABELS "comm") +endforeach() + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommConfig.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommConfig.c new file mode 100644 index 0000000000000000000000000000000000000000..fcba6efbc6b1678c141fdb1ca15997cda5898e4d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommConfig.c @@ -0,0 +1,150 @@ +/** + * WinPR: Windows Portable Runtime + * Serial Communication API + * + * Copyright 2014 Marc-Andre Moreau + * 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 + +#include +#include +#include +#include +#include + +int TestCommConfig(int argc, char* argv[]) +{ + DCB dcb = { 0 }; + BOOL success = FALSE; + LPCSTR lpFileName = "\\\\.\\COM1"; + COMMPROP commProp = { 0 }; + struct stat statbuf = { 0 }; + + HANDLE hComm = + CreateFileA(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (hComm && (hComm != INVALID_HANDLE_VALUE)) + { + (void)fprintf( + stderr, "CreateFileA failure: could create a handle on a not yet defined device: %s\n", + lpFileName); + return EXIT_FAILURE; + } + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + success = DefineCommDevice(lpFileName, "/dev/ttyS0"); + if (!success) + { + (void)fprintf(stderr, "DefineCommDevice failure: %s\n", lpFileName); + return EXIT_FAILURE; + } + + hComm = CreateFileA(lpFileName, GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_WRITE, /* invalid parameter */ + NULL, CREATE_NEW, /* invalid parameter */ + 0, (HANDLE)1234); /* invalid parameter */ + if (hComm != INVALID_HANDLE_VALUE) + { + (void)fprintf( + stderr, "CreateFileA failure: could create a handle with some invalid parameters %s\n", + lpFileName); + return EXIT_FAILURE; + } + + hComm = CreateFileA(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (!hComm || (hComm == INVALID_HANDLE_VALUE)) + { + (void)fprintf(stderr, "CreateFileA failure: %s GetLastError() = 0x%08x\n", lpFileName, + GetLastError()); + return EXIT_FAILURE; + } + + /* TODO: a second call to CreateFileA should failed and + * GetLastError should return ERROR_SHARING_VIOLATION */ + + dcb.DCBlength = sizeof(DCB); + success = GetCommState(hComm, &dcb); + if (!success) + { + (void)fprintf(stderr, "GetCommState failure: GetLastError() = Ox%x\n", GetLastError()); + return EXIT_FAILURE; + } + + (void)fprintf(stderr, + "BaudRate: %" PRIu32 " ByteSize: %" PRIu8 " Parity: %" PRIu8 " StopBits: %" PRIu8 + "\n", + dcb.BaudRate, dcb.ByteSize, dcb.Parity, dcb.StopBits); + + if (!GetCommProperties(hComm, &commProp)) + { + (void)fprintf(stderr, "GetCommProperties failure: GetLastError(): 0x%08x\n", + GetLastError()); + return EXIT_FAILURE; + } + + if ((commProp.dwSettableBaud & BAUD_57600) <= 0) + { + (void)fprintf(stderr, "BAUD_57600 unsupported!\n"); + return EXIT_FAILURE; + } + + if ((commProp.dwSettableBaud & BAUD_14400) > 0) + { + (void)fprintf(stderr, "BAUD_14400 supported!\n"); + return EXIT_FAILURE; + } + + dcb.BaudRate = CBR_57600; + dcb.ByteSize = 8; + dcb.Parity = NOPARITY; + dcb.StopBits = ONESTOPBIT; + + success = SetCommState(hComm, &dcb); + + if (!success) + { + (void)fprintf(stderr, "SetCommState failure: GetLastError() = 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + success = GetCommState(hComm, &dcb); + + if (!success) + { + (void)fprintf(stderr, "GetCommState failure: GetLastError() = 0x%x\n", GetLastError()); + return 0; + } + + if ((dcb.BaudRate != CBR_57600) || (dcb.ByteSize != 8) || (dcb.Parity != NOPARITY) || + (dcb.StopBits != ONESTOPBIT)) + { + (void)fprintf(stderr, + "Got an unexpected value among: BaudRate: %" PRIu32 " ByteSize: %" PRIu8 + " Parity: %" PRIu8 " StopBits: %" PRIu8 "\n", + dcb.BaudRate, dcb.ByteSize, dcb.Parity, dcb.StopBits); + } + + (void)CloseHandle(hComm); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommDevice.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommDevice.c new file mode 100644 index 0000000000000000000000000000000000000000..370fdb03de5b635ea70dfdd6536d279d9b90610b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommDevice.c @@ -0,0 +1,114 @@ +/** + * 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 + +#include +#include + +static int test_CommDevice(LPCTSTR lpDeviceName, BOOL expectedResult) +{ + TCHAR lpTargetPath[MAX_PATH] = { 0 }; + + BOOL result = DefineCommDevice(lpDeviceName, _T("/dev/test")); + if ((!expectedResult && result) || (expectedResult && !result)) /* logical XOR */ + { + _tprintf(_T("DefineCommDevice failure: device name: %s, expected result: %s, result: %s\n"), + lpDeviceName, (expectedResult ? "TRUE" : "FALSE"), (result ? "TRUE" : "FALSE")); + + return FALSE; + } + + result = IsCommDevice(lpDeviceName); + if ((!expectedResult && result) || (expectedResult && !result)) /* logical XOR */ + { + _tprintf(_T("IsCommDevice failure: device name: %s, expected result: %s, result: %s\n"), + lpDeviceName, (expectedResult ? "TRUE" : "FALSE"), (result ? "TRUE" : "FALSE")); + + return FALSE; + } + + const size_t tclen = QueryCommDevice(lpDeviceName, lpTargetPath, MAX_PATH); + if (expectedResult) + { + const size_t tlen = _tcsnlen(lpTargetPath, ARRAYSIZE(lpTargetPath) - 1); + if (tclen <= tlen) /* at least 2 more TCHAR are expected */ + { + _tprintf(_T("QueryCommDevice failure: didn't find the device name: %s\n"), + lpDeviceName); + return FALSE; + } + + if (_tcsncmp(_T("/dev/test"), lpTargetPath, ARRAYSIZE(lpTargetPath)) != 0) + { + _tprintf( + _T("QueryCommDevice failure: device name: %s, expected result: %s, result: %s\n"), + lpDeviceName, _T("/dev/test"), lpTargetPath); + + return FALSE; + } + + if ((tlen >= (ARRAYSIZE(lpTargetPath) - 1)) || (lpTargetPath[tlen + 1] != 0)) + { + _tprintf(_T("QueryCommDevice failure: device name: %s, the second NULL character is ") + _T("missing at the end of the buffer\n"), + lpDeviceName); + return FALSE; + } + } + else + { + if (tclen > 0) + { + _tprintf(_T("QueryCommDevice failure: device name: %s, expected result: , ") + _T("result: %") _T(PRIuz) _T(" %s\n"), + lpDeviceName, tclen, lpTargetPath); + + return FALSE; + } + } + + return TRUE; +} + +int TestCommDevice(int argc, char* argv[]) +{ + if (!test_CommDevice(_T("COM0"), FALSE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("COM1"), TRUE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("COM1"), TRUE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("COM10"), FALSE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("\\\\.\\COM5"), TRUE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("\\\\.\\COM10"), TRUE)) + return EXIT_FAILURE; + + if (!test_CommDevice(_T("\\\\.COM10"), FALSE)) + return EXIT_FAILURE; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommMonitor.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommMonitor.c new file mode 100644 index 0000000000000000000000000000000000000000..33c722df9a0a753f7ea00b978c914685115e065e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestCommMonitor.c @@ -0,0 +1,70 @@ + +#include +#include +#include +#include +#include + +int TestCommMonitor(int argc, char* argv[]) +{ + HANDLE hComm = NULL; + DWORD dwError = 0; + BOOL fSuccess = 0; + DWORD dwEvtMask = 0; + OVERLAPPED overlapped = { 0 }; + LPCSTR lpFileName = "\\\\.\\COM1"; + + hComm = CreateFileA(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, NULL); + + if (!hComm || (hComm == INVALID_HANDLE_VALUE)) + { + printf("CreateFileA failure: %s\n", lpFileName); + return -1; + } + + fSuccess = SetCommMask(hComm, EV_CTS | EV_DSR); + + if (!fSuccess) + { + printf("SetCommMask failure: GetLastError() = %" PRIu32 "\n", GetLastError()); + return -1; + } + + if (!(overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("CreateEvent failed: GetLastError() = %" PRIu32 "\n", GetLastError()); + return -1; + } + + if (WaitCommEvent(hComm, &dwEvtMask, &overlapped)) + { + if (dwEvtMask & EV_DSR) + { + printf("EV_DSR\n"); + } + + if (dwEvtMask & EV_CTS) + { + printf("EV_CTS\n"); + } + } + else + { + dwError = GetLastError(); + + if (dwError == ERROR_IO_PENDING) + { + printf("ERROR_IO_PENDING\n"); + } + else + { + printf("WaitCommEvent failure: GetLastError() = %" PRIu32 "\n", dwError); + return -1; + } + } + + (void)CloseHandle(hComm); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestControlSettings.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestControlSettings.c new file mode 100644 index 0000000000000000000000000000000000000000..1a1ad269b5a8fae0235f1e7af87a39b5223a50a4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestControlSettings.c @@ -0,0 +1,123 @@ +/** + * 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 + +#include + +#include +#include + +#include "../comm.h" + +int TestControlSettings(int argc, char* argv[]) +{ + struct stat statbuf = { 0 }; + BOOL result = 0; + HANDLE hComm = NULL; + DCB dcb = { 0 }; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + (void)fprintf(stderr, "DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (hComm == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + /* Test 1 */ + + dcb.ByteSize = 5; + dcb.StopBits = ONESTOPBIT; + dcb.Parity = MARKPARITY; + + if (!SetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "SetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + if ((dcb.ByteSize != 5) || (dcb.StopBits != ONESTOPBIT) || (dcb.Parity != MARKPARITY)) + { + (void)fprintf(stderr, "test1 failed.\n"); + return FALSE; + } + + /* Test 2 */ + + dcb.ByteSize = 8; + dcb.StopBits = ONESTOPBIT; + dcb.Parity = NOPARITY; + + if (!SetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "SetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + if ((dcb.ByteSize != 8) || (dcb.StopBits != ONESTOPBIT) || (dcb.Parity != NOPARITY)) + { + (void)fprintf(stderr, "test2 failed.\n"); + return FALSE; + } + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestGetCommState.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestGetCommState.c new file mode 100644 index 0000000000000000000000000000000000000000..914911053b8bffd574b93c145a9adf8c51ee7498 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestGetCommState.c @@ -0,0 +1,139 @@ +/** + * 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 +#include + +#include +#include + +#include "../comm.h" + +static BOOL test_generic(HANDLE hComm) +{ + DCB dcb = { 0 }; + DCB* pDcb = NULL; + BOOL result = 0; + + ZeroMemory(&dcb, sizeof(DCB)); + result = GetCommState(hComm, &dcb); + if (result) + { + printf("GetCommState failure, should have returned false because dcb.DCBlength has been " + "let uninitialized\n"); + return FALSE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB) / 2; /* improper value */ + result = GetCommState(hComm, &dcb); + if (result) + { + printf("GetCommState failure, should have return false because dcb.DCBlength was not " + "correctly initialized\n"); + return FALSE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB); + result = GetCommState(hComm, &dcb); + if (!result) + { + printf("GetCommState failure: Ox%x, with adjusted DCBlength\n", GetLastError()); + return FALSE; + } + + pDcb = (DCB*)calloc(2, sizeof(DCB)); + if (!pDcb) + return FALSE; + pDcb->DCBlength = sizeof(DCB) * 2; + result = GetCommState(hComm, pDcb); + result = result && (pDcb->DCBlength == sizeof(DCB) * 2); + free(pDcb); + if (!result) + { + printf("GetCommState failure: 0x%x, with bigger DCBlength\n", GetLastError()); + return FALSE; + } + + return TRUE; +} + +int TestGetCommState(int argc, char* argv[]) +{ + struct stat statbuf = { 0 }; + BOOL result = 0; + HANDLE hComm = NULL; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + printf("DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFileA("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (hComm == INVALID_HANDLE_VALUE) + { + printf("CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + if (!test_generic(hComm)) + { + printf("test_generic failure (SerialDriverUnknown)\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerialSys); + if (!test_generic(hComm)) + { + printf("test_generic failure (SerialDriverSerialSys)\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCxSys); + if (!test_generic(hComm)) + { + printf("test_generic failure (SerialDriverSerCxSys)\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCx2Sys); + if (!test_generic(hComm)) + { + printf("test_generic failure (SerialDriverSerCx2Sys)\n"); + return EXIT_FAILURE; + } + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestHandflow.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestHandflow.c new file mode 100644 index 0000000000000000000000000000000000000000..6e7f7330fa3d1d9c1acfa64346487fe4e3060bfc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestHandflow.c @@ -0,0 +1,92 @@ +/** + * 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 +#include + +#ifndef _WIN32 +#include +#endif + +#include +#include + +#include "../comm.h" + +static BOOL test_SerialSys(HANDLE hComm) +{ + // TMP: TODO: + return TRUE; +} + +int TestHandflow(int argc, char* argv[]) +{ + struct stat statbuf = { 0 }; + BOOL result = 0; + HANDLE hComm = NULL; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + (void)fprintf(stderr, "DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (hComm == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerialSys); + if (!test_SerialSys(hComm)) + { + (void)fprintf(stderr, "test_SerCxSys failure\n"); + return EXIT_FAILURE; + } + + /* _comm_setServerSerialDriver(hComm, SerialDriverSerCxSys); */ + /* if (!test_SerCxSys(hComm)) */ + /* { */ + /* (void)fprintf(stderr, "test_SerCxSys failure\n"); */ + /* return EXIT_FAILURE; */ + /* } */ + + /* _comm_setServerSerialDriver(hComm, SerialDriverSerCx2Sys); */ + /* if (!test_SerCx2Sys(hComm)) */ + /* { */ + /* (void)fprintf(stderr, "test_SerCxSys failure\n"); */ + /* return EXIT_FAILURE; */ + /* } */ + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSerialChars.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSerialChars.c new file mode 100644 index 0000000000000000000000000000000000000000..aebcbfce3905d9f6a5e18eba2883800bc882152d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSerialChars.c @@ -0,0 +1,180 @@ +/** + * 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 +#include + +#ifndef _WIN32 +#include +#endif + +#include +#include + +#include "../comm.h" + +static BOOL test_SerCxSys(HANDLE hComm) +{ + DCB dcb = { 0 }; + UCHAR XonChar = 0; + UCHAR XoffChar = 0; + + struct termios currentTermios = { 0 }; + + if (tcgetattr(((WINPR_COMM*)hComm)->fd, ¤tTermios) < 0) + { + (void)fprintf(stderr, "tcgetattr failure.\n"); + return FALSE; + } + + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure, GetLastError(): 0x%08x\n", GetLastError()); + return FALSE; + } + + if ((dcb.XonChar == '\0') || (dcb.XoffChar == '\0')) + { + (void)fprintf(stderr, "test_SerCxSys failure, expected XonChar and XoffChar to be set\n"); + return FALSE; + } + + /* retrieve Xon/Xoff chars */ + if ((dcb.XonChar != currentTermios.c_cc[VSTART]) || + (dcb.XoffChar != currentTermios.c_cc[VSTOP])) + { + (void)fprintf(stderr, "test_SerCxSys failure, could not retrieve XonChar and XoffChar\n"); + return FALSE; + } + + /* swap XonChar/XoffChar */ + + XonChar = dcb.XonChar; + XoffChar = dcb.XoffChar; + dcb.XonChar = XoffChar; + dcb.XoffChar = XonChar; + if (!SetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "SetCommState failure, GetLastError(): 0x%08x\n", GetLastError()); + return FALSE; + } + + ZeroMemory(&dcb, sizeof(DCB)); + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure, GetLastError(): 0x%08x\n", GetLastError()); + return FALSE; + } + + if ((dcb.XonChar != XoffChar) || (dcb.XoffChar != XonChar)) + { + (void)fprintf(stderr, "test_SerCxSys, expected XonChar and XoffChar to be swapped\n"); + return FALSE; + } + + /* same XonChar / XoffChar */ + dcb.XonChar = dcb.XoffChar; + if (SetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, + "test_SerCxSys failure, SetCommState() was supposed to failed because " + "XonChar and XoffChar are the same\n"); + return FALSE; + } + if (GetLastError() != ERROR_INVALID_PARAMETER) + { + (void)fprintf(stderr, "test_SerCxSys failure, SetCommState() was supposed to failed with " + "GetLastError()=ERROR_INVALID_PARAMETER\n"); + return FALSE; + } + + return TRUE; +} + +static BOOL test_SerCx2Sys(HANDLE hComm) +{ + DCB dcb = { 0 }; + + dcb.DCBlength = sizeof(DCB); + if (!GetCommState(hComm, &dcb)) + { + (void)fprintf(stderr, "GetCommState failure; GetLastError(): %08x\n", GetLastError()); + return FALSE; + } + + if ((dcb.ErrorChar != '\0') || (dcb.EofChar != '\0') || (dcb.EvtChar != '\0') || + (dcb.XonChar != '\0') || (dcb.XoffChar != '\0')) + { + (void)fprintf(stderr, "test_SerCx2Sys failure, expected all characters to be: '\\0'\n"); + return FALSE; + } + + return TRUE; +} + +int TestSerialChars(int argc, char* argv[]) +{ + struct stat statbuf = { 0 }; + BOOL result = 0; + HANDLE hComm = NULL; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + (void)fprintf(stderr, "DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (hComm == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCxSys); + if (!test_SerCxSys(hComm)) + { + (void)fprintf(stderr, "test_SerCxSys failure\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCx2Sys); + if (!test_SerCx2Sys(hComm)) + { + (void)fprintf(stderr, "test_SerCxSys failure\n"); + return EXIT_FAILURE; + } + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSetCommState.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSetCommState.c new file mode 100644 index 0000000000000000000000000000000000000000..5b5d298d540ab1f0a64509198ce305329766d728 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestSetCommState.c @@ -0,0 +1,335 @@ +/** + * 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 +#include + +#include +#include + +#include "../comm.h" + +static void init_empty_dcb(DCB* pDcb) +{ + WINPR_ASSERT(pDcb); + + ZeroMemory(pDcb, sizeof(DCB)); + pDcb->DCBlength = sizeof(DCB); + pDcb->XonChar = 1; + pDcb->XoffChar = 2; +} + +static BOOL test_fParity(HANDLE hComm) +{ + DCB dcb = { 0 }; + BOOL result = 0; + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + /* test 1 */ + dcb.fParity = TRUE; + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + if (!dcb.fParity) + { + (void)fprintf(stderr, "unexpected fParity: %" PRIu32 " instead of TRUE\n", dcb.fParity); + return FALSE; + } + + /* test 2 */ + dcb.fParity = FALSE; + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + if (dcb.fParity) + { + (void)fprintf(stderr, "unexpected fParity: %" PRIu32 " instead of FALSE\n", dcb.fParity); + return FALSE; + } + + /* test 3 (redo test 1) */ + dcb.fParity = TRUE; + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%08" PRIx32 "\n", GetLastError()); + return FALSE; + } + + if (!dcb.fParity) + { + (void)fprintf(stderr, "unexpected fParity: %" PRIu32 " instead of TRUE\n", dcb.fParity); + return FALSE; + } + + return TRUE; +} + +static BOOL test_SerialSys(HANDLE hComm) +{ + DCB dcb = { 0 }; + BOOL result = 0; + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + + /* Test 1 */ + dcb.BaudRate = CBR_115200; + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%08x\n", GetLastError()); + return FALSE; + } + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + if (dcb.BaudRate != CBR_115200) + { + (void)fprintf(stderr, "SetCommState failure: could not set BaudRate=%d (CBR_115200)\n", + CBR_115200); + return FALSE; + } + + /* Test 2 using a different baud rate */ + + dcb.BaudRate = CBR_57600; + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + if (dcb.BaudRate != CBR_57600) + { + (void)fprintf(stderr, "SetCommState failure: could not set BaudRate=%d (CBR_57600)\n", + CBR_57600); + return FALSE; + } + + /* Test 3 using an unsupported baud rate on Linux */ + dcb.BaudRate = CBR_128000; + result = SetCommState(hComm, &dcb); + if (result) + { + (void)fprintf(stderr, + "SetCommState failure: unexpected support of BaudRate=%d (CBR_128000)\n", + CBR_128000); + return FALSE; + } + + return TRUE; +} + +static BOOL test_SerCxSys(HANDLE hComm) +{ + /* as of today there is no difference */ + return test_SerialSys(hComm); +} + +static BOOL test_SerCx2Sys(HANDLE hComm) +{ + /* as of today there is no difference */ + return test_SerialSys(hComm); +} + +static BOOL test_generic(HANDLE hComm) +{ + DCB dcb = { 0 }; + DCB dcb2 = { 0 }; + BOOL result = 0; + + init_empty_dcb(&dcb); + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + + /* Checks whether we get the same information before and after SetCommState */ + memcpy(&dcb2, &dcb, sizeof(DCB)); + result = SetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "SetCommState failure: 0x%08x\n", GetLastError()); + return FALSE; + } + + result = GetCommState(hComm, &dcb); + if (!result) + { + (void)fprintf(stderr, "GetCommState failure: 0x%x\n", GetLastError()); + return FALSE; + } + + if (memcmp(&dcb, &dcb2, sizeof(DCB)) != 0) + { + (void)fprintf(stderr, + "DCB is different after SetCommState() whereas it should have not changed\n"); + return FALSE; + } + + // TODO: a more complete and generic test using GetCommProperties() + + /* TMP: TODO: fBinary tests */ + + /* fParity tests */ + if (!test_fParity(hComm)) + { + (void)fprintf(stderr, "test_fParity failure\n"); + return FALSE; + } + + return TRUE; +} + +int TestSetCommState(int argc, char* argv[]) +{ + struct stat statbuf = { 0 }; + BOOL result = 0; + HANDLE hComm = NULL; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + (void)fprintf(stderr, "DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (hComm == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_generic failure (SerialDriverUnknown)\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerialSys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_generic failure (SerialDriverSerialSys)\n"); + return EXIT_FAILURE; + } + if (!test_SerialSys(hComm)) + { + (void)fprintf(stderr, "test_SerialSys failure\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCxSys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_generic failure (SerialDriverSerCxSys)\n"); + return EXIT_FAILURE; + } + if (!test_SerCxSys(hComm)) + { + (void)fprintf(stderr, "test_SerCxSys failure\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCx2Sys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_generic failure (SerialDriverSerCx2Sys)\n"); + return EXIT_FAILURE; + } + if (!test_SerCx2Sys(hComm)) + { + (void)fprintf(stderr, "test_SerCx2Sys failure\n"); + return EXIT_FAILURE; + } + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestTimeouts.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestTimeouts.c new file mode 100644 index 0000000000000000000000000000000000000000..76a5dec248227caa92bfccd2e24a58f78449f8da --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/comm/test/TestTimeouts.c @@ -0,0 +1,141 @@ +/** + * 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 +#include + +#ifndef _WIN32 +#include +#endif + +#include +#include + +#include "../comm.h" + +static BOOL test_generic(HANDLE hComm) +{ + COMMTIMEOUTS timeouts = { 0 }; + COMMTIMEOUTS timeouts2 = { 0 }; + + timeouts.ReadIntervalTimeout = 1; + timeouts.ReadTotalTimeoutMultiplier = 2; + timeouts.ReadTotalTimeoutConstant = 3; + timeouts.WriteTotalTimeoutMultiplier = 4; + timeouts.WriteTotalTimeoutConstant = 5; + + if (!SetCommTimeouts(hComm, &timeouts)) + { + (void)fprintf(stderr, "SetCommTimeouts failure, GetLastError: 0x%08x\n", GetLastError()); + return FALSE; + } + + if (!GetCommTimeouts(hComm, &timeouts2)) + { + (void)fprintf(stderr, "GetCommTimeouts failure, GetLastError: 0x%08x\n", GetLastError()); + return FALSE; + } + + if (memcmp(&timeouts, &timeouts2, sizeof(COMMTIMEOUTS)) != 0) + { + (void)fprintf(stderr, "TestTimeouts failure, didn't get back the same timeouts.\n"); + return FALSE; + } + + /* not supported combination */ + timeouts.ReadIntervalTimeout = MAXULONG; + timeouts.ReadTotalTimeoutConstant = MAXULONG; + if (SetCommTimeouts(hComm, &timeouts)) + { + (void)fprintf( + stderr, + "SetCommTimeouts succeeded with ReadIntervalTimeout and ReadTotalTimeoutConstant " + "set to MAXULONG. GetLastError: 0x%08x\n", + GetLastError()); + return FALSE; + } + + if (GetLastError() != ERROR_INVALID_PARAMETER) + { + (void)fprintf( + stderr, + "SetCommTimeouts failure, expected GetLastError to return ERROR_INVALID_PARAMETER " + "and got: 0x%08x\n", + GetLastError()); + return FALSE; + } + + return TRUE; +} + +int TestTimeouts(int argc, char* argv[]) +{ + struct stat statbuf; + BOOL result = 0; + HANDLE hComm = NULL; + + if (stat("/dev/ttyS0", &statbuf) < 0) + { + (void)fprintf(stderr, "/dev/ttyS0 not available, making the test to succeed though\n"); + return EXIT_SUCCESS; + } + + result = DefineCommDevice("COM1", "/dev/ttyS0"); + if (!result) + { + (void)fprintf(stderr, "DefineCommDevice failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (hComm == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "CreateFileA failure: 0x%x\n", GetLastError()); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerialSys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_SerialSys failure\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCxSys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_SerCxSys failure\n"); + return EXIT_FAILURE; + } + + _comm_setServerSerialDriver(hComm, SerialDriverSerCx2Sys); + if (!test_generic(hComm)) + { + (void)fprintf(stderr, "test_SerCx2Sys failure\n"); + return EXIT_FAILURE; + } + + if (!CloseHandle(hComm)) + { + (void)fprintf(stderr, "CloseHandle failure, GetLastError()=%08x\n", GetLastError()); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6318d529fb5d1785636a8ded8033a67741e4ec4f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/CMakeLists.txt @@ -0,0 +1,49 @@ +# WinPR: Windows Portable Runtime +# libwinpr-crt cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(CRT_FILES + alignment.c + conversion.c + buffer.c + memory.c + unicode.c + string.c + assert.c +) + +if(WITH_UNICODE_BUILTIN) + list(APPEND CRT_FILES unicode_builtin.c) +else() + if(ANDROID) + list(APPEND CRT_FILES unicode_android.c) + elseif(NOT APPLE AND NOT WIN32) + find_package(ICU REQUIRED i18n uc io data) + list(APPEND CRT_FILES unicode_icu.c) + winpr_system_include_directory_add(${ICU_INCLUDE_DIRS}) + winpr_library_add_private(${ICU_LIBRARIES}) + elseif(APPLE) + list(APPEND CRT_FILES unicode_apple.m) + find_library(FOUNDATION_FRAMEWORK Foundation REQUIRED) + winpr_library_add_private(${FOUNDATION_FRAMEWORK}) + endif() +endif() + +winpr_module_add(${CRT_FILES}) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..827ff7386b72a7c7027782d69534f9f56c15bbdc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/ModuleOptions.cmake @@ -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 "crt") +set(MINWIN_LONG_NAME "Microsoft C Run-Time") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/alignment.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/alignment.c new file mode 100644 index 0000000000000000000000000000000000000000..04907098310ac7cd2b0ac1b73b77b231e46c6e3f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/alignment.c @@ -0,0 +1,260 @@ +/** + * WinPR: Windows Portable Runtime + * Data Alignment + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +/* Data Alignment: http://msdn.microsoft.com/en-us/library/fs9stz4e/ */ + +#if !defined(_WIN32) || (defined(__MINGW32__) && !defined(_UCRT)) + +#include +#include + +#define WINPR_ALIGNED_MEM_SIGNATURE 0x0BA0BAB + +#define WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(_memptr) \ + (WINPR_ALIGNED_MEM*)(((size_t)(((BYTE*)(_memptr)) - sizeof(WINPR_ALIGNED_MEM)))) + +#include + +#include "../log.h" +#define TAG WINPR_TAG("crt") + +struct winpr_aligned_mem +{ + UINT32 sig; + size_t size; + void* base_addr; +}; +typedef struct winpr_aligned_mem WINPR_ALIGNED_MEM; + +void* winpr_aligned_malloc(size_t size, size_t alignment) +{ + return winpr_aligned_offset_malloc(size, alignment, 0); +} + +void* winpr_aligned_calloc(size_t count, size_t size, size_t alignment) +{ + return winpr_aligned_recalloc(NULL, count, size, alignment); +} + +void* winpr_aligned_realloc(void* memblock, size_t size, size_t alignment) +{ + return winpr_aligned_offset_realloc(memblock, size, alignment, 0); +} + +void* winpr_aligned_recalloc(void* memblock, size_t num, size_t size, size_t alignment) +{ + return winpr_aligned_offset_recalloc(memblock, num, size, alignment, 0); +} + +void* winpr_aligned_offset_malloc(size_t size, size_t alignment, size_t offset) +{ + size_t header = 0; + size_t alignsize = 0; + uintptr_t basesize = 0; + void* base = NULL; + void* memblock = NULL; + WINPR_ALIGNED_MEM* pMem = NULL; + + /* alignment must be a power of 2 */ + if (alignment % 2 == 1) + return NULL; + + /* offset must be less than size */ + if (offset >= size) + return NULL; + + /* minimum alignment is pointer size */ + if (alignment < sizeof(void*)) + alignment = sizeof(void*); + + if (alignment > SIZE_MAX - sizeof(WINPR_ALIGNED_MEM)) + return NULL; + + header = sizeof(WINPR_ALIGNED_MEM) + alignment; + + if (size > SIZE_MAX - header) + return NULL; + + alignsize = size + header; + /* malloc size + alignment to make sure we can align afterwards */ +#if defined(_ISOC11_SOURCE) + base = aligned_alloc(alignment, alignsize); +#elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L) || (_XOPEN_SOURCE >= 600) + if (posix_memalign(&base, alignment, alignsize) != 0) + return NULL; +#else + base = malloc(alignsize); +#endif + if (!base) + return NULL; + + basesize = (uintptr_t)base; + + if ((offset > UINTPTR_MAX) || (header > UINTPTR_MAX - offset) || + (basesize > UINTPTR_MAX - header - offset)) + { + free(base); + return NULL; + } + + memblock = (void*)(((basesize + header + offset) & ~(alignment - 1)) - offset); + pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock); + pMem->sig = WINPR_ALIGNED_MEM_SIGNATURE; + pMem->base_addr = base; + pMem->size = size; + return memblock; +} + +void* winpr_aligned_offset_realloc(void* memblock, size_t size, size_t alignment, size_t offset) +{ + size_t copySize = 0; + void* newMemblock = NULL; + WINPR_ALIGNED_MEM* pMem = NULL; + WINPR_ALIGNED_MEM* pNewMem = NULL; + + if (!memblock) + return winpr_aligned_offset_malloc(size, alignment, offset); + + pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock); + + if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE) + { + WLog_ERR(TAG, + "_aligned_offset_realloc: memory block was not allocated by _aligned_malloc!"); + return NULL; + } + + if (size == 0) + { + winpr_aligned_free(memblock); + return NULL; + } + + newMemblock = winpr_aligned_offset_malloc(size, alignment, offset); + + if (!newMemblock) + return NULL; + + pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock); + copySize = (pNewMem->size < pMem->size) ? pNewMem->size : pMem->size; + CopyMemory(newMemblock, memblock, copySize); + winpr_aligned_free(memblock); + return newMemblock; +} + +static INLINE size_t cMIN(size_t a, size_t b) +{ + if (a > b) + return b; + return a; +} + +void* winpr_aligned_offset_recalloc(void* memblock, size_t num, size_t size, size_t alignment, + size_t offset) +{ + char* newMemblock = NULL; + WINPR_ALIGNED_MEM* pMem = NULL; + WINPR_ALIGNED_MEM* pNewMem = NULL; + + if (!memblock) + { + newMemblock = winpr_aligned_offset_malloc(size * num, alignment, offset); + + if (newMemblock) + { + pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock); + ZeroMemory(newMemblock, pNewMem->size); + } + + return newMemblock; + } + + pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock); + + if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE) + { + WLog_ERR(TAG, + "_aligned_offset_recalloc: memory block was not allocated by _aligned_malloc!"); + goto fail; + } + + if ((num == 0) || (size == 0)) + goto fail; + + if (pMem->size > (1ull * num * size) + alignment) + return memblock; + + newMemblock = winpr_aligned_offset_malloc(size * num, alignment, offset); + + if (!newMemblock) + goto fail; + + pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock); + { + const size_t csize = cMIN(pMem->size, pNewMem->size); + memcpy(newMemblock, memblock, csize); + ZeroMemory(newMemblock + csize, pNewMem->size - csize); + } +fail: + winpr_aligned_free(memblock); + return newMemblock; +} + +size_t winpr_aligned_msize(void* memblock, size_t alignment, size_t offset) +{ + WINPR_ALIGNED_MEM* pMem = NULL; + + if (!memblock) + return 0; + + pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock); + + if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE) + { + WLog_ERR(TAG, "_aligned_msize: memory block was not allocated by _aligned_malloc!"); + return 0; + } + + return pMem->size; +} + +void winpr_aligned_free(void* memblock) +{ + WINPR_ALIGNED_MEM* pMem = NULL; + + if (!memblock) + return; + + pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock); + + if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE) + { + WLog_ERR(TAG, "_aligned_free: memory block was not allocated by _aligned_malloc!"); + return; + } + + free(pMem->base_addr); +} + +#endif /* _WIN32 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/assert.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/assert.c new file mode 100644 index 0000000000000000000000000000000000000000..bfc4684320d2c5d9dadfff679872484f7c6593e9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/assert.c @@ -0,0 +1,31 @@ +/** + * WinPR: Windows Portable Runtime + * Runtime ASSERT macros + * + * Copyright 2021 Armin Novak + * 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. + */ + +#include +#include +#include + +void winpr_int_assert(const char* condstr, const char* file, const char* fkt, size_t line) +{ + wLog* _log_cached_ptr = WLog_Get("com.freerdp.winpr.assert"); + WLog_Print(_log_cached_ptr, WLOG_FATAL, "%s [%s:%s:%" PRIuz "]", condstr, file, fkt, line); + winpr_log_backtrace_ex(_log_cached_ptr, WLOG_FATAL, 20); + abort(); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/buffer.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..fc914c9e838272b872c078f597a22c51f33dcced --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/buffer.c @@ -0,0 +1,50 @@ +/** + * WinPR: Windows Portable Runtime + * Buffer Manipulation + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +/* Buffer Manipulation: http://msdn.microsoft.com/en-us/library/b3893xdy/ */ + +#ifndef _WIN32 + +#include + +errno_t memmove_s(void* dest, size_t numberOfElements, const void* src, size_t count) +{ + if (count > numberOfElements) + return -1; + + memmove(dest, src, count); + + return 0; +} + +errno_t wmemmove_s(WCHAR* dest, size_t numberOfElements, const WCHAR* src, size_t count) +{ + if (count * 2 > numberOfElements) + return -1; + + memmove(dest, src, count * 2); + + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/casing.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/casing.h new file mode 100644 index 0000000000000000000000000000000000000000..36485ab668352d07a0a001deaf7562e22fff790b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/casing.h @@ -0,0 +1,726 @@ +/** + * Unicode case mappings + * + * This code is generated by wine's make_unicode script + * which downloads data from unicode.org and produces + * readily usable conversion tables. + * + * After asking permission from Alexandre Julliard in May 2011, + * it was clarified that no copyright was claimed by the wine + * project on the script's generated output. + */ + +#define WINPR_TOLOWERW(_wch) \ + (_wch + winpr_casemap_lower[winpr_casemap_lower[_wch >> 8] + (_wch & 0xFF)]) + +#define WINPR_TOUPPERW(_wch) \ + (_wch + winpr_casemap_upper[winpr_casemap_upper[_wch >> 8] + (_wch & 0xFF)]) + +static const WCHAR winpr_casemap_lower[3807] = { + /* index */ + 0x01bf, 0x02bf, 0x03bf, 0x044f, 0x054f, 0x064f, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x06af, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x07af, 0x08ae, 0x0100, 0x09ab, 0x0100, 0x0100, + 0x0a2f, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0b2f, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0c22, 0x0d00, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0ddf, + /* defaults */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0041 .. 0x00ff */ + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0000, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0100 .. 0x01ff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0xff39, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0xff87, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x00d2, 0x0001, 0x0000, + 0x0001, 0x0000, 0x00ce, 0x0001, 0x0000, 0x00cd, 0x00cd, 0x0001, 0x0000, 0x0000, 0x004f, 0x00ca, + 0x00cb, 0x0001, 0x0000, 0x00cd, 0x00cf, 0x0000, 0x00d3, 0x00d1, 0x0001, 0x0000, 0x0000, 0x0000, + 0x00d3, 0x00d5, 0x0000, 0x00d6, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x00da, 0x0001, + 0x0000, 0x00da, 0x0000, 0x0000, 0x0001, 0x0000, 0x00da, 0x0001, 0x0000, 0x00d9, 0x00d9, 0x0001, + 0x0000, 0x0001, 0x0000, 0x00db, 0x0001, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0000, 0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0xff9f, 0xffc8, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, + /* 0x0200 .. 0x02ff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0xff7e, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2a2b, 0x0001, + 0x0000, 0xff5d, 0x2a28, 0x0000, 0x0000, 0x0001, 0x0000, 0xff3d, 0x0045, 0x0047, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0370 .. 0x03ff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0026, 0x0000, + 0x0025, 0x0025, 0x0025, 0x0000, 0x0040, 0x0000, 0x003f, 0x003f, 0x0000, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0000, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0xffc4, 0x0000, 0x0000, 0x0001, 0x0000, 0xfff9, 0x0001, 0x0000, 0x0000, 0xff7e, 0xff7e, 0xff7e, + /* 0x0400 .. 0x04ff */ + 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, + 0x0050, 0x0050, 0x0050, 0x0050, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x000f, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, + /* 0x0500 .. 0x05ff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x10a0 .. 0x10ff */ + 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, + 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, + 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, 0x1c60, + 0x1c60, 0x1c60, 0x0000, 0x1c60, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1c60, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x1e00 .. 0x1eff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0xe241, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, + /* 0x1f01 .. 0x1fff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, 0x0000, 0xfff8, 0x0000, 0xfff8, 0x0000, 0xfff8, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, + 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0xfff8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xffb6, 0xffb6, 0xfff7, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffaa, 0xffaa, 0xffaa, 0xffaa, 0xfff7, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xfff8, + 0xfff8, 0xff9c, 0xff9c, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xfff8, 0xfff8, 0xff90, 0xff90, 0xfff9, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xff80, 0xff80, 0xff82, 0xff82, 0xfff7, + 0x0000, 0x0000, 0x0000, + /* 0x2103 .. 0x21ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xe2a3, + 0x0000, 0x0000, 0x0000, 0xdf41, 0xdfba, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x001c, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0010, 0x0010, 0x0010, + 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, + 0x0010, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, + /* 0x247c .. 0x24ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x001a, 0x001a, + 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, + 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, 0x001a, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x2c00 .. 0x2cff */ + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, + 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0001, 0x0000, 0xd609, 0xf11a, 0xd619, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0xd5e4, 0xd603, 0xd5e1, 0xd5e2, 0x0000, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xd5c1, 0xd5c1, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0xa60d .. 0xa6ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, + 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, + /* 0xa722 .. 0xa7ff */ + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x75fc, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x5ad8, + 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, + 0x0001, 0x0000, 0x0001, 0x0000, 0x5abc, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0xff21 .. 0xffff */ + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, + 0x0020, 0x0020, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 +}; +static const WCHAR winpr_casemap_upper[3994] = { + /* index */ + 0x019f, 0x029f, 0x039f, 0x045a, 0x0556, 0x0656, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x06dd, 0x07dc, 0x08dc, 0x0100, 0x09d0, 0x0100, 0x0100, + 0x0a55, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0b3f, 0x0c3f, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0cfe, 0x0ddb, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, + 0x0100, 0x0100, 0x0100, 0x0e9a, + /* defaults */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0061 .. 0x00ff */ + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x02e7, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0x0000, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0x0079, + /* 0x0100 .. 0x01ff */ + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xff18, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0xfed4, 0x00c3, 0x0000, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0061, 0x0000, 0x0000, 0x0000, 0xffff, 0x00a3, 0x0000, + 0x0000, 0x0000, 0x0082, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, + 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0038, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0xfffe, 0x0000, 0xffff, 0xfffe, 0x0000, 0xffff, + 0xfffe, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0xffb1, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0x0000, 0xffff, 0xfffe, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, + /* 0x0200 .. 0x02ff */ + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0xffff, 0x0000, 0x0000, 0x2a3f, 0x2a3f, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x2a1f, 0x2a1c, 0x2a1e, 0xff2e, + 0xff32, 0x0000, 0xff33, 0xff33, 0x0000, 0xff36, 0x0000, 0xff35, 0x0000, 0x0000, 0x0000, 0x0000, + 0xff33, 0x0000, 0x0000, 0xff31, 0x0000, 0xa528, 0xa544, 0x0000, 0xff2f, 0xff2d, 0x0000, 0x29f7, + 0x0000, 0x0000, 0x0000, 0xff2d, 0x0000, 0x29fd, 0xff2b, 0x0000, 0x0000, 0xff2a, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x29e7, 0x0000, 0x0000, 0xff26, 0x0000, 0x0000, 0xff26, + 0x0000, 0x0000, 0x0000, 0x0000, 0xff26, 0xffbb, 0xff27, 0xff27, 0xffb9, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0xff25, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0345 .. 0x03ff */ + 0x0054, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0082, 0x0082, 0x0082, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffda, 0xffdb, 0xffdb, 0xffdb, 0x0000, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe1, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffc0, 0xffc1, 0xffc1, 0x0000, 0xffc2, 0xffc7, 0x0000, 0x0000, 0x0000, + 0xffd1, 0xffca, 0xfff8, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0xffaa, 0xffb0, 0x0007, 0x0000, 0x0000, 0xffa0, 0x0000, 0x0000, 0xffff, + 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x0404 .. 0x04ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, + 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0xffb0, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0xfff1, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + /* 0x0500 .. 0x05ff */ + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x1d79 .. 0x1dff */ + 0x8a04, 0x0000, 0x0000, 0x0000, 0x0ee6, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, + /* 0x1e01 .. 0x1eff */ + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffc5, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, + /* 0x1f00 .. 0x1fff */ + 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000, 0x0008, + 0x0000, 0x0008, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x004a, 0x004a, 0x0056, 0x0056, 0x0056, 0x0056, 0x0064, 0x0064, + 0x0080, 0x0080, 0x0070, 0x0070, 0x007e, 0x007e, 0x0000, 0x0000, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0009, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xe3db, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0009, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0000, + 0x0000, 0x0007, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0009, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x210c .. 0x21ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffe4, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, + 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0xfff0, 0x0000, 0x0000, 0x0000, 0x0000, + 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x247b .. 0x24ff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, + 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, 0xffe6, + 0xffe6, 0xffe6, 0xffe6, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, + /* 0x2c16 .. 0x2cff */ + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, 0xffd0, + 0xffd0, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0xd5d5, 0xd5d8, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, + 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, + 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0x2d00 .. 0x2dff */ + 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, + 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, + 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, 0xe3a0, + 0xe3a0, 0xe3a0, 0x0000, 0xe3a0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xe3a0, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, + /* 0xa641 .. 0xa6ff */ + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0xa723 .. 0xa7ff */ + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, + 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, + 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + /* 0xff41 .. 0xffff */ + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, 0xffe0, + 0xffe0, 0xffe0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 +}; diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/conversion.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/conversion.c new file mode 100644 index 0000000000000000000000000000000000000000..26044e57fba24de59b54fc387813efc10b0bf274 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/conversion.c @@ -0,0 +1,44 @@ +/** + * WinPR: Windows Portable Runtime + * Data Conversion + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +/* Data Conversion: http://msdn.microsoft.com/en-us/library/0heszx3w/ */ + +#ifndef _WIN32 + +errno_t _itoa_s(int value, char* buffer, size_t sizeInCharacters, int radix) +{ + int length = sprintf_s(NULL, 0, "%d", value); + + if (length < 0) + return -1; + + if (sizeInCharacters < (size_t)length) + return -1; + + (void)sprintf_s(buffer, WINPR_ASSERTING_INT_CAST(size_t, length + 1), "%d", value); + + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/memory.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/memory.c new file mode 100644 index 0000000000000000000000000000000000000000..ffe62bff2609d6d0ffedd3aab65ba06f9eb0b00d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/memory.c @@ -0,0 +1,42 @@ +/** + * WinPR: Windows Portable Runtime + * Memory Allocation + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +/* Memory Allocation: http://msdn.microsoft.com/en-us/library/hk1k7x6x.aspx */ +/* Memory Management Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366781/ */ + +#ifndef _WIN32 + +PVOID SecureZeroMemory(PVOID ptr, size_t cnt) +{ + volatile BYTE* p = ptr; + + while (cnt--) + { + *p = 0; + p++; + } + + return ptr; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/string.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/string.c new file mode 100644 index 0000000000000000000000000000000000000000..2e4c60de2e2198ed967fc6bd17a6dc309549d517 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/string.c @@ -0,0 +1,847 @@ +/** + * WinPR: Windows Portable Runtime + * String Manipulation (CRT) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include +#include +#include + +#include +#include + +#if defined(WITH_URIPARSER) +#include +#endif + +/* String Manipulation (CRT): http://msdn.microsoft.com/en-us/library/f0151s4x.aspx */ + +#include "../log.h" +#define TAG WINPR_TAG("crt") + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +#if defined(WITH_URIPARSER) +char* winpr_str_url_decode(const char* str, size_t len) +{ + char* dst = strndup(str, len); + if (!dst) + return NULL; + + if (!uriUnescapeInPlaceExA(dst, URI_FALSE, URI_FALSE)) + { + free(dst); + return NULL; + } + + return dst; +} + +char* winpr_str_url_encode(const char* str, size_t len) +{ + char* dst = calloc(len + 1, sizeof(char) * 3); + if (!dst) + return NULL; + + if (!uriEscapeA(str, dst, URI_FALSE, URI_FALSE)) + { + free(dst); + return NULL; + } + return dst; +} + +#else +static const char rfc3986[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x2e, 0x00, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x5f, + 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x00, 0x00, 0x00, 0x7e, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +static char hex2bin(char what) +{ + if (what >= 'a') + what -= 'a' - 'A'; + if (what >= 'A') + what -= ('A' - 10); + else + what -= '0'; + return what; +} + +static char unescape(const char* what, size_t* px) +{ + if ((*what == '%') && (isxdigit(what[1]) && isxdigit(what[2]))) + { + *px += 2; + return 16 * hex2bin(what[1]) + hex2bin(what[2]); + } + + return *what; +} + +char* winpr_str_url_decode(const char* str, size_t len) +{ + char* dst = calloc(len + 1, sizeof(char)); + if (!dst) + return NULL; + + size_t pos = 0; + for (size_t x = 0; x < strnlen(str, len); x++) + { + const char* cur = &str[x]; + dst[pos++] = unescape(cur, &x); + } + return dst; +} + +static char* escape(char* dst, char what) +{ + if (rfc3986[what & 0xff]) + { + *dst = what; + return dst + 1; + } + + sprintf(dst, "%%%02" PRIX8, (BYTE)(what & 0xff)); + return dst + 3; +} + +char* winpr_str_url_encode(const char* str, size_t len) +{ + char* dst = calloc(len + 1, sizeof(char) * 3); + if (!dst) + return NULL; + + char* ptr = dst; + for (size_t x = 0; x < strnlen(str, len); x++) + { + const char cur = str[x]; + ptr = escape(ptr, cur); + } + return dst; +} +#endif + +BOOL winpr_str_append(const char* what, char* buffer, size_t size, const char* separator) +{ + const size_t used = strnlen(buffer, size); + const size_t add = strnlen(what, size); + const size_t sep_len = separator ? strnlen(separator, size) : 0; + const size_t sep = (used > 0) ? sep_len : 0; + + if (used + add + sep >= size) + return FALSE; + + if ((used > 0) && (sep_len > 0)) + strncat(buffer, separator, sep_len); + + strncat(buffer, what, add); + return TRUE; +} + +WINPR_ATTR_FORMAT_ARG(3, 4) +int winpr_asprintf(char** s, size_t* slen, WINPR_FORMAT_ARG const char* templ, ...) +{ + va_list ap = { 0 }; + + va_start(ap, templ); + int rc = winpr_vasprintf(s, slen, templ, ap); + va_end(ap); + return rc; +} + +WINPR_ATTR_FORMAT_ARG(3, 0) +int winpr_vasprintf(char** s, size_t* slen, WINPR_FORMAT_ARG const char* templ, va_list oap) +{ + va_list ap = { 0 }; + + *s = NULL; + *slen = 0; + + va_copy(ap, oap); + const int length = vsnprintf(NULL, 0, templ, ap); + va_end(ap); + if (length < 0) + return length; + + char* str = calloc((size_t)length + 1UL, sizeof(char)); + if (!str) + return -1; + + va_copy(ap, oap); + const int plen = vsnprintf(str, (size_t)length + 1UL, templ, ap); + va_end(ap); + + if (length != plen) + { + free(str); + return -1; + } + *s = str; + *slen = (size_t)length; + return length; +} + +#ifndef _WIN32 + +char* _strdup(const char* strSource) +{ + if (strSource == NULL) + return NULL; + + char* strDestination = strdup(strSource); + + if (strDestination == NULL) + WLog_ERR(TAG, "strdup"); + + return strDestination; +} + +WCHAR* _wcsdup(const WCHAR* strSource) +{ + if (!strSource) + return NULL; + + size_t len = _wcslen(strSource); + WCHAR* strDestination = calloc(len + 1, sizeof(WCHAR)); + + if (strDestination != NULL) + memcpy(strDestination, strSource, len * sizeof(WCHAR)); + + if (strDestination == NULL) + WLog_ERR(TAG, "wcsdup"); + + return strDestination; +} + +WCHAR* _wcsncat(WCHAR* dst, const WCHAR* src, size_t sz) +{ + WINPR_ASSERT(dst); + WINPR_ASSERT(src || (sz == 0)); + + const size_t dlen = _wcslen(dst); + const size_t slen = _wcsnlen(src, sz); + for (size_t x = 0; x < slen; x++) + dst[dlen + x] = src[x]; + dst[dlen + slen] = '\0'; + return dst; +} + +int _stricmp(const char* string1, const char* string2) +{ + return strcasecmp(string1, string2); +} + +int _strnicmp(const char* string1, const char* string2, size_t count) +{ + return strncasecmp(string1, string2, count); +} + +/* _wcscmp -> wcscmp */ + +int _wcscmp(const WCHAR* string1, const WCHAR* string2) +{ + WINPR_ASSERT(string1); + WINPR_ASSERT(string2); + + while (TRUE) + { + const WCHAR w1 = *string1++; + const WCHAR w2 = *string2++; + + if (w1 != w2) + return (int)w1 - w2; + else if ((w1 == '\0') || (w2 == '\0')) + return (int)w1 - w2; + } +} + +int _wcsncmp(const WCHAR* string1, const WCHAR* string2, size_t count) +{ + WINPR_ASSERT(string1); + WINPR_ASSERT(string2); + + for (size_t x = 0; x < count; x++) + { + const WCHAR a = string1[x]; + const WCHAR b = string2[x]; + + if (a != b) + return (int)a - b; + else if ((a == '\0') || (b == '\0')) + return (int)a - b; + } + return 0; +} + +/* _wcslen -> wcslen */ + +size_t _wcslen(const WCHAR* str) +{ + const WCHAR* p = str; + + WINPR_ASSERT(p); + + while (*p) + p++; + + return (size_t)(p - str); +} + +/* _wcsnlen -> wcsnlen */ + +size_t _wcsnlen(const WCHAR* str, size_t max) +{ + WINPR_ASSERT(str); + + size_t x = 0; + for (; x < max; x++) + { + if (str[x] == 0) + return x; + } + + return x; +} + +/* _wcsstr -> wcsstr */ + +WCHAR* _wcsstr(const WCHAR* str, const WCHAR* strSearch) +{ + WINPR_ASSERT(str); + WINPR_ASSERT(strSearch); + + if (strSearch[0] == '\0') + return WINPR_CAST_CONST_PTR_AWAY(str, WCHAR*); + + const size_t searchLen = _wcslen(strSearch); + while (*str) + { + if (_wcsncmp(str, strSearch, searchLen) == 0) + return WINPR_CAST_CONST_PTR_AWAY(str, WCHAR*); + str++; + } + return NULL; +} + +/* _wcschr -> wcschr */ + +WCHAR* _wcschr(const WCHAR* str, WCHAR c) +{ + union + { + const WCHAR* cc; + WCHAR* c; + } cnv; + const WCHAR* p = str; + + while (*p && (*p != c)) + p++; + + cnv.cc = (*p == c) ? p : NULL; + return cnv.c; +} + +/* _wcsrchr -> wcsrchr */ + +WCHAR* _wcsrchr(const WCHAR* str, WCHAR c) +{ + union + { + const WCHAR* cc; + WCHAR* c; + } cnv; + const WCHAR* p = NULL; + + if (!str) + return NULL; + + for (; *str != '\0'; str++) + { + const WCHAR ch = *str; + if (ch == c) + p = str; + } + + cnv.cc = p; + return cnv.c; +} + +char* strtok_s(char* strToken, const char* strDelimit, char** context) +{ + return strtok_r(strToken, strDelimit, context); +} + +WCHAR* wcstok_s(WCHAR* strToken, const WCHAR* strDelimit, WCHAR** context) +{ + WCHAR* nextToken = NULL; + WCHAR value = 0; + + if (!strToken) + strToken = *context; + + value = *strToken; + + while (*strToken && _wcschr(strDelimit, value)) + { + strToken++; + value = *strToken; + } + + if (!*strToken) + return NULL; + + nextToken = strToken++; + value = *strToken; + + while (*strToken && !(_wcschr(strDelimit, value))) + { + strToken++; + value = *strToken; + } + + if (*strToken) + *strToken++ = 0; + + *context = strToken; + return nextToken; +} + +#endif + +#if !defined(_WIN32) || defined(_UWP) + +/* Windows API Sets - api-ms-win-core-string-l2-1-0.dll + * http://msdn.microsoft.com/en-us/library/hh802935/ + */ + +#include "casing.h" + +LPSTR CharUpperA(LPSTR lpsz) +{ + size_t length = 0; + + if (!lpsz) + return NULL; + + length = strlen(lpsz); + + if (length < 1) + return (LPSTR)NULL; + + if (length == 1) + { + char c = *lpsz; + + if ((c >= 'a') && (c <= 'z')) + c = (char)(c - 'a' + 'A'); + + *lpsz = c; + return lpsz; + } + + for (size_t i = 0; i < length; i++) + { + if ((lpsz[i] >= 'a') && (lpsz[i] <= 'z')) + lpsz[i] = (char)(lpsz[i] - 'a' + 'A'); + } + + return lpsz; +} + +LPWSTR CharUpperW(LPWSTR lpsz) +{ + size_t length = 0; + + if (!lpsz) + return NULL; + + length = _wcslen(lpsz); + + if (length < 1) + return (LPWSTR)NULL; + + if (length == 1) + { + WCHAR c = *lpsz; + + if ((c >= L'a') && (c <= L'z')) + c = c - L'a' + L'A'; + + *lpsz = c; + return lpsz; + } + + for (size_t i = 0; i < length; i++) + { + if ((lpsz[i] >= L'a') && (lpsz[i] <= L'z')) + lpsz[i] = lpsz[i] - L'a' + L'A'; + } + + return lpsz; +} + +DWORD CharUpperBuffA(LPSTR lpsz, DWORD cchLength) +{ + if (cchLength < 1) + return 0; + + for (DWORD i = 0; i < cchLength; i++) + { + if ((lpsz[i] >= 'a') && (lpsz[i] <= 'z')) + lpsz[i] = (char)(lpsz[i] - 'a' + 'A'); + } + + return cchLength; +} + +DWORD CharUpperBuffW(LPWSTR lpsz, DWORD cchLength) +{ + for (DWORD i = 0; i < cchLength; i++) + { + WCHAR value = winpr_Data_Get_UINT16(&lpsz[i]); + value = WINPR_TOUPPERW(value); + winpr_Data_Write_UINT16(&lpsz[i], value); + } + + return cchLength; +} + +LPSTR CharLowerA(LPSTR lpsz) +{ + size_t length = 0; + + if (!lpsz) + return (LPSTR)NULL; + + length = strlen(lpsz); + + if (length < 1) + return (LPSTR)NULL; + + if (length == 1) + { + char c = *lpsz; + + if ((c >= 'A') && (c <= 'Z')) + c = (char)(c - 'A' + 'a'); + + *lpsz = c; + return lpsz; + } + + for (size_t i = 0; i < length; i++) + { + if ((lpsz[i] >= 'A') && (lpsz[i] <= 'Z')) + lpsz[i] = (char)(lpsz[i] - 'A' + 'a'); + } + + return lpsz; +} + +LPWSTR CharLowerW(LPWSTR lpsz) +{ + const size_t len = _wcsnlen(lpsz, UINT32_MAX + 1); + if (len > UINT32_MAX) + return NULL; + CharLowerBuffW(lpsz, (UINT32)len); + return lpsz; +} + +DWORD CharLowerBuffA(LPSTR lpsz, DWORD cchLength) +{ + if (cchLength < 1) + return 0; + + for (DWORD i = 0; i < cchLength; i++) + { + if ((lpsz[i] >= 'A') && (lpsz[i] <= 'Z')) + lpsz[i] = (char)(lpsz[i] - 'A' + 'a'); + } + + return cchLength; +} + +DWORD CharLowerBuffW(LPWSTR lpsz, DWORD cchLength) +{ + for (DWORD i = 0; i < cchLength; i++) + { + WCHAR value = winpr_Data_Get_UINT16(&lpsz[i]); + value = WINPR_TOLOWERW(value); + winpr_Data_Write_UINT16(&lpsz[i], value); + } + + return cchLength; +} + +BOOL IsCharAlphaA(CHAR ch) +{ + if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) + return 1; + else + return 0; +} + +BOOL IsCharAlphaW(WCHAR ch) +{ + if (((ch >= L'a') && (ch <= L'z')) || ((ch >= L'A') && (ch <= L'Z'))) + return 1; + else + return 0; +} + +BOOL IsCharAlphaNumericA(CHAR ch) +{ + if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) || + ((ch >= '0') && (ch <= '9'))) + return 1; + else + return 0; +} + +BOOL IsCharAlphaNumericW(WCHAR ch) +{ + if (((ch >= L'a') && (ch <= L'z')) || ((ch >= L'A') && (ch <= L'Z')) || + ((ch >= L'0') && (ch <= L'9'))) + return 1; + else + return 0; +} + +BOOL IsCharUpperA(CHAR ch) +{ + if ((ch >= 'A') && (ch <= 'Z')) + return 1; + else + return 0; +} + +BOOL IsCharUpperW(WCHAR ch) +{ + if ((ch >= L'A') && (ch <= L'Z')) + return 1; + else + return 0; +} + +BOOL IsCharLowerA(CHAR ch) +{ + if ((ch >= 'a') && (ch <= 'z')) + return 1; + else + return 0; +} + +BOOL IsCharLowerW(WCHAR ch) +{ + if ((ch >= L'a') && (ch <= L'z')) + return 1; + else + return 0; +} + +#endif + +size_t ConvertLineEndingToLF(char* str, size_t size) +{ + size_t skip = 0; + + WINPR_ASSERT(str || (size == 0)); + for (size_t x = 0; x < size; x++) + { + char c = str[x]; + switch (c) + { + case '\r': + str[x - skip] = '\n'; + if ((x + 1 < size) && (str[x + 1] == '\n')) + skip++; + break; + default: + str[x - skip] = c; + break; + } + } + return size - skip; +} + +char* ConvertLineEndingToCRLF(const char* str, size_t* size) +{ + WINPR_ASSERT(size); + const size_t s = *size; + WINPR_ASSERT(str || (s == 0)); + + *size = 0; + if (s == 0) + return NULL; + + size_t linebreaks = 0; + for (size_t x = 0; x < s - 1; x++) + { + char c = str[x]; + switch (c) + { + case '\r': + case '\n': + linebreaks++; + break; + default: + break; + } + } + char* cnv = calloc(s + linebreaks * 2ull + 1ull, sizeof(char)); + if (!cnv) + return NULL; + + size_t pos = 0; + for (size_t x = 0; x < s; x++) + { + const char c = str[x]; + switch (c) + { + case '\r': + cnv[pos++] = '\r'; + cnv[pos++] = '\n'; + break; + case '\n': + /* Do not duplicate existing \r\n sequences */ + if ((x > 0) && (str[x - 1] != '\r')) + { + cnv[pos++] = '\r'; + cnv[pos++] = '\n'; + } + break; + default: + cnv[pos++] = c; + break; + } + } + *size = pos; + return cnv; +} + +char* StrSep(char** stringp, const char* delim) +{ + char* start = *stringp; + char* p = NULL; + p = (start != NULL) ? strpbrk(start, delim) : NULL; + + if (!p) + *stringp = NULL; + else + { + *p = '\0'; + *stringp = p + 1; + } + + return start; +} + +INT64 GetLine(char** lineptr, size_t* size, FILE* stream) +{ +#if defined(_WIN32) + char c; + char* n; + size_t step = 32; + size_t used = 0; + + if (!lineptr || !size) + { + errno = EINVAL; + return -1; + } + + do + { + if (used + 2 >= *size) + { + *size += step; + n = realloc(*lineptr, *size); + + if (!n) + { + return -1; + } + + *lineptr = n; + } + + c = fgetc(stream); + + if (c != EOF) + (*lineptr)[used++] = c; + } while ((c != '\n') && (c != '\r') && (c != EOF)); + + (*lineptr)[used] = '\0'; + return used; +#elif !defined(ANDROID) && !defined(IOS) + return getline(lineptr, size, stream); +#else + return -1; +#endif +} + +#if !defined(WINPR_HAVE_STRNDUP) +char* strndup(const char* src, size_t n) +{ + char* dst = calloc(n + 1, sizeof(char)); + if (dst) + strncpy(dst, src, n); + return dst; +} +#endif + +const WCHAR* InitializeConstWCharFromUtf8(const char* str, WCHAR* buffer, size_t len) +{ + WINPR_ASSERT(str); + WINPR_ASSERT(buffer || (len == 0)); + (void)ConvertUtf8ToWChar(str, buffer, len); + return buffer; +} + +WCHAR* wcsndup(const WCHAR* s, size_t n) +{ + if (!s) + return NULL; + + WCHAR* copy = calloc(n + 1, sizeof(WCHAR)); + if (!copy) + return NULL; + memcpy(copy, s, n * sizeof(WCHAR)); + return copy; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..83571933848457da7065b07f433f3202f26197d6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestCrt") +set(MODULE_PREFIX "TEST_CRT") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestTypes.c TestFormatSpecifiers.c TestAlignment.c TestString.c TestUnicodeConversion.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestAlignment.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestAlignment.c new file mode 100644 index 0000000000000000000000000000000000000000..07bac7f8d5f9b428bb9dd25186a9d1f4c1b10425 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestAlignment.c @@ -0,0 +1,87 @@ + +#include +#include +#include + +int TestAlignment(int argc, char* argv[]) +{ + void* ptr = NULL; + size_t alignment = 0; + size_t offset = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Alignment should be 2^N where N is a positive integer */ + + alignment = 16; + offset = 8; + + /* _aligned_malloc */ + + ptr = winpr_aligned_malloc(100, alignment); + + if (ptr == NULL) + { + printf("Error allocating aligned memory.\n"); + return -1; + } + + if (((size_t)ptr % alignment) != 0) + { + printf("This pointer, %p, is not aligned on %" PRIuz "\n", ptr, alignment); + return -1; + } + + /* _aligned_realloc */ + + ptr = winpr_aligned_realloc(ptr, 200, alignment); + + if (((size_t)ptr % alignment) != 0) + { + printf("This pointer, %p, is not aligned on %" PRIuz "\n", ptr, alignment); + return -1; + } + + winpr_aligned_free(ptr); + + /* _aligned_offset_malloc */ + + ptr = winpr_aligned_offset_malloc(200, alignment, offset); + + if (ptr == NULL) + { + printf("Error reallocating aligned offset memory."); + return -1; + } + + if (((((size_t)ptr) + offset) % alignment) != 0) + { + printf("This pointer, %p, does not satisfy offset %" PRIuz " and alignment %" PRIuz "\n", + ptr, offset, alignment); + return -1; + } + + /* _aligned_offset_realloc */ + + ptr = winpr_aligned_offset_realloc(ptr, 200, alignment, offset); + + if (ptr == NULL) + { + printf("Error reallocating aligned offset memory."); + return -1; + } + + if (((((size_t)ptr) + offset) % alignment) != 0) + { + printf("This pointer, %p, does not satisfy offset %" PRIuz " and alignment %" PRIuz "\n", + ptr, offset, alignment); + return -1; + } + + /* _aligned_free works for both _aligned_malloc and _aligned_offset_malloc. free() should not be + * used. */ + winpr_aligned_free(ptr); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestFormatSpecifiers.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestFormatSpecifiers.c new file mode 100644 index 0000000000000000000000000000000000000000..cc5603446429eba843a3cb5cf84f9a4e274a902d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestFormatSpecifiers.c @@ -0,0 +1,169 @@ +#include +#include +#include + +int TestFormatSpecifiers(int argc, char* argv[]) +{ + unsigned errors = 0; + + char fmt[4096]; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* size_t */ + { + size_t arg = 0xabcd; + const char* chk = "uz:43981 oz:125715 xz:abcd Xz:ABCD"; + + (void)sprintf_s(fmt, sizeof(fmt), "uz:%" PRIuz " oz:%" PRIoz " xz:%" PRIxz " Xz:%" PRIXz "", + arg, arg, arg, arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed size_t test: got [%s] instead of [%s]\n", __func__, + fmt, chk); + errors++; + } + } + + /* INT8 */ + { + INT8 arg = -16; + const char* chk = "d8:-16 x8:f0 X8:F0"; + + (void)sprintf_s(fmt, sizeof(fmt), "d8:%" PRId8 " x8:%" PRIx8 " X8:%" PRIX8 "", arg, + (UINT8)arg, (UINT8)arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed INT8 test: got [%s] instead of [%s]\n", __func__, fmt, + chk); + errors++; + } + } + + /* UINT8 */ + { + UINT8 arg = 0xFE; + const char* chk = "u8:254 o8:376 x8:fe X8:FE"; + + (void)sprintf_s(fmt, sizeof(fmt), "u8:%" PRIu8 " o8:%" PRIo8 " x8:%" PRIx8 " X8:%" PRIX8 "", + arg, arg, arg, arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed UINT8 test: got [%s] instead of [%s]\n", __func__, fmt, + chk); + errors++; + } + } + + /* INT16 */ + { + INT16 arg = -16; + const char* chk = "d16:-16 x16:fff0 X16:FFF0"; + + (void)sprintf_s(fmt, sizeof(fmt), "d16:%" PRId16 " x16:%" PRIx16 " X16:%" PRIX16 "", arg, + (UINT16)arg, (UINT16)arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed INT16 test: got [%s] instead of [%s]\n", __func__, fmt, + chk); + errors++; + } + } + + /* UINT16 */ + { + UINT16 arg = 0xFFFE; + const char* chk = "u16:65534 o16:177776 x16:fffe X16:FFFE"; + + (void)sprintf_s(fmt, sizeof(fmt), + "u16:%" PRIu16 " o16:%" PRIo16 " x16:%" PRIx16 " X16:%" PRIX16 "", arg, arg, + arg, arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed UINT16 test: got [%s] instead of [%s]\n", __func__, + fmt, chk); + errors++; + } + } + + /* INT32 */ + { + INT32 arg = -16; + const char* chk = "d32:-16 x32:fffffff0 X32:FFFFFFF0"; + + (void)sprintf_s(fmt, sizeof(fmt), "d32:%" PRId32 " x32:%" PRIx32 " X32:%" PRIX32 "", arg, + (UINT32)arg, (UINT32)arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed INT32 test: got [%s] instead of [%s]\n", __func__, fmt, + chk); + errors++; + } + } + + /* UINT32 */ + { + UINT32 arg = 0xFFFFFFFE; + const char* chk = "u32:4294967294 o32:37777777776 x32:fffffffe X32:FFFFFFFE"; + + (void)sprintf_s(fmt, sizeof(fmt), + "u32:%" PRIu32 " o32:%" PRIo32 " x32:%" PRIx32 " X32:%" PRIX32 "", arg, arg, + arg, arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed UINT16 test: got [%s] instead of [%s]\n", __func__, + fmt, chk); + errors++; + } + } + + /* INT64 */ + { + INT64 arg = -16; + const char* chk = "d64:-16 x64:fffffffffffffff0 X64:FFFFFFFFFFFFFFF0"; + + (void)sprintf_s(fmt, sizeof(fmt), "d64:%" PRId64 " x64:%" PRIx64 " X64:%" PRIX64 "", arg, + (UINT64)arg, (UINT64)arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed INT64 test: got [%s] instead of [%s]\n", __func__, fmt, + chk); + errors++; + } + } + + /* UINT64 */ + { + UINT64 arg = 0xFFFFFFFFFFFFFFFE; + const char* chk = "u64:18446744073709551614 o64:1777777777777777777776 " + "x64:fffffffffffffffe X64:FFFFFFFFFFFFFFFE"; + + (void)sprintf_s(fmt, sizeof(fmt), + "u64:%" PRIu64 " o64:%" PRIo64 " x64:%016" PRIx64 " X64:%016" PRIX64 "", + arg, arg, arg, arg); + + if (strcmp(fmt, chk) != 0) + { + (void)fprintf(stderr, "%s failed UINT64 test: got [%s] instead of [%s]\n", __func__, + fmt, chk); + errors++; + } + } + + if (errors) + { + (void)fprintf(stderr, "%s produced %u errors\n", __func__, errors); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestString.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestString.c new file mode 100644 index 0000000000000000000000000000000000000000..e77bf02dabc57377cf7c5563db8ae8fae0e4a298 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestString.c @@ -0,0 +1,222 @@ + +#include +#include +#include +#include + +static const CHAR testStringA[] = { 'T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ' ', 'b', + 'r', 'o', 'w', 'n', ' ', 'f', 'o', 'x', ' ', 'j', 'u', + 'm', 'p', 's', ' ', 'o', 'v', 'e', 'r', ' ', 't', 'h', + 'e', ' ', 'l', 'a', 'z', 'y', ' ', 'd', 'o', 'g', '\0' }; + +#define testStringA_Length ((sizeof(testStringA) / sizeof(CHAR)) - 1) + +static const CHAR testToken1A[] = { 'q', 'u', 'i', 'c', 'k', '\0' }; +static const CHAR testToken2A[] = { 'b', 'r', 'o', 'w', 'n', '\0' }; +static const CHAR testToken3A[] = { 'f', 'o', 'x', '\0' }; + +#define testToken1A_Length ((sizeof(testToken1A) / sizeof(CHAR)) - 1) +#define testToken2A_Length ((sizeof(testToken2A) / sizeof(CHAR)) - 1) +#define testToken3A_Length ((sizeof(testToken3A) / sizeof(CHAR)) - 1) + +static const CHAR testTokensA[] = { 'q', 'u', 'i', 'c', 'k', '\r', '\n', 'b', 'r', 'o', + 'w', 'n', '\r', '\n', 'f', 'o', 'x', '\r', '\n', '\0' }; + +#define testTokensA_Length ((sizeof(testTokensA) / sizeof(CHAR)) - 1) + +static const CHAR testDelimiterA[] = { '\r', '\n', '\0' }; + +#define testDelimiterA_Length ((sizeof(testDelimiter) / sizeof(CHAR)) - 1) + +struct url_test_pair +{ + const char* what; + const char* escaped; +}; + +static const struct url_test_pair url_tests[] = { + { "xxx%bar gaee#%%#%{h}g{f{e%d|c\\b^a~p[q]r`s;t/u?v:w@x=y&z$xxx", + "xxx%25bar%20ga%3Cka%3Eee%23%25%25%23%25%7Bh%7Dg%7Bf%7Be%25d%7Cc%5Cb%5Ea~p%5Bq%5Dr%60s%3Bt%" + "2Fu%3Fv%3Aw%40x%3Dy%26z%24xxx" }, + { "äöúëü", "%C3%A4%C3%B6%C3%BA%C3%AB%C3%BC" }, + { "🎅🏄🤘😈", "%F0%9F%8E%85%F0%9F%8F%84%F0%9F%A4%98%F0%9F%98%88" }, + { "foo$.%.^.&.\\.txt+", "foo%24.%25.%5E.%26.%5C.txt%2B" } +}; + +static BOOL test_url_escape(void) +{ + for (size_t x = 0; x < ARRAYSIZE(url_tests); x++) + { + const struct url_test_pair* cur = &url_tests[x]; + + char* escaped = winpr_str_url_encode(cur->what, strlen(cur->what) + 1); + char* what = winpr_str_url_decode(cur->escaped, strlen(cur->escaped) + 1); + + const size_t elen = strlen(escaped); + const size_t wlen = strlen(what); + const size_t pelen = strlen(cur->escaped); + const size_t pwlen = strlen(cur->what); + BOOL rc = TRUE; + if (!escaped || (elen != pelen) || (strcmp(escaped, cur->escaped) != 0)) + { + printf("expected: [%" PRIuz "] %s\n", pelen, cur->escaped); + printf("got : [%" PRIuz "] %s\n", elen, escaped); + rc = FALSE; + } + else if (!what || (wlen != pwlen) || (strcmp(what, cur->what) != 0)) + { + printf("expected: [%" PRIuz "] %s\n", pwlen, cur->what); + printf("got : [%" PRIuz "] %s\n", wlen, what); + rc = FALSE; + } + + free(escaped); + free(what); + if (!rc) + return FALSE; + } + + return TRUE; +} + +static BOOL test_winpr_asprintf(void) +{ + BOOL rc = FALSE; + const char test[] = "test string case"; + const size_t len = strnlen(test, sizeof(test)); + + char* str = NULL; + size_t slen = 0; + const int res = winpr_asprintf(&str, &slen, "%s", test); + if (!str) + goto fail; + if (res < 0) + goto fail; + if ((size_t)res != len) + goto fail; + if (len != slen) + goto fail; + if (strnlen(str, slen + 10) != slen) + goto fail; + rc = TRUE; +fail: + free(str); + return rc; +} + +int TestString(int argc, char* argv[]) +{ + const WCHAR* p = NULL; + size_t pos = 0; + size_t length = 0; + WCHAR* context = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_winpr_asprintf()) + return -1; + + if (!test_url_escape()) + return -1; + + /* _wcslen */ + WCHAR testStringW[ARRAYSIZE(testStringA)] = { 0 }; + (void)ConvertUtf8NToWChar(testStringA, ARRAYSIZE(testStringA), testStringW, + ARRAYSIZE(testStringW)); + const size_t testStringW_Length = testStringA_Length; + length = _wcslen(testStringW); + + if (length != testStringW_Length) + { + printf("_wcslen error: length mismatch: Actual: %" PRIuz ", Expected: %" PRIuz "\n", length, + testStringW_Length); + return -1; + } + + /* _wcschr */ + union + { + char c[2]; + WCHAR w; + } search; + search.c[0] = 'r'; + search.c[1] = '\0'; + + p = _wcschr(testStringW, search.w); + pos = (p - testStringW); + + if (pos != 11) + { + printf("_wcschr error: position mismatch: Actual: %" PRIuz ", Expected: 11\n", pos); + return -1; + } + + p = _wcschr(&testStringW[pos + 1], search.w); + pos = (p - testStringW); + + if (pos != 29) + { + printf("_wcschr error: position mismatch: Actual: %" PRIuz ", Expected: 29\n", pos); + return -1; + } + + p = _wcschr(&testStringW[pos + 1], search.w); + + if (p != NULL) + { + printf("_wcschr error: return value mismatch: Actual: %p, Expected: NULL\n", + (const void*)p); + return -1; + } + + /* wcstok_s */ + WCHAR testDelimiterW[ARRAYSIZE(testDelimiterA)] = { 0 }; + WCHAR testTokensW[ARRAYSIZE(testTokensA)] = { 0 }; + (void)ConvertUtf8NToWChar(testTokensA, ARRAYSIZE(testTokensA), testTokensW, + ARRAYSIZE(testTokensW)); + (void)ConvertUtf8NToWChar(testDelimiterA, ARRAYSIZE(testDelimiterA), testDelimiterW, + ARRAYSIZE(testDelimiterW)); + p = wcstok_s(testTokensW, testDelimiterW, &context); + + WCHAR testToken1W[ARRAYSIZE(testToken1A)] = { 0 }; + (void)ConvertUtf8NToWChar(testToken1A, ARRAYSIZE(testToken1A), testToken1W, + ARRAYSIZE(testToken1W)); + if (memcmp(p, testToken1W, sizeof(testToken1W)) != 0) + { + printf("wcstok_s error: token #1 mismatch\n"); + return -1; + } + + p = wcstok_s(NULL, testDelimiterW, &context); + + WCHAR testToken2W[ARRAYSIZE(testToken2A)] = { 0 }; + (void)ConvertUtf8NToWChar(testToken2A, ARRAYSIZE(testToken2A), testToken2W, + ARRAYSIZE(testToken2W)); + if (memcmp(p, testToken2W, sizeof(testToken2W)) != 0) + { + printf("wcstok_s error: token #2 mismatch\n"); + return -1; + } + + p = wcstok_s(NULL, testDelimiterW, &context); + + WCHAR testToken3W[ARRAYSIZE(testToken3A)] = { 0 }; + (void)ConvertUtf8NToWChar(testToken3A, ARRAYSIZE(testToken3A), testToken3W, + ARRAYSIZE(testToken3W)); + if (memcmp(p, testToken3W, sizeof(testToken3W)) != 0) + { + printf("wcstok_s error: token #3 mismatch\n"); + return -1; + } + + p = wcstok_s(NULL, testDelimiterW, &context); + + if (p != NULL) + { + printf("wcstok_s error: return value is not NULL\n"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestTypes.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestTypes.c new file mode 100644 index 0000000000000000000000000000000000000000..1d9a0346ab54362cf46b7709258b2b461624c79f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestTypes.c @@ -0,0 +1,115 @@ + +#include +#include +#include + +#define EXPECTED_SIZEOF_BYTE 1 +#define EXPECTED_SIZEOF_BOOLEAN 1 +#define EXPECTED_SIZEOF_CHAR 1 +#define EXPECTED_SIZEOF_UCHAR 1 +#define EXPECTED_SIZEOF_INT8 1 +#define EXPECTED_SIZEOF_UINT8 1 +#define EXPECTED_SIZEOF_INT16 2 +#define EXPECTED_SIZEOF_UINT16 2 +#define EXPECTED_SIZEOF_WORD 2 +#define EXPECTED_SIZEOF_WCHAR 2 +#define EXPECTED_SIZEOF_SHORT 2 +#define EXPECTED_SIZEOF_USHORT 2 +#define EXPECTED_SIZEOF_BOOL 4 +#define EXPECTED_SIZEOF_INT 4 +#define EXPECTED_SIZEOF_UINT 4 +#define EXPECTED_SIZEOF_INT32 4 +#define EXPECTED_SIZEOF_UINT32 4 +#define EXPECTED_SIZEOF_DWORD 4 +#define EXPECTED_SIZEOF_DWORD32 4 +#define EXPECTED_SIZEOF_LONG 4 +#define EXPECTED_SIZEOF_LONG32 4 +#define EXPECTED_SIZEOF_INT64 8 +#define EXPECTED_SIZEOF_UINT64 8 +#define EXPECTED_SIZEOF_DWORD64 8 +#define EXPECTED_SIZEOF_DWORDLONG 8 +#define EXPECTED_SIZEOF_LONG64 8 +#define EXPECTED_SIZEOF_ULONGLONG 8 +#define EXPECTED_SIZEOF_LUID 8 +#define EXPECTED_SIZEOF_FILETIME 8 +#define EXPECTED_SIZEOF_LARGE_INTEGER 8 +#define EXPECTED_SIZEOF_ULARGE_INTEGER 8 +#define EXPECTED_SIZEOF_GUID 16 +#define EXPECTED_SIZEOF_SYSTEMTIME 16 +#define EXPECTED_SIZEOF_size_t sizeof(void*) +#define EXPECTED_SIZEOF_INT_PTR sizeof(void*) +#define EXPECTED_SIZEOF_UINT_PTR sizeof(void*) +#define EXPECTED_SIZEOF_DWORD_PTR sizeof(void*) +#define EXPECTED_SIZEOF_LONG_PTR sizeof(void*) +#define EXPECTED_SIZEOF_ULONG_PTR sizeof(void*) + +#define TEST_SIZEOF_TYPE(_name) \ + if (sizeof(_name) != EXPECTED_SIZEOF_##_name) \ + { \ + (void)fprintf(stderr, "sizeof(%s) mismatch: Actual: %" PRIuz ", Expected: %" PRIuz "\n", \ + #_name, sizeof(_name), (size_t)EXPECTED_SIZEOF_##_name); \ + status = -1; \ + } + +int TestTypes(int argc, char* argv[]) +{ + int status = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + TEST_SIZEOF_TYPE(INT8) + TEST_SIZEOF_TYPE(UINT8) + + TEST_SIZEOF_TYPE(BYTE) + TEST_SIZEOF_TYPE(BOOLEAN) + TEST_SIZEOF_TYPE(CHAR) + TEST_SIZEOF_TYPE(UCHAR) + + TEST_SIZEOF_TYPE(INT16) + TEST_SIZEOF_TYPE(UINT16) + + TEST_SIZEOF_TYPE(WORD) + TEST_SIZEOF_TYPE(WCHAR) + TEST_SIZEOF_TYPE(SHORT) + TEST_SIZEOF_TYPE(USHORT) + + /* fails on OS X */ + // TEST_SIZEOF_TYPE(BOOL) + + TEST_SIZEOF_TYPE(INT) + TEST_SIZEOF_TYPE(UINT) + TEST_SIZEOF_TYPE(DWORD) + TEST_SIZEOF_TYPE(DWORD32) + TEST_SIZEOF_TYPE(LONG) + TEST_SIZEOF_TYPE(LONG32) + + TEST_SIZEOF_TYPE(INT32) + TEST_SIZEOF_TYPE(UINT32) + + TEST_SIZEOF_TYPE(INT64) + TEST_SIZEOF_TYPE(UINT64) + + TEST_SIZEOF_TYPE(DWORD64) + TEST_SIZEOF_TYPE(DWORDLONG) + + TEST_SIZEOF_TYPE(LONG64) + TEST_SIZEOF_TYPE(ULONGLONG) + + TEST_SIZEOF_TYPE(LUID) + TEST_SIZEOF_TYPE(FILETIME) + TEST_SIZEOF_TYPE(LARGE_INTEGER) + TEST_SIZEOF_TYPE(ULARGE_INTEGER) + + TEST_SIZEOF_TYPE(GUID) + TEST_SIZEOF_TYPE(SYSTEMTIME) + + TEST_SIZEOF_TYPE(size_t) + TEST_SIZEOF_TYPE(INT_PTR) + TEST_SIZEOF_TYPE(UINT_PTR) + TEST_SIZEOF_TYPE(DWORD_PTR) + TEST_SIZEOF_TYPE(LONG_PTR) + TEST_SIZEOF_TYPE(ULONG_PTR) + + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestUnicodeConversion.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestUnicodeConversion.c new file mode 100644 index 0000000000000000000000000000000000000000..91e817f5f0ae895f5f74d74bbfc0763b7dd15a0c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/test/TestUnicodeConversion.c @@ -0,0 +1,1305 @@ + +#include +#include +#include +#include +#include +#include +#include + +#define TESTCASE_BUFFER_SIZE 8192 + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +typedef struct +{ + const char* utf8; + size_t utf8len; + const WCHAR* utf16; + size_t utf16len; +} testcase_t; + +// TODO: The unit tests do not check for valid code points, so always end the test +// strings with a simple ASCII symbol for now. +static const testcase_t unit_testcases[] = { + { "foo", 3, (const WCHAR*)"f\x00o\x00o\x00\x00\x00", 3 }, + { "foo", 4, (const WCHAR*)"f\x00o\x00o\x00\x00\x00", 4 }, + { "✊🎅ęʥ꣸𑗊a", 19, + (const WCHAR*)"\x0a\x27\x3c\xd8\x85\xdf\x19\x01\xa5\x02\xf8\xa8\x05\xd8\xca\xdd\x61\x00\x00" + "\x00", + 9 } +}; + +static void create_prefix(char* prefix, size_t prefixlen, size_t buffersize, SSIZE_T rc, + SSIZE_T inputlen, const testcase_t* test, const char* fkt, size_t line) +{ + (void)_snprintf(prefix, prefixlen, + "[%s:%" PRIuz "] '%s' [utf8: %" PRIuz ", utf16: %" PRIuz "] buffersize: %" PRIuz + ", rc: %" PRIdz ", inputlen: %" PRIdz ":: ", + fkt, line, test->utf8, test->utf8len, test->utf16len, buffersize, rc, inputlen); +} + +static BOOL check_short_buffer(const char* prefix, int rc, size_t buffersize, + const testcase_t* test, BOOL utf8) +{ + if ((rc > 0) && ((size_t)rc <= buffersize)) + return TRUE; + + size_t len = test->utf8len; + if (!utf8) + len = test->utf16len; + + if (buffersize > len) + { + (void)fprintf(stderr, + "%s length does not match buffersize: %" PRId32 " != %" PRIuz + ",but is large enough to hold result\n", + prefix, rc, buffersize); + return FALSE; + } + const DWORD err = GetLastError(); + if (err != ERROR_INSUFFICIENT_BUFFER) + { + + (void)fprintf(stderr, + "%s length does not match buffersize: %" PRId32 " != %" PRIuz + ", unexpected GetLastError() 0x08%" PRIx32 "\n", + prefix, rc, buffersize, err); + return FALSE; + } + else + return TRUE; +} + +#define compare_utf16(what, buffersize, rc, inputlen, test) \ + compare_utf16_int((what), (buffersize), (rc), (inputlen), (test), __func__, __LINE__) +static BOOL compare_utf16_int(const WCHAR* what, size_t buffersize, SSIZE_T rc, SSIZE_T inputlen, + const testcase_t* test, const char* fkt, size_t line) +{ + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), buffersize, rc, inputlen, test, fkt, line); + + WINPR_ASSERT(what || (buffersize == 0)); + WINPR_ASSERT(test); + + const size_t welen = _wcsnlen(test->utf16, test->utf16len); + if (buffersize > welen) + { + if ((rc < 0) || ((size_t)rc != welen)) + { + (void)fprintf(stderr, + "%s length does not match expectation: %" PRIdz " != %" PRIuz "\n", + prefix, rc, welen); + return FALSE; + } + } + else + { + if (!check_short_buffer(prefix, WINPR_ASSERTING_INT_CAST(SSIZE_T, rc), buffersize, test, + FALSE)) + return FALSE; + } + + if ((rc > 0) && (buffersize > (size_t)rc)) + { + const size_t wlen = _wcsnlen(what, buffersize); + if ((rc < 0) || (wlen > (size_t)rc)) + { + (void)fprintf(stderr, "%s length does not match wcslen: %" PRIdz " < %" PRIuz "\n", + prefix, rc, wlen); + return FALSE; + } + } + + if (rc >= 0) + { + if (memcmp(test->utf16, what, rc * sizeof(WCHAR)) != 0) + { + (void)fprintf(stderr, "%s contents does not match expectations: TODO '%s' != '%s'\n", + prefix, test->utf8, test->utf8); + return FALSE; + } + } + + printf("%s success\n", prefix); + + return TRUE; +} + +#define compare_utf8(what, buffersize, rc, inputlen, test) \ + compare_utf8_int((what), (buffersize), (rc), (inputlen), (test), __func__, __LINE__) +static BOOL compare_utf8_int(const char* what, size_t buffersize, SSIZE_T rc, SSIZE_T inputlen, + const testcase_t* test, const char* fkt, size_t line) +{ + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), buffersize, rc, inputlen, test, fkt, line); + + WINPR_ASSERT(what || (buffersize == 0)); + WINPR_ASSERT(test); + + const size_t slen = strnlen(test->utf8, test->utf8len); + if (buffersize > slen) + { + if ((rc < 0) || ((size_t)rc != slen)) + { + (void)fprintf(stderr, + "%s length does not match expectation: %" PRIdz " != %" PRIuz "\n", + prefix, rc, slen); + return FALSE; + } + } + else + { + if (!check_short_buffer(prefix, WINPR_ASSERTING_INT_CAST(SSIZE_T, rc), buffersize, test, + TRUE)) + return FALSE; + } + + if ((rc > 0) && (buffersize > (size_t)rc)) + { + const size_t wlen = strnlen(what, buffersize); + if (wlen != (size_t)rc) + { + (void)fprintf(stderr, "%s length does not match strnlen: %" PRIdz " != %" PRIuz "\n", + prefix, rc, wlen); + return FALSE; + } + } + + if (rc >= 0) + { + if (memcmp(test->utf8, what, rc) != 0) + { + (void)fprintf(stderr, "%s contents does not match expectations: '%s' != '%s'\n", prefix, + what, test->utf8); + return FALSE; + } + } + + printf("%s success\n", prefix); + + return TRUE; +} + +static BOOL test_convert_to_utf16(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t max = test->utf16len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const SSIZE_T rc2 = ConvertUtf8ToWChar(test->utf8, NULL, 0); + const size_t wlen = _wcsnlen(test->utf16, test->utf16len); + if ((rc2 < 0) || ((size_t)rc2 != wlen)) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, -1, test, __func__, __LINE__); + (void)fprintf(stderr, + "%s ConvertUtf8ToWChar(%s, NULL, 0) expected %" PRIuz ", got %" PRIdz "\n", + prefix, test->utf8, wlen, rc2); + return FALSE; + } + for (size_t x = 0; x < max; x++) + { + WCHAR buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + const SSIZE_T rc = ConvertUtf8ToWChar(test->utf8, buffer, len[x]); + if (!compare_utf16(buffer, len[x], rc, -1, test)) + return FALSE; + } + + return TRUE; +} + +static BOOL test_convert_to_utf16_n(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t max = test->utf16len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const SSIZE_T rc2 = ConvertUtf8NToWChar(test->utf8, test->utf8len, NULL, 0); + const size_t wlen = _wcsnlen(test->utf16, test->utf16len); + if ((rc2 < 0) || ((size_t)rc2 != wlen)) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, + WINPR_ASSERTING_INT_CAST(SSIZE_T, test->utf8len), test, __func__, __LINE__); + (void)fprintf(stderr, + "%s ConvertUtf8NToWChar(%s, %" PRIuz ", NULL, 0) expected %" PRIuz + ", got %" PRIdz "\n", + prefix, test->utf8, test->utf8len, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + const size_t ilen[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t imax = test->utf8len > 0 ? ARRAYSIZE(ilen) : ARRAYSIZE(ilen) - 1; + + for (size_t y = 0; y < imax; y++) + { + WCHAR buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + SSIZE_T rc = ConvertUtf8NToWChar(test->utf8, ilen[x], buffer, len[x]); + if (!compare_utf16(buffer, len[x], rc, ilen[x], test)) + return FALSE; + } + } + return TRUE; +} + +static BOOL test_convert_to_utf8(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t max = test->utf8len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const SSIZE_T rc2 = ConvertWCharToUtf8(test->utf16, NULL, 0); + const size_t wlen = strnlen(test->utf8, test->utf8len); + if ((rc2 < 0) || ((size_t)rc2 != wlen)) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, -1, test, __func__, __LINE__); + (void)fprintf(stderr, + "%s ConvertWCharToUtf8(%s, NULL, 0) expected %" PRIuz ", got %" PRIdz "\n", + prefix, test->utf8, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + char buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + SSIZE_T rc = ConvertWCharToUtf8(test->utf16, buffer, len[x]); + if (!compare_utf8(buffer, len[x], rc, -1, test)) + return FALSE; + } + + return TRUE; +} + +static BOOL test_convert_to_utf8_n(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t max = test->utf8len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const SSIZE_T rc2 = ConvertWCharNToUtf8(test->utf16, test->utf16len, NULL, 0); + const size_t wlen = strnlen(test->utf8, test->utf8len); + if ((rc2 < 0) || ((size_t)rc2 != wlen)) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, + WINPR_ASSERTING_INT_CAST(SSIZE_T, test->utf16len), test, __func__, __LINE__); + (void)fprintf(stderr, + "%s ConvertWCharNToUtf8(%s, %" PRIuz ", NULL, 0) expected %" PRIuz + ", got %" PRIdz "\n", + prefix, test->utf8, test->utf16len, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + const size_t ilen[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t imax = test->utf16len > 0 ? ARRAYSIZE(ilen) : ARRAYSIZE(ilen) - 1; + + for (size_t y = 0; y < imax; y++) + { + char buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + SSIZE_T rc = ConvertWCharNToUtf8(test->utf16, ilen[x], buffer, len[x]); + if (!compare_utf8(buffer, len[x], rc, ilen[x], test)) + return FALSE; + } + } + + return TRUE; +} + +static BOOL test_conversion(const testcase_t* testcases, size_t count) +{ + WINPR_ASSERT(testcases || (count == 0)); + for (size_t x = 0; x < count; x++) + { + const testcase_t* test = &testcases[x]; + + printf("Running test case %" PRIuz " [%s]\n", x, test->utf8); + if (!test_convert_to_utf16(test)) + return FALSE; + if (!test_convert_to_utf16_n(test)) + return FALSE; + if (!test_convert_to_utf8(test)) + return FALSE; + if (!test_convert_to_utf8_n(test)) + return FALSE; + } + return TRUE; +} + +#if defined(WITH_WINPR_DEPRECATED) + +#define compare_win_utf16(what, buffersize, rc, inputlen, test) \ + compare_win_utf16_int((what), (buffersize), (rc), (inputlen), (test), __func__, __LINE__) +static BOOL compare_win_utf16_int(const WCHAR* what, size_t buffersize, int rc, int inputlen, + const testcase_t* test, const char* fkt, size_t line) +{ + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), buffersize, rc, inputlen, test, fkt, line); + + WINPR_ASSERT(what || (buffersize == 0)); + WINPR_ASSERT(test); + + BOOL isNullTerminated = TRUE; + if (inputlen > 0) + isNullTerminated = strnlen(test->utf8, inputlen) < inputlen; + size_t welen = _wcsnlen(test->utf16, buffersize); + if (isNullTerminated) + welen++; + + if (buffersize >= welen) + { + if ((inputlen >= 0) && (rc > buffersize)) + { + (void)fprintf(stderr, "%s length does not match expectation: %d > %" PRIuz "\n", prefix, + rc, buffersize); + return FALSE; + } + else if ((inputlen < 0) && (rc != welen)) + { + (void)fprintf(stderr, "%s length does not match expectation: %d != %" PRIuz "\n", + prefix, rc, welen); + return FALSE; + } + } + else + { + if (!check_short_buffer(prefix, rc, buffersize, test, FALSE)) + return FALSE; + } + + if ((rc > 0) && (buffersize > rc)) + { + size_t wlen = _wcsnlen(what, buffersize); + if (isNullTerminated) + wlen++; + if ((inputlen >= 0) && (buffersize < rc)) + { + (void)fprintf(stderr, "%s length does not match wcslen: %d > %" PRIuz "\n", prefix, rc, + buffersize); + return FALSE; + } + else if ((inputlen < 0) && (welen > rc)) + { + (void)fprintf(stderr, "%s length does not match wcslen: %d < %" PRIuz "\n", prefix, rc, + wlen); + return FALSE; + } + } + + const size_t cmp_size = MIN(rc, test->utf16len) * sizeof(WCHAR); + if (memcmp(test->utf16, what, cmp_size) != 0) + { + (void)fprintf(stderr, "%s contents does not match expectations: TODO '%s' != '%s'\n", + prefix, test->utf8, test->utf8); + return FALSE; + } + + printf("%s success\n", prefix); + + return TRUE; +} + +#define compare_win_utf8(what, buffersize, rc, inputlen, test) \ + compare_win_utf8_int((what), (buffersize), (rc), (inputlen), (test), __func__, __LINE__) +static BOOL compare_win_utf8_int(const char* what, size_t buffersize, SSIZE_T rc, SSIZE_T inputlen, + const testcase_t* test, const char* fkt, size_t line) +{ + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), buffersize, rc, inputlen, test, fkt, line); + + WINPR_ASSERT(what || (buffersize == 0)); + WINPR_ASSERT(test); + + BOOL isNullTerminated = TRUE; + if (inputlen > 0) + isNullTerminated = _wcsnlen(test->utf16, inputlen) < inputlen; + + size_t slen = strnlen(test->utf8, test->utf8len); + if (isNullTerminated) + slen++; + + if (buffersize > slen) + { + if ((inputlen >= 0) && (rc > buffersize)) + { + (void)fprintf(stderr, "%s length does not match expectation: %" PRIdz " > %" PRIuz "\n", + prefix, rc, buffersize); + return FALSE; + } + else if ((inputlen < 0) && (rc != slen)) + { + (void)fprintf(stderr, + "%s length does not match expectation: %" PRIdz " != %" PRIuz "\n", + prefix, rc, slen); + return FALSE; + } + } + else + { + if (!check_short_buffer(prefix, rc, buffersize, test, TRUE)) + return FALSE; + } + + if ((rc > 0) && (buffersize > rc)) + { + size_t wlen = strnlen(what, buffersize); + if (isNullTerminated) + wlen++; + + if (wlen > rc) + { + (void)fprintf(stderr, "%s length does not match wcslen: %" PRIdz " < %" PRIuz "\n", + prefix, rc, wlen); + return FALSE; + } + } + + const size_t cmp_size = MIN(test->utf8len, rc); + if (memcmp(test->utf8, what, cmp_size) != 0) + { + (void)fprintf(stderr, "%s contents does not match expectations: '%s' != '%s'\n", prefix, + what, test->utf8); + return FALSE; + } + printf("%s success\n", prefix); + + return TRUE; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +static BOOL test_win_convert_to_utf16(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t max = test->utf16len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const int rc2 = MultiByteToWideChar(CP_UTF8, 0, test->utf8, -1, NULL, 0); + const size_t wlen = _wcsnlen(test->utf16, test->utf16len); + if (rc2 != wlen + 1) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, -1, test, __func__, __LINE__); + (void)fprintf(stderr, + "%s MultiByteToWideChar(CP_UTF8, 0, %s, [-1], NULL, 0) expected %" PRIuz + ", got %d\n", + prefix, test->utf8, wlen + 1, rc2); + return FALSE; + } + for (size_t x = 0; x < max; x++) + { + WCHAR buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + const int rc = MultiByteToWideChar(CP_UTF8, 0, test->utf8, -1, buffer, len[x]); + if (!compare_win_utf16(buffer, len[x], rc, -1, test)) + return FALSE; + } + + return TRUE; +} + +static BOOL test_win_convert_to_utf16_n(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t max = test->utf16len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + BOOL isNullTerminated = strnlen(test->utf8, test->utf8len) < test->utf8len; + const int rc2 = MultiByteToWideChar(CP_UTF8, 0, test->utf8, test->utf8len, NULL, 0); + size_t wlen = _wcsnlen(test->utf16, test->utf16len); + if (isNullTerminated) + wlen++; + + if (rc2 != wlen) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, test->utf8len, test, __func__, __LINE__); + (void)fprintf(stderr, + "%s MultiByteToWideChar(CP_UTF8, 0, %s, %" PRIuz ", NULL, 0) expected %" PRIuz + ", got %d\n", + prefix, test->utf8, test->utf8len, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + const size_t ilen[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t imax = test->utf8len > 0 ? ARRAYSIZE(ilen) : ARRAYSIZE(ilen) - 1; + + for (size_t y = 0; y < imax; y++) + { + char mbuffer[TESTCASE_BUFFER_SIZE] = { 0 }; + WCHAR buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + strncpy(mbuffer, test->utf8, test->utf8len); + const int rc = MultiByteToWideChar(CP_UTF8, 0, mbuffer, ilen[x], buffer, len[x]); + if (!compare_win_utf16(buffer, len[x], rc, ilen[x], test)) + return FALSE; + } + } + return TRUE; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +static BOOL test_win_convert_to_utf8(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t max = test->utf8len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const int rc2 = WideCharToMultiByte(CP_UTF8, 0, test->utf16, -1, NULL, 0, NULL, NULL); + const size_t wlen = strnlen(test->utf8, test->utf8len) + 1; + if (rc2 != wlen) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, -1, test, __func__, __LINE__); + (void)fprintf( + stderr, + "%s WideCharToMultiByte(CP_UTF8, 0, %s, -1, NULL, 0, NULL, NULL) expected %" PRIuz + ", got %d\n", + prefix, test->utf8, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + char buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + int rc = WideCharToMultiByte(CP_UTF8, 0, test->utf16, -1, buffer, len[x], NULL, NULL); + if (!compare_win_utf8(buffer, len[x], rc, -1, test)) + return FALSE; + } + + return TRUE; +} + +static BOOL test_win_convert_to_utf8_n(const testcase_t* test) +{ + const size_t len[] = { TESTCASE_BUFFER_SIZE, test->utf8len, test->utf8len + 1, + test->utf8len - 1 }; + const size_t max = test->utf8len > 0 ? ARRAYSIZE(len) : ARRAYSIZE(len) - 1; + + const BOOL isNullTerminated = _wcsnlen(test->utf16, test->utf16len) < test->utf16len; + const int rc2 = + WideCharToMultiByte(CP_UTF8, 0, test->utf16, test->utf16len, NULL, 0, NULL, NULL); + size_t wlen = strnlen(test->utf8, test->utf8len); + if (isNullTerminated) + wlen++; + + if (rc2 != wlen) + { + char prefix[8192] = { 0 }; + create_prefix(prefix, ARRAYSIZE(prefix), 0, rc2, test->utf16len, test, __func__, __LINE__); + (void)fprintf(stderr, + "%s WideCharToMultiByte(CP_UTF8, 0, %s, %" PRIuz + ", NULL, 0, NULL, NULL) expected %" PRIuz ", got %d\n", + prefix, test->utf8, test->utf16len, wlen, rc2); + return FALSE; + } + + for (size_t x = 0; x < max; x++) + { + const size_t ilen[] = { TESTCASE_BUFFER_SIZE, test->utf16len, test->utf16len + 1, + test->utf16len - 1 }; + const size_t imax = test->utf16len > 0 ? ARRAYSIZE(ilen) : ARRAYSIZE(ilen) - 1; + + for (size_t y = 0; y < imax; y++) + { + WCHAR wbuffer[TESTCASE_BUFFER_SIZE] = { 0 }; + char buffer[TESTCASE_BUFFER_SIZE] = { 0 }; + memcpy(wbuffer, test->utf16, test->utf16len * sizeof(WCHAR)); + const int rc = + WideCharToMultiByte(CP_UTF8, 0, wbuffer, ilen[x], buffer, len[x], NULL, NULL); + if (!compare_win_utf8(buffer, len[x], rc, ilen[x], test)) + return FALSE; + } + } + + return TRUE; +} + +static BOOL test_win_conversion(const testcase_t* testcases, size_t count) +{ + WINPR_ASSERT(testcases || (count == 0)); + for (size_t x = 0; x < count; x++) + { + const testcase_t* test = &testcases[x]; + + printf("Running test case %" PRIuz " [%s]\n", x, test->utf8); + if (!test_win_convert_to_utf16(test)) + return FALSE; + if (!test_win_convert_to_utf16_n(test)) + return FALSE; + if (!test_win_convert_to_utf8(test)) + return FALSE; + if (!test_win_convert_to_utf8_n(test)) + return FALSE; + } + return TRUE; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +/* Letters */ + +static BYTE c_cedilla_UTF8[] = "\xC3\xA7\x00"; +static BYTE c_cedilla_UTF16[] = "\xE7\x00\x00\x00"; +static int c_cedilla_cchWideChar = 2; +static int c_cedilla_cbMultiByte = 3; + +/* English */ + +static BYTE en_Hello_UTF8[] = "Hello\0"; +static BYTE en_Hello_UTF16[] = "\x48\x00\x65\x00\x6C\x00\x6C\x00\x6F\x00\x00\x00"; +static int en_Hello_cchWideChar = 6; +static int en_Hello_cbMultiByte = 6; + +static BYTE en_HowAreYou_UTF8[] = "How are you?\0"; +static BYTE en_HowAreYou_UTF16[] = + "\x48\x00\x6F\x00\x77\x00\x20\x00\x61\x00\x72\x00\x65\x00\x20\x00" + "\x79\x00\x6F\x00\x75\x00\x3F\x00\x00\x00"; +static int en_HowAreYou_cchWideChar = 13; +static int en_HowAreYou_cbMultiByte = 13; + +/* French */ + +static BYTE fr_Hello_UTF8[] = "Allo\0"; +static BYTE fr_Hello_UTF16[] = "\x41\x00\x6C\x00\x6C\x00\x6F\x00\x00\x00"; +static int fr_Hello_cchWideChar = 5; +static int fr_Hello_cbMultiByte = 5; + +static BYTE fr_HowAreYou_UTF8[] = + "\x43\x6F\x6D\x6D\x65\x6E\x74\x20\xC3\xA7\x61\x20\x76\x61\x3F\x00"; +static BYTE fr_HowAreYou_UTF16[] = + "\x43\x00\x6F\x00\x6D\x00\x6D\x00\x65\x00\x6E\x00\x74\x00\x20\x00" + "\xE7\x00\x61\x00\x20\x00\x76\x00\x61\x00\x3F\x00\x00\x00"; +static int fr_HowAreYou_cchWideChar = 15; +static int fr_HowAreYou_cbMultiByte = 16; + +/* Russian */ + +static BYTE ru_Hello_UTF8[] = "\xD0\x97\xD0\xB4\xD0\xBE\xD1\x80\xD0\xBE\xD0\xB2\xD0\xBE\x00"; +static BYTE ru_Hello_UTF16[] = "\x17\x04\x34\x04\x3E\x04\x40\x04\x3E\x04\x32\x04\x3E\x04\x00\x00"; +static int ru_Hello_cchWideChar = 8; +static int ru_Hello_cbMultiByte = 15; + +static BYTE ru_HowAreYou_UTF8[] = + "\xD0\x9A\xD0\xB0\xD0\xBA\x20\xD0\xB4\xD0\xB5\xD0\xBB\xD0\xB0\x3F\x00"; +static BYTE ru_HowAreYou_UTF16[] = + "\x1A\x04\x30\x04\x3A\x04\x20\x00\x34\x04\x35\x04\x3B\x04\x30\x04" + "\x3F\x00\x00\x00"; +static int ru_HowAreYou_cchWideChar = 10; +static int ru_HowAreYou_cbMultiByte = 17; + +/* Arabic */ + +static BYTE ar_Hello_UTF8[] = "\xD8\xA7\xD9\x84\xD8\xB3\xD9\x84\xD8\xA7\xD9\x85\x20\xD8\xB9\xD9" + "\x84\xD9\x8A\xD9\x83\xD9\x85\x00"; +static BYTE ar_Hello_UTF16[] = "\x27\x06\x44\x06\x33\x06\x44\x06\x27\x06\x45\x06\x20\x00\x39\x06" + "\x44\x06\x4A\x06\x43\x06\x45\x06\x00\x00"; +static int ar_Hello_cchWideChar = 13; +static int ar_Hello_cbMultiByte = 24; + +static BYTE ar_HowAreYou_UTF8[] = "\xD9\x83\xD9\x8A\xD9\x81\x20\xD8\xAD\xD8\xA7\xD9\x84\xD9\x83\xD8" + "\x9F\x00"; +static BYTE ar_HowAreYou_UTF16[] = + "\x43\x06\x4A\x06\x41\x06\x20\x00\x2D\x06\x27\x06\x44\x06\x43\x06" + "\x1F\x06\x00\x00"; +static int ar_HowAreYou_cchWideChar = 10; +static int ar_HowAreYou_cbMultiByte = 18; + +/* Chinese */ + +static BYTE ch_Hello_UTF8[] = "\xE4\xBD\xA0\xE5\xA5\xBD\x00"; +static BYTE ch_Hello_UTF16[] = "\x60\x4F\x7D\x59\x00\x00"; +static int ch_Hello_cchWideChar = 3; +static int ch_Hello_cbMultiByte = 7; + +static BYTE ch_HowAreYou_UTF8[] = "\xE4\xBD\xA0\xE5\xA5\xBD\xE5\x90\x97\x00"; +static BYTE ch_HowAreYou_UTF16[] = "\x60\x4F\x7D\x59\x17\x54\x00\x00"; +static int ch_HowAreYou_cchWideChar = 4; +static int ch_HowAreYou_cbMultiByte = 10; + +/* Uppercasing */ + +static BYTE ru_Administrator_lower[] = "\xd0\x90\xd0\xb4\xd0\xbc\xd0\xb8\xd0\xbd\xd0\xb8\xd1\x81" + "\xd1\x82\xd1\x80\xd0\xb0\xd1\x82\xd0\xbe\xd1\x80\x00"; + +static BYTE ru_Administrator_upper[] = "\xd0\x90\xd0\x94\xd0\x9c\xd0\x98\xd0\x9d\xd0\x98\xd0\xa1" + "\xd0\xa2\xd0\xa0\xd0\x90\xd0\xa2\xd0\x9e\xd0\xa0\x00"; + +static void string_hexdump(const BYTE* data, size_t length) +{ + size_t offset = 0; + + char* str = winpr_BinToHexString(data, length, TRUE); + if (!str) + return; + + while (offset < length) + { + const size_t diff = (length - offset) * 3; + WINPR_ASSERT(diff <= INT_MAX); + printf("%04" PRIxz " %.*s\n", offset, (int)diff, &str[offset]); + offset += 16; + } + + free(str); +} + +static int convert_utf8_to_utf16(BYTE* lpMultiByteStr, BYTE* expected_lpWideCharStr, + int expected_cchWideChar) +{ + int rc = -1; + int length = 0; + size_t cbMultiByte = 0; + int cchWideChar = 0; + LPWSTR lpWideCharStr = NULL; + + cbMultiByte = strlen((char*)lpMultiByteStr); + cchWideChar = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)lpMultiByteStr, -1, NULL, 0); + + printf("MultiByteToWideChar Input UTF8 String:\n"); + string_hexdump(lpMultiByteStr, cbMultiByte + 1); + + printf("MultiByteToWideChar required cchWideChar: %d\n", cchWideChar); + + if (cchWideChar != expected_cchWideChar) + { + printf("MultiByteToWideChar unexpected cchWideChar: actual: %d expected: %d\n", cchWideChar, + expected_cchWideChar); + goto fail; + } + + lpWideCharStr = (LPWSTR)calloc((size_t)cchWideChar, sizeof(WCHAR)); + if (!lpWideCharStr) + { + printf("MultiByteToWideChar: unable to allocate memory for test\n"); + goto fail; + } + lpWideCharStr[cchWideChar - 1] = + 0xFFFF; /* should be overwritten if null terminator is inserted properly */ + length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)lpMultiByteStr, cbMultiByte + 1, lpWideCharStr, + cchWideChar); + + printf("MultiByteToWideChar converted length (WCHAR): %d\n", length); + + if (!length) + { + DWORD error = GetLastError(); + printf("MultiByteToWideChar error: 0x%08" PRIX32 "\n", error); + goto fail; + } + + if (length != expected_cchWideChar) + { + printf("MultiByteToWideChar unexpected converted length (WCHAR): actual: %d expected: %d\n", + length, expected_cchWideChar); + goto fail; + } + + if (_wcscmp(lpWideCharStr, (WCHAR*)expected_lpWideCharStr) != 0) + { + printf("MultiByteToWideChar unexpected string:\n"); + + printf("UTF8 String:\n"); + string_hexdump(lpMultiByteStr, cbMultiByte + 1); + + printf("UTF16 String (actual):\n"); + string_hexdump((BYTE*)lpWideCharStr, length * sizeof(WCHAR)); + + printf("UTF16 String (expected):\n"); + string_hexdump(expected_lpWideCharStr, expected_cchWideChar * sizeof(WCHAR)); + + goto fail; + } + + printf("MultiByteToWideChar Output UTF16 String:\n"); + string_hexdump((BYTE*)lpWideCharStr, length * sizeof(WCHAR)); + printf("\n"); + + rc = length; +fail: + free(lpWideCharStr); + + return rc; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +static int convert_utf16_to_utf8(BYTE* lpWideCharStr, BYTE* expected_lpMultiByteStr, + int expected_cbMultiByte) +{ + int rc = -1; + int length = 0; + int cchWideChar = 0; + int cbMultiByte = 0; + LPSTR lpMultiByteStr = NULL; + + cchWideChar = _wcslen((WCHAR*)lpWideCharStr); + cbMultiByte = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)lpWideCharStr, -1, NULL, 0, NULL, NULL); + + printf("WideCharToMultiByte Input UTF16 String:\n"); + string_hexdump(lpWideCharStr, (cchWideChar + 1) * sizeof(WCHAR)); + + printf("WideCharToMultiByte required cbMultiByte: %d\n", cbMultiByte); + + if (cbMultiByte != expected_cbMultiByte) + { + printf("WideCharToMultiByte unexpected cbMultiByte: actual: %d expected: %d\n", cbMultiByte, + expected_cbMultiByte); + goto fail; + } + + lpMultiByteStr = (LPSTR)malloc(cbMultiByte); + if (!lpMultiByteStr) + { + printf("WideCharToMultiByte: unable to allocate memory for test\n"); + goto fail; + } + lpMultiByteStr[cbMultiByte - 1] = + (CHAR)0xFF; /* should be overwritten if null terminator is inserted properly */ + length = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)lpWideCharStr, cchWideChar + 1, + lpMultiByteStr, cbMultiByte, NULL, NULL); + + printf("WideCharToMultiByte converted length (BYTE): %d\n", length); + + if (!length) + { + DWORD error = GetLastError(); + printf("WideCharToMultiByte error: 0x%08" PRIX32 "\n", error); + goto fail; + } + + if (length != expected_cbMultiByte) + { + printf("WideCharToMultiByte unexpected converted length (BYTE): actual: %d expected: %d\n", + length, expected_cbMultiByte); + goto fail; + } + + if (strcmp(lpMultiByteStr, (char*)expected_lpMultiByteStr) != 0) + { + printf("WideCharToMultiByte unexpected string:\n"); + + printf("UTF16 String:\n"); + string_hexdump(lpWideCharStr, (cchWideChar + 1) * sizeof(WCHAR)); + + printf("UTF8 String (actual):\n"); + string_hexdump((BYTE*)lpMultiByteStr, cbMultiByte); + + printf("UTF8 String (expected):\n"); + string_hexdump(expected_lpMultiByteStr, expected_cbMultiByte); + + goto fail; + } + + printf("WideCharToMultiByte Output UTF8 String:\n"); + string_hexdump((BYTE*)lpMultiByteStr, cbMultiByte); + printf("\n"); + + rc = length; +fail: + free(lpMultiByteStr); + + return rc; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +static BOOL test_unicode_uppercasing(BYTE* lower, BYTE* upper) +{ + WCHAR* lowerW = NULL; + int lowerLength = 0; + WCHAR* upperW = NULL; + int upperLength = 0; + + lowerLength = ConvertToUnicode(CP_UTF8, 0, (LPSTR)lower, -1, &lowerW, 0); + upperLength = ConvertToUnicode(CP_UTF8, 0, (LPSTR)upper, -1, &upperW, 0); + + CharUpperBuffW(lowerW, lowerLength); + + if (_wcscmp(lowerW, upperW) != 0) + { + printf("Lowercase String:\n"); + string_hexdump((BYTE*)lowerW, lowerLength * 2); + + printf("Uppercase String:\n"); + string_hexdump((BYTE*)upperW, upperLength * 2); + + return FALSE; + } + + free(lowerW); + free(upperW); + + printf("success\n\n"); + return TRUE; +} +#endif + +#if defined(WITH_WINPR_DEPRECATED) +static BOOL test_ConvertFromUnicode_wrapper(void) +{ + const BYTE src1[] = + "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00\x20\x00\x46\x00" + "\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x40\x00\x40\x00\x40\x00"; + const BYTE src2[] = "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00" + "\x20\x00\x46\x00\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x00\x00"; + /* 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 */ + const CHAR cmp0[] = { 'R', 'I', 'C', 'H', ' ', 'T', 'E', 'X', 'T', + ' ', 'F', 'O', 'R', 'M', 'A', 'T', 0 }; + CHAR* dst = NULL; + int i = 0; + + /* Test unterminated unicode string: + * ConvertFromUnicode must always null-terminate, even if the src string isn't + */ + + printf("Input UTF16 String:\n"); + string_hexdump((const BYTE*)src1, 19 * sizeof(WCHAR)); + + i = ConvertFromUnicode(CP_UTF8, 0, (const WCHAR*)src1, 16, &dst, 0, NULL, NULL); + if (i != 16) + { + (void)fprintf(stderr, + "ConvertFromUnicode failure A1: unexpectedly returned %d instead of 16\n", i); + goto fail; + } + if (dst == NULL) + { + (void)fprintf(stderr, "ConvertFromUnicode failure A2: destination is NULL\n"); + goto fail; + } + if ((i = strlen(dst)) != 16) + { + (void)fprintf(stderr, "ConvertFromUnicode failure A3: dst length is %d instead of 16\n", i); + goto fail; + } + if (strcmp(dst, cmp0)) + { + (void)fprintf(stderr, "ConvertFromUnicode failure A4: data mismatch\n"); + goto fail; + } + printf("Output UTF8 String:\n"); + string_hexdump((BYTE*)dst, i + 1); + + free(dst); + dst = NULL; + + /* Test null-terminated string */ + + printf("Input UTF16 String:\n"); + string_hexdump((const BYTE*)src2, (_wcslen((const WCHAR*)src2) + 1) * sizeof(WCHAR)); + + i = ConvertFromUnicode(CP_UTF8, 0, (const WCHAR*)src2, -1, &dst, 0, NULL, NULL); + if (i != 17) + { + (void)fprintf(stderr, + "ConvertFromUnicode failure B1: unexpectedly returned %d instead of 17\n", i); + goto fail; + } + if (dst == NULL) + { + (void)fprintf(stderr, "ConvertFromUnicode failure B2: destination is NULL\n"); + goto fail; + } + if ((i = strlen(dst)) != 16) + { + (void)fprintf(stderr, "ConvertFromUnicode failure B3: dst length is %d instead of 16\n", i); + goto fail; + } + if (strcmp(dst, cmp0)) + { + (void)fprintf(stderr, "ConvertFromUnicode failure B: data mismatch\n"); + goto fail; + } + printf("Output UTF8 String:\n"); + string_hexdump((BYTE*)dst, i + 1); + + free(dst); + dst = NULL; + + printf("success\n\n"); + + return TRUE; + +fail: + free(dst); + return FALSE; +} + +static BOOL test_ConvertToUnicode_wrapper(void) +{ + /* 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 */ + const CHAR src1[] = { 'R', 'I', 'C', 'H', ' ', 'T', 'E', 'X', 'T', ' ', + 'F', 'O', 'R', 'M', 'A', 'T', '@', '@', '@' }; + const CHAR src2[] = { 'R', 'I', 'C', 'H', ' ', 'T', 'E', 'X', 'T', + ' ', 'F', 'O', 'R', 'M', 'A', 'T', 0 }; + const BYTE cmp0[] = "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00" + "\x20\x00\x46\x00\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x00\x00"; + WCHAR* dst = NULL; + int ii = 0; + size_t i = 0; + + /* Test static string buffers of differing sizes */ + { + char name[] = "someteststring"; + const BYTE cmp[] = { 's', 0, 'o', 0, 'm', 0, 'e', 0, 't', 0, 'e', 0, 's', 0, 't', 0, + 's', 0, 't', 0, 'r', 0, 'i', 0, 'n', 0, 'g', 0, 0, 0 }; + WCHAR xname[128] = { 0 }; + LPWSTR aname = NULL; + LPWSTR wname = &xname[0]; + const size_t len = strnlen(name, ARRAYSIZE(name) - 1); + ii = ConvertToUnicode(CP_UTF8, 0, name, len, &wname, ARRAYSIZE(xname)); + if (ii != (SSIZE_T)len) + goto fail; + + if (memcmp(wname, cmp, sizeof(cmp)) != 0) + goto fail; + + ii = ConvertToUnicode(CP_UTF8, 0, name, len, &aname, 0); + if (ii != (SSIZE_T)len) + goto fail; + ii = memcmp(aname, cmp, sizeof(cmp)); + free(aname); + if (ii != 0) + goto fail; + } + + /* Test unterminated unicode string: + * ConvertToUnicode must always null-terminate, even if the src string isn't + */ + + printf("Input UTF8 String:\n"); + string_hexdump((const BYTE*)src1, 19); + + ii = ConvertToUnicode(CP_UTF8, 0, src1, 16, &dst, 0); + if (ii != 16) + { + (void)fprintf(stderr, + "ConvertToUnicode failure A1: unexpectedly returned %d instead of 16\n", ii); + goto fail; + } + i = (size_t)ii; + if (dst == NULL) + { + (void)fprintf(stderr, "ConvertToUnicode failure A2: destination is NULL\n"); + goto fail; + } + if ((i = _wcslen(dst)) != 16) + { + (void)fprintf(stderr, + "ConvertToUnicode failure A3: dst length is %" PRIuz " instead of 16\n", i); + goto fail; + } + if (_wcscmp(dst, (const WCHAR*)cmp0)) + { + (void)fprintf(stderr, "ConvertToUnicode failure A4: data mismatch\n"); + goto fail; + } + printf("Output UTF16 String:\n"); + string_hexdump((const BYTE*)dst, (i + 1) * sizeof(WCHAR)); + + free(dst); + dst = NULL; + + /* Test null-terminated string */ + + printf("Input UTF8 String:\n"); + string_hexdump((const BYTE*)src2, strlen(src2) + 1); + + i = ConvertToUnicode(CP_UTF8, 0, src2, -1, &dst, 0); + if (i != 17) + { + (void)fprintf( + stderr, "ConvertToUnicode failure B1: unexpectedly returned %" PRIuz " instead of 17\n", + i); + goto fail; + } + if (dst == NULL) + { + (void)fprintf(stderr, "ConvertToUnicode failure B2: destination is NULL\n"); + goto fail; + } + if ((i = _wcslen(dst)) != 16) + { + (void)fprintf(stderr, + "ConvertToUnicode failure B3: dst length is %" PRIuz " instead of 16\n", i); + goto fail; + } + if (_wcscmp(dst, (const WCHAR*)cmp0)) + { + (void)fprintf(stderr, "ConvertToUnicode failure B: data mismatch\n"); + goto fail; + } + printf("Output UTF16 String:\n"); + string_hexdump((BYTE*)dst, (i + 1) * 2); + + free(dst); + dst = NULL; + + printf("success\n\n"); + + return TRUE; + +fail: + free(dst); + return FALSE; +} +#endif + +int TestUnicodeConversion(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_conversion(unit_testcases, ARRAYSIZE(unit_testcases))) + return -1; + +#if defined(WITH_WINPR_DEPRECATED) + if (!test_win_conversion(unit_testcases, ARRAYSIZE(unit_testcases))) + return -1; + + /* Letters */ + + printf("Letters\n"); + + if (convert_utf8_to_utf16(c_cedilla_UTF8, c_cedilla_UTF16, c_cedilla_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(c_cedilla_UTF16, c_cedilla_UTF8, c_cedilla_cbMultiByte) < 1) + return -1; + + /* English */ + + printf("English\n"); + + if (convert_utf8_to_utf16(en_Hello_UTF8, en_Hello_UTF16, en_Hello_cchWideChar) < 1) + return -1; + if (convert_utf8_to_utf16(en_HowAreYou_UTF8, en_HowAreYou_UTF16, en_HowAreYou_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(en_Hello_UTF16, en_Hello_UTF8, en_Hello_cbMultiByte) < 1) + return -1; + if (convert_utf16_to_utf8(en_HowAreYou_UTF16, en_HowAreYou_UTF8, en_HowAreYou_cbMultiByte) < 1) + return -1; + + /* French */ + + printf("French\n"); + + if (convert_utf8_to_utf16(fr_Hello_UTF8, fr_Hello_UTF16, fr_Hello_cchWideChar) < 1) + return -1; + if (convert_utf8_to_utf16(fr_HowAreYou_UTF8, fr_HowAreYou_UTF16, fr_HowAreYou_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(fr_Hello_UTF16, fr_Hello_UTF8, fr_Hello_cbMultiByte) < 1) + return -1; + if (convert_utf16_to_utf8(fr_HowAreYou_UTF16, fr_HowAreYou_UTF8, fr_HowAreYou_cbMultiByte) < 1) + return -1; + + /* Russian */ + + printf("Russian\n"); + + if (convert_utf8_to_utf16(ru_Hello_UTF8, ru_Hello_UTF16, ru_Hello_cchWideChar) < 1) + return -1; + if (convert_utf8_to_utf16(ru_HowAreYou_UTF8, ru_HowAreYou_UTF16, ru_HowAreYou_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(ru_Hello_UTF16, ru_Hello_UTF8, ru_Hello_cbMultiByte) < 1) + return -1; + if (convert_utf16_to_utf8(ru_HowAreYou_UTF16, ru_HowAreYou_UTF8, ru_HowAreYou_cbMultiByte) < 1) + return -1; + + /* Arabic */ + + printf("Arabic\n"); + + if (convert_utf8_to_utf16(ar_Hello_UTF8, ar_Hello_UTF16, ar_Hello_cchWideChar) < 1) + return -1; + if (convert_utf8_to_utf16(ar_HowAreYou_UTF8, ar_HowAreYou_UTF16, ar_HowAreYou_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(ar_Hello_UTF16, ar_Hello_UTF8, ar_Hello_cbMultiByte) < 1) + return -1; + if (convert_utf16_to_utf8(ar_HowAreYou_UTF16, ar_HowAreYou_UTF8, ar_HowAreYou_cbMultiByte) < 1) + return -1; + + /* Chinese */ + + printf("Chinese\n"); + + if (convert_utf8_to_utf16(ch_Hello_UTF8, ch_Hello_UTF16, ch_Hello_cchWideChar) < 1) + return -1; + if (convert_utf8_to_utf16(ch_HowAreYou_UTF8, ch_HowAreYou_UTF16, ch_HowAreYou_cchWideChar) < 1) + return -1; + + if (convert_utf16_to_utf8(ch_Hello_UTF16, ch_Hello_UTF8, ch_Hello_cbMultiByte) < 1) + return -1; + if (convert_utf16_to_utf8(ch_HowAreYou_UTF16, ch_HowAreYou_UTF8, ch_HowAreYou_cbMultiByte) < 1) + return -1; + +#endif + + /* Uppercasing */ +#if defined(WITH_WINPR_DEPRECATED) + printf("Uppercasing\n"); + + if (!test_unicode_uppercasing(ru_Administrator_lower, ru_Administrator_upper)) + return -1; +#endif + + /* ConvertFromUnicode */ +#if defined(WITH_WINPR_DEPRECATED) + printf("ConvertFromUnicode\n"); + + if (!test_ConvertFromUnicode_wrapper()) + return -1; + + /* ConvertToUnicode */ + + printf("ConvertToUnicode\n"); + + if (!test_ConvertToUnicode_wrapper()) + return -1; +#endif + /* + + printf("----------------------------------------------------------\n\n"); + + if (0) + { + BYTE src[] = { 'R',0,'I',0,'C',0,'H',0,' ',0, 'T',0,'E',0,'X',0,'T',0,' + ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 }; + //BYTE src[] = { 'R',0,'I',0,'C',0,'H',0,' ',0, 0,0, 'T',0,'E',0,'X',0,'T',0,' + ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 }; + //BYTE src[] = { 0,0,'R',0,'I',0,'C',0,'H',0,' ',0, 'T',0,'E',0,'X',0,'T',0,' + ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 }; char* dst = NULL; int num; num = + ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) src, 16, &dst, 0, NULL, NULL); + printf("ConvertFromUnicode returned %d dst=[%s]\n", num, dst); + string_hexdump((BYTE*)dst, num+1); + } + if (1) + { + char src[] = "RICH TEXT FORMAT@@@@@@"; + WCHAR *dst = NULL; + int num; + num = ConvertToUnicode(CP_UTF8, 0, src, 16, &dst, 0); + printf("ConvertToUnicode returned %d dst=%p\n", num, (void*) dst); + string_hexdump((BYTE*)dst, num * 2 + 2); + + } + */ + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.c new file mode 100644 index 0000000000000000000000000000000000000000..9131e7cf1b06d3ac415078ddd4843efe90d550cc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.c @@ -0,0 +1,656 @@ +/** + * WinPR: Windows Portable Runtime + * Unicode Conversion (CRT) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2022 Armin Novak + * Copyright 2022 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 +#include + +#include +#include + +#include +#include +#include + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +#ifndef _WIN32 + +#include "unicode.h" + +#include "../log.h" +#define TAG WINPR_TAG("unicode") + +/** + * Notes on cross-platform Unicode portability: + * + * Unicode has many possible Unicode Transformation Format (UTF) encodings, + * where some of the most commonly used are UTF-8, UTF-16 and sometimes UTF-32. + * + * The number in the UTF encoding name (8, 16, 32) refers to the number of bits + * per code unit. A code unit is the minimal bit combination that can represent + * a unit of encoded text in the given encoding. For instance, UTF-8 encodes + * the English alphabet using 8 bits (or one byte) each, just like in ASCII. + * + * However, the total number of code points (values in the Unicode codespace) + * only fits completely within 32 bits. This means that for UTF-8 and UTF-16, + * more than one code unit may be required to fully encode a specific value. + * UTF-8 and UTF-16 are variable-width encodings, while UTF-32 is fixed-width. + * + * UTF-8 has the advantage of being backwards compatible with ASCII, and is + * one of the most commonly used Unicode encoding. + * + * UTF-16 is used everywhere in the Windows API. The strategy employed by + * Microsoft to provide backwards compatibility in their API was to create + * an ANSI and a Unicode version of the same function, ending with A (ANSI) + * and W (Wide character, or UTF-16 Unicode). In headers, the original + * function name is replaced by a macro that defines to either the ANSI + * or Unicode version based on the definition of the _UNICODE macro. + * + * UTF-32 has the advantage of being fixed width, but wastes a lot of space + * for English text (4x more than UTF-8, 2x more than UTF-16). + * + * In C, wide character strings are often defined with the wchar_t type. + * Many functions are provided to deal with those wide character strings, + * such as wcslen (strlen equivalent) or wprintf (printf equivalent). + * + * This may lead to some confusion, since many of these functions exist + * on both Windows and Linux, but they are *not* the same! + * + * This sample hello world is a good example: + * + * #include + * + * wchar_t hello[] = L"Hello, World!\n"; + * + * int main(int argc, char** argv) + * { + * wprintf(hello); + * wprintf(L"sizeof(wchar_t): %d\n", sizeof(wchar_t)); + * return 0; + * } + * + * There is a reason why the sample prints the size of the wchar_t type: + * On Windows, wchar_t is two bytes (UTF-16), while on most other systems + * it is 4 bytes (UTF-32). This means that if you write code on Windows, + * use L"" to define a string which is meant to be UTF-16 and not UTF-32, + * you will have a little surprise when trying to port your code to Linux. + * + * Since the Windows API uses UTF-16, not UTF-32, WinPR defines the WCHAR + * type to always be 2-bytes long and uses it instead of wchar_t. Do not + * ever use wchar_t with WinPR unless you know what you are doing. + * + * As for L"", it is unfortunately unusable in a portable way, unless a + * special option is passed to GCC to define wchar_t as being two bytes. + * For string constants that must be UTF-16, it is a pain, but they can + * be defined in a portable way like this: + * + * WCHAR hello[] = { 'H','e','l','l','o','\0' }; + * + * Such strings cannot be passed to native functions like wcslen(), which + * may expect a different wchar_t size. For this reason, WinPR provides + * _wcslen, which expects UTF-16 WCHAR strings on all platforms. + * + */ + +/** \deprecated We no longer export this function, see ConvertUtf8ToWChar family of functions for a + * replacement + * + * Conversion to Unicode (UTF-16) + * MultiByteToWideChar: http://msdn.microsoft.com/en-us/library/windows/desktop/dd319072/ + * + * cbMultiByte is an input size in bytes (BYTE) + * cchWideChar is an output size in wide characters (WCHAR) + * + * Null-terminated UTF-8 strings: + * + * cchWideChar *cannot* be assumed to be cbMultiByte since UTF-8 is variable-width! + * + * Instead, obtain the required cchWideChar output size like this: + * cchWideChar = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) lpMultiByteStr, -1, NULL, 0); + * + * A value of -1 for cbMultiByte indicates that the input string is null-terminated, + * and the null terminator *will* be processed. The size returned by MultiByteToWideChar + * will therefore include the null terminator. Equivalent behavior can be obtained by + * computing the length in bytes of the input buffer, including the null terminator: + * + * cbMultiByte = strlen((char*) lpMultiByteStr) + 1; + * + * An output buffer of the proper size can then be allocated: + * + * lpWideCharStr = (LPWSTR) malloc(cchWideChar * sizeof(WCHAR)); + * + * Since cchWideChar is an output size in wide characters, the actual buffer size is: + * (cchWideChar * sizeof(WCHAR)) or (cchWideChar * 2) + * + * Finally, perform the conversion: + * + * cchWideChar = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) lpMultiByteStr, -1, lpWideCharStr, + * cchWideChar); + * + * The value returned by MultiByteToWideChar corresponds to the number of wide characters written + * to the output buffer, and should match the value obtained on the first call to + * MultiByteToWideChar. + * + */ + +#if !defined(WITH_WINPR_DEPRECATED) +static +#endif + int + MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar) +{ + return int_MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, lpWideCharStr, + cchWideChar); +} + +/** \deprecated We no longer export this function, see ConvertWCharToUtf8 family of functions for a + * replacement + * + * Conversion from Unicode (UTF-16) + * WideCharToMultiByte: http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130/ + * + * cchWideChar is an input size in wide characters (WCHAR) + * cbMultiByte is an output size in bytes (BYTE) + * + * Null-terminated UTF-16 strings: + * + * cbMultiByte *cannot* be assumed to be cchWideChar since UTF-8 is variable-width! + * + * Instead, obtain the required cbMultiByte output size like this: + * cbMultiByte = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) lpWideCharStr, -1, NULL, 0, NULL, NULL); + * + * A value of -1 for cbMultiByte indicates that the input string is null-terminated, + * and the null terminator *will* be processed. The size returned by WideCharToMultiByte + * will therefore include the null terminator. Equivalent behavior can be obtained by + * computing the length in bytes of the input buffer, including the null terminator: + * + * cchWideChar = _wcslen((WCHAR*) lpWideCharStr) + 1; + * + * An output buffer of the proper size can then be allocated: + * lpMultiByteStr = (LPSTR) malloc(cbMultiByte); + * + * Since cbMultiByte is an output size in bytes, it is the same as the buffer size + * + * Finally, perform the conversion: + * + * cbMultiByte = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) lpWideCharStr, -1, lpMultiByteStr, + * cbMultiByte, NULL, NULL); + * + * The value returned by WideCharToMultiByte corresponds to the number of bytes written + * to the output buffer, and should match the value obtained on the first call to + * WideCharToMultiByte. + * + */ + +#if !defined(WITH_WINPR_DEPRECATED) +static +#endif + int + WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + return int_WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, + cbMultiByte, lpDefaultChar, lpUsedDefaultChar); +} + +#endif + +/** + * ConvertToUnicode is a convenience wrapper for MultiByteToWideChar: + * + * If the lpWideCharStr parameter for the converted string points to NULL + * or if the cchWideChar parameter is set to 0 this function will automatically + * allocate the required memory which is guaranteed to be null-terminated + * after the conversion, even if the source c string isn't. + * + * If the cbMultiByte parameter is set to -1 the passed lpMultiByteStr must + * be null-terminated and the required length for the converted string will be + * calculated accordingly. + */ +#if defined(WITH_WINPR_DEPRECATED) +int ConvertToUnicode(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR* lpWideCharStr, int cchWideChar) +{ + int status = 0; + BOOL allocate = FALSE; + + if (!lpMultiByteStr) + return 0; + + if (!lpWideCharStr) + return 0; + + if (cbMultiByte == -1) + { + size_t len = strnlen(lpMultiByteStr, INT_MAX); + if (len >= INT_MAX) + return 0; + cbMultiByte = (int)(len + 1); + } + + if (cchWideChar == 0) + { + cchWideChar = MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, NULL, 0); + allocate = TRUE; + } + else if (!(*lpWideCharStr)) + allocate = TRUE; + + if (cchWideChar < 1) + return 0; + + if (allocate) + { + *lpWideCharStr = (LPWSTR)calloc(cchWideChar + 1, sizeof(WCHAR)); + + if (!(*lpWideCharStr)) + { + // SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + } + + status = MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, *lpWideCharStr, + cchWideChar); + + if (status != cchWideChar) + { + if (allocate) + { + free(*lpWideCharStr); + *lpWideCharStr = NULL; + status = 0; + } + } + + return status; +} +#endif + +/** + * ConvertFromUnicode is a convenience wrapper for WideCharToMultiByte: + * + * If the lpMultiByteStr parameter for the converted string points to NULL + * or if the cbMultiByte parameter is set to 0 this function will automatically + * allocate the required memory which is guaranteed to be null-terminated + * after the conversion, even if the source unicode string isn't. + * + * If the cchWideChar parameter is set to -1 the passed lpWideCharStr must + * be null-terminated and the required length for the converted string will be + * calculated accordingly. + */ +#if defined(WITH_WINPR_DEPRECATED) +int ConvertFromUnicode(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR* lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + int status = 0; + BOOL allocate = FALSE; + + if (!lpWideCharStr) + return 0; + + if (!lpMultiByteStr) + return 0; + + if (cchWideChar == -1) + cchWideChar = (int)(_wcslen(lpWideCharStr) + 1); + + if (cbMultiByte == 0) + { + cbMultiByte = + WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, NULL, 0, NULL, NULL); + allocate = TRUE; + } + else if (!(*lpMultiByteStr)) + allocate = TRUE; + + if (cbMultiByte < 1) + return 0; + + if (allocate) + { + *lpMultiByteStr = (LPSTR)calloc(1, cbMultiByte + 1); + + if (!(*lpMultiByteStr)) + { + // SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + } + + status = WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, *lpMultiByteStr, + cbMultiByte, lpDefaultChar, lpUsedDefaultChar); + + if ((status != cbMultiByte) && allocate) + { + status = 0; + } + + if ((status <= 0) && allocate) + { + free(*lpMultiByteStr); + *lpMultiByteStr = NULL; + } + + return status; +} +#endif + +/** + * Swap Unicode byte order (UTF16LE <-> UTF16BE) + */ + +const WCHAR* ByteSwapUnicode(WCHAR* wstr, size_t length) +{ + WINPR_ASSERT(wstr || (length == 0)); + + for (size_t x = 0; x < length; x++) + wstr[x] = _byteswap_ushort(wstr[x]); + return wstr; +} + +SSIZE_T ConvertWCharToUtf8(const WCHAR* wstr, char* str, size_t len) +{ + if (!wstr) + { + if (str && len) + str[0] = 0; + return 0; + } + + const size_t wlen = _wcslen(wstr); + return ConvertWCharNToUtf8(wstr, wlen + 1, str, len); +} + +SSIZE_T ConvertWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t len) +{ + BOOL isNullTerminated = FALSE; + if (wlen == 0) + return 0; + + WINPR_ASSERT(wstr); + size_t iwlen = _wcsnlen(wstr, wlen); + + if ((len > INT32_MAX) || (wlen > INT32_MAX)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + + if (iwlen < wlen) + { + isNullTerminated = TRUE; + iwlen++; + } + const int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)iwlen, str, (int)len, NULL, NULL); + if ((rc <= 0) || ((len > 0) && ((size_t)rc > len))) + return -1; + else if (!isNullTerminated) + { + if (str && ((size_t)rc < len)) + str[rc] = '\0'; + return rc; + } + else if ((size_t)rc == len) + { + if (str && (str[rc - 1] != '\0')) + return rc; + } + return rc - 1; +} + +SSIZE_T ConvertMszWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t len) +{ + if (wlen == 0) + return 0; + + WINPR_ASSERT(wstr); + + if ((len > INT32_MAX) || (wlen > INT32_MAX)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + + const int iwlen = (int)len; + const int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)wlen, str, iwlen, NULL, NULL); + if ((rc <= 0) || ((len > 0) && (rc > iwlen))) + return -1; + + return rc; +} + +SSIZE_T ConvertUtf8ToWChar(const char* str, WCHAR* wstr, size_t wlen) +{ + if (!str) + { + if (wstr && wlen) + wstr[0] = 0; + return 0; + } + + const size_t len = strlen(str); + return ConvertUtf8NToWChar(str, len + 1, wstr, wlen); +} + +SSIZE_T ConvertUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wlen) +{ + size_t ilen = strnlen(str, len); + BOOL isNullTerminated = FALSE; + if (len == 0) + return 0; + + WINPR_ASSERT(str); + + if ((len > INT32_MAX) || (wlen > INT32_MAX)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + if (ilen < len) + { + isNullTerminated = TRUE; + ilen++; + } + + const int iwlen = (int)wlen; + const int rc = MultiByteToWideChar(CP_UTF8, 0, str, (int)ilen, wstr, iwlen); + if ((rc <= 0) || ((wlen > 0) && (rc > iwlen))) + return -1; + if (!isNullTerminated) + { + if (wstr && (rc < iwlen)) + wstr[rc] = '\0'; + return rc; + } + else if (rc == iwlen) + { + if (wstr && (wstr[rc - 1] != '\0')) + return rc; + } + return rc - 1; +} + +SSIZE_T ConvertMszUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wlen) +{ + if (len == 0) + return 0; + + WINPR_ASSERT(str); + + if ((len > INT32_MAX) || (wlen > INT32_MAX)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + + const int iwlen = (int)wlen; + const int rc = MultiByteToWideChar(CP_UTF8, 0, str, (int)len, wstr, iwlen); + if ((rc <= 0) || ((wlen > 0) && (rc > iwlen))) + return -1; + + return rc; +} + +char* ConvertWCharToUtf8Alloc(const WCHAR* wstr, size_t* pUtfCharLength) +{ + char* tmp = NULL; + const SSIZE_T rc = ConvertWCharToUtf8(wstr, NULL, 0); + if (pUtfCharLength) + *pUtfCharLength = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(char)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertWCharToUtf8(wstr, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pUtfCharLength) + *pUtfCharLength = (size_t)rc2; + return tmp; +} + +char* ConvertWCharNToUtf8Alloc(const WCHAR* wstr, size_t wlen, size_t* pUtfCharLength) +{ + char* tmp = NULL; + const SSIZE_T rc = ConvertWCharNToUtf8(wstr, wlen, NULL, 0); + + if (pUtfCharLength) + *pUtfCharLength = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(char)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertWCharNToUtf8(wstr, wlen, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pUtfCharLength) + *pUtfCharLength = (size_t)rc2; + return tmp; +} + +char* ConvertMszWCharNToUtf8Alloc(const WCHAR* wstr, size_t wlen, size_t* pUtfCharLength) +{ + char* tmp = NULL; + const SSIZE_T rc = ConvertMszWCharNToUtf8(wstr, wlen, NULL, 0); + + if (pUtfCharLength) + *pUtfCharLength = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(char)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertMszWCharNToUtf8(wstr, wlen, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pUtfCharLength) + *pUtfCharLength = (size_t)rc2; + return tmp; +} + +WCHAR* ConvertUtf8ToWCharAlloc(const char* str, size_t* pSize) +{ + WCHAR* tmp = NULL; + const SSIZE_T rc = ConvertUtf8ToWChar(str, NULL, 0); + if (pSize) + *pSize = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(WCHAR)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertUtf8ToWChar(str, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pSize) + *pSize = (size_t)rc2; + return tmp; +} + +WCHAR* ConvertUtf8NToWCharAlloc(const char* str, size_t len, size_t* pSize) +{ + WCHAR* tmp = NULL; + const SSIZE_T rc = ConvertUtf8NToWChar(str, len, NULL, 0); + if (pSize) + *pSize = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(WCHAR)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertUtf8NToWChar(str, len, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pSize) + *pSize = (size_t)rc2; + return tmp; +} + +WCHAR* ConvertMszUtf8NToWCharAlloc(const char* str, size_t len, size_t* pSize) +{ + WCHAR* tmp = NULL; + const SSIZE_T rc = ConvertMszUtf8NToWChar(str, len, NULL, 0); + if (pSize) + *pSize = 0; + if (rc < 0) + return NULL; + tmp = calloc((size_t)rc + 1ull, sizeof(WCHAR)); + if (!tmp) + return NULL; + const SSIZE_T rc2 = ConvertMszUtf8NToWChar(str, len, tmp, (size_t)rc + 1ull); + if (rc2 < 0) + { + free(tmp); + return NULL; + } + WINPR_ASSERT(rc == rc2); + if (pSize) + *pSize = (size_t)rc2; + return tmp; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.h new file mode 100644 index 0000000000000000000000000000000000000000..9305f2ce188d48db36001145aeca4928eac5410a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode.h @@ -0,0 +1,32 @@ +/** + * WinPR: Windows Portable Runtime + * Unicode Conversion (CRT) + * + * Copyright 2022 Armin Novak + * Copyright 2022 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_CRT_UNICODE_INTERNAL +#define WINPR_CRT_UNICODE_INTERNAL + +#include + +int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar); + +int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar); +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_android.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_android.c new file mode 100644 index 0000000000000000000000000000000000000000..9fa16f6d495ce4d66eb4677dab26afee518a4ae0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_android.c @@ -0,0 +1,184 @@ +/** + * WinPR: Windows Portable Runtime + * Unicode Conversion (CRT) + * + * Copyright 2022 Armin Novak + * Copyright 2022 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 +#include +#include + +#include "../utils/android.h" +#include "unicode.h" + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +#include "../log.h" +#define TAG WINPR_TAG("unicode") + +static int convert_int(JNIEnv* env, const void* data, size_t size, void* buffer, size_t buffersize, + BOOL toUTF16) +{ + WINPR_ASSERT(env); + WINPR_ASSERT(data || (size == 0)); + WINPR_ASSERT(buffer || (buffersize == 0)); + + jstring utf8 = (*env)->NewStringUTF(env, "UTF-8"); + jstring utf16 = (*env)->NewStringUTF(env, "UTF-16LE"); + jclass stringClass = (*env)->FindClass(env, "java/lang/String"); + + if (!utf8 || !utf16 || !stringClass) + { + WLog_ERR(TAG, "utf8-%p, utf16=%p, stringClass=%p", utf8, utf16, stringClass); + return -1; + } + + jmethodID constructorID = + (*env)->GetMethodID(env, stringClass, "", "([BLjava/lang/String;)V"); + jmethodID getBytesID = + (*env)->GetMethodID(env, stringClass, "getBytes", "(Ljava/lang/String;)[B"); + if (!constructorID || !getBytesID) + { + WLog_ERR(TAG, "constructorID=%p, getBytesID=%p", constructorID, getBytesID); + return -2; + } + + jbyteArray ret = (*env)->NewByteArray(env, size); + if (!ret) + { + WLog_ERR(TAG, "NewByteArray(%" PRIuz ") failed", size); + return -3; + } + + (*env)->SetByteArrayRegion(env, ret, 0, size, data); + + jobject obj = (*env)->NewObject(env, stringClass, constructorID, ret, toUTF16 ? utf8 : utf16); + if (!obj) + { + WLog_ERR(TAG, "NewObject(String, byteArray, UTF-%d) failed", toUTF16 ? 16 : 8); + return -4; + } + + jbyteArray res = (*env)->CallObjectMethod(env, obj, getBytesID, toUTF16 ? utf16 : utf8); + if (!res) + { + WLog_ERR(TAG, "CallObjectMethod(String, getBytes, UTF-%d) failed", toUTF16 ? 16 : 8); + return -4; + } + + jsize rlen = (*env)->GetArrayLength(env, res); + if (buffersize > 0) + { + if (rlen > buffersize) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + rlen = MIN(rlen, buffersize); + (*env)->GetByteArrayRegion(env, res, 0, rlen, buffer); + } + + if (toUTF16) + rlen /= sizeof(WCHAR); + + return rlen; +} + +static int convert(const void* data, size_t size, void* buffer, size_t buffersize, BOOL toUTF16) +{ + int rc; + JNIEnv* env = NULL; + jboolean attached = winpr_jni_attach_thread(&env); + rc = convert_int(env, data, size, buffer, buffersize, toUTF16); + if (attached) + winpr_jni_detach_thread(); + return rc; +} + +int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar) +{ + size_t cbCharLen = (size_t)cbMultiByte; + + WINPR_UNUSED(dwFlags); + + /* If cbMultiByte is 0, the function fails */ + if ((cbMultiByte == 0) || (cbMultiByte < -1)) + return 0; + + if (cchWideChar < 0) + return -1; + + if (cbMultiByte < 0) + { + const size_t len = strlen(lpMultiByteStr); + if (len >= INT32_MAX) + return 0; + cbCharLen = (int)len + 1; + } + else + cbCharLen = cbMultiByte; + + WINPR_ASSERT(lpMultiByteStr); + switch (CodePage) + { + case CP_ACP: + case CP_UTF8: + break; + + default: + WLog_ERR(TAG, "Unsupported encoding %u", CodePage); + return 0; + } + + return convert(lpMultiByteStr, cbCharLen, lpWideCharStr, cchWideChar * sizeof(WCHAR), TRUE); +} + +int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + size_t cbCharLen = (size_t)cchWideChar; + + WINPR_UNUSED(dwFlags); + /* If cchWideChar is 0, the function fails */ + if ((cchWideChar == 0) || (cchWideChar < -1)) + return 0; + + if (cbMultiByte < 0) + return -1; + + WINPR_ASSERT(lpWideCharStr); + /* If cchWideChar is -1, the string is null-terminated */ + if (cchWideChar == -1) + { + const size_t len = _wcslen(lpWideCharStr); + if (len >= INT32_MAX) + return 0; + cbCharLen = (int)len + 1; + } + else + cbCharLen = cchWideChar; + + /* + * if cbMultiByte is 0, the function returns the required buffer size + * in bytes for lpMultiByteStr and makes no use of the output parameter itself. + */ + return convert(lpWideCharStr, cbCharLen * sizeof(WCHAR), lpMultiByteStr, cbMultiByte, FALSE); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_apple.m b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_apple.m new file mode 100644 index 0000000000000000000000000000000000000000..3b966634aa22f932c8560869083abe97494e1be3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_apple.m @@ -0,0 +1,148 @@ +/** + * WinPR: Windows Portable Runtime + * Unicode Conversion (CRT) + * + * Copyright 2022 Armin Novak + * Copyright 2022 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. + */ + +#import + +#include +#include + +#include +#include + +#include +#include +#include + +#include "unicode.h" + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +#include "../log.h" +#define TAG WINPR_TAG("unicode") + +int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar) +{ + const BOOL isNullTerminated = cbMultiByte < 0; + + /* If cbMultiByte is 0, the function fails */ + if ((cbMultiByte == 0) || (cbMultiByte < -1)) + return 0; + + /* If cbMultiByte is -1, the string is null-terminated */ + if (isNullTerminated) + { + size_t len = strnlen(lpMultiByteStr, INT32_MAX); + if (len >= INT32_MAX) + return 0; + cbMultiByte = (int)len + 1; + } + + NSString *utf = [[NSString alloc] initWithBytes:lpMultiByteStr + length:cbMultiByte + encoding:NSUTF8StringEncoding]; + if (!utf) + { + WLog_WARN(TAG, "[NSString alloc] NSUTF8StringEncoding failed [%d] '%s'", cbMultiByte, + lpMultiByteStr); + return -1; + } + + const WCHAR *utf16 = + (const WCHAR *)[utf cStringUsingEncoding:NSUTF16LittleEndianStringEncoding]; + const size_t utf16ByteLen = [utf lengthOfBytesUsingEncoding:NSUTF16LittleEndianStringEncoding]; + const size_t utf16CharLen = utf16ByteLen / sizeof(WCHAR); + if (!utf16) + { + WLog_WARN(TAG, "[utf cStringUsingEncoding:NSUTF16LittleEndianStringEncoding] failed"); + return -1; + } + + if (cchWideChar == 0) + return utf16CharLen; + else if (cchWideChar < utf16CharLen) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + else + { + const size_t mlen = MIN((size_t)utf16CharLen, cchWideChar); + const size_t len = _wcsnlen(utf16, mlen); + memcpy(lpWideCharStr, utf16, len * sizeof(WCHAR)); + if ((len < (size_t)cchWideChar) && (len > 0) && (lpWideCharStr[len - 1] != '\0')) + lpWideCharStr[len] = '\0'; + return utf16CharLen; + } +} + +int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + const BOOL isNullTerminated = cchWideChar < 0; + + /* If cchWideChar is 0, the function fails */ + if ((cchWideChar == 0) || (cchWideChar < -1)) + return 0; + + /* If cchWideChar is -1, the string is null-terminated */ + if (isNullTerminated) + { + size_t len = _wcslen(lpWideCharStr); + if (len >= INT32_MAX) + return 0; + cchWideChar = (int)len + 1; + } + + NSString *utf = [[NSString alloc] initWithCharacters:lpWideCharStr length:cchWideChar]; + if (!utf) + { + WLog_WARN(TAG, "[NSString alloc] initWithCharacters failed [%d] 'XXX'", cchWideChar); + return -1; + } + + const char *utf8 = [utf cStringUsingEncoding:NSUTF8StringEncoding]; + const size_t utf8Len = [utf lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + if (!utf8) + { + WLog_WARN(TAG, "[utf cStringUsingEncoding:NSUTF8StringEncoding] failed"); + return -1; + } + + if (cbMultiByte == 0) + return utf8Len; + else if (cbMultiByte < utf8Len) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + else + { + const size_t mlen = MIN((size_t)cbMultiByte, utf8Len); + const size_t len = strnlen(utf8, mlen); + memcpy(lpMultiByteStr, utf8, len * sizeof(char)); + if ((len < (size_t)cbMultiByte) && (len > 0) && (lpMultiByteStr[len - 1] != '\0')) + lpMultiByteStr[len] = '\0'; + return utf8Len; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_builtin.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_builtin.c new file mode 100644 index 0000000000000000000000000000000000000000..394122fdc78a419c08e71292fb7e3428c931c3ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_builtin.c @@ -0,0 +1,699 @@ +/* + * Copyright 2001-2004 Unicode, Inc. + * + * Disclaimer + * + * This source code is provided as is by Unicode, Inc. No claims are + * made as to fitness for any particular purpose. No warranties of any + * kind are expressed or implied. The recipient agrees to determine + * applicability of information provided. If this file has been + * purchased on magnetic or optical media from Unicode, Inc., the + * sole remedy for any claim will be exchange of defective media + * within 90 days of receipt. + * + * Limitations on Rights to Redistribute This Code + * + * Unicode, Inc. hereby grants the right to freely use the information + * supplied in this file in the creation of products supporting the + * Unicode Standard, and to make copies of this file in any form + * for internal or external distribution as long as this notice + * remains attached. + */ + +/* --------------------------------------------------------------------- + +Conversions between UTF32, UTF-16, and UTF-8. Source code file. +Author: Mark E. Davis, 1994. +Rev History: Rick McGowan, fixes & updates May 2001. +Sept 2001: fixed const & error conditions per +mods suggested by S. Parent & A. Lillich. +June 2002: Tim Dodd added detection and handling of incomplete +source sequences, enhanced error detection, added casts +to eliminate compiler warnings. +July 2003: slight mods to back out aggressive FFFE detection. +Jan 2004: updated switches in from-UTF8 conversions. +Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions. + +See the header file "utf.h" for complete documentation. + +------------------------------------------------------------------------ */ + +#include +#include +#include +#include + +#include "unicode.h" + +#include "../log.h" +#define TAG WINPR_TAG("unicode") + +/* + * Character Types: + * + * UTF8: uint8_t 8 bits + * UTF16: uint16_t 16 bits + * UTF32: uint32_t 32 bits + */ + +/* Some fundamental constants */ +#define UNI_REPLACEMENT_CHAR (uint32_t)0x0000FFFD +#define UNI_MAX_BMP (uint32_t)0x0000FFFF +#define UNI_MAX_UTF16 (uint32_t)0x0010FFFF +#define UNI_MAX_UTF32 (uint32_t)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (uint32_t)0x0010FFFF + +typedef enum +{ + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +typedef enum +{ + strictConversion = 0, + lenientConversion +} ConversionFlags; + +static const int halfShift = 10; /* used for shifting by 10 bits */ + +static const uint32_t halfBase = 0x0010000UL; +static const uint32_t halfMask = 0x3FFUL; + +#define UNI_SUR_HIGH_START (uint32_t)0xD800 +#define UNI_SUR_HIGH_END (uint32_t)0xDBFF +#define UNI_SUR_LOW_START (uint32_t)0xDC00 +#define UNI_SUR_LOW_END (uint32_t)0xDFFF + +/* --------------------------------------------------------------------- */ + +/* + * Index into the table below with the first byte of a UTF-8 sequence to + * get the number of trailing bytes that are supposed to follow it. + * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is + * left as-is for anyone who may want to do such conversion, which was + * allowed in earlier algorithms. + */ +static const char trailingBytesForUTF8[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 +}; + +/* + * Magic values subtracted from a buffer value during UTF8 conversion. + * This table contains as many values as there might be trailing bytes + * in a UTF-8 sequence. + */ +static const uint32_t offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, + 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; + +/* + * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed + * into the first byte, depending on how many bytes follow. There are + * as many entries in this table as there are UTF-8 sequence types. + * (I.e., one byte sequence, two byte... etc.). Remember that sequence + * for *legal* UTF-8 will be 4 or fewer bytes total. + */ +static const uint8_t firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + +/* --------------------------------------------------------------------- */ + +/* The interface converts a whole buffer to avoid function-call overhead. + * Constants have been gathered. Loops & conditionals have been removed as + * much as possible for efficiency, in favor of drop-through switches. + * (See "Note A" at the bottom of the file for equivalent code.) + * If your compiler supports it, the "isLegalUTF8" call can be turned + * into an inline function. + */ + +/* --------------------------------------------------------------------- */ + +static ConversionResult winpr_ConvertUTF16toUTF8_Internal(const uint16_t** sourceStart, + const uint16_t* sourceEnd, + uint8_t** targetStart, uint8_t* targetEnd, + ConversionFlags flags) +{ + bool computeLength = (!targetEnd) ? true : false; + const uint16_t* source = *sourceStart; + uint8_t* target = *targetStart; + ConversionResult result = conversionOK; + + while (source < sourceEnd) + { + uint32_t ch = 0; + unsigned short bytesToWrite = 0; + const uint32_t byteMask = 0xBF; + const uint32_t byteMark = 0x80; + const uint16_t* oldSource = + source; /* In case we have to back up because of target overflow. */ + + ch = *source++; + + /* If we have a surrogate pair, convert to UTF32 first. */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) + { + /* If the 16 bits following the high surrogate are in the source buffer... */ + if (source < sourceEnd) + { + uint32_t ch2 = *source; + + /* If it's a low surrogate, convert to UTF32. */ + if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) + { + ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + + halfBase; + ++source; + } + else if (flags == strictConversion) + { + /* it's an unpaired high surrogate */ + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + else + { + /* We don't have the 16 bits following the high surrogate. */ + --source; /* return to the high surrogate */ + result = sourceExhausted; + break; + } + } + else if (flags == strictConversion) + { + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) + { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + + /* Figure out how many bytes the result will require */ + if (ch < (uint32_t)0x80) + { + bytesToWrite = 1; + } + else if (ch < (uint32_t)0x800) + { + bytesToWrite = 2; + } + else if (ch < (uint32_t)0x10000) + { + bytesToWrite = 3; + } + else if (ch < (uint32_t)0x110000) + { + bytesToWrite = 4; + } + else + { + bytesToWrite = 3; + ch = UNI_REPLACEMENT_CHAR; + } + + target += bytesToWrite; + + if ((target > targetEnd) && (!computeLength)) + { + source = oldSource; /* Back up source pointer! */ + target -= bytesToWrite; + result = targetExhausted; + break; + } + + if (!computeLength) + { + switch (bytesToWrite) + { + /* note: everything falls through. */ + case 4: + *--target = (uint8_t)((ch | byteMark) & byteMask); + ch >>= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + case 3: + *--target = (uint8_t)((ch | byteMark) & byteMask); + ch >>= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 2: + *--target = (uint8_t)((ch | byteMark) & byteMask); + ch >>= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 1: + *--target = (uint8_t)(ch | firstByteMark[bytesToWrite]); + } + } + else + { + switch (bytesToWrite) + { + /* note: everything falls through. */ + case 4: + --target; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 3: + --target; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 2: + --target; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 1: + --target; + } + } + + target += bytesToWrite; + } + + *sourceStart = source; + *targetStart = target; + return result; +} + +/* --------------------------------------------------------------------- */ + +/* + * Utility routine to tell whether a sequence of bytes is legal UTF-8. + * This must be called with the length pre-determined by the first byte. + * If not calling this from ConvertUTF8to*, then the length can be set by: + * length = trailingBytesForUTF8[*source]+1; + * and the sequence is illegal right away if there aren't that many bytes + * available. + * If presented with a length > 4, this returns false. The Unicode + * definition of UTF-8 goes up to 4-byte sequences. + */ + +static bool isLegalUTF8(const uint8_t* source, int length) +{ + uint8_t a = 0; + const uint8_t* srcptr = source + length; + + switch (length) + { + default: + return false; + + /* Everything else falls through when "true"... */ + case 4: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) + return false; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 3: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) + return false; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 2: + if ((a = (*--srcptr)) > 0xBF) + return false; + + switch (*source) + { + /* no fall-through in this inner switch */ + case 0xE0: + if (a < 0xA0) + return false; + + break; + + case 0xED: + if (a > 0x9F) + return false; + + break; + + case 0xF0: + if (a < 0x90) + return false; + + break; + + case 0xF4: + if (a > 0x8F) + return false; + + break; + + default: + if (a < 0x80) + return false; + break; + } + /* fallthrough */ + WINPR_FALLTHROUGH + + case 1: + if (*source >= 0x80 && *source < 0xC2) + return false; + } + + if (*source > 0xF4) + return false; + + return true; +} + +/* --------------------------------------------------------------------- */ + +static ConversionResult winpr_ConvertUTF8toUTF16_Internal(const uint8_t** sourceStart, + const uint8_t* sourceEnd, + uint16_t** targetStart, + uint16_t* targetEnd, + ConversionFlags flags) +{ + bool computeLength = (!targetEnd) ? true : false; + ConversionResult result = conversionOK; + const uint8_t* source = *sourceStart; + uint16_t* target = *targetStart; + + while (source < sourceEnd) + { + uint32_t ch = 0; + unsigned short extraBytesToRead = + WINPR_ASSERTING_INT_CAST(unsigned short, trailingBytesForUTF8[*source]); + + if ((source + extraBytesToRead) >= sourceEnd) + { + result = sourceExhausted; + break; + } + + /* Do this check whether lenient or strict */ + if (!isLegalUTF8(source, extraBytesToRead + 1)) + { + result = sourceIllegal; + break; + } + + /* + * The cases all fall through. See "Note A" below. + */ + switch (extraBytesToRead) + { + case 5: + ch += *source++; + ch <<= 6; /* remember, illegal UTF-8 */ + /* fallthrough */ + WINPR_FALLTHROUGH + + case 4: + ch += *source++; + ch <<= 6; /* remember, illegal UTF-8 */ + /* fallthrough */ + WINPR_FALLTHROUGH + + case 3: + ch += *source++; + ch <<= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 2: + ch += *source++; + ch <<= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 1: + ch += *source++; + ch <<= 6; + /* fallthrough */ + WINPR_FALLTHROUGH + + case 0: + ch += *source++; + } + + ch -= offsetsFromUTF8[extraBytesToRead]; + + if ((target >= targetEnd) && (!computeLength)) + { + source -= (extraBytesToRead + 1); /* Back up source pointer! */ + result = targetExhausted; + break; + } + + if (ch <= UNI_MAX_BMP) + { + /* Target is a character <= 0xFFFF */ + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + { + if (flags == strictConversion) + { + source -= (extraBytesToRead + 1); /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + else + { + if (!computeLength) + *target++ = UNI_REPLACEMENT_CHAR; + else + target++; + } + } + else + { + if (!computeLength) + *target++ = (uint16_t)ch; /* normal case */ + else + target++; + } + } + else if (ch > UNI_MAX_UTF16) + { + if (flags == strictConversion) + { + result = sourceIllegal; + source -= (extraBytesToRead + 1); /* return to the start */ + break; /* Bail out; shouldn't continue */ + } + else + { + if (!computeLength) + *target++ = UNI_REPLACEMENT_CHAR; + else + target++; + } + } + else + { + /* target is a character in range 0xFFFF - 0x10FFFF. */ + if ((target + 1 >= targetEnd) && (!computeLength)) + { + source -= (extraBytesToRead + 1); /* Back up source pointer! */ + result = targetExhausted; + break; + } + + ch -= halfBase; + + if (!computeLength) + { + *target++ = (uint16_t)((ch >> halfShift) + UNI_SUR_HIGH_START); + *target++ = (uint16_t)((ch & halfMask) + UNI_SUR_LOW_START); + } + else + { + target++; + target++; + } + } + } + + *sourceStart = source; + *targetStart = target; + return result; +} + +/** + * WinPR built-in Unicode API + */ + +static int winpr_ConvertUTF8toUTF16(const uint8_t* src, int cchSrc, uint16_t* dst, int cchDst) +{ + size_t length = 0; + uint16_t* dstBeg = NULL; + uint16_t* dstEnd = NULL; + const uint8_t* srcBeg = NULL; + const uint8_t* srcEnd = NULL; + ConversionResult result = sourceIllegal; + + if (cchSrc == -1) + cchSrc = (int)strnlen((const char*)src, INT32_MAX - 1) + 1; + + srcBeg = src; + srcEnd = &src[cchSrc]; + + if (cchDst == 0) + { + result = + winpr_ConvertUTF8toUTF16_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd, strictConversion); + + length = dstBeg - (uint16_t*)NULL; + } + else + { + dstBeg = dst; + dstEnd = &dst[cchDst]; + + result = + winpr_ConvertUTF8toUTF16_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd, strictConversion); + + length = dstBeg - dst; + } + + if (result == targetExhausted) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + + return (result == conversionOK) ? WINPR_ASSERTING_INT_CAST(int, length) : 0; +} + +static int winpr_ConvertUTF16toUTF8(const uint16_t* src, int cchSrc, uint8_t* dst, int cchDst) +{ + size_t length = 0; + uint8_t* dstBeg = NULL; + uint8_t* dstEnd = NULL; + const uint16_t* srcBeg = NULL; + const uint16_t* srcEnd = NULL; + ConversionResult result = sourceIllegal; + + if (cchSrc == -1) + cchSrc = (int)_wcsnlen((const WCHAR*)src, INT32_MAX - 1) + 1; + + srcBeg = src; + srcEnd = &src[cchSrc]; + + if (cchDst == 0) + { + result = + winpr_ConvertUTF16toUTF8_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd, strictConversion); + + length = dstBeg - ((uint8_t*)NULL); + } + else + { + dstBeg = dst; + dstEnd = &dst[cchDst]; + + result = + winpr_ConvertUTF16toUTF8_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd, strictConversion); + + length = dstBeg - dst; + } + + if (result == targetExhausted) + { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + + return (result == conversionOK) ? WINPR_ASSERTING_INT_CAST(int, length) : 0; +} + +/* --------------------------------------------------------------------- */ + +int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar) +{ + size_t cbCharLen = (size_t)cbMultiByte; + + WINPR_UNUSED(dwFlags); + + /* If cbMultiByte is 0, the function fails */ + if ((cbMultiByte == 0) || (cbMultiByte < -1)) + return 0; + + if (cchWideChar < 0) + return -1; + + if (cbMultiByte < 0) + { + const size_t len = strlen(lpMultiByteStr); + if (len >= INT32_MAX) + return 0; + cbCharLen = (int)len + 1; + } + else + cbCharLen = cbMultiByte; + + WINPR_ASSERT(lpMultiByteStr); + switch (CodePage) + { + case CP_ACP: + case CP_UTF8: + break; + + default: + WLog_ERR(TAG, "Unsupported encoding %u", CodePage); + return 0; + } + + return winpr_ConvertUTF8toUTF16((const uint8_t*)lpMultiByteStr, + WINPR_ASSERTING_INT_CAST(int, cbCharLen), + (uint16_t*)lpWideCharStr, cchWideChar); +} + +int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + size_t cbCharLen = (size_t)cchWideChar; + + WINPR_UNUSED(dwFlags); + /* If cchWideChar is 0, the function fails */ + if ((cchWideChar == 0) || (cchWideChar < -1)) + return 0; + + if (cbMultiByte < 0) + return -1; + + WINPR_ASSERT(lpWideCharStr); + /* If cchWideChar is -1, the string is null-terminated */ + if (cchWideChar == -1) + { + const size_t len = _wcslen(lpWideCharStr); + if (len >= INT32_MAX) + return 0; + cbCharLen = (int)len + 1; + } + else + cbCharLen = cchWideChar; + + /* + * if cbMultiByte is 0, the function returns the required buffer size + * in bytes for lpMultiByteStr and makes no use of the output parameter itself. + */ + + return winpr_ConvertUTF16toUTF8((const uint16_t*)lpWideCharStr, + WINPR_ASSERTING_INT_CAST(int, cbCharLen), + (uint8_t*)lpMultiByteStr, cbMultiByte); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_icu.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_icu.c new file mode 100644 index 0000000000000000000000000000000000000000..0f8c3ab0fb41b25735eec9fed6c9e0c511d38b50 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crt/unicode_icu.c @@ -0,0 +1,237 @@ +/** + * WinPR: Windows Portable Runtime + * Unicode Conversion (CRT) + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2022 Armin Novak + * Copyright 2022 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 +#include + +#include +#include + +#include +#include +#include + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +#include +#include + +#include "unicode.h" + +#include "../log.h" +#define TAG WINPR_TAG("unicode") + +#define UCNV_CONVERT 1 + +int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, + LPWSTR lpWideCharStr, int cchWideChar) +{ + const BOOL isNullTerminated = cbMultiByte < 0; + + WINPR_UNUSED(dwFlags); + + /* If cbMultiByte is 0, the function fails */ + + if ((cbMultiByte == 0) || (cbMultiByte < -1)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + + size_t len = 0; + if (isNullTerminated) + len = strlen(lpMultiByteStr) + 1; + else + len = WINPR_ASSERTING_INT_CAST(size_t, cbMultiByte); + + if (len >= INT_MAX) + { + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + cbMultiByte = WINPR_ASSERTING_INT_CAST(int, len); + + /* + * if cchWideChar is 0, the function returns the required buffer size + * in characters for lpWideCharStr and makes no use of the output parameter itself. + */ + { + UErrorCode error = U_ZERO_ERROR; + int32_t targetLength = -1; + + switch (CodePage) + { + case CP_ACP: + case CP_UTF8: + break; + + default: + WLog_ERR(TAG, "Unsupported encoding %u", CodePage); + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + + const int32_t targetCapacity = cchWideChar; +#if defined(UCNV_CONVERT) + char* targetStart = (char*)lpWideCharStr; + targetLength = + ucnv_convert("UTF-16LE", "UTF-8", targetStart, targetCapacity * (int32_t)sizeof(WCHAR), + lpMultiByteStr, cbMultiByte, &error); + if (targetLength > 0) + targetLength /= sizeof(WCHAR); +#else + WCHAR* targetStart = lpWideCharStr; + u_strFromUTF8(targetStart, targetCapacity, &targetLength, lpMultiByteStr, cbMultiByte, + &error); +#endif + + switch (error) + { + case U_BUFFER_OVERFLOW_ERROR: + if (targetCapacity > 0) + { + cchWideChar = 0; + WLog_ERR(TAG, "insufficient buffer supplied, got %d, required %d", + targetCapacity, targetLength); + SetLastError(ERROR_INSUFFICIENT_BUFFER); + } + else + cchWideChar = targetLength; + break; + case U_STRING_NOT_TERMINATED_WARNING: + cchWideChar = targetLength; + break; + case U_ZERO_ERROR: + cchWideChar = targetLength; + break; + default: + WLog_WARN(TAG, "unexpected ICU error code %s [0x%08" PRIx32 "]", u_errorName(error), + error); + if (U_FAILURE(error)) + { + WLog_ERR(TAG, "unexpected ICU error code %s [0x%08" PRIx32 "] is fatal", + u_errorName(error), error); + cchWideChar = 0; + SetLastError(ERROR_NO_UNICODE_TRANSLATION); + } + else + cchWideChar = targetLength; + break; + } + } + + return cchWideChar; +} + +int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, + LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, + LPBOOL lpUsedDefaultChar) +{ + /* If cchWideChar is 0, the function fails */ + + if ((cchWideChar == 0) || (cchWideChar < -1)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + + /* If cchWideChar is -1, the string is null-terminated */ + + size_t len = 0; + if (cchWideChar == -1) + len = _wcslen(lpWideCharStr) + 1; + else + len = WINPR_ASSERTING_INT_CAST(size_t, cchWideChar); + + if (len >= INT32_MAX) + { + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + cchWideChar = WINPR_ASSERTING_INT_CAST(int, len); + + /* + * if cbMultiByte is 0, the function returns the required buffer size + * in bytes for lpMultiByteStr and makes no use of the output parameter itself. + */ + { + UErrorCode error = U_ZERO_ERROR; + int32_t targetLength = -1; + + switch (CodePage) + { + case CP_ACP: + case CP_UTF8: + break; + + default: + WLog_ERR(TAG, "Unsupported encoding %u", CodePage); + SetLastError(ERROR_INVALID_PARAMETER); + return 0; + } + + char* targetStart = lpMultiByteStr; + const int32_t targetCapacity = cbMultiByte; +#if defined(UCNV_CONVERT) + const char* str = (const char*)lpWideCharStr; + targetLength = ucnv_convert("UTF-8", "UTF-16LE", targetStart, targetCapacity, str, + cchWideChar * (int32_t)sizeof(WCHAR), &error); +#else + u_strToUTF8(targetStart, targetCapacity, &targetLength, lpWideCharStr, cchWideChar, &error); +#endif + switch (error) + { + case U_BUFFER_OVERFLOW_ERROR: + if (targetCapacity > 0) + { + WLog_ERR(TAG, "insufficient buffer supplied, got %d, required %d", + targetCapacity, targetLength); + cbMultiByte = 0; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + } + else + cbMultiByte = targetLength; + break; + case U_STRING_NOT_TERMINATED_WARNING: + cbMultiByte = targetLength; + break; + case U_ZERO_ERROR: + cbMultiByte = targetLength; + break; + default: + WLog_WARN(TAG, "unexpected ICU error code %s [0x%08" PRIx32 "]", u_errorName(error), + error); + if (U_FAILURE(error)) + { + WLog_ERR(TAG, "unexpected ICU error code %s [0x%08" PRIx32 "] is fatal", + u_errorName(error), error); + cbMultiByte = 0; + SetLastError(ERROR_NO_UNICODE_TRANSLATION); + } + else + cbMultiByte = targetLength; + break; + } + } + return cbMultiByte; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..229d3ecd2d424a68d79d48c571e963be3dce0bdb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/CMakeLists.txt @@ -0,0 +1,50 @@ +# WinPR: Windows Portable Runtime +# libwinpr-crypto cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(SRCS hash.c rand.c cipher.c cert.c crypto.c crypto.h) +if(WITH_INTERNAL_RC4) + list(APPEND SRCS rc4.c rc4.h) +endif() + +if(WITH_INTERNAL_MD4) + list(APPEND SRCS md4.c md4.h) +endif() + +if(WITH_INTERNAL_MD5) + list(APPEND SRCS md5.c md5.h) + list(APPEND SRCS hmac_md5.c hmac_md5.h) +endif() + +winpr_module_add(${SRCS}) + +if(OPENSSL_FOUND) + winpr_system_include_directory_add(${OPENSSL_INCLUDE_DIR}) + winpr_library_add_private(${OPENSSL_LIBRARIES}) +endif() + +if(MBEDTLS_FOUND) + winpr_system_include_directory_add(${MBEDTLS_INCLUDE_DIR}) + winpr_library_add_private(${MBEDTLS_LIBRARIES}) +endif() + +if(WIN32) + winpr_library_add_public(crypt32) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3c7d9cdf1cd0ca42b980130a2b64e77b5c358f78 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/ModuleOptions.cmake @@ -0,0 +1,7 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "crypto") +set(MINWIN_LONG_NAME "Cryptography API (CryptoAPI)") +set(MODULE_LIBRARY_NAME "crypt32") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cert.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cert.c new file mode 100644 index 0000000000000000000000000000000000000000..83b7213fda2a8c5989056a70be43b2726323ac15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cert.c @@ -0,0 +1,223 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012-2013 Marc-Andre Moreau + * + * 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 + +#include + +/** + * CertOpenStore + * CertCloseStore + * CertControlStore + * CertDuplicateStore + * CertSaveStore + * CertRegisterPhysicalStore + * CertRegisterSystemStore + * CertAddStoreToCollection + * CertRemoveStoreFromCollection + * CertOpenSystemStoreA + * CertOpenSystemStoreW + * CertEnumPhysicalStore + * CertEnumSystemStore + * CertEnumSystemStoreLocation + * CertSetStoreProperty + * CertUnregisterPhysicalStore + * CertUnregisterSystemStore + * + * CertAddCertificateContextToStore + * CertAddCertificateLinkToStore + * CertAddCRLContextToStore + * CertAddCRLLinkToStore + * CertAddCTLContextToStore + * CertAddCTLLinkToStore + * CertAddEncodedCertificateToStore + * CertAddEncodedCertificateToSystemStoreA + * CertAddEncodedCertificateToSystemStoreW + * CertAddEncodedCRLToStore + * CertAddEncodedCTLToStore + * CertAddSerializedElementToStore + * CertDeleteCertificateFromStore + * CertDeleteCRLFromStore + * CertDeleteCTLFromStore + * CertGetCRLFromStore + * CertEnumCertificatesInStore + * CertEnumCRLsInStore + * CertEnumCTLsInStore + * CertFindCertificateInStore + * CertFindChainInStore + * CertFindCRLInStore + * CertFindCTLInStore + * CertGetIssuerCertificateFromStore + * CertGetStoreProperty + * CertGetSubjectCertificateFromStore + * CertSerializeCertificateStoreElement + * CertSerializeCRLStoreElement + * CertSerializeCTLStoreElement + * + * CertAddEnhancedKeyUsageIdentifier + * CertAddRefServerOcspResponse + * CertAddRefServerOcspResponseContext + * CertAlgIdToOID + * CertCloseServerOcspResponse + * CertCompareCertificate + * CertCompareCertificateName + * CertCompareIntegerBlob + * CertComparePublicKeyInfo + * CertCreateCertificateChainEngine + * CertCreateCertificateContext + * CertCreateContext + * CertCreateCRLContext + * CertCreateCTLContext + * CertCreateCTLEntryFromCertificateContextProperties + * CertCreateSelfSignCertificate + * CertDuplicateCertificateChain + * CertDuplicateCertificateContext + * CertDuplicateCRLContext + * CertDuplicateCTLContext + * CertEnumCertificateContextProperties + * CertEnumCRLContextProperties + * CertEnumCTLContextProperties + * CertEnumSubjectInSortedCTL + * CertFindAttribute + * CertFindCertificateInCRL + * CertFindExtension + * CertFindRDNAttr + * CertFindSubjectInCTL + * CertFindSubjectInSortedCTL + * CertFreeCertificateChain + * CertFreeCertificateChainEngine + * CertFreeCertificateChainList + * CertFreeCertificateContext + * CertFreeCRLContext + * CertFreeCTLContext + * CertFreeServerOcspResponseContext + * CertGetCertificateChain + * CertGetCertificateContextProperty + * CertGetCRLContextProperty + * CertGetCTLContextProperty + * CertGetEnhancedKeyUsage + * CertGetIntendedKeyUsage + * CertGetNameStringA + * CertGetNameStringW + * CertGetPublicKeyLength + * CertGetServerOcspResponseContext + * CertGetValidUsages + * CertIsRDNAttrsInCertificateName + * CertIsStrongHashToSign + * CertIsValidCRLForCertificate + * CertNameToStrA + * CertNameToStrW + * CertOIDToAlgId + * CertOpenServerOcspResponse + * CertRDNValueToStrA + * CertRDNValueToStrW + * CertRemoveEnhancedKeyUsageIdentifier + * CertResyncCertificateChainEngine + * CertRetrieveLogoOrBiometricInfo + * CertSelectCertificateChains + * CertSetCertificateContextPropertiesFromCTLEntry + * CertSetCertificateContextProperty + * CertSetCRLContextProperty + * CertSetCTLContextProperty + * CertSetEnhancedKeyUsage + * CertStrToNameA + * CertStrToNameW + * CertVerifyCertificateChainPolicy + * CertVerifyCRLRevocation + * CertVerifyCRLTimeValidity + * CertVerifyCTLUsage + * CertVerifyRevocation + * CertVerifySubjectCertificateContext + * CertVerifyTimeValidity + * CertVerifyValidityNesting + */ + +#include +#include + +#ifndef _WIN32 + +#include "crypto.h" + +HCERTSTORE CertOpenStore(LPCSTR lpszStoreProvider, DWORD dwMsgAndCertEncodingType, + HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const void* pvPara) +{ + WINPR_CERTSTORE* certstore = NULL; + + certstore = (WINPR_CERTSTORE*)calloc(1, sizeof(WINPR_CERTSTORE)); + + if (certstore) + { + certstore->lpszStoreProvider = lpszStoreProvider; + certstore->dwMsgAndCertEncodingType = dwMsgAndCertEncodingType; + } + + return (HCERTSTORE)certstore; +} + +HCERTSTORE CertOpenSystemStoreW(HCRYPTPROV_LEGACY hProv, LPCWSTR szSubsystemProtocol) +{ + HCERTSTORE hCertStore = NULL; + + hCertStore = CertOpenStore(CERT_STORE_PROV_FILE, X509_ASN_ENCODING, hProv, 0, NULL); + + return hCertStore; +} + +HCERTSTORE CertOpenSystemStoreA(HCRYPTPROV_LEGACY hProv, LPCSTR szSubsystemProtocol) +{ + return CertOpenSystemStoreW(hProv, NULL); +} + +BOOL CertCloseStore(HCERTSTORE hCertStore, DWORD dwFlags) +{ + WINPR_CERTSTORE* certstore = NULL; + + certstore = (WINPR_CERTSTORE*)hCertStore; + + free(certstore); + + return TRUE; +} + +PCCERT_CONTEXT CertFindCertificateInStore(HCERTSTORE hCertStore, DWORD dwCertEncodingType, + DWORD dwFindFlags, DWORD dwFindType, + const void* pvFindPara, PCCERT_CONTEXT pPrevCertContext) +{ + return (PCCERT_CONTEXT)1; +} + +PCCERT_CONTEXT CertEnumCertificatesInStore(HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext) +{ + return (PCCERT_CONTEXT)NULL; +} + +DWORD CertGetNameStringW(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags, void* pvTypePara, + LPWSTR pszNameString, DWORD cchNameString) +{ + return 0; +} + +DWORD CertGetNameStringA(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags, void* pvTypePara, + LPSTR pszNameString, DWORD cchNameString) +{ + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cipher.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cipher.c new file mode 100644 index 0000000000000000000000000000000000000000..4233713f35b13b68bd74071ba07aed9113909ecc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/cipher.c @@ -0,0 +1,899 @@ +/** + * WinPR: Windows Portable Runtime + * + * Copyright 2015 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "../log.h" +#define TAG WINPR_TAG("crypto.cipher") + +#if defined(WITH_INTERNAL_RC4) +#include "rc4.h" +#endif + +#ifdef WITH_OPENSSL +#include +#include +#include +#include +#endif + +#ifdef WITH_MBEDTLS +#include +#include +#include +#include +#if MBEDTLS_VERSION_MAJOR < 3 +#define mbedtls_cipher_info_get_iv_size(_info) (_info->iv_size) +#define mbedtls_cipher_info_get_key_bitlen(_info) (_info->key_bitlen) +#endif +#endif + +struct winpr_cipher_ctx_private_st +{ + WINPR_CIPHER_TYPE cipher; + WINPR_CRYPTO_OPERATION op; + +#ifdef WITH_OPENSSL + EVP_CIPHER_CTX* ectx; +#endif +#ifdef WITH_MBEDTLS + mbedtls_cipher_context_t* mctx; +#endif +}; + +/** + * RC4 + */ + +struct winpr_rc4_ctx_private_st +{ +#if defined(WITH_INTERNAL_RC4) + winpr_int_RC4_CTX* ictx; +#else +#if defined(WITH_OPENSSL) + EVP_CIPHER_CTX* ctx; +#endif +#endif +}; + +static WINPR_RC4_CTX* winpr_RC4_New_Internal(const BYTE* key, size_t keylen, BOOL override_fips) +{ + if (!key || (keylen == 0)) + return NULL; + + WINPR_RC4_CTX* ctx = (WINPR_RC4_CTX*)calloc(1, sizeof(WINPR_RC4_CTX)); + if (!ctx) + return NULL; + +#if defined(WITH_INTERNAL_RC4) + WINPR_UNUSED(override_fips); + ctx->ictx = winpr_int_rc4_new(key, keylen); + if (!ctx->ictx) + goto fail; +#elif defined(WITH_OPENSSL) + const EVP_CIPHER* evp = NULL; + + if (keylen > INT_MAX) + goto fail; + + ctx->ctx = EVP_CIPHER_CTX_new(); + if (!ctx->ctx) + goto fail; + + evp = EVP_rc4(); + + if (!evp) + goto fail; + + EVP_CIPHER_CTX_reset(ctx->ctx); + if (EVP_EncryptInit_ex(ctx->ctx, evp, NULL, NULL, NULL) != 1) + goto fail; + + /* EVP_CIPH_FLAG_NON_FIPS_ALLOW does not exist before openssl 1.0.1 */ +#if !(OPENSSL_VERSION_NUMBER < 0x10001000L) + + if (override_fips == TRUE) + EVP_CIPHER_CTX_set_flags(ctx->ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); + +#endif + EVP_CIPHER_CTX_set_key_length(ctx->ctx, (int)keylen); + if (EVP_EncryptInit_ex(ctx->ctx, NULL, NULL, key, NULL) != 1) + goto fail; +#endif + return ctx; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + + winpr_RC4_Free(ctx); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +WINPR_RC4_CTX* winpr_RC4_New_Allow_FIPS(const void* key, size_t keylen) +{ + return winpr_RC4_New_Internal(key, keylen, TRUE); +} + +WINPR_RC4_CTX* winpr_RC4_New(const void* key, size_t keylen) +{ + return winpr_RC4_New_Internal(key, keylen, FALSE); +} + +BOOL winpr_RC4_Update(WINPR_RC4_CTX* ctx, size_t length, const void* input, void* output) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_INTERNAL_RC4) + return winpr_int_rc4_update(ctx->ictx, length, input, output); +#elif defined(WITH_OPENSSL) + WINPR_ASSERT(ctx->ctx); + int outputLength = 0; + if (length > INT_MAX) + return FALSE; + + WINPR_ASSERT(ctx); + if (EVP_CipherUpdate(ctx->ctx, output, &outputLength, input, (int)length) != 1) + return FALSE; + return TRUE; +#endif + return FALSE; +} + +void winpr_RC4_Free(WINPR_RC4_CTX* ctx) +{ + if (!ctx) + return; + +#if defined(WITH_INTERNAL_RC4) + winpr_int_rc4_free(ctx->ictx); +#elif defined(WITH_OPENSSL) + EVP_CIPHER_CTX_free(ctx->ctx); +#endif + free(ctx); +} + +/** + * Generic Cipher API + */ + +#ifdef WITH_OPENSSL +extern const EVP_MD* winpr_openssl_get_evp_md(WINPR_MD_TYPE md); +#endif + +#ifdef WITH_MBEDTLS +extern mbedtls_md_type_t winpr_mbedtls_get_md_type(int md); +#endif + +struct cipher_map +{ + WINPR_CIPHER_TYPE md; + const char* name; +}; +static const struct cipher_map s_cipher_map[] = { + { WINPR_CIPHER_NONE, "none" }, + { WINPR_CIPHER_NULL, "null" }, + { WINPR_CIPHER_AES_128_ECB, "aes-128-ecb" }, + { WINPR_CIPHER_AES_192_ECB, "aes-192-ecb" }, + { WINPR_CIPHER_AES_256_ECB, "aes-256-ecb" }, + { WINPR_CIPHER_AES_128_CBC, "aes-128-cbc" }, + { WINPR_CIPHER_AES_192_CBC, "aes-192-cbc" }, + { WINPR_CIPHER_AES_256_CBC, "aes-256-cbc" }, + { WINPR_CIPHER_AES_128_CFB128, "aes-128-cfb128" }, + { WINPR_CIPHER_AES_192_CFB128, "aes-192-cfb128" }, + { WINPR_CIPHER_AES_256_CFB128, "aes-256-cfb128" }, + { WINPR_CIPHER_AES_128_CTR, "aes-128-ctr" }, + { WINPR_CIPHER_AES_192_CTR, "aes-192-ctr" }, + { WINPR_CIPHER_AES_256_CTR, "aes-256-ctr" }, + { WINPR_CIPHER_AES_128_GCM, "aes-128-gcm" }, + { WINPR_CIPHER_AES_192_GCM, "aes-192-gcm" }, + { WINPR_CIPHER_AES_256_GCM, "aes-256-gcm" }, + { WINPR_CIPHER_CAMELLIA_128_ECB, "camellia-128-ecb" }, + { WINPR_CIPHER_CAMELLIA_192_ECB, "camellia-192-ecb" }, + { WINPR_CIPHER_CAMELLIA_256_ECB, "camellia-256-ecb" }, + { WINPR_CIPHER_CAMELLIA_128_CBC, "camellia-128-cbc" }, + { WINPR_CIPHER_CAMELLIA_192_CBC, "camellia-192-cbc" }, + { WINPR_CIPHER_CAMELLIA_256_CBC, "camellia-256-cbc" }, + { WINPR_CIPHER_CAMELLIA_128_CFB128, "camellia-128-cfb128" }, + { WINPR_CIPHER_CAMELLIA_192_CFB128, "camellia-192-cfb128" }, + { WINPR_CIPHER_CAMELLIA_256_CFB128, "camellia-256-cfb128" }, + { WINPR_CIPHER_CAMELLIA_128_CTR, "camellia-128-ctr" }, + { WINPR_CIPHER_CAMELLIA_192_CTR, "camellia-192-ctr" }, + { WINPR_CIPHER_CAMELLIA_256_CTR, "camellia-256-ctr" }, + { WINPR_CIPHER_CAMELLIA_128_GCM, "camellia-128-gcm" }, + { WINPR_CIPHER_CAMELLIA_192_GCM, "camellia-192-gcm" }, + { WINPR_CIPHER_CAMELLIA_256_GCM, "camellia-256-gcm" }, + { WINPR_CIPHER_DES_ECB, "des-ecb" }, + { WINPR_CIPHER_DES_CBC, "des-cbc" }, + { WINPR_CIPHER_DES_EDE_ECB, "des-ede-ecb" }, + { WINPR_CIPHER_DES_EDE_CBC, "des-ede-cbc" }, + { WINPR_CIPHER_DES_EDE3_ECB, "des-ede3-ecb" }, + { WINPR_CIPHER_DES_EDE3_CBC, "des-ede3-cbc" }, + { WINPR_CIPHER_BLOWFISH_ECB, "blowfish-ecb" }, + { WINPR_CIPHER_BLOWFISH_CBC, "blowfish-cbc" }, + { WINPR_CIPHER_BLOWFISH_CFB64, "blowfish-cfb64" }, + { WINPR_CIPHER_BLOWFISH_CTR, "blowfish-ctr" }, + { WINPR_CIPHER_ARC4_128, "rc4" }, + { WINPR_CIPHER_AES_128_CCM, "aes-128-ccm" }, + { WINPR_CIPHER_AES_192_CCM, "aes-192-ccm" }, + { WINPR_CIPHER_AES_256_CCM, "aes-256-ccm" }, + { WINPR_CIPHER_CAMELLIA_128_CCM, "camellia-128-ccm" }, + { WINPR_CIPHER_CAMELLIA_192_CCM, "camellia-192-ccm" }, + { WINPR_CIPHER_CAMELLIA_256_CCM, "camellia-256-ccm" }, +}; + +static int cipher_compare(const void* a, const void* b) +{ + const WINPR_CIPHER_TYPE* cipher = a; + const struct cipher_map* map = b; + if (*cipher == map->md) + return 0; + return *cipher > map->md ? 1 : -1; +} + +const char* winpr_cipher_type_to_string(WINPR_CIPHER_TYPE md) +{ + WINPR_CIPHER_TYPE lc = md; + const struct cipher_map* ret = bsearch(&lc, s_cipher_map, ARRAYSIZE(s_cipher_map), + sizeof(struct cipher_map), cipher_compare); + if (!ret) + return "unknown"; + return ret->name; +} + +static int cipher_string_compare(const void* a, const void* b) +{ + const char* cipher = a; + const struct cipher_map* map = b; + return strcmp(cipher, map->name); +} + +WINPR_CIPHER_TYPE winpr_cipher_type_from_string(const char* name) +{ + const struct cipher_map* ret = bsearch(name, s_cipher_map, ARRAYSIZE(s_cipher_map), + sizeof(struct cipher_map), cipher_string_compare); + if (!ret) + return WINPR_CIPHER_NONE; + return ret->md; +} + +#if defined(WITH_OPENSSL) +static const EVP_CIPHER* winpr_openssl_get_evp_cipher(WINPR_CIPHER_TYPE cipher) +{ + const EVP_CIPHER* evp = NULL; + + switch (cipher) + { + case WINPR_CIPHER_NULL: + evp = EVP_enc_null(); + break; + + case WINPR_CIPHER_AES_128_ECB: + evp = EVP_get_cipherbyname("aes-128-ecb"); + break; + + case WINPR_CIPHER_AES_192_ECB: + evp = EVP_get_cipherbyname("aes-192-ecb"); + break; + + case WINPR_CIPHER_AES_256_ECB: + evp = EVP_get_cipherbyname("aes-256-ecb"); + break; + + case WINPR_CIPHER_AES_128_CBC: + evp = EVP_get_cipherbyname("aes-128-cbc"); + break; + + case WINPR_CIPHER_AES_192_CBC: + evp = EVP_get_cipherbyname("aes-192-cbc"); + break; + + case WINPR_CIPHER_AES_256_CBC: + evp = EVP_get_cipherbyname("aes-256-cbc"); + break; + + case WINPR_CIPHER_AES_128_CFB128: + evp = EVP_get_cipherbyname("aes-128-cfb128"); + break; + + case WINPR_CIPHER_AES_192_CFB128: + evp = EVP_get_cipherbyname("aes-192-cfb128"); + break; + + case WINPR_CIPHER_AES_256_CFB128: + evp = EVP_get_cipherbyname("aes-256-cfb128"); + break; + + case WINPR_CIPHER_AES_128_CTR: + evp = EVP_get_cipherbyname("aes-128-ctr"); + break; + + case WINPR_CIPHER_AES_192_CTR: + evp = EVP_get_cipherbyname("aes-192-ctr"); + break; + + case WINPR_CIPHER_AES_256_CTR: + evp = EVP_get_cipherbyname("aes-256-ctr"); + break; + + case WINPR_CIPHER_AES_128_GCM: + evp = EVP_get_cipherbyname("aes-128-gcm"); + break; + + case WINPR_CIPHER_AES_192_GCM: + evp = EVP_get_cipherbyname("aes-192-gcm"); + break; + + case WINPR_CIPHER_AES_256_GCM: + evp = EVP_get_cipherbyname("aes-256-gcm"); + break; + + case WINPR_CIPHER_AES_128_CCM: + evp = EVP_get_cipherbyname("aes-128-ccm"); + break; + + case WINPR_CIPHER_AES_192_CCM: + evp = EVP_get_cipherbyname("aes-192-ccm"); + break; + + case WINPR_CIPHER_AES_256_CCM: + evp = EVP_get_cipherbyname("aes-256-ccm"); + break; + + case WINPR_CIPHER_CAMELLIA_128_ECB: + evp = EVP_get_cipherbyname("camellia-128-ecb"); + break; + + case WINPR_CIPHER_CAMELLIA_192_ECB: + evp = EVP_get_cipherbyname("camellia-192-ecb"); + break; + + case WINPR_CIPHER_CAMELLIA_256_ECB: + evp = EVP_get_cipherbyname("camellia-256-ecb"); + break; + + case WINPR_CIPHER_CAMELLIA_128_CBC: + evp = EVP_get_cipherbyname("camellia-128-cbc"); + break; + + case WINPR_CIPHER_CAMELLIA_192_CBC: + evp = EVP_get_cipherbyname("camellia-192-cbc"); + break; + + case WINPR_CIPHER_CAMELLIA_256_CBC: + evp = EVP_get_cipherbyname("camellia-256-cbc"); + break; + + case WINPR_CIPHER_CAMELLIA_128_CFB128: + evp = EVP_get_cipherbyname("camellia-128-cfb128"); + break; + + case WINPR_CIPHER_CAMELLIA_192_CFB128: + evp = EVP_get_cipherbyname("camellia-192-cfb128"); + break; + + case WINPR_CIPHER_CAMELLIA_256_CFB128: + evp = EVP_get_cipherbyname("camellia-256-cfb128"); + break; + + case WINPR_CIPHER_CAMELLIA_128_CTR: + evp = EVP_get_cipherbyname("camellia-128-ctr"); + break; + + case WINPR_CIPHER_CAMELLIA_192_CTR: + evp = EVP_get_cipherbyname("camellia-192-ctr"); + break; + + case WINPR_CIPHER_CAMELLIA_256_CTR: + evp = EVP_get_cipherbyname("camellia-256-ctr"); + break; + + case WINPR_CIPHER_CAMELLIA_128_GCM: + evp = EVP_get_cipherbyname("camellia-128-gcm"); + break; + + case WINPR_CIPHER_CAMELLIA_192_GCM: + evp = EVP_get_cipherbyname("camellia-192-gcm"); + break; + + case WINPR_CIPHER_CAMELLIA_256_GCM: + evp = EVP_get_cipherbyname("camellia-256-gcm"); + break; + + case WINPR_CIPHER_CAMELLIA_128_CCM: + evp = EVP_get_cipherbyname("camellia-128-ccm"); + break; + + case WINPR_CIPHER_CAMELLIA_192_CCM: + evp = EVP_get_cipherbyname("camellia-192-ccm"); + break; + + case WINPR_CIPHER_CAMELLIA_256_CCM: + evp = EVP_get_cipherbyname("camellia-256-ccm"); + break; + + case WINPR_CIPHER_DES_ECB: + evp = EVP_get_cipherbyname("des-ecb"); + break; + + case WINPR_CIPHER_DES_CBC: + evp = EVP_get_cipherbyname("des-cbc"); + break; + + case WINPR_CIPHER_DES_EDE_ECB: + evp = EVP_get_cipherbyname("des-ede-ecb"); + break; + + case WINPR_CIPHER_DES_EDE_CBC: + evp = EVP_get_cipherbyname("des-ede-cbc"); + break; + + case WINPR_CIPHER_DES_EDE3_ECB: + evp = EVP_get_cipherbyname("des-ede3-ecb"); + break; + + case WINPR_CIPHER_DES_EDE3_CBC: + evp = EVP_get_cipherbyname("des-ede3-cbc"); + break; + + case WINPR_CIPHER_ARC4_128: + evp = EVP_get_cipherbyname("rc4"); + break; + + case WINPR_CIPHER_BLOWFISH_ECB: + evp = EVP_get_cipherbyname("blowfish-ecb"); + break; + + case WINPR_CIPHER_BLOWFISH_CBC: + evp = EVP_get_cipherbyname("blowfish-cbc"); + break; + + case WINPR_CIPHER_BLOWFISH_CFB64: + evp = EVP_get_cipherbyname("blowfish-cfb64"); + break; + + case WINPR_CIPHER_BLOWFISH_CTR: + evp = EVP_get_cipherbyname("blowfish-ctr"); + break; + default: + break; + } + + return evp; +} + +#elif defined(WITH_MBEDTLS) +mbedtls_cipher_type_t winpr_mbedtls_get_cipher_type(int cipher) +{ + mbedtls_cipher_type_t type = MBEDTLS_CIPHER_NONE; + + switch (cipher) + { + case WINPR_CIPHER_NONE: + type = MBEDTLS_CIPHER_NONE; + break; + + case WINPR_CIPHER_NULL: + type = MBEDTLS_CIPHER_NULL; + break; + + case WINPR_CIPHER_AES_128_ECB: + type = MBEDTLS_CIPHER_AES_128_ECB; + break; + + case WINPR_CIPHER_AES_192_ECB: + type = MBEDTLS_CIPHER_AES_192_ECB; + break; + + case WINPR_CIPHER_AES_256_ECB: + type = MBEDTLS_CIPHER_AES_256_ECB; + break; + + case WINPR_CIPHER_AES_128_CBC: + type = MBEDTLS_CIPHER_AES_128_CBC; + break; + + case WINPR_CIPHER_AES_192_CBC: + type = MBEDTLS_CIPHER_AES_192_CBC; + break; + + case WINPR_CIPHER_AES_256_CBC: + type = MBEDTLS_CIPHER_AES_256_CBC; + break; + + case WINPR_CIPHER_AES_128_CFB128: + type = MBEDTLS_CIPHER_AES_128_CFB128; + break; + + case WINPR_CIPHER_AES_192_CFB128: + type = MBEDTLS_CIPHER_AES_192_CFB128; + break; + + case WINPR_CIPHER_AES_256_CFB128: + type = MBEDTLS_CIPHER_AES_256_CFB128; + break; + + case WINPR_CIPHER_AES_128_CTR: + type = MBEDTLS_CIPHER_AES_128_CTR; + break; + + case WINPR_CIPHER_AES_192_CTR: + type = MBEDTLS_CIPHER_AES_192_CTR; + break; + + case WINPR_CIPHER_AES_256_CTR: + type = MBEDTLS_CIPHER_AES_256_CTR; + break; + + case WINPR_CIPHER_AES_128_GCM: + type = MBEDTLS_CIPHER_AES_128_GCM; + break; + + case WINPR_CIPHER_AES_192_GCM: + type = MBEDTLS_CIPHER_AES_192_GCM; + break; + + case WINPR_CIPHER_AES_256_GCM: + type = MBEDTLS_CIPHER_AES_256_GCM; + break; + + case WINPR_CIPHER_AES_128_CCM: + type = MBEDTLS_CIPHER_AES_128_CCM; + break; + + case WINPR_CIPHER_AES_192_CCM: + type = MBEDTLS_CIPHER_AES_192_CCM; + break; + + case WINPR_CIPHER_AES_256_CCM: + type = MBEDTLS_CIPHER_AES_256_CCM; + break; + } + + return type; +} +#endif + +WINPR_CIPHER_CTX* winpr_Cipher_New(WINPR_CIPHER_TYPE cipher, WINPR_CRYPTO_OPERATION op, + const void* key, const void* iv) +{ + return winpr_Cipher_NewEx(cipher, op, key, 0, iv, 0); +} + +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) +{ + if (cipher == WINPR_CIPHER_ARC4_128) + { + WLog_ERR(TAG, + "WINPR_CIPHER_ARC4_128 (RC4) cipher not supported, use winpr_RC4_new instead"); + return NULL; + } + + WINPR_CIPHER_CTX* ctx = calloc(1, sizeof(WINPR_CIPHER_CTX)); + if (!ctx) + return NULL; + + ctx->cipher = cipher; + ctx->op = op; + +#if defined(WITH_OPENSSL) + const EVP_CIPHER* evp = winpr_openssl_get_evp_cipher(cipher); + if (!evp) + goto fail; + + ctx->ectx = EVP_CIPHER_CTX_new(); + if (!ctx->ectx) + goto fail; + +#if 0 + if (keylen != 0) + { + WINPR_ASSERT(keylen <= INT32_MAX); + const int len = EVP_CIPHER_CTX_key_length(ctx->ectx); + if ((len > 0) && (len != keylen)) + { + if (EVP_CIPHER_CTX_set_key_length(ctx->ectx, (int)keylen) != 1) + goto fail; + } + } + + if (ivlen != 0) + { + WINPR_ASSERT(ivlen <= INT32_MAX); + const int len = EVP_CIPHER_CTX_iv_length(ctx->ectx); + if ((len > 0) && (ivlen != len)) + goto fail; + } +#endif + + const int operation = (op == WINPR_ENCRYPT) ? 1 : 0; + + if (EVP_CipherInit_ex(ctx->ectx, evp, NULL, key, iv, operation) != 1) + goto fail; + + EVP_CIPHER_CTX_set_padding(ctx->ectx, 0); + +#elif defined(WITH_MBEDTLS) + mbedtls_cipher_type_t cipher_type = winpr_mbedtls_get_cipher_type(cipher); + const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(cipher_type); + + if (!cipher_info) + goto fail; + + ctx->mctx = calloc(1, sizeof(mbedtls_cipher_context_t)); + if (!ctx->mctx) + goto fail; + + const mbedtls_operation_t operation = (op == WINPR_ENCRYPT) ? MBEDTLS_ENCRYPT : MBEDTLS_DECRYPT; + mbedtls_cipher_init(ctx->mctx); + + if (mbedtls_cipher_setup(ctx->mctx, cipher_info) != 0) + goto fail; + + const int key_bitlen = mbedtls_cipher_get_key_bitlen(ctx->mctx); + + if (mbedtls_cipher_setkey(ctx->mctx, key, key_bitlen, operation) != 0) + goto fail; + + if (mbedtls_cipher_set_padding_mode(ctx->mctx, MBEDTLS_PADDING_NONE) != 0) + goto fail; + +#endif + return ctx; + +fail: + winpr_Cipher_Free(ctx); + return NULL; +} + +BOOL winpr_Cipher_SetPadding(WINPR_CIPHER_CTX* ctx, BOOL enabled) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_OPENSSL) + if (!ctx->ectx) + return FALSE; + EVP_CIPHER_CTX_set_padding(ctx->ectx, enabled); +#elif defined(WITH_MBEDTLS) + mbedtls_cipher_padding_t option = enabled ? MBEDTLS_PADDING_PKCS7 : MBEDTLS_PADDING_NONE; + if (mbedtls_cipher_set_padding_mode((mbedtls_cipher_context_t*)ctx, option) != 0) + return FALSE; +#else + return FALSE; +#endif + return TRUE; +} + +BOOL winpr_Cipher_Update(WINPR_CIPHER_CTX* ctx, const void* input, size_t ilen, void* output, + size_t* olen) +{ + WINPR_ASSERT(ctx); + WINPR_ASSERT(olen); + +#if defined(WITH_OPENSSL) + int outl = (int)*olen; + + if (ilen > INT_MAX) + { + WLog_ERR(TAG, "input length %" PRIuz " > %d, abort", ilen, INT_MAX); + return FALSE; + } + + WINPR_ASSERT(ctx->ectx); + if (EVP_CipherUpdate(ctx->ectx, output, &outl, input, (int)ilen) == 1) + { + *olen = (size_t)outl; + return TRUE; + } + +#elif defined(WITH_MBEDTLS) + WINPR_ASSERT(ctx->mctx); + if (mbedtls_cipher_update(ctx->mctx, input, ilen, output, olen) == 0) + return TRUE; + +#endif + + WLog_ERR(TAG, "Failed to update the data"); + return FALSE; +} + +BOOL winpr_Cipher_Final(WINPR_CIPHER_CTX* ctx, void* output, size_t* olen) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_OPENSSL) + int outl = (int)*olen; + + WINPR_ASSERT(ctx->ectx); + if (EVP_CipherFinal_ex(ctx->ectx, output, &outl) == 1) + { + *olen = (size_t)outl; + return TRUE; + } + +#elif defined(WITH_MBEDTLS) + + WINPR_ASSERT(ctx->mctx); + if (mbedtls_cipher_finish(ctx->mctx, output, olen) == 0) + return TRUE; + +#endif + + return FALSE; +} + +void winpr_Cipher_Free(WINPR_CIPHER_CTX* ctx) +{ + if (!ctx) + return; + +#if defined(WITH_OPENSSL) + if (ctx->ectx) + EVP_CIPHER_CTX_free(ctx->ectx); +#elif defined(WITH_MBEDTLS) + if (ctx->mctx) + { + mbedtls_cipher_free(ctx->mctx); + free(ctx->mctx); + } +#endif + + free(ctx); +} + +/** + * Key Generation + */ + +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) +{ + /** + * Key and IV generation compatible with OpenSSL EVP_BytesToKey(): + * https://www.openssl.org/docs/manmaster/crypto/EVP_BytesToKey.html + */ +#if defined(WITH_OPENSSL) + const EVP_MD* evp_md = NULL; + const EVP_CIPHER* evp_cipher = NULL; + evp_md = winpr_openssl_get_evp_md(md); + evp_cipher = winpr_openssl_get_evp_cipher(WINPR_ASSERTING_INT_CAST(WINPR_CIPHER_TYPE, cipher)); + WINPR_ASSERT(datal <= INT_MAX); + WINPR_ASSERT(count <= INT_MAX); + return EVP_BytesToKey(evp_cipher, evp_md, salt, data, (int)datal, (int)count, key, iv); +#elif defined(WITH_MBEDTLS) + int rv = 0; + BYTE md_buf[64]; + int niv, nkey, addmd = 0; + unsigned int mds = 0; + mbedtls_md_context_t ctx; + const mbedtls_md_info_t* md_info; + mbedtls_cipher_type_t cipher_type; + const mbedtls_cipher_info_t* cipher_info; + mbedtls_md_type_t md_type = winpr_mbedtls_get_md_type(md); + md_info = mbedtls_md_info_from_type(md_type); + cipher_type = winpr_mbedtls_get_cipher_type(cipher); + cipher_info = mbedtls_cipher_info_from_type(cipher_type); + nkey = mbedtls_cipher_info_get_key_bitlen(cipher_info) / 8; + niv = mbedtls_cipher_info_get_iv_size(cipher_info); + + if ((nkey > 64) || (niv > 64)) + return 0; + + if (!data) + return nkey; + + mbedtls_md_init(&ctx); + + if (mbedtls_md_setup(&ctx, md_info, 0) != 0) + goto err; + + while (1) + { + if (mbedtls_md_starts(&ctx) != 0) + goto err; + + if (addmd++) + { + if (mbedtls_md_update(&ctx, md_buf, mds) != 0) + goto err; + } + + if (mbedtls_md_update(&ctx, data, datal) != 0) + goto err; + + if (salt) + { + if (mbedtls_md_update(&ctx, salt, 8) != 0) + goto err; + } + + if (mbedtls_md_finish(&ctx, md_buf) != 0) + goto err; + + mds = mbedtls_md_get_size(md_info); + + for (unsigned int i = 1; i < (unsigned int)count; i++) + { + if (mbedtls_md_starts(&ctx) != 0) + goto err; + + if (mbedtls_md_update(&ctx, md_buf, mds) != 0) + goto err; + + if (mbedtls_md_finish(&ctx, md_buf) != 0) + goto err; + } + + unsigned int i = 0; + + if (nkey) + { + while (1) + { + if (nkey == 0) + break; + + if (i == mds) + break; + + if (key) + *(BYTE*)(key++) = md_buf[i]; + + nkey--; + i++; + } + } + + if (niv && (i != mds)) + { + while (1) + { + if (niv == 0) + break; + + if (i == mds) + break; + + if (iv) + *(BYTE*)(iv++) = md_buf[i]; + + niv--; + i++; + } + } + + if ((nkey == 0) && (niv == 0)) + break; + } + + rv = mbedtls_cipher_info_get_key_bitlen(cipher_info) / 8; +err: + mbedtls_md_free(&ctx); + SecureZeroMemory(md_buf, 64); + return rv; +#else + return 0; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..9a0cc8773190c99b33b85a61b7acd027f621e425 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.c @@ -0,0 +1,303 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012-2013 Marc-Andre Moreau + * + * 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 + +#include + +/** + * CryptAcquireCertificatePrivateKey + * CryptBinaryToStringA + * CryptBinaryToStringW + * CryptCloseAsyncHandle + * CryptCreateAsyncHandle + * CryptCreateKeyIdentifierFromCSP + * CryptDecodeMessage + * CryptDecodeObject + * CryptDecodeObjectEx + * CryptDecryptAndVerifyMessageSignature + * CryptDecryptMessage + * CryptEncodeObject + * CryptEncodeObjectEx + * CryptEncryptMessage + * CryptEnumKeyIdentifierProperties + * CryptEnumOIDFunction + * CryptEnumOIDInfo + * CryptExportPKCS8 + * CryptExportPublicKeyInfo + * CryptExportPublicKeyInfoEx + * CryptExportPublicKeyInfoFromBCryptKeyHandle + * CryptFindCertificateKeyProvInfo + * CryptFindLocalizedName + * CryptFindOIDInfo + * CryptFormatObject + * CryptFreeOIDFunctionAddress + * CryptGetAsyncParam + * CryptGetDefaultOIDDllList + * CryptGetDefaultOIDFunctionAddress + * CryptGetKeyIdentifierProperty + * CryptGetMessageCertificates + * CryptGetMessageSignerCount + * CryptGetOIDFunctionAddress + * CryptGetOIDFunctionValue + * CryptHashCertificate + * CryptHashCertificate2 + * CryptHashMessage + * CryptHashPublicKeyInfo + * CryptHashToBeSigned + * CryptImportPKCS8 + * CryptImportPublicKeyInfo + * CryptImportPublicKeyInfoEx + * CryptImportPublicKeyInfoEx2 + * CryptInitOIDFunctionSet + * CryptInstallDefaultContext + * CryptInstallOIDFunctionAddress + * CryptLoadSip + * CryptMemAlloc + * CryptMemFree + * CryptMemRealloc + * CryptMsgCalculateEncodedLength + * CryptMsgClose + * CryptMsgControl + * CryptMsgCountersign + * CryptMsgCountersignEncoded + * CryptMsgDuplicate + * CryptMsgEncodeAndSignCTL + * CryptMsgGetAndVerifySigner + * CryptMsgGetParam + * CryptMsgOpenToDecode + * CryptMsgOpenToEncode + * CryptMsgSignCTL + * CryptMsgUpdate + * CryptMsgVerifyCountersignatureEncoded + * CryptMsgVerifyCountersignatureEncodedEx + * CryptQueryObject + * CryptRegisterDefaultOIDFunction + * CryptRegisterOIDFunction + * CryptRegisterOIDInfo + * CryptRetrieveTimeStamp + * CryptSetAsyncParam + * CryptSetKeyIdentifierProperty + * CryptSetOIDFunctionValue + * CryptSignAndEncodeCertificate + * CryptSignAndEncryptMessage + * CryptSignCertificate + * CryptSignMessage + * CryptSignMessageWithKey + * CryptSIPAddProvider + * CryptSIPCreateIndirectData + * CryptSIPGetCaps + * CryptSIPGetSignedDataMsg + * CryptSIPLoad + * CryptSIPPutSignedDataMsg + * CryptSIPRemoveProvider + * CryptSIPRemoveSignedDataMsg + * CryptSIPRetrieveSubjectGuid + * CryptSIPRetrieveSubjectGuidForCatalogFile + * CryptSIPVerifyIndirectData + * CryptUninstallDefaultContext + * CryptUnregisterDefaultOIDFunction + * CryptUnregisterOIDFunction + * CryptUnregisterOIDInfo + * CryptUpdateProtectedState + * CryptVerifyCertificateSignature + * CryptVerifyCertificateSignatureEx + * CryptVerifyDetachedMessageHash + * CryptVerifyDetachedMessageSignature + * CryptVerifyMessageHash + * CryptVerifyMessageSignature + * CryptVerifyMessageSignatureWithKey + * CryptVerifyTimeStampSignature + * DbgInitOSS + * DbgPrintf + * PFXExportCertStore + * PFXExportCertStore2 + * PFXExportCertStoreEx + * PFXImportCertStore + * PFXIsPFXBlob + * PFXVerifyPassword + */ + +#ifndef _WIN32 + +#include "crypto.h" + +#include +#include + +static wListDictionary* g_ProtectedMemoryBlocks = NULL; + +BOOL CryptProtectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags) +{ + BYTE* pCipherText = NULL; + size_t cbOut = 0; + size_t cbFinal = 0; + WINPR_CIPHER_CTX* enc = NULL; + BYTE randomKey[256] = { 0 }; + WINPR_PROTECTED_MEMORY_BLOCK* pMemBlock = NULL; + + if (dwFlags != CRYPTPROTECTMEMORY_SAME_PROCESS) + return FALSE; + + if (!g_ProtectedMemoryBlocks) + { + g_ProtectedMemoryBlocks = ListDictionary_New(TRUE); + + if (!g_ProtectedMemoryBlocks) + return FALSE; + } + + pMemBlock = (WINPR_PROTECTED_MEMORY_BLOCK*)calloc(1, sizeof(WINPR_PROTECTED_MEMORY_BLOCK)); + + if (!pMemBlock) + return FALSE; + + pMemBlock->pData = pData; + pMemBlock->cbData = cbData; + pMemBlock->dwFlags = dwFlags; + + winpr_RAND(pMemBlock->salt, 8); + winpr_RAND(randomKey, sizeof(randomKey)); + + winpr_Cipher_BytesToKey(WINPR_CIPHER_AES_256_CBC, WINPR_MD_SHA1, pMemBlock->salt, randomKey, + sizeof(randomKey), 4, pMemBlock->key, pMemBlock->iv); + + SecureZeroMemory(randomKey, sizeof(randomKey)); + + cbOut = pMemBlock->cbData + 16 - 1; + pCipherText = (BYTE*)calloc(1, cbOut); + + if (!pCipherText) + goto out; + + if ((enc = winpr_Cipher_NewEx(WINPR_CIPHER_AES_256_CBC, WINPR_ENCRYPT, pMemBlock->key, + sizeof(pMemBlock->key), pMemBlock->iv, sizeof(pMemBlock->iv))) == + NULL) + goto out; + if (!winpr_Cipher_Update(enc, pMemBlock->pData, pMemBlock->cbData, pCipherText, &cbOut)) + goto out; + if (!winpr_Cipher_Final(enc, pCipherText + cbOut, &cbFinal)) + goto out; + winpr_Cipher_Free(enc); + + CopyMemory(pMemBlock->pData, pCipherText, pMemBlock->cbData); + free(pCipherText); + + return ListDictionary_Add(g_ProtectedMemoryBlocks, pData, pMemBlock); +out: + free(pMemBlock); + free(pCipherText); + winpr_Cipher_Free(enc); + + return FALSE; +} + +BOOL CryptUnprotectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags) +{ + BYTE* pPlainText = NULL; + size_t cbOut = 0; + size_t cbFinal = 0; + WINPR_CIPHER_CTX* dec = NULL; + WINPR_PROTECTED_MEMORY_BLOCK* pMemBlock = NULL; + + if (dwFlags != CRYPTPROTECTMEMORY_SAME_PROCESS) + return FALSE; + + if (!g_ProtectedMemoryBlocks) + return FALSE; + + pMemBlock = + (WINPR_PROTECTED_MEMORY_BLOCK*)ListDictionary_GetItemValue(g_ProtectedMemoryBlocks, pData); + + if (!pMemBlock) + goto out; + + cbOut = pMemBlock->cbData + 16 - 1; + + pPlainText = (BYTE*)malloc(cbOut); + + if (!pPlainText) + goto out; + + if ((dec = winpr_Cipher_NewEx(WINPR_CIPHER_AES_256_CBC, WINPR_DECRYPT, pMemBlock->key, + sizeof(pMemBlock->key), pMemBlock->iv, sizeof(pMemBlock->iv))) == + NULL) + goto out; + if (!winpr_Cipher_Update(dec, pMemBlock->pData, pMemBlock->cbData, pPlainText, &cbOut)) + goto out; + if (!winpr_Cipher_Final(dec, pPlainText + cbOut, &cbFinal)) + goto out; + winpr_Cipher_Free(dec); + + CopyMemory(pMemBlock->pData, pPlainText, pMemBlock->cbData); + SecureZeroMemory(pPlainText, pMemBlock->cbData); + free(pPlainText); + + ListDictionary_Remove(g_ProtectedMemoryBlocks, pData); + + free(pMemBlock); + + return TRUE; + +out: + free(pPlainText); + free(pMemBlock); + winpr_Cipher_Free(dec); + return FALSE; +} + +BOOL CryptProtectData(DATA_BLOB* pDataIn, LPCWSTR szDataDescr, DATA_BLOB* pOptionalEntropy, + PVOID pvReserved, CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct, DWORD dwFlags, + DATA_BLOB* pDataOut) +{ + return TRUE; +} + +BOOL CryptUnprotectData(DATA_BLOB* pDataIn, LPWSTR* ppszDataDescr, DATA_BLOB* pOptionalEntropy, + PVOID pvReserved, CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct, DWORD dwFlags, + DATA_BLOB* pDataOut) +{ + return TRUE; +} + +BOOL CryptStringToBinaryW(LPCWSTR pszString, DWORD cchString, DWORD dwFlags, BYTE* pbBinary, + DWORD* pcbBinary, DWORD* pdwSkip, DWORD* pdwFlags) +{ + return TRUE; +} + +BOOL CryptStringToBinaryA(LPCSTR pszString, DWORD cchString, DWORD dwFlags, BYTE* pbBinary, + DWORD* pcbBinary, DWORD* pdwSkip, DWORD* pdwFlags) +{ + return TRUE; +} + +BOOL CryptBinaryToStringW(CONST BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, + DWORD* pcchString) +{ + return TRUE; +} + +BOOL CryptBinaryToStringA(CONST BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, + DWORD* pcchString) +{ + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..c5ec0dd9bd954335721da2e18143acbf48d896a1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/crypto.h @@ -0,0 +1,43 @@ +/** + * WinPR: Windows Portable Runtime + * Cryptography API (CryptoAPI) + * + * Copyright 2012-2013 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_CRYPTO_PRIVATE_H + +#ifndef _WIN32 + +typedef struct +{ + BYTE* pData; + DWORD cbData; + DWORD dwFlags; + BYTE key[32]; + BYTE iv[32]; + BYTE salt[8]; +} WINPR_PROTECTED_MEMORY_BLOCK; + +typedef struct +{ + LPCSTR lpszStoreProvider; + DWORD dwMsgAndCertEncodingType; +} WINPR_CERTSTORE; + +#endif + +#endif /* WINPR_CRYPTO_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hash.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hash.c new file mode 100644 index 0000000000000000000000000000000000000000..18af44cad538ec20ab87109eb5247cde5f2e5c3a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hash.c @@ -0,0 +1,792 @@ +/** + * WinPR: Windows Portable Runtime + * + * Copyright 2015 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#ifdef WITH_OPENSSL +#include +#include +#include +#include +#include +#if OPENSSL_VERSION_NUMBER >= 0x30000000L +#include +#endif +#endif + +#ifdef WITH_MBEDTLS +#ifdef MBEDTLS_MD5_C +#include +#endif +#include +#include +#if MBEDTLS_VERSION_MAJOR < 3 +#define mbedtls_md_info_from_ctx(_ctx) (_ctx->md_info) +#endif +#endif + +#if defined(WITH_INTERNAL_MD4) +#include "md4.h" +#endif + +#if defined(WITH_INTERNAL_MD5) +#include "md5.h" +#include "hmac_md5.h" +#endif + +#include "../log.h" +#define TAG WINPR_TAG("crypto.hash") + +/** + * HMAC + */ + +#ifdef WITH_OPENSSL +extern const EVP_MD* winpr_openssl_get_evp_md(WINPR_MD_TYPE md); +#endif + +#ifdef WITH_OPENSSL +const EVP_MD* winpr_openssl_get_evp_md(WINPR_MD_TYPE md) +{ + const char* name = winpr_md_type_to_string(md); + if (!name) + return NULL; + return EVP_get_digestbyname(name); +} +#endif + +#ifdef WITH_MBEDTLS +mbedtls_md_type_t winpr_mbedtls_get_md_type(int md) +{ + mbedtls_md_type_t type = MBEDTLS_MD_NONE; + + switch (md) + { + case WINPR_MD_MD5: + type = MBEDTLS_MD_MD5; + break; + + case WINPR_MD_SHA1: + type = MBEDTLS_MD_SHA1; + break; + + case WINPR_MD_SHA224: + type = MBEDTLS_MD_SHA224; + break; + + case WINPR_MD_SHA256: + type = MBEDTLS_MD_SHA256; + break; + + case WINPR_MD_SHA384: + type = MBEDTLS_MD_SHA384; + break; + + case WINPR_MD_SHA512: + type = MBEDTLS_MD_SHA512; + break; + } + + return type; +} +#endif + +struct hash_map +{ + const char* name; + WINPR_MD_TYPE md; +}; +static const struct hash_map hashes[] = { { "md2", WINPR_MD_MD2 }, + { "md4", WINPR_MD_MD4 }, + { "md5", WINPR_MD_MD5 }, + { "sha1", WINPR_MD_SHA1 }, + { "sha224", WINPR_MD_SHA224 }, + { "sha256", WINPR_MD_SHA256 }, + { "sha384", WINPR_MD_SHA384 }, + { "sha512", WINPR_MD_SHA512 }, + { "sha3_224", WINPR_MD_SHA3_224 }, + { "sha3_256", WINPR_MD_SHA3_256 }, + { "sha3_384", WINPR_MD_SHA3_384 }, + { "sha3_512", WINPR_MD_SHA3_512 }, + { "shake128", WINPR_MD_SHAKE128 }, + { "shake256", WINPR_MD_SHAKE256 }, + { NULL, WINPR_MD_NONE } }; + +WINPR_MD_TYPE winpr_md_type_from_string(const char* name) +{ + const struct hash_map* cur = hashes; + while (cur->name) + { + if (_stricmp(cur->name, name) == 0) + return cur->md; + cur++; + } + return WINPR_MD_NONE; +} + +const char* winpr_md_type_to_string(WINPR_MD_TYPE md) +{ + const struct hash_map* cur = hashes; + while (cur->name) + { + if (cur->md == md) + return cur->name; + cur++; + } + return NULL; +} + +struct winpr_hmac_ctx_private_st +{ + WINPR_MD_TYPE md; + +#if defined(WITH_INTERNAL_MD5) + WINPR_HMAC_MD5_CTX hmac_md5; +#endif +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + EVP_MAC_CTX* xhmac; +#else + HMAC_CTX* hmac; +#endif +#endif +#if defined(WITH_MBEDTLS) + mbedtls_md_context_t hmac; +#endif +}; + +WINPR_HMAC_CTX* winpr_HMAC_New(void) +{ + WINPR_HMAC_CTX* ctx = (WINPR_HMAC_CTX*)calloc(1, sizeof(WINPR_HMAC_CTX)); + if (!ctx) + return NULL; +#if defined(WITH_OPENSSL) +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + + if (!(ctx->hmac = (HMAC_CTX*)calloc(1, sizeof(HMAC_CTX)))) + goto fail; + + HMAC_CTX_init(ctx->hmac); +#elif OPENSSL_VERSION_NUMBER < 0x30000000L + if (!(ctx->hmac = HMAC_CTX_new())) + goto fail; +#else + EVP_MAC* emac = EVP_MAC_fetch(NULL, "HMAC", NULL); + if (!emac) + goto fail; + ctx->xhmac = EVP_MAC_CTX_new(emac); + EVP_MAC_free(emac); + if (!ctx->xhmac) + goto fail; +#endif +#elif defined(WITH_MBEDTLS) + mbedtls_md_init(&ctx->hmac); +#endif + return ctx; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + winpr_HMAC_Free(ctx); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +BOOL winpr_HMAC_Init(WINPR_HMAC_CTX* ctx, WINPR_MD_TYPE md, const void* key, size_t keylen) +{ + WINPR_ASSERT(ctx); + + ctx->md = md; + switch (ctx->md) + { +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + hmac_md5_init(&ctx->hmac_md5, key, keylen); + return TRUE; +#endif + default: + break; + } + +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + char* hash = WINPR_CAST_CONST_PTR_AWAY(winpr_md_type_to_string(md), char*); + + if (!ctx->xhmac) + return FALSE; + + const char* param_name = OSSL_MAC_PARAM_DIGEST; + const OSSL_PARAM param[] = { OSSL_PARAM_construct_utf8_string(param_name, hash, 0), + OSSL_PARAM_construct_end() }; + + if (EVP_MAC_init(ctx->xhmac, key, keylen, param) == 1) + return TRUE; +#else + HMAC_CTX* hmac = ctx->hmac; + const EVP_MD* evp = winpr_openssl_get_evp_md(md); + + if (!evp || !hmac) + return FALSE; + + if (keylen > INT_MAX) + return FALSE; +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + HMAC_Init_ex(hmac, key, (int)keylen, evp, NULL); /* no return value on OpenSSL 0.9.x */ + return TRUE; +#else + + if (HMAC_Init_ex(hmac, key, (int)keylen, evp, NULL) == 1) + return TRUE; + +#endif +#endif +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* hmac = &ctx->hmac; + mbedtls_md_type_t md_type = winpr_mbedtls_get_md_type(md); + const mbedtls_md_info_t* md_info = mbedtls_md_info_from_type(md_type); + + if (!md_info || !hmac) + return FALSE; + + if (mbedtls_md_info_from_ctx(hmac) != md_info) + { + mbedtls_md_free(hmac); /* can be called at any time after mbedtls_md_init */ + + if (mbedtls_md_setup(hmac, md_info, 1) != 0) + return FALSE; + } + + if (mbedtls_md_hmac_starts(hmac, key, keylen) == 0) + return TRUE; + +#endif + return FALSE; +} + +BOOL winpr_HMAC_Update(WINPR_HMAC_CTX* ctx, const void* input, size_t ilen) +{ + WINPR_ASSERT(ctx); + + switch (ctx->md) + { +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + hmac_md5_update(&ctx->hmac_md5, input, ilen); + return TRUE; +#endif + default: + break; + } + +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + if (EVP_MAC_update(ctx->xhmac, input, ilen) == 1) + return TRUE; +#else + HMAC_CTX* hmac = ctx->hmac; +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + HMAC_Update(hmac, input, ilen); /* no return value on OpenSSL 0.9.x */ + return TRUE; +#else + + if (HMAC_Update(hmac, input, ilen) == 1) + return TRUE; +#endif +#endif +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* mdctx = &ctx->hmac; + + if (mbedtls_md_hmac_update(mdctx, input, ilen) == 0) + return TRUE; + +#endif + return FALSE; +} + +BOOL winpr_HMAC_Final(WINPR_HMAC_CTX* ctx, void* output, size_t olen) +{ + WINPR_ASSERT(ctx); + + switch (ctx->md) + { +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + if (olen < WINPR_MD5_DIGEST_LENGTH) + return FALSE; + hmac_md5_finalize(&ctx->hmac_md5, output); + return TRUE; +#endif + default: + break; + } + +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + const int rc = EVP_MAC_final(ctx->xhmac, output, NULL, olen); + if (rc == 1) + return TRUE; +#else + HMAC_CTX* hmac = ctx->hmac; +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + HMAC_Final(hmac, output, NULL); /* no return value on OpenSSL 0.9.x */ + return TRUE; +#else + + if (HMAC_Final(hmac, output, NULL) == 1) + return TRUE; + +#endif +#endif +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* mdctx = &ctx->hmac; + + if (mbedtls_md_hmac_finish(mdctx, output) == 0) + return TRUE; + +#endif + return FALSE; +} + +void winpr_HMAC_Free(WINPR_HMAC_CTX* ctx) +{ + if (!ctx) + return; + +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + EVP_MAC_CTX_free(ctx->xhmac); +#else + HMAC_CTX* hmac = ctx->hmac; + + if (hmac) + { +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + HMAC_CTX_cleanup(hmac); + free(hmac); +#else + HMAC_CTX_free(hmac); +#endif + } +#endif +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* hmac = &ctx->hmac; + + if (hmac) + mbedtls_md_free(hmac); + +#endif + + free(ctx); +} + +BOOL winpr_HMAC(WINPR_MD_TYPE md, const void* key, size_t keylen, const void* input, size_t ilen, + void* output, size_t olen) +{ + BOOL result = FALSE; + WINPR_HMAC_CTX* ctx = winpr_HMAC_New(); + + if (!ctx) + return FALSE; + + if (!winpr_HMAC_Init(ctx, md, key, keylen)) + goto out; + + if (!winpr_HMAC_Update(ctx, input, ilen)) + goto out; + + if (!winpr_HMAC_Final(ctx, output, olen)) + goto out; + + result = TRUE; +out: + winpr_HMAC_Free(ctx); + return result; +} + +/** + * Generic Digest API + */ + +struct winpr_digest_ctx_private_st +{ + WINPR_MD_TYPE md; + +#if defined(WITH_INTERNAL_MD4) + WINPR_MD4_CTX md4; +#endif +#if defined(WITH_INTERNAL_MD5) + WINPR_MD5_CTX md5; +#endif +#if defined(WITH_OPENSSL) + EVP_MD_CTX* mdctx; +#endif +#if defined(WITH_MBEDTLS) + mbedtls_md_context_t* mdctx; +#endif +}; + +WINPR_DIGEST_CTX* winpr_Digest_New(void) +{ + WINPR_DIGEST_CTX* ctx = calloc(1, sizeof(WINPR_DIGEST_CTX)); + if (!ctx) + return NULL; + +#if defined(WITH_OPENSSL) +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + ctx->mdctx = EVP_MD_CTX_create(); +#else + ctx->mdctx = EVP_MD_CTX_new(); +#endif + if (!ctx->mdctx) + goto fail; + +#elif defined(WITH_MBEDTLS) + ctx->mdctx = (mbedtls_md_context_t*)calloc(1, sizeof(mbedtls_md_context_t)); + + if (!ctx->mdctx) + goto fail; + + mbedtls_md_init(ctx->mdctx); +#endif + return ctx; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + winpr_Digest_Free(ctx); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +#if defined(WITH_OPENSSL) +static BOOL winpr_Digest_Init_Internal(WINPR_DIGEST_CTX* ctx, const EVP_MD* evp) +{ + WINPR_ASSERT(ctx); + EVP_MD_CTX* mdctx = ctx->mdctx; + + if (!mdctx || !evp) + return FALSE; + + if (EVP_DigestInit_ex(mdctx, evp, NULL) != 1) + { + WLog_ERR(TAG, "Failed to initialize digest %s", winpr_md_type_to_string(ctx->md)); + return FALSE; + } + + return TRUE; +} + +#elif defined(WITH_MBEDTLS) +static BOOL winpr_Digest_Init_Internal(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md) +{ + WINPR_ASSERT(ctx); + mbedtls_md_context_t* mdctx = ctx->mdctx; + mbedtls_md_type_t md_type = winpr_mbedtls_get_md_type(md); + const mbedtls_md_info_t* md_info = mbedtls_md_info_from_type(md_type); + + if (!md_info) + return FALSE; + + if (mbedtls_md_info_from_ctx(mdctx) != md_info) + { + mbedtls_md_free(mdctx); /* can be called at any time after mbedtls_md_init */ + + if (mbedtls_md_setup(mdctx, md_info, 0) != 0) + return FALSE; + } + + if (mbedtls_md_starts(mdctx) != 0) + return FALSE; + + return TRUE; +} +#endif + +BOOL winpr_Digest_Init_Allow_FIPS(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md) +{ + WINPR_ASSERT(ctx); + + ctx->md = md; + switch (md) + { + case WINPR_MD_MD5: +#if defined(WITH_INTERNAL_MD5) + winpr_MD5_Init(&ctx->md5); + return TRUE; +#else + break; +#endif + default: + WLog_ERR(TAG, "Invalid FIPS digest %s requested", winpr_md_type_to_string(md)); + return FALSE; + } + +#if defined(WITH_OPENSSL) +#if OPENSSL_VERSION_NUMBER >= 0x30000000L +#if !defined(WITH_INTERNAL_MD5) + if (md == WINPR_MD_MD5) + { + EVP_MD* md5 = EVP_MD_fetch(NULL, "MD5", "fips=no"); + BOOL rc = winpr_Digest_Init_Internal(ctx, md5); + EVP_MD_free(md5); + return rc; + } +#endif +#endif + const EVP_MD* evp = winpr_openssl_get_evp_md(md); + EVP_MD_CTX_set_flags(ctx->mdctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); + return winpr_Digest_Init_Internal(ctx, evp); +#elif defined(WITH_MBEDTLS) + return winpr_Digest_Init_Internal(ctx, md); +#endif +} + +BOOL winpr_Digest_Init(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md) +{ + WINPR_ASSERT(ctx); + + ctx->md = md; + switch (md) + { +#if defined(WITH_INTERNAL_MD4) + case WINPR_MD_MD4: + winpr_MD4_Init(&ctx->md4); + return TRUE; +#endif +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + winpr_MD5_Init(&ctx->md5); + return TRUE; +#endif + default: + break; + } + +#if defined(WITH_OPENSSL) + const EVP_MD* evp = winpr_openssl_get_evp_md(md); + return winpr_Digest_Init_Internal(ctx, evp); +#else + return winpr_Digest_Init_Internal(ctx, md); +#endif +} + +BOOL winpr_Digest_Update(WINPR_DIGEST_CTX* ctx, const void* input, size_t ilen) +{ + WINPR_ASSERT(ctx); + + switch (ctx->md) + { +#if defined(WITH_INTERNAL_MD4) + case WINPR_MD_MD4: + winpr_MD4_Update(&ctx->md4, input, ilen); + return TRUE; +#endif +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + winpr_MD5_Update(&ctx->md5, input, ilen); + return TRUE; +#endif + default: + break; + } + +#if defined(WITH_OPENSSL) + EVP_MD_CTX* mdctx = ctx->mdctx; + + if (EVP_DigestUpdate(mdctx, input, ilen) != 1) + return FALSE; + +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* mdctx = ctx->mdctx; + + if (mbedtls_md_update(mdctx, input, ilen) != 0) + return FALSE; + +#endif + return TRUE; +} + +BOOL winpr_Digest_Final(WINPR_DIGEST_CTX* ctx, void* output, size_t olen) +{ + WINPR_ASSERT(ctx); + + switch (ctx->md) + { +#if defined(WITH_INTERNAL_MD4) + case WINPR_MD_MD4: + if (olen < WINPR_MD4_DIGEST_LENGTH) + return FALSE; + winpr_MD4_Final(output, &ctx->md4); + return TRUE; +#endif +#if defined(WITH_INTERNAL_MD5) + case WINPR_MD_MD5: + if (olen < WINPR_MD5_DIGEST_LENGTH) + return FALSE; + winpr_MD5_Final(output, &ctx->md5); + return TRUE; +#endif + + default: + break; + } + +#if defined(WITH_OPENSSL) + EVP_MD_CTX* mdctx = ctx->mdctx; + + if (EVP_DigestFinal_ex(mdctx, output, NULL) == 1) + return TRUE; + +#elif defined(WITH_MBEDTLS) + mbedtls_md_context_t* mdctx = ctx->mdctx; + + if (mbedtls_md_finish(mdctx, output) == 0) + return TRUE; + +#endif + return FALSE; +} + +BOOL winpr_DigestSign_Init(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md, void* key) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_OPENSSL) + const EVP_MD* evp = winpr_openssl_get_evp_md(md); + if (!evp) + return FALSE; + + const int rdsi = EVP_DigestSignInit(ctx->mdctx, NULL, evp, NULL, key); + if (rdsi <= 0) + return FALSE; + return TRUE; +#else + return FALSE; +#endif +} + +BOOL winpr_DigestSign_Update(WINPR_DIGEST_CTX* ctx, const void* input, size_t ilen) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_OPENSSL) + EVP_MD_CTX* mdctx = ctx->mdctx; + + if (EVP_DigestSignUpdate(mdctx, input, ilen) != 1) + return FALSE; + return TRUE; +#else + return FALSE; +#endif +} + +BOOL winpr_DigestSign_Final(WINPR_DIGEST_CTX* ctx, void* output, size_t* piolen) +{ + WINPR_ASSERT(ctx); + +#if defined(WITH_OPENSSL) + EVP_MD_CTX* mdctx = ctx->mdctx; + + return EVP_DigestSignFinal(mdctx, output, piolen) == 1; +#else + return FALSE; +#endif +} + +void winpr_Digest_Free(WINPR_DIGEST_CTX* ctx) +{ + if (!ctx) + return; +#if defined(WITH_OPENSSL) + if (ctx->mdctx) + { +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \ + (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL) + EVP_MD_CTX_destroy(ctx->mdctx); +#else + EVP_MD_CTX_free(ctx->mdctx); +#endif + } + +#elif defined(WITH_MBEDTLS) + if (ctx->mdctx) + { + mbedtls_md_free(ctx->mdctx); + free(ctx->mdctx); + } + +#endif + free(ctx); +} + +BOOL winpr_Digest_Allow_FIPS(WINPR_MD_TYPE md, const void* input, size_t ilen, void* output, + size_t olen) +{ + BOOL result = FALSE; + WINPR_DIGEST_CTX* ctx = winpr_Digest_New(); + + if (!ctx) + return FALSE; + + if (!winpr_Digest_Init_Allow_FIPS(ctx, md)) + goto out; + + if (!winpr_Digest_Update(ctx, input, ilen)) + goto out; + + if (!winpr_Digest_Final(ctx, output, olen)) + goto out; + + result = TRUE; +out: + winpr_Digest_Free(ctx); + return result; +} + +BOOL winpr_Digest(WINPR_MD_TYPE md, const void* input, size_t ilen, void* output, size_t olen) +{ + BOOL result = FALSE; + WINPR_DIGEST_CTX* ctx = winpr_Digest_New(); + + if (!ctx) + return FALSE; + + if (!winpr_Digest_Init(ctx, md)) + goto out; + + if (!winpr_Digest_Update(ctx, input, ilen)) + goto out; + + if (!winpr_Digest_Final(ctx, output, olen)) + goto out; + + result = TRUE; +out: + winpr_Digest_Free(ctx); + return result; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.c new file mode 100644 index 0000000000000000000000000000000000000000..100c212f1ea2315fae85aec998cc4edde61714ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.c @@ -0,0 +1,56 @@ +#include +#include + +#include "hmac_md5.h" +#include "md5.h" + +void hmac_md5_init(WINPR_HMAC_MD5_CTX* ctx, const unsigned char* key, size_t key_len) +{ + const WINPR_HMAC_MD5_CTX empty = { 0 }; + unsigned char k_ipad[KEY_IOPAD_SIZE] = { 0 }; + unsigned char k_opad[KEY_IOPAD_SIZE] = { 0 }; + + assert(ctx); + *ctx = empty; + + if (key_len <= KEY_IOPAD_SIZE) + { + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + } + else + { + WINPR_MD5_CTX lctx = { 0 }; + + winpr_MD5_Init(&lctx); + winpr_MD5_Update(&lctx, key, key_len); + winpr_MD5_Final(k_ipad, &lctx); + memcpy(k_opad, k_ipad, KEY_IOPAD_SIZE); + } + for (size_t i = 0; i < KEY_IOPAD_SIZE; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + winpr_MD5_Init(&ctx->icontext); + winpr_MD5_Update(&ctx->icontext, k_ipad, KEY_IOPAD_SIZE); + + winpr_MD5_Init(&ctx->ocontext); + winpr_MD5_Update(&ctx->ocontext, k_opad, KEY_IOPAD_SIZE); +} + +void hmac_md5_update(WINPR_HMAC_MD5_CTX* ctx, const unsigned char* text, size_t text_len) +{ + assert(ctx); + winpr_MD5_Update(&ctx->icontext, text, text_len); +} + +void hmac_md5_finalize(WINPR_HMAC_MD5_CTX* ctx, unsigned char* hmac) +{ + assert(ctx); + winpr_MD5_Final(hmac, &ctx->icontext); + + winpr_MD5_Update(&ctx->ocontext, hmac, 16); + winpr_MD5_Final(hmac, &ctx->ocontext); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.h new file mode 100644 index 0000000000000000000000000000000000000000..8ade3e42422402c5a2d018b478b43d3186ec7dfb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/hmac_md5.h @@ -0,0 +1,19 @@ +#ifndef WINPR_HMAC_MD5 +#define WINPR_HMAC_MD5 + +#include + +#include "md5.h" + +#define KEY_IOPAD_SIZE 64 +typedef struct +{ + WINPR_MD5_CTX icontext; + WINPR_MD5_CTX ocontext; +} WINPR_HMAC_MD5_CTX; + +void hmac_md5_init(WINPR_HMAC_MD5_CTX* ctx, const unsigned char* key, size_t key_len); +void hmac_md5_update(WINPR_HMAC_MD5_CTX* ctx, const unsigned char* text, size_t text_len); +void hmac_md5_finalize(WINPR_HMAC_MD5_CTX* ctx, unsigned char* hmac); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.c new file mode 100644 index 0000000000000000000000000000000000000000..78ceb8cbe4819eae53b5f17d6a2b6935aef83b3c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.c @@ -0,0 +1,271 @@ +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD4 Message-Digest Algorithm (RFC 1320). + * + * Homepage: + * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there's no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +#include + +#include "md4.h" + +/* + * The basic MD4 functions. + * + * F and G are optimized compared to their RFC 1320 definitions, with the + * optimization for F borrowed from Colin Plumb's MD5 implementation. + */ +static inline winpr_MD4_u32plus F(winpr_MD4_u32plus x, winpr_MD4_u32plus y, winpr_MD4_u32plus z) +{ + return ((z) ^ ((x) & ((y) ^ (z)))); +} +static inline winpr_MD4_u32plus G(winpr_MD4_u32plus x, winpr_MD4_u32plus y, winpr_MD4_u32plus z) +{ + return (((x) & ((y) | (z))) | ((y) & (z))); +} +static inline winpr_MD4_u32plus H(winpr_MD4_u32plus x, winpr_MD4_u32plus y, winpr_MD4_u32plus z) +{ + return ((x) ^ (y) ^ (z)); +} + +/* + * The MD4 transformation for all three rounds. + */ +#define STEP(f, a, b, c, d, x, s) \ + (a) += f((b), (c), (d)) + (x); \ + (a) = (((a) << (s)) | (((a)&0xffffffff) >> (32 - (s)))); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them in a + * properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned memory + * accesses is just an optimization. Nothing will break if it fails to detect + * a suitable architecture. + * + * Unfortunately, this optimization may be a C strict aliasing rules violation + * if the caller's data buffer has effective type that cannot be aliased by + * winpr_MD4_u32plus. In practice, this problem may occur if these MD4 routines are + * inlined into a calling function, or with future and dangerously advanced + * link-time optimizations. For the time being, keeping these MD4 routines in + * their own translation unit avoids the problem. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define SET(n) (*(const winpr_MD4_u32plus*)&ptr[4ULL * (n)]) +#define GET(n) SET(n) +#else +#define SET(n) \ + (ctx->block[(n)] = (winpr_MD4_u32plus)ptr[4ULL * (n)] | \ + ((winpr_MD4_u32plus)ptr[4ULL * (n) + 1] << 8) | \ + ((winpr_MD4_u32plus)ptr[4ULL * (n) + 2] << 16) | \ + ((winpr_MD4_u32plus)ptr[4ULL * (n) + 3] << 24)) +#define GET(n) (ctx->block[(n)]) +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update the bit + * counters. There are no alignment requirements. + */ +static const void* body(WINPR_MD4_CTX* ctx, const void* data, unsigned long size) +{ + const winpr_MD4_u32plus ac1 = 0x5a827999; + const winpr_MD4_u32plus ac2 = 0x6ed9eba1; + + const unsigned char* ptr = (const unsigned char*)data; + + winpr_MD4_u32plus a = ctx->a; + winpr_MD4_u32plus b = ctx->b; + winpr_MD4_u32plus c = ctx->c; + winpr_MD4_u32plus d = ctx->d; + + do + { + const winpr_MD4_u32plus saved_a = a; + const winpr_MD4_u32plus saved_b = b; + const winpr_MD4_u32plus saved_c = c; + const winpr_MD4_u32plus saved_d = d; + + /* Round 1 */ + STEP(F, a, b, c, d, SET(0), 3) + STEP(F, d, a, b, c, SET(1), 7) + STEP(F, c, d, a, b, SET(2), 11) + STEP(F, b, c, d, a, SET(3), 19) + STEP(F, a, b, c, d, SET(4), 3) + STEP(F, d, a, b, c, SET(5), 7) + STEP(F, c, d, a, b, SET(6), 11) + STEP(F, b, c, d, a, SET(7), 19) + STEP(F, a, b, c, d, SET(8), 3) + STEP(F, d, a, b, c, SET(9), 7) + STEP(F, c, d, a, b, SET(10), 11) + STEP(F, b, c, d, a, SET(11), 19) + STEP(F, a, b, c, d, SET(12), 3) + STEP(F, d, a, b, c, SET(13), 7) + STEP(F, c, d, a, b, SET(14), 11) + STEP(F, b, c, d, a, SET(15), 19) + + /* Round 2 */ + STEP(G, a, b, c, d, GET(0) + ac1, 3) + STEP(G, d, a, b, c, GET(4) + ac1, 5) + STEP(G, c, d, a, b, GET(8) + ac1, 9) + STEP(G, b, c, d, a, GET(12) + ac1, 13) + STEP(G, a, b, c, d, GET(1) + ac1, 3) + STEP(G, d, a, b, c, GET(5) + ac1, 5) + STEP(G, c, d, a, b, GET(9) + ac1, 9) + STEP(G, b, c, d, a, GET(13) + ac1, 13) + STEP(G, a, b, c, d, GET(2) + ac1, 3) + STEP(G, d, a, b, c, GET(6) + ac1, 5) + STEP(G, c, d, a, b, GET(10) + ac1, 9) + STEP(G, b, c, d, a, GET(14) + ac1, 13) + STEP(G, a, b, c, d, GET(3) + ac1, 3) + STEP(G, d, a, b, c, GET(7) + ac1, 5) + STEP(G, c, d, a, b, GET(11) + ac1, 9) + STEP(G, b, c, d, a, GET(15) + ac1, 13) + + /* Round 3 */ + STEP(H, a, b, c, d, GET(0) + ac2, 3) + STEP(H, d, a, b, c, GET(8) + ac2, 9) + STEP(H, c, d, a, b, GET(4) + ac2, 11) + STEP(H, b, c, d, a, GET(12) + ac2, 15) + STEP(H, a, b, c, d, GET(2) + ac2, 3) + STEP(H, d, a, b, c, GET(10) + ac2, 9) + STEP(H, c, d, a, b, GET(6) + ac2, 11) + STEP(H, b, c, d, a, GET(14) + ac2, 15) + STEP(H, a, b, c, d, GET(1) + ac2, 3) + STEP(H, d, a, b, c, GET(9) + ac2, 9) + STEP(H, c, d, a, b, GET(5) + ac2, 11) + STEP(H, b, c, d, a, GET(13) + ac2, 15) + STEP(H, a, b, c, d, GET(3) + ac2, 3) + STEP(H, d, a, b, c, GET(11) + ac2, 9) + STEP(H, c, d, a, b, GET(7) + ac2, 11) + STEP(H, b, c, d, a, GET(15) + ac2, 15) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while (size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +void winpr_MD4_Init(WINPR_MD4_CTX* ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; +} + +void winpr_MD4_Update(WINPR_MD4_CTX* ctx, const void* data, unsigned long size) +{ + winpr_MD4_u32plus saved_lo = ctx->lo; + if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) + ctx->hi++; + ctx->hi += size >> 29; + + unsigned long used = saved_lo & 0x3f; + + if (used) + { + unsigned long available = 64 - used; + + if (size < available) + { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char*)data + available; + size -= available; + body(ctx, ctx->buffer, 64); + } + + if (size >= 64) + { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +static inline void mdOUT(unsigned char* dst, winpr_MD4_u32plus src) +{ + (dst)[0] = (unsigned char)(src); + (dst)[1] = (unsigned char)((src) >> 8); + (dst)[2] = (unsigned char)((src) >> 16); + (dst)[3] = (unsigned char)((src) >> 24); +} + +void winpr_MD4_Final(unsigned char* result, WINPR_MD4_CTX* ctx) +{ + unsigned long used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + unsigned long available = 64 - used; + + if (available < 8) + { + memset(&ctx->buffer[used], 0, available); + body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + mdOUT(&ctx->buffer[56], ctx->lo); + mdOUT(&ctx->buffer[60], ctx->hi); + + body(ctx, ctx->buffer, 64); + + mdOUT(&result[0], ctx->a); + mdOUT(&result[4], ctx->b); + mdOUT(&result[8], ctx->c); + mdOUT(&result[12], ctx->d); + + memset(ctx, 0, sizeof(*ctx)); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.h new file mode 100644 index 0000000000000000000000000000000000000000..1ea008eccbefd73053af6a4a3c66277013a1b858 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md4.h @@ -0,0 +1,46 @@ +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD4 Message-Digest Algorithm (RFC 1320). + * + * Homepage: + * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See md4.c for more information. + */ + +#if !defined(WINPR_MD4_H) +#define WINPR_MD4_H + +#include + +/* Any 32-bit or wider unsigned integer data type will do */ +typedef UINT32 winpr_MD4_u32plus; + +typedef struct +{ + winpr_MD4_u32plus lo, hi; + winpr_MD4_u32plus a, b, c, d; + unsigned char buffer[64]; + winpr_MD4_u32plus block[16]; +} WINPR_MD4_CTX; + +extern void winpr_MD4_Init(WINPR_MD4_CTX* ctx); +extern void winpr_MD4_Update(WINPR_MD4_CTX* ctx, const void* data, unsigned long size); +extern void winpr_MD4_Final(unsigned char* result, WINPR_MD4_CTX* ctx); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.c new file mode 100644 index 0000000000000000000000000000000000000000..c832e700523bdeeeed51137245c9953233a4ee2e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.c @@ -0,0 +1,296 @@ +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there's no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +#include + +#include "md5.h" + +/* + * The basic MD5 functions. + * + * F and G are optimized compared to their RFC 1321 definitions for + * architectures that lack an AND-NOT instruction, just like in Colin Plumb's + * implementation. + */ +static inline winpr_MD5_u32plus F(winpr_MD5_u32plus x, winpr_MD5_u32plus y, winpr_MD5_u32plus z) +{ + return ((z) ^ ((x) & ((y) ^ (z)))); +} +static inline winpr_MD5_u32plus G(winpr_MD5_u32plus x, winpr_MD5_u32plus y, winpr_MD5_u32plus z) +{ + return ((y) ^ ((z) & ((x) ^ (y)))); +} +static inline winpr_MD5_u32plus H(winpr_MD5_u32plus x, winpr_MD5_u32plus y, winpr_MD5_u32plus z) +{ + return (((x) ^ (y)) ^ (z)); +} +static inline winpr_MD5_u32plus H2(winpr_MD5_u32plus x, winpr_MD5_u32plus y, winpr_MD5_u32plus z) +{ + return ((x) ^ ((y) ^ (z))); +} +static inline winpr_MD5_u32plus I(winpr_MD5_u32plus x, winpr_MD5_u32plus y, winpr_MD5_u32plus z) +{ + return ((y) ^ ((x) | ~(z))); +} + +/* + * The MD5 transformation for all four rounds. + */ +#define STEP(f, a, b, c, d, x, t, s) \ + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a)&0xffffffff) >> (32 - (s)))); \ + (a) += (b); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them in a + * properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned memory + * accesses is just an optimization. Nothing will break if it fails to detect + * a suitable architecture. + * + * Unfortunately, this optimization may be a C strict aliasing rules violation + * if the caller's data buffer has effective type that cannot be aliased by + * MD5_u32plus. In practice, this problem may occur if these MD5 routines are + * inlined into a calling function, or with future and dangerously advanced + * link-time optimizations. For the time being, keeping these MD5 routines in + * their own translation unit avoids the problem. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define SET(n) (*(const winpr_MD5_u32plus*)&ptr[4ULL * (n)]) +#define GET(n) SET(n) +#else +#define SET(n) \ + (ctx->block[(n)] = (winpr_MD5_u32plus)ptr[4ULL * (n)] | \ + ((winpr_MD5_u32plus)ptr[4ULL * (n) + 1] << 8) | \ + ((winpr_MD5_u32plus)ptr[4ULL * (n) + 2] << 16) | \ + ((winpr_MD5_u32plus)ptr[4ULL * (n) + 3] << 24)) +#define GET(n) (ctx->block[(n)]) +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update the bit + * counters. There are no alignment requirements. + */ +static const void* body(WINPR_MD5_CTX* ctx, const void* data, unsigned long size) +{ + const unsigned char* ptr = (const unsigned char*)data; + + winpr_MD5_u32plus a = ctx->a; + winpr_MD5_u32plus b = ctx->b; + winpr_MD5_u32plus c = ctx->c; + winpr_MD5_u32plus d = ctx->d; + + do + { + const winpr_MD5_u32plus saved_a = a; + const winpr_MD5_u32plus saved_b = b; + const winpr_MD5_u32plus saved_c = c; + const winpr_MD5_u32plus saved_d = d; + + /* Round 1 */ + STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) + STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) + STEP(F, c, d, a, b, SET(2), 0x242070db, 17) + STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) + STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) + STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) + STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) + STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) + STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) + STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) + STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) + STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) + STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) + STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) + STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) + STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) + + /* Round 2 */ + STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) + STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) + STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) + STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) + STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) + STEP(G, d, a, b, c, GET(10), 0x02441453, 9) + STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) + STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) + STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) + STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) + STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) + STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) + STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) + STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) + STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) + STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) + + /* Round 3 */ + STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) + STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) + STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) + STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) + STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) + STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) + STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) + STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) + STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) + STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) + STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) + STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) + STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) + STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) + STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) + STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) + + /* Round 4 */ + STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) + STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) + STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) + STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) + STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) + STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) + STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) + STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) + STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) + STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) + STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) + STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) + STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) + STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) + STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) + STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while (size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +void winpr_MD5_Init(WINPR_MD5_CTX* ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; +} + +void winpr_MD5_Update(WINPR_MD5_CTX* ctx, const void* data, unsigned long size) +{ + winpr_MD5_u32plus saved_lo = ctx->lo; + if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) + ctx->hi++; + ctx->hi += size >> 29; + + unsigned long used = saved_lo & 0x3f; + + if (used) + { + unsigned long available = 64 - used; + + if (size < available) + { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char*)data + available; + size -= available; + body(ctx, ctx->buffer, 64); + } + + if (size >= 64) + { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +static inline void mdOUT(unsigned char* dst, winpr_MD5_u32plus src) +{ + (dst)[0] = (unsigned char)(src); + (dst)[1] = (unsigned char)((src) >> 8); + (dst)[2] = (unsigned char)((src) >> 16); + (dst)[3] = (unsigned char)((src) >> 24); +} + +void winpr_MD5_Final(unsigned char* result, WINPR_MD5_CTX* ctx) +{ + unsigned long used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + unsigned long available = 64 - used; + + if (available < 8) + { + memset(&ctx->buffer[used], 0, available); + body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + mdOUT(&ctx->buffer[56], ctx->lo); + mdOUT(&ctx->buffer[60], ctx->hi); + + body(ctx, ctx->buffer, 64); + + mdOUT(&result[0], ctx->a); + mdOUT(&result[4], ctx->b); + mdOUT(&result[8], ctx->c); + mdOUT(&result[12], ctx->d); + + memset(ctx, 0, sizeof(*ctx)); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.h new file mode 100644 index 0000000000000000000000000000000000000000..2056b9a806fcb72ca829dfbe2026bdb0215c9dfa --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/md5.h @@ -0,0 +1,48 @@ + + +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See md5.c for more information. + */ + +#if !defined(WINPR_MD5_H) +#define WINPR_MD5_H + +#include + +/* Any 32-bit or wider unsigned integer data type will do */ +typedef UINT32 winpr_MD5_u32plus; + +typedef struct +{ + winpr_MD5_u32plus lo, hi; + winpr_MD5_u32plus a, b, c, d; + unsigned char buffer[64]; + winpr_MD5_u32plus block[16]; +} WINPR_MD5_CTX; + +extern void winpr_MD5_Init(WINPR_MD5_CTX* ctx); +extern void winpr_MD5_Update(WINPR_MD5_CTX* ctx, const void* data, unsigned long size); +extern void winpr_MD5_Final(unsigned char* result, WINPR_MD5_CTX* ctx); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rand.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rand.c new file mode 100644 index 0000000000000000000000000000000000000000..41fe06f53b3cb5fff2f1ff4df86d0498cebc12c9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rand.c @@ -0,0 +1,83 @@ +/** + * WinPR: Windows Portable Runtime + * + * Copyright 2015 Marc-Andre Moreau + * + * 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 + +#include + +#include + +#ifdef WITH_OPENSSL +#include +#include +#endif + +#ifdef WITH_MBEDTLS +#include +#include +#ifdef MBEDTLS_HAVEGE_C +#include +#endif +#include +#endif + +int winpr_RAND(void* output, size_t len) +{ +#if defined(WITH_OPENSSL) + if (len > INT_MAX) + return -1; + if (RAND_bytes(output, (int)len) != 1) + return -1; +#elif defined(WITH_MBEDTLS) +#if defined(MBEDTLS_HAVEGE_C) + mbedtls_havege_state hs; + mbedtls_havege_init(&hs); + + if (mbedtls_havege_random(&hs, output, len) != 0) + return -1; + + mbedtls_havege_free(&hs); +#else + int status; + mbedtls_entropy_context entropy; + mbedtls_hmac_drbg_context hmac_drbg; + const mbedtls_md_info_t* md_info; + + mbedtls_entropy_init(&entropy); + mbedtls_hmac_drbg_init(&hmac_drbg); + + md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); + if ((status = mbedtls_hmac_drbg_seed(&hmac_drbg, md_info, mbedtls_entropy_func, &entropy, NULL, + 0)) != 0) + return -1; + + status = mbedtls_hmac_drbg_random(&hmac_drbg, output, len); + mbedtls_hmac_drbg_free(&hmac_drbg); + mbedtls_entropy_free(&entropy); + + if (status != 0) + return -1; +#endif +#endif + return 0; +} + +int winpr_RAND_pseudo(void* output, size_t len) +{ + return winpr_RAND(output, len); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.c new file mode 100644 index 0000000000000000000000000000000000000000..c1ea61706acd20fb901cdb30eec6c21669069736 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.c @@ -0,0 +1,89 @@ +/** + * WinPR: Windows Portable Runtime + * RC4 implementation for RDP + * + * Copyright 2023 Armin Novak + * Copyright 2023 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 +#include + +#include "rc4.h" + +#define CTX_SIZE 256 + +struct winpr_int_rc4_ctx +{ + size_t i; + size_t j; + BYTE s[CTX_SIZE]; + BYTE t[CTX_SIZE]; +}; + +static void swap(BYTE* p1, BYTE* p2) +{ + BYTE t = *p1; + *p1 = *p2; + *p2 = t; +} + +winpr_int_RC4_CTX* winpr_int_rc4_new(const BYTE* key, size_t keylength) +{ + winpr_int_RC4_CTX* ctx = calloc(1, sizeof(winpr_int_RC4_CTX)); + if (!ctx) + return NULL; + + for (size_t i = 0; i < CTX_SIZE; i++) + { + ctx->s[i] = WINPR_ASSERTING_INT_CAST(BYTE, i); + ctx->t[i] = key[i % keylength]; + } + + size_t j = 0; + for (size_t i = 0; i < CTX_SIZE; i++) + { + j = (j + ctx->s[i] + ctx->t[i]) % CTX_SIZE; + swap(&ctx->s[i], &ctx->s[j]); + } + return ctx; +} + +void winpr_int_rc4_free(winpr_int_RC4_CTX* ctx) +{ + free(ctx); +} + +BOOL winpr_int_rc4_update(winpr_int_RC4_CTX* ctx, size_t length, const BYTE* input, BYTE* output) +{ + WINPR_ASSERT(ctx); + + size_t t1 = ctx->i; + size_t t2 = ctx->j; + for (size_t i = 0; i < length; i++) + { + t1 = (t1 + 1) % CTX_SIZE; + t2 = (t2 + ctx->s[t1]) % CTX_SIZE; + swap(&ctx->s[t1], &ctx->s[t2]); + + const size_t idx = ((size_t)ctx->s[t1] + ctx->s[t2]) % CTX_SIZE; + const BYTE val = ctx->s[idx]; + const BYTE out = *input++ ^ val; + *output++ = out; + } + + ctx->i = t1; + ctx->j = t2; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.h new file mode 100644 index 0000000000000000000000000000000000000000..63c99544c7619d5f89f030e33fc3c9c5a64dffda --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/rc4.h @@ -0,0 +1,34 @@ +/** + * WinPR: Windows Portable Runtime + * RC4 implementation for RDP + * + * Copyright 2023 Armin Novak + * Copyright 2023 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_RC4_H +#define WINPR_RC4_H + +#include +#include + +typedef struct winpr_int_rc4_ctx winpr_int_RC4_CTX; + +void winpr_int_rc4_free(winpr_int_RC4_CTX* ctx); + +WINPR_ATTR_MALLOC(winpr_int_rc4_free, 1) +winpr_int_RC4_CTX* winpr_int_rc4_new(const BYTE* key, size_t keylength); +BOOL winpr_int_rc4_update(winpr_int_RC4_CTX* ctx, size_t length, const BYTE* input, BYTE* output); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8257950b765e108c6a1bc3e8126be80f56b91bd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/CMakeLists.txt @@ -0,0 +1,29 @@ +set(MODULE_NAME "TestCrypto") +set(MODULE_PREFIX "TEST_CRYPTO") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestCryptoHash.c TestCryptoRand.c TestCryptoCipher.c TestCryptoProtectData.c + TestCryptoProtectMemory.c TestCryptoCertEnumCertificatesInStore.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +if(WIN32) + set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} secur32 crypt32 cryptui) +endif() + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCertEnumCertificatesInStore.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCertEnumCertificatesInStore.c new file mode 100644 index 0000000000000000000000000000000000000000..6b40c8d96a5c53cd3de4c50b59f319cae2dfcbb1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCertEnumCertificatesInStore.c @@ -0,0 +1,86 @@ + + +#include +#include +#include + +#ifdef _WIN32 +//#define WITH_CRYPTUI 1 +#endif + +#ifdef WITH_CRYPTUI +#include +#endif + +int TestCryptoCertEnumCertificatesInStore(int argc, char* argv[]) +{ + int index = 0; + DWORD status = 0; + LPTSTR pszNameString = NULL; + HCERTSTORE hCertStore = NULL; + PCCERT_CONTEXT pCertContext = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /** + * System Store Locations: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa388136/ + */ + + /** + * Requires elevated rights: + * hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, + * CERT_SYSTEM_STORE_LOCAL_MACHINE, _T("Remote Desktop")); + */ + + hCertStore = CertOpenSystemStore((HCRYPTPROV_LEGACY)NULL, _T("MY")); + // hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, + // CERT_SYSTEM_STORE_CURRENT_USER, _T("MY")); + + if (!hCertStore) + { + printf("Failed to open system store\n"); + return -1; + } + + index = 0; + + while ((pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext))) + { + status = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0); + if (status == 0) + return -1; + + pszNameString = (LPTSTR)calloc(status, sizeof(TCHAR)); + if (!pszNameString) + { + printf("Unable to allocate memory\n"); + return -1; + } + + status = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, + pszNameString, status); + if (status == 0) + { + free(pszNameString); + return -1; + } + + _tprintf(_T("Certificate #%d: %s\n"), index++, pszNameString); + + free(pszNameString); + +#ifdef WITH_CRYPTUI + CryptUIDlgViewContext(CERT_STORE_CERTIFICATE_CONTEXT, pCertContext, NULL, NULL, 0, NULL); +#endif + } + + if (!CertCloseStore(hCertStore, 0)) + { + printf("Failed to close system store\n"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCipher.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCipher.c new file mode 100644 index 0000000000000000000000000000000000000000..afa661ddcd8bcddaf21c6f22cf568394f3fba1cf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoCipher.c @@ -0,0 +1,240 @@ + +#include +#include +#include +#include + +static BOOL test_crypto_cipher_aes_128_cbc(BOOL ex) +{ + BOOL result = FALSE; + BYTE key[16] = "0123456789abcdeF"; + BYTE iv[16] = "1234567887654321"; + BYTE ibuf[1024] = { 0 }; + BYTE obuf[1024] = { 0 }; + size_t ilen = 0; + size_t olen = 0; + size_t xlen = 0; + const char plaintext[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " + "eiusmod tempor incididunt ut labore et dolore magna aliqua."; + + /* encrypt */ + + WINPR_CIPHER_CTX* ctx = NULL; + if (ex) + ctx = winpr_Cipher_NewEx(WINPR_CIPHER_AES_128_CBC, WINPR_ENCRYPT, key, sizeof(key), iv, + sizeof(iv)); + else + ctx = winpr_Cipher_New(WINPR_CIPHER_AES_128_CBC, WINPR_ENCRYPT, key, iv); + if (!ctx) + { + (void)fprintf(stderr, "%s: winpr_Cipher_New (encrypt) failed\n", __func__); + return FALSE; + } + + ilen = strnlen(plaintext, sizeof(plaintext)) + 1; + memcpy(ibuf, plaintext, ilen); + + ilen = ((ilen + 15) / 16) * 16; + olen = 0; + xlen = 0; + + if (!winpr_Cipher_Update(ctx, ibuf, ilen, obuf, &olen)) + { + (void)fprintf(stderr, "%s: winpr_Cipher_New (encrypt) failed\n", __func__); + goto out; + } + xlen += olen; + + if (!winpr_Cipher_Final(ctx, obuf + xlen, &olen)) + { + (void)fprintf(stderr, "%s: winpr_Cipher_Final (encrypt) failed\n", __func__); + goto out; + } + xlen += olen; + + if (xlen != ilen) + { + (void)fprintf(stderr, "%s: error, xlen (%" PRIuz ") != ilen (%" PRIuz ") (encrypt)\n", + __func__, xlen, ilen); + goto out; + } + + winpr_Cipher_Free(ctx); + + /* decrypt */ + + if (!(ctx = winpr_Cipher_New(WINPR_CIPHER_AES_128_CBC, WINPR_DECRYPT, key, iv))) + { + (void)fprintf(stderr, "%s: winpr_Cipher_New (decrypt) failed\n", __func__); + return FALSE; + } + + memset(ibuf, 0, sizeof(ibuf)); + memcpy(ibuf, obuf, xlen); + memset(obuf, 0, sizeof(obuf)); + + ilen = xlen; + olen = 0; + xlen = 0; + + if (!winpr_Cipher_Update(ctx, ibuf, ilen, obuf, &olen)) + { + (void)fprintf(stderr, "%s: winpr_Cipher_New (decrypt) failed\n", __func__); + goto out; + } + xlen += olen; + + if (!winpr_Cipher_Final(ctx, obuf + xlen, &olen)) + { + (void)fprintf(stderr, "%s: winpr_Cipher_Final (decrypt) failed\n", __func__); + goto out; + } + xlen += olen; + + if (xlen != ilen) + { + (void)fprintf(stderr, "%s: error, xlen (%" PRIuz ") != ilen (%" PRIuz ") (decrypt)\n", + __func__, xlen, ilen); + goto out; + } + + if (strcmp((const char*)obuf, plaintext) != 0) + { + (void)fprintf(stderr, "%s: error, decrypted data does not match plaintext\n", __func__); + goto out; + } + + result = TRUE; + +out: + winpr_Cipher_Free(ctx); + return result; +} + +static const char TEST_RC4_KEY[] = "Key"; +static const char TEST_RC4_PLAINTEXT[] = "Plaintext"; +static const char TEST_RC4_CIPHERTEXT[] = "\xBB\xF3\x16\xE8\xD9\x40\xAF\x0A\xD3"; + +static BOOL test_crypto_cipher_rc4(void) +{ + BOOL rc = FALSE; + WINPR_RC4_CTX* ctx = NULL; + + const size_t len = strnlen(TEST_RC4_PLAINTEXT, sizeof(TEST_RC4_PLAINTEXT)); + BYTE* text = (BYTE*)calloc(1, len); + if (!text) + { + (void)fprintf(stderr, "%s: failed to allocate text buffer (len=%" PRIuz ")\n", __func__, + len); + goto out; + } + + if ((ctx = winpr_RC4_New(TEST_RC4_KEY, strnlen(TEST_RC4_KEY, sizeof(TEST_RC4_KEY)))) == NULL) + { + (void)fprintf(stderr, "%s: winpr_RC4_New failed\n", __func__); + goto out; + } + rc = winpr_RC4_Update(ctx, len, (const BYTE*)TEST_RC4_PLAINTEXT, text); + winpr_RC4_Free(ctx); + if (!rc) + { + (void)fprintf(stderr, "%s: winpr_RC4_Update failed\n", __func__); + goto out; + } + + if (memcmp(text, TEST_RC4_CIPHERTEXT, len) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(text, len, FALSE); + expected = winpr_BinToHexString(TEST_RC4_CIPHERTEXT, len, FALSE); + + (void)fprintf(stderr, "%s: unexpected RC4 ciphertext: Actual: %s Expected: %s\n", __func__, + actual, expected); + + free(actual); + free(expected); + goto out; + } + + rc = TRUE; + +out: + free(text); + return rc; +} + +static const BYTE* TEST_RAND_DATA = + (BYTE*)"\x1F\xC2\xEE\x4C\xA3\x66\x80\xA2\xCE\xFE\x56\xB4\x9E\x08\x30\x96" + "\x33\x6A\xA9\x6D\x36\xFD\x3C\xB7\x83\x04\x4E\x5E\xDC\x22\xCD\xF3" + "\x48\xDF\x3A\x2A\x61\xF1\xA8\xFA\x1F\xC6\xC7\x1B\x81\xB4\xE1\x0E" + "\xCB\xA2\xEF\xA1\x12\x4A\x83\xE5\x1D\x72\x1D\x2D\x26\xA8\x6B\xC0"; + +static const BYTE* TEST_CIPHER_KEY = + (BYTE*)"\x9D\x7C\xC0\xA1\x94\x3B\x07\x67\x2F\xD3\x83\x10\x51\x83\x38\x0E" + "\x1C\x74\x8C\x4E\x15\x79\xD6\xFF\xE2\xF0\x37\x7F\x8C\xD7\xD2\x13"; + +static const BYTE* TEST_CIPHER_IV = + (BYTE*)"\xFE\xE3\x9F\xF0\xD1\x5E\x37\x0C\xAB\xAB\x9B\x04\xF3\xDB\x99\x15"; + +static BOOL test_crypto_cipher_key(void) +{ + int status = 0; + BYTE key[32] = { 0 }; + BYTE iv[16] = { 0 }; + BYTE salt[8] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 }; + + status = winpr_Cipher_BytesToKey(WINPR_CIPHER_AES_256_CBC, WINPR_MD_SHA1, salt, TEST_RAND_DATA, + 64, 4, key, iv); + + if (status != 32 || memcmp(key, TEST_CIPHER_KEY, 32) != 0 || + memcmp(iv, TEST_CIPHER_IV, 16) != 0) + { + char* akstr = NULL; + char* ekstr = NULL; + char* aivstr = NULL; + char* eivstr = NULL; + + akstr = winpr_BinToHexString(key, 32, 0); + ekstr = winpr_BinToHexString(TEST_CIPHER_KEY, 32, 0); + + aivstr = winpr_BinToHexString(iv, 16, 0); + eivstr = winpr_BinToHexString(TEST_CIPHER_IV, 16, 0); + + (void)fprintf(stderr, "Unexpected EVP_BytesToKey Key: Actual: %s, Expected: %s\n", akstr, + ekstr); + (void)fprintf(stderr, "Unexpected EVP_BytesToKey IV : Actual: %s, Expected: %s\n", aivstr, + eivstr); + + free(akstr); + free(ekstr); + free(aivstr); + free(eivstr); + } + + return TRUE; +} + +int TestCryptoCipher(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + if (!test_crypto_cipher_aes_128_cbc(TRUE)) + return -1; + + if (!test_crypto_cipher_aes_128_cbc(FALSE)) + return -1; + + if (!test_crypto_cipher_rc4()) + return -1; + + if (!test_crypto_cipher_key()) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoHash.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoHash.c new file mode 100644 index 0000000000000000000000000000000000000000..2d068855ea7b4fe27a5b1e2e1e7464a5daa57882 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoHash.c @@ -0,0 +1,318 @@ + +#include +#include +#include +#include + +static const char TEST_MD5_DATA[] = "test"; +static const BYTE TEST_MD5_HASH[] = + "\x09\x8f\x6b\xcd\x46\x21\xd3\x73\xca\xde\x4e\x83\x26\x27\xb4\xf6"; + +static BOOL test_crypto_hash_md5(void) +{ + BOOL result = FALSE; + BYTE hash[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + WINPR_DIGEST_CTX* ctx = NULL; + + if (!(ctx = winpr_Digest_New())) + { + (void)fprintf(stderr, "%s: winpr_Digest_New failed\n", __func__); + return FALSE; + } + if (!winpr_Digest_Init(ctx, WINPR_MD_MD5)) + { + (void)fprintf(stderr, "%s: winpr_Digest_Init failed\n", __func__); + goto out; + } + if (!winpr_Digest_Update(ctx, (const BYTE*)TEST_MD5_DATA, + strnlen(TEST_MD5_DATA, sizeof(TEST_MD5_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Update failed\n", __func__); + goto out; + } + if (!winpr_Digest_Final(ctx, hash, sizeof(hash))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Final failed\n", __func__); + goto out; + } + if (memcmp(hash, TEST_MD5_HASH, WINPR_MD5_DIGEST_LENGTH) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(hash, WINPR_MD5_DIGEST_LENGTH, FALSE); + expected = winpr_BinToHexString(TEST_MD5_HASH, WINPR_MD5_DIGEST_LENGTH, FALSE); + + (void)fprintf(stderr, "unexpected MD5 hash: Actual: %s Expected: %s\n", actual, expected); + + free(actual); + free(expected); + + goto out; + } + + result = TRUE; +out: + winpr_Digest_Free(ctx); + return result; +} + +static const char TEST_MD4_DATA[] = "test"; +static const BYTE TEST_MD4_HASH[] = + "\xdb\x34\x6d\x69\x1d\x7a\xcc\x4d\xc2\x62\x5d\xb1\x9f\x9e\x3f\x52"; + +static BOOL test_crypto_hash_md4(void) +{ + BOOL result = FALSE; + BYTE hash[WINPR_MD4_DIGEST_LENGTH] = { 0 }; + WINPR_DIGEST_CTX* ctx = NULL; + + if (!(ctx = winpr_Digest_New())) + { + (void)fprintf(stderr, "%s: winpr_Digest_New failed\n", __func__); + return FALSE; + } + if (!winpr_Digest_Init(ctx, WINPR_MD_MD4)) + { + (void)fprintf(stderr, "%s: winpr_Digest_Init failed\n", __func__); + goto out; + } + if (!winpr_Digest_Update(ctx, (const BYTE*)TEST_MD4_DATA, + strnlen(TEST_MD4_DATA, sizeof(TEST_MD4_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Update failed\n", __func__); + goto out; + } + if (!winpr_Digest_Final(ctx, hash, sizeof(hash))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Final failed\n", __func__); + goto out; + } + if (memcmp(hash, TEST_MD4_HASH, WINPR_MD4_DIGEST_LENGTH) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(hash, WINPR_MD4_DIGEST_LENGTH, FALSE); + expected = winpr_BinToHexString(TEST_MD4_HASH, WINPR_MD4_DIGEST_LENGTH, FALSE); + + (void)fprintf(stderr, "unexpected MD4 hash: Actual: %s Expected: %s\n", actual, expected); + + free(actual); + free(expected); + + goto out; + } + + result = TRUE; +out: + winpr_Digest_Free(ctx); + return result; +} + +static const char TEST_SHA1_DATA[] = "test"; +static const BYTE TEST_SHA1_HASH[] = + "\xa9\x4a\x8f\xe5\xcc\xb1\x9b\xa6\x1c\x4c\x08\x73\xd3\x91\xe9\x87\x98\x2f\xbb\xd3"; + +static BOOL test_crypto_hash_sha1(void) +{ + BOOL result = FALSE; + BYTE hash[WINPR_SHA1_DIGEST_LENGTH] = { 0 }; + WINPR_DIGEST_CTX* ctx = NULL; + + if (!(ctx = winpr_Digest_New())) + { + (void)fprintf(stderr, "%s: winpr_Digest_New failed\n", __func__); + return FALSE; + } + if (!winpr_Digest_Init(ctx, WINPR_MD_SHA1)) + { + (void)fprintf(stderr, "%s: winpr_Digest_Init failed\n", __func__); + goto out; + } + if (!winpr_Digest_Update(ctx, (const BYTE*)TEST_SHA1_DATA, + strnlen(TEST_SHA1_DATA, sizeof(TEST_SHA1_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Update failed\n", __func__); + goto out; + } + if (!winpr_Digest_Final(ctx, hash, sizeof(hash))) + { + (void)fprintf(stderr, "%s: winpr_Digest_Final failed\n", __func__); + goto out; + } + + if (memcmp(hash, TEST_SHA1_HASH, WINPR_MD5_DIGEST_LENGTH) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(hash, WINPR_SHA1_DIGEST_LENGTH, FALSE); + expected = winpr_BinToHexString(TEST_SHA1_HASH, WINPR_SHA1_DIGEST_LENGTH, FALSE); + + (void)fprintf(stderr, "unexpected SHA1 hash: Actual: %s Expected: %s\n", actual, expected); + + free(actual); + free(expected); + + goto out; + } + + result = TRUE; +out: + winpr_Digest_Free(ctx); + return result; +} + +static const char TEST_HMAC_MD5_DATA[] = "Hi There"; +static const BYTE TEST_HMAC_MD5_KEY[] = + "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; +static const BYTE TEST_HMAC_MD5_HASH[] = + "\xb5\x79\x91\xa2\x20\x3d\x49\x2d\x73\xfb\x71\x43\xdf\xc5\x08\x28"; + +static BOOL test_crypto_hash_hmac_md5(void) +{ + BYTE hash[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + WINPR_HMAC_CTX* ctx = NULL; + BOOL result = FALSE; + + if (!(ctx = winpr_HMAC_New())) + { + (void)fprintf(stderr, "%s: winpr_HMAC_New failed\n", __func__); + return FALSE; + } + + if (!winpr_HMAC_Init(ctx, WINPR_MD_MD5, TEST_HMAC_MD5_KEY, WINPR_MD5_DIGEST_LENGTH)) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Init failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Update(ctx, (const BYTE*)TEST_HMAC_MD5_DATA, + strnlen(TEST_HMAC_MD5_DATA, sizeof(TEST_HMAC_MD5_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Update failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Update(ctx, (const BYTE*)TEST_HMAC_MD5_DATA, + strnlen(TEST_HMAC_MD5_DATA, sizeof(TEST_HMAC_MD5_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Update failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Final(ctx, hash, sizeof(hash))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Final failed\n", __func__); + goto out; + } + + if (memcmp(hash, TEST_HMAC_MD5_HASH, WINPR_MD5_DIGEST_LENGTH) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(hash, WINPR_MD5_DIGEST_LENGTH, FALSE); + expected = winpr_BinToHexString(TEST_HMAC_MD5_HASH, WINPR_MD5_DIGEST_LENGTH, FALSE); + + (void)fprintf(stderr, "unexpected HMAC-MD5 hash: Actual: %s Expected: %s\n", actual, + expected); + + free(actual); + free(expected); + + goto out; + } + + result = TRUE; +out: + winpr_HMAC_Free(ctx); + return result; +} + +static const char TEST_HMAC_SHA1_DATA[] = "Hi There"; +static const BYTE TEST_HMAC_SHA1_KEY[] = + "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; +static const BYTE TEST_HMAC_SHA1_HASH[] = + "\xab\x23\x08\x2d\xca\x0c\x75\xea\xca\x60\x09\xc0\xb8\x8c\x2d\xf4\xf4\xbf\x88\xee"; + +static BOOL test_crypto_hash_hmac_sha1(void) +{ + BYTE hash[WINPR_SHA1_DIGEST_LENGTH] = { 0 }; + WINPR_HMAC_CTX* ctx = NULL; + BOOL result = FALSE; + + if (!(ctx = winpr_HMAC_New())) + { + (void)fprintf(stderr, "%s: winpr_HMAC_New failed\n", __func__); + return FALSE; + } + + if (!winpr_HMAC_Init(ctx, WINPR_MD_SHA1, TEST_HMAC_SHA1_KEY, WINPR_SHA1_DIGEST_LENGTH)) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Init failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Update(ctx, (const BYTE*)TEST_HMAC_SHA1_DATA, + strnlen(TEST_HMAC_SHA1_DATA, sizeof(TEST_HMAC_SHA1_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Update failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Update(ctx, (const BYTE*)TEST_HMAC_SHA1_DATA, + strnlen(TEST_HMAC_SHA1_DATA, sizeof(TEST_HMAC_SHA1_DATA)))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Update failed\n", __func__); + goto out; + } + if (!winpr_HMAC_Final(ctx, hash, sizeof(hash))) + { + (void)fprintf(stderr, "%s: winpr_HMAC_Final failed\n", __func__); + goto out; + } + + if (memcmp(hash, TEST_HMAC_SHA1_HASH, WINPR_SHA1_DIGEST_LENGTH) != 0) + { + char* actual = NULL; + char* expected = NULL; + + actual = winpr_BinToHexString(hash, WINPR_SHA1_DIGEST_LENGTH, FALSE); + expected = winpr_BinToHexString(TEST_HMAC_SHA1_HASH, WINPR_SHA1_DIGEST_LENGTH, FALSE); + + (void)fprintf(stderr, "unexpected HMAC-SHA1 hash: Actual: %s Expected: %s\n", actual, + expected); + + free(actual); + free(expected); + + goto out; + } + + result = TRUE; +out: + winpr_HMAC_Free(ctx); + return result; +} + +int TestCryptoHash(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + if (!test_crypto_hash_md5()) + return -1; + + if (!test_crypto_hash_md4()) + return -1; + + if (!test_crypto_hash_sha1()) + return -1; + + if (!test_crypto_hash_hmac_md5()) + return -1; + + if (!test_crypto_hash_hmac_sha1()) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectData.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectData.c new file mode 100644 index 0000000000000000000000000000000000000000..45ef3e09dfdf0c72a32d564a0d981d195ebc0028 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectData.c @@ -0,0 +1,10 @@ + + +#include +#include +#include + +int TestCryptoProtectData(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectMemory.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectMemory.c new file mode 100644 index 0000000000000000000000000000000000000000..d904c7f7053a3e3d3cb3d4a5e1892bbce108f86d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoProtectMemory.c @@ -0,0 +1,55 @@ + +#include +#include +#include +#include +#include + +static const char* SECRET_PASSWORD_TEST = "MySecretPassword123!"; + +int TestCryptoProtectMemory(int argc, char* argv[]) +{ + UINT32 cbPlainText = 0; + UINT32 cbCipherText = 0; + const char* pPlainText = NULL; + BYTE* pCipherText = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + pPlainText = SECRET_PASSWORD_TEST; + cbPlainText = strlen(pPlainText) + 1; + cbCipherText = cbPlainText + + (CRYPTPROTECTMEMORY_BLOCK_SIZE - (cbPlainText % CRYPTPROTECTMEMORY_BLOCK_SIZE)); + printf("cbPlainText: %" PRIu32 " cbCipherText: %" PRIu32 "\n", cbPlainText, cbCipherText); + pCipherText = (BYTE*)malloc(cbCipherText); + if (!pCipherText) + { + printf("Unable to allocate memory\n"); + return -1; + } + CopyMemory(pCipherText, pPlainText, cbPlainText); + ZeroMemory(&pCipherText[cbPlainText], (cbCipherText - cbPlainText)); + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + if (!CryptProtectMemory(pCipherText, cbCipherText, CRYPTPROTECTMEMORY_SAME_PROCESS)) + { + printf("CryptProtectMemory failure\n"); + return -1; + } + + printf("PlainText: %s (cbPlainText = %" PRIu32 ", cbCipherText = %" PRIu32 ")\n", pPlainText, + cbPlainText, cbCipherText); + winpr_HexDump("crypto.test", WLOG_DEBUG, pCipherText, cbCipherText); + + if (!CryptUnprotectMemory(pCipherText, cbCipherText, CRYPTPROTECTMEMORY_SAME_PROCESS)) + { + printf("CryptUnprotectMemory failure\n"); + return -1; + } + + printf("Decrypted CipherText: %s\n", pCipherText); + SecureZeroMemory(pCipherText, cbCipherText); + free(pCipherText); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoRand.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoRand.c new file mode 100644 index 0000000000000000000000000000000000000000..3935d7e7fffafb3c30b24d20d9751d17e84c0b2f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/crypto/test/TestCryptoRand.c @@ -0,0 +1,26 @@ + +#include +#include +#include + +int TestCryptoRand(int argc, char* argv[]) +{ + char* str = NULL; + BYTE rnd[16] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + winpr_RAND(rnd, sizeof(rnd)); + + str = winpr_BinToHexString(rnd, sizeof(rnd), FALSE); + // (void)fprintf(stderr, "Rand: %s\n", str); + free(str); + + if (memcmp(rnd, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) == 0) + { + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b65e4a5414fa939548f579006829abf7b651bdcd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/CMakeLists.txt @@ -0,0 +1,26 @@ +# WinPR: Windows Portable Runtime +# libwinpr-dsparse cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(dsparse.c) + +if(WIN32) + winpr_library_add_public(ntdsapi) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d5e46e9ecb502d38e1567b47015a6d73c785d719 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/ModuleOptions.cmake @@ -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 "dsparse") +set(MINWIN_LONG_NAME "Domain Controller and Replication Management Functions") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/dsparse.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/dsparse.c new file mode 100644 index 0000000000000000000000000000000000000000..fd8bbfb225c2a49b27e58f65649c16b07bf2edcc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/dsparse.c @@ -0,0 +1,142 @@ +/** + * WinPR: Windows Portable Runtime + * Active Directory Domain Services Parsing Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +/** + * dsparse.dll: + * + * DsCrackSpnA + * DsCrackSpnW + * DsCrackUnquotedMangledRdnA + * DsCrackUnquotedMangledRdnW + * DsGetRdnW + * DsIsMangledDnA + * DsIsMangledDnW + * DsIsMangledRdnValueA + * DsIsMangledRdnValueW + * DsMakeSpnA + * DsMakeSpnW + * DsQuoteRdnValueA + * DsQuoteRdnValueW + * DsUnquoteRdnValueA + * DsUnquoteRdnValueW + */ + +#if !defined(_WIN32) || defined(_UWP) + +DWORD DsMakeSpnW(LPCWSTR ServiceClass, LPCWSTR ServiceName, LPCWSTR InstanceName, + USHORT InstancePort, LPCWSTR Referrer, DWORD* pcSpnLength, LPWSTR pszSpn) +{ + DWORD res = ERROR_OUTOFMEMORY; + char* ServiceClassA = NULL; + char* ServiceNameA = NULL; + char* InstanceNameA = NULL; + char* ReferrerA = NULL; + char* pszSpnA = NULL; + size_t length = 0; + + WINPR_ASSERT(ServiceClass); + WINPR_ASSERT(ServiceName); + WINPR_ASSERT(pcSpnLength); + + length = *pcSpnLength; + if ((length > 0) && pszSpn) + pszSpnA = calloc(length + 1, sizeof(char)); + + if (ServiceClass) + { + ServiceClassA = ConvertWCharToUtf8Alloc(ServiceClass, NULL); + if (!ServiceClassA) + goto fail; + } + if (ServiceName) + { + ServiceNameA = ConvertWCharToUtf8Alloc(ServiceName, NULL); + if (!ServiceNameA) + goto fail; + } + if (InstanceName) + { + InstanceNameA = ConvertWCharToUtf8Alloc(InstanceName, NULL); + if (!InstanceNameA) + goto fail; + } + if (Referrer) + { + ReferrerA = ConvertWCharToUtf8Alloc(Referrer, NULL); + if (!ReferrerA) + goto fail; + } + res = DsMakeSpnA(ServiceClassA, ServiceNameA, InstanceNameA, InstancePort, ReferrerA, + pcSpnLength, pszSpnA); + + if (res == ERROR_SUCCESS) + { + if (ConvertUtf8NToWChar(pszSpnA, *pcSpnLength, pszSpn, length) < 0) + res = ERROR_OUTOFMEMORY; + } + +fail: + free(ServiceClassA); + free(ServiceNameA); + free(InstanceNameA); + free(ReferrerA); + free(pszSpnA); + return res; +} + +DWORD DsMakeSpnA(LPCSTR ServiceClass, LPCSTR ServiceName, LPCSTR InstanceName, USHORT InstancePort, + LPCSTR Referrer, DWORD* pcSpnLength, LPSTR pszSpn) +{ + DWORD SpnLength = 0; + DWORD ServiceClassLength = 0; + DWORD ServiceNameLength = 0; + + WINPR_ASSERT(ServiceClass); + WINPR_ASSERT(ServiceName); + WINPR_ASSERT(pcSpnLength); + + WINPR_UNUSED(InstanceName); + WINPR_UNUSED(InstancePort); + WINPR_UNUSED(Referrer); + + if ((*pcSpnLength != 0) && (pszSpn == NULL)) + return ERROR_INVALID_PARAMETER; + + ServiceClassLength = (DWORD)strlen(ServiceClass); + ServiceNameLength = (DWORD)strlen(ServiceName); + + SpnLength = ServiceClassLength + 1 + ServiceNameLength + 1; + + if ((*pcSpnLength == 0) || (*pcSpnLength < SpnLength)) + { + *pcSpnLength = SpnLength; + return ERROR_BUFFER_OVERFLOW; + } + + (void)sprintf_s(pszSpn, *pcSpnLength, "%s/%s", ServiceClass, ServiceName); + + return ERROR_SUCCESS; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..05cb6b0c9d929b91ae4f108afaa710e683c9c369 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestDsParse") +set(MODULE_PREFIX "TEST_DSPARSE") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestDsMakeSpn.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/TestDsMakeSpn.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/TestDsMakeSpn.c new file mode 100644 index 0000000000000000000000000000000000000000..91aa87923776c4e0d4849d8b873f6fe45bf57a41 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dsparse/test/TestDsMakeSpn.c @@ -0,0 +1,151 @@ + +#include +#include +#include +#include +#include + +static BOOL test_DsMakeSpnA(void) +{ + LPCSTR testServiceClass = "HTTP"; + LPCSTR testServiceName = "LAB1-W2K8R2-GW.lab1.awake.local"; + LPCSTR testSpn = "HTTP/LAB1-W2K8R2-GW.lab1.awake.local"; + BOOL rc = FALSE; + CHAR Spn[100] = { 0 }; + DWORD status = 0; + DWORD SpnLength = -1; + + status = DsMakeSpnA(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, NULL); + + if (status != ERROR_INVALID_PARAMETER) + { + printf("DsMakeSpnA: expected ERROR_INVALID_PARAMETER\n"); + goto fail; + } + + SpnLength = 0; + status = DsMakeSpnA(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, NULL); + + if (status != ERROR_BUFFER_OVERFLOW) + { + printf("DsMakeSpnA: expected ERROR_BUFFER_OVERFLOW\n"); + goto fail; + } + + if (SpnLength != 37) + { + printf("DsMakeSpnA: SpnLength mismatch: Actual: %" PRIu32 ", Expected: 37\n", SpnLength); + goto fail; + } + + status = DsMakeSpnA(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, Spn); + + if (status != ERROR_SUCCESS) + { + printf("DsMakeSpnA: expected ERROR_SUCCESS\n"); + goto fail; + } + + if (strcmp(Spn, testSpn) != 0) + { + printf("DsMakeSpnA: SPN mismatch: Actual: %s, Expected: %s\n", Spn, testSpn); + goto fail; + } + + printf("DsMakeSpnA: %s\n", Spn); + rc = TRUE; +fail: + return rc; +} + +static BOOL test_DsMakeSpnW(void) +{ + const CHAR ctestServiceClass[] = { 'H', 'T', 'T', 'P', '\0' }; + const CHAR ctestServiceName[] = { 'L', 'A', 'B', '1', '-', 'W', '2', 'K', '8', 'R', '2', + '-', 'G', 'W', '.', 'l', 'a', 'b', '1', '.', 'a', 'w', + 'a', 'k', 'e', '.', 'l', 'o', 'c', 'a', 'l', '\0' }; + const CHAR ctestSpn[] = { 'H', 'T', 'T', 'P', '/', 'L', 'A', 'B', '1', '-', 'W', '2', 'K', + '8', 'R', '2', '-', 'G', 'W', '.', 'l', 'a', 'b', '1', '.', 'a', + 'w', 'a', 'k', 'e', '.', 'l', 'o', 'c', 'a', 'l', '\0' }; + WCHAR testServiceClass[ARRAYSIZE(ctestServiceClass)] = { 0 }; + WCHAR testServiceName[ARRAYSIZE(ctestServiceName)] = { 0 }; + WCHAR testSpn[ARRAYSIZE(ctestSpn)] = { 0 }; + + BOOL rc = FALSE; + WCHAR Spn[100] = { 0 }; + DWORD status = 0; + DWORD SpnLength = -1; + + (void)ConvertUtf8NToWChar(ctestServiceClass, ARRAYSIZE(ctestServiceClass), testServiceClass, + ARRAYSIZE(testServiceClass)); + (void)ConvertUtf8NToWChar(ctestServiceName, ARRAYSIZE(ctestServiceName), testServiceName, + ARRAYSIZE(testServiceName)); + (void)ConvertUtf8NToWChar(ctestSpn, ARRAYSIZE(ctestSpn), testSpn, ARRAYSIZE(testSpn)); + + status = DsMakeSpnW(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, NULL); + + if (status != ERROR_INVALID_PARAMETER) + { + printf("DsMakeSpnW: expected ERROR_INVALID_PARAMETER\n"); + goto fail; + } + + SpnLength = 0; + status = DsMakeSpnW(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, NULL); + + if (status != ERROR_BUFFER_OVERFLOW) + { + printf("DsMakeSpnW: expected ERROR_BUFFER_OVERFLOW\n"); + goto fail; + } + + if (SpnLength != 37) + { + printf("DsMakeSpnW: SpnLength mismatch: Actual: %" PRIu32 ", Expected: 37\n", SpnLength); + goto fail; + } + + status = DsMakeSpnW(testServiceClass, testServiceName, NULL, 0, NULL, &SpnLength, Spn); + + if (status != ERROR_SUCCESS) + { + printf("DsMakeSpnW: expected ERROR_SUCCESS\n"); + goto fail; + } + + if (_wcscmp(Spn, testSpn) != 0) + { + char buffer1[8192] = { 0 }; + char buffer2[8192] = { 0 }; + char* SpnA = buffer1; + char* testSpnA = buffer2; + + (void)ConvertWCharToUtf8(Spn, SpnA, ARRAYSIZE(buffer1)); + (void)ConvertWCharToUtf8(testSpn, testSpnA, ARRAYSIZE(buffer2)); + printf("DsMakeSpnW: SPN mismatch: Actual: %s, Expected: %s\n", SpnA, testSpnA); + goto fail; + } + + { + char buffer[8192] = { 0 }; + char* SpnA = buffer; + + (void)ConvertWCharToUtf8(Spn, SpnA, ARRAYSIZE(buffer)); + printf("DsMakeSpnW: %s\n", SpnA); + } + + rc = TRUE; +fail: + return rc; +} +int TestDsMakeSpn(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_DsMakeSpnA()) + return -1; + if (!test_DsMakeSpnW()) + return -2; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dummy.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dummy.c new file mode 100644 index 0000000000000000000000000000000000000000..bd2de45830b385ec06d75fbc4aad3c7ddefdc22e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/dummy.c @@ -0,0 +1,5 @@ + +int winpr_dummy() +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..91c8d726df980215d7eb3001d07054384e914276 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-environment cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(environment.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..76a4281ca61d2dcba1e0e1053896debbf33e8a2c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "processenvironment") +set(MINWIN_LONG_NAME "Process Environment Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/environment.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/environment.c new file mode 100644 index 0000000000000000000000000000000000000000..2aaa2959a09063a05faf5eb2cc68b3aacd8f2995 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/environment.c @@ -0,0 +1,731 @@ +/** + * WinPR: Windows Portable Runtime + * Process Environment Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Thincast Technologies GmbH + * Copyright 2013 DI (FH) Martin Haimberger + * + * 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 + +#include +#include +#include +#include +#include + +#include + +#ifndef _WIN32 + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#if defined(__IOS__) + +#elif defined(__MACOSX__) +#include +#define environ (*_NSGetEnviron()) +#endif + +DWORD GetCurrentDirectoryA(DWORD nBufferLength, LPSTR lpBuffer) +{ + size_t length = 0; + char* cwd = NULL; + char* ccwd = NULL; + + do + { + length += MAX_PATH; + char* tmp = realloc(cwd, length); + if (!tmp) + { + free(cwd); + return 0; + } + cwd = tmp; + + ccwd = getcwd(cwd, length); + } while (!ccwd && (errno == ERANGE)); + + if (!ccwd) + { + free(cwd); + return 0; + } + + length = strnlen(cwd, length); + + if ((nBufferLength == 0) && (lpBuffer == NULL)) + { + free(cwd); + return (DWORD)length; + } + else + { + if (lpBuffer == NULL) + { + free(cwd); + return 0; + } + + if ((length + 1) > nBufferLength) + { + free(cwd); + return (DWORD)(length + 1); + } + + memcpy(lpBuffer, cwd, length + 1); + free(cwd); + return (DWORD)length; + } +} + +DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer) +{ + return 0; +} + +BOOL SetCurrentDirectoryA(LPCSTR lpPathName) +{ + return TRUE; +} + +BOOL SetCurrentDirectoryW(LPCWSTR lpPathName) +{ + return TRUE; +} + +DWORD SearchPathA(LPCSTR lpPath, LPCSTR lpFileName, LPCSTR lpExtension, DWORD nBufferLength, + LPSTR lpBuffer, LPSTR* lpFilePart) +{ + return 0; +} + +DWORD SearchPathW(LPCWSTR lpPath, LPCWSTR lpFileName, LPCWSTR lpExtension, DWORD nBufferLength, + LPWSTR lpBuffer, LPWSTR* lpFilePart) +{ + return 0; +} + +LPSTR GetCommandLineA(VOID) +{ + return NULL; +} + +LPWSTR GetCommandLineW(VOID) +{ + return NULL; +} + +BOOL NeedCurrentDirectoryForExePathA(LPCSTR ExeName) +{ + return TRUE; +} + +BOOL NeedCurrentDirectoryForExePathW(LPCWSTR ExeName) +{ + return TRUE; +} + +#endif + +#if !defined(_WIN32) || defined(_UWP) + +DWORD GetEnvironmentVariableA(LPCSTR lpName, LPSTR lpBuffer, DWORD nSize) +{ +#if !defined(_UWP) + size_t length = 0; + + // NOLINTNEXTLINE(concurrency-mt-unsafe) + char* env = getenv(lpName); + + if (!env) + { + SetLastError(ERROR_ENVVAR_NOT_FOUND); + return 0; + } + + length = strlen(env); + + if ((length + 1 > nSize) || (!lpBuffer)) + return (DWORD)length + 1; + + CopyMemory(lpBuffer, env, length); + lpBuffer[length] = '\0'; + + return (DWORD)length; +#else + SetLastError(ERROR_ENVVAR_NOT_FOUND); + return 0; +#endif +} + +DWORD GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize) +{ + SetLastError(ERROR_ENVVAR_NOT_FOUND); + return 0; +} + +BOOL SetEnvironmentVariableA(LPCSTR lpName, LPCSTR lpValue) +{ +#if !defined(_UWP) + if (!lpName) + return FALSE; + + if (lpValue) + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (0 != setenv(lpName, lpValue, 1)) + return FALSE; + } + else + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + if (0 != unsetenv(lpName)) + return FALSE; + } + + return TRUE; +#else + return FALSE; +#endif +} + +BOOL SetEnvironmentVariableW(LPCWSTR lpName, LPCWSTR lpValue) +{ + return FALSE; +} + +/** + * GetEnvironmentStrings function: + * http://msdn.microsoft.com/en-us/library/windows/desktop/ms683187/ + * + * The GetEnvironmentStrings function returns a pointer to a block of memory + * that contains the environment variables of the calling process (both the + * system and the user environment variables). Each environment block contains + * the environment variables in the following format: + * + * Var1=Value1\0 + * Var2=Value2\0 + * Var3=Value3\0 + * ... + * VarN=ValueN\0\0 + */ + +extern char** environ; + +LPCH GetEnvironmentStringsA(VOID) +{ +#if !defined(_UWP) + char* p = NULL; + size_t offset = 0; + size_t length = 0; + char** envp = NULL; + DWORD cchEnvironmentBlock = 0; + LPCH lpszEnvironmentBlock = NULL; + + offset = 0; + envp = environ; + + cchEnvironmentBlock = 128; + lpszEnvironmentBlock = (LPCH)calloc(cchEnvironmentBlock, sizeof(CHAR)); + if (!lpszEnvironmentBlock) + return NULL; + + while (*envp) + { + length = strlen(*envp); + + while ((offset + length + 8) > cchEnvironmentBlock) + { + DWORD new_size = 0; + LPCH new_blk = NULL; + + new_size = cchEnvironmentBlock * 2; + new_blk = (LPCH)realloc(lpszEnvironmentBlock, new_size * sizeof(CHAR)); + if (!new_blk) + { + free(lpszEnvironmentBlock); + return NULL; + } + + lpszEnvironmentBlock = new_blk; + cchEnvironmentBlock = new_size; + } + + p = &(lpszEnvironmentBlock[offset]); + + CopyMemory(p, *envp, length * sizeof(CHAR)); + p[length] = '\0'; + + offset += (length + 1); + envp++; + } + + lpszEnvironmentBlock[offset] = '\0'; + + return lpszEnvironmentBlock; +#else + return NULL; +#endif +} + +LPWCH GetEnvironmentStringsW(VOID) +{ + return NULL; +} + +BOOL SetEnvironmentStringsA(LPCH NewEnvironment) +{ + return TRUE; +} + +BOOL SetEnvironmentStringsW(LPWCH NewEnvironment) +{ + return TRUE; +} + +DWORD ExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize) +{ + return 0; +} + +DWORD ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize) +{ + return 0; +} + +BOOL FreeEnvironmentStringsA(LPCH lpszEnvironmentBlock) +{ + free(lpszEnvironmentBlock); + + return TRUE; +} + +BOOL FreeEnvironmentStringsW(LPWCH lpszEnvironmentBlock) +{ + free(lpszEnvironmentBlock); + + return TRUE; +} + +#endif + +LPCH MergeEnvironmentStrings(PCSTR original, PCSTR merge) +{ + const char* cp = NULL; + char* p = NULL; + size_t offset = 0; + size_t length = 0; + const char* envp = NULL; + DWORD cchEnvironmentBlock = 0; + LPCH lpszEnvironmentBlock = NULL; + const char** mergeStrings = NULL; + size_t mergeStringLength = 0; + size_t mergeArraySize = 128; + size_t mergeLength = 0; + size_t foundMerge = 0; + char* foundEquals = NULL; + + mergeStrings = (LPCSTR*)calloc(mergeArraySize, sizeof(char*)); + + if (!mergeStrings) + return NULL; + + mergeStringLength = 0; + + cp = merge; + + while (*cp && *(cp + 1)) + { + length = strlen(cp); + + if (mergeStringLength == mergeArraySize) + { + const char** new_str = NULL; + + mergeArraySize += 128; + new_str = (const char**)realloc((void*)mergeStrings, mergeArraySize * sizeof(char*)); + + if (!new_str) + { + free((void*)mergeStrings); + return NULL; + } + mergeStrings = new_str; + } + + mergeStrings[mergeStringLength] = cp; + cp += length + 1; + mergeStringLength++; + } + + offset = 0; + + cchEnvironmentBlock = 128; + lpszEnvironmentBlock = (LPCH)calloc(cchEnvironmentBlock, sizeof(CHAR)); + + if (!lpszEnvironmentBlock) + { + free((void*)mergeStrings); + return NULL; + } + + envp = original; + + while ((original != NULL) && (*envp && *(envp + 1))) + { + size_t old_offset = offset; + length = strlen(envp); + + while ((offset + length + 8) > cchEnvironmentBlock) + { + cchEnvironmentBlock *= 2; + LPCH tmp = (LPCH)realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR)); + + if (!tmp) + { + free((void*)lpszEnvironmentBlock); + free((void*)mergeStrings); + return NULL; + } + lpszEnvironmentBlock = tmp; + } + + p = &(lpszEnvironmentBlock[offset]); + + // check if this value is in the mergeStrings + foundMerge = 0; + for (size_t run = 0; run < mergeStringLength; run++) + { + if (!mergeStrings[run]) + continue; + + mergeLength = strlen(mergeStrings[run]); + foundEquals = strstr(mergeStrings[run], "="); + + if (!foundEquals) + continue; + + const intptr_t len = foundEquals - mergeStrings[run] + 1; + if (strncmp(envp, mergeStrings[run], WINPR_ASSERTING_INT_CAST(size_t, len)) == 0) + { + // found variable in merge list ... use this .... + if (*(foundEquals + 1) == '\0') + { + // check if the argument is set ... if not remove variable ... + foundMerge = 1; + } + else + { + while ((offset + mergeLength + 8) > cchEnvironmentBlock) + { + cchEnvironmentBlock *= 2; + LPCH tmp = + (LPCH)realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR)); + + if (!tmp) + { + free((void*)lpszEnvironmentBlock); + free((void*)mergeStrings); + return NULL; + } + lpszEnvironmentBlock = tmp; + p = &(lpszEnvironmentBlock[old_offset]); + } + + foundMerge = 1; + CopyMemory(p, mergeStrings[run], mergeLength); + mergeStrings[run] = NULL; + p[mergeLength] = '\0'; + offset += (mergeLength + 1); + } + } + } + + if (foundMerge == 0) + { + CopyMemory(p, envp, length * sizeof(CHAR)); + p[length] = '\0'; + offset += (length + 1); + } + + envp += (length + 1); + } + + // now merge the not already merged env + for (size_t run = 0; run < mergeStringLength; run++) + { + if (!mergeStrings[run]) + continue; + + mergeLength = strlen(mergeStrings[run]); + + while ((offset + mergeLength + 8) > cchEnvironmentBlock) + { + cchEnvironmentBlock *= 2; + LPCH tmp = (LPCH)realloc(lpszEnvironmentBlock, cchEnvironmentBlock * sizeof(CHAR)); + + if (!tmp) + { + free((void*)lpszEnvironmentBlock); + free((void*)mergeStrings); + return NULL; + } + + lpszEnvironmentBlock = tmp; + } + + p = &(lpszEnvironmentBlock[offset]); + + CopyMemory(p, mergeStrings[run], mergeLength); + mergeStrings[run] = NULL; + p[mergeLength] = '\0'; + offset += (mergeLength + 1); + } + + lpszEnvironmentBlock[offset] = '\0'; + + free((void*)mergeStrings); + + return lpszEnvironmentBlock; +} + +DWORD GetEnvironmentVariableEBA(LPCSTR envBlock, LPCSTR lpName, LPSTR lpBuffer, DWORD nSize) +{ + size_t vLength = 0; + char* env = NULL; + char* foundEquals = NULL; + const char* penvb = envBlock; + size_t nLength = 0; + size_t fLength = 0; + size_t lpNameLength = 0; + + if (!lpName || NULL == envBlock) + return 0; + + lpNameLength = strlen(lpName); + + if (lpNameLength < 1) + return 0; + + while (*penvb && *(penvb + 1)) + { + fLength = strlen(penvb); + foundEquals = strstr(penvb, "="); + + if (!foundEquals) + { + /* if no = sign is found the envBlock is broken */ + return 0; + } + + nLength = WINPR_ASSERTING_INT_CAST(size_t, (foundEquals - penvb)); + + if (nLength != lpNameLength) + { + penvb += (fLength + 1); + continue; + } + + if (strncmp(penvb, lpName, nLength) == 0) + { + env = foundEquals + 1; + break; + } + + penvb += (fLength + 1); + } + + if (!env) + return 0; + + vLength = strlen(env); + if (vLength >= UINT32_MAX) + return 0; + + if ((vLength + 1 > nSize) || (!lpBuffer)) + return (DWORD)vLength + 1; + + CopyMemory(lpBuffer, env, vLength + 1); + + return (DWORD)vLength; +} + +BOOL SetEnvironmentVariableEBA(LPSTR* envBlock, LPCSTR lpName, LPCSTR lpValue) +{ + size_t length = 0; + char* envstr = NULL; + char* newEB = NULL; + + if (!lpName) + return FALSE; + + if (lpValue) + { + length = (strlen(lpName) + strlen(lpValue) + 2); /* +2 because of = and \0 */ + envstr = (char*)malloc(length + 1); /* +1 because of closing \0 */ + + if (!envstr) + return FALSE; + + (void)sprintf_s(envstr, length, "%s=%s", lpName, lpValue); + } + else + { + length = strlen(lpName) + 2; /* +2 because of = and \0 */ + envstr = (char*)malloc(length + 1); /* +1 because of closing \0 */ + + if (!envstr) + return FALSE; + + (void)sprintf_s(envstr, length, "%s=", lpName); + } + + envstr[length] = '\0'; + + newEB = MergeEnvironmentStrings((LPCSTR)*envBlock, envstr); + + free(envstr); + free(*envBlock); + + *envBlock = newEB; + + return TRUE; +} + +char** EnvironmentBlockToEnvpA(LPCH lpszEnvironmentBlock) +{ + char* p = NULL; + SSIZE_T index = 0; + size_t count = 0; + size_t length = 0; + char** envp = NULL; + + count = 0; + if (!lpszEnvironmentBlock) + return NULL; + + p = (char*)lpszEnvironmentBlock; + + while (p[0] && p[1]) + { + length = strlen(p); + p += (length + 1); + count++; + } + + index = 0; + p = (char*)lpszEnvironmentBlock; + + envp = (char**)calloc(count + 1, sizeof(char*)); + if (!envp) + return NULL; + envp[count] = NULL; + + while (p[0] && p[1]) + { + length = strlen(p); + envp[index] = _strdup(p); + if (!envp[index]) + { + for (index -= 1; index >= 0; --index) + { + free(envp[index]); + } + free((void*)envp); + return NULL; + } + p += (length + 1); + index++; + } + + return envp; +} + +#ifdef _WIN32 + +// https://devblogs.microsoft.com/oldnewthing/20100203-00/?p=15083 +#define WINPR_MAX_ENVIRONMENT_LENGTH 2048 + +DWORD GetEnvironmentVariableX(const char* lpName, char* lpBuffer, DWORD nSize) +{ + DWORD result = 0; + DWORD nSizeW = 0; + LPWSTR lpNameW = NULL; + LPWSTR lpBufferW = NULL; + LPSTR lpBufferA = lpBuffer; + + lpNameW = ConvertUtf8ToWCharAlloc(lpName, NULL); + if (!lpNameW) + goto cleanup; + + if (!lpBuffer) + { + char lpBufferMaxA[WINPR_MAX_ENVIRONMENT_LENGTH] = { 0 }; + WCHAR lpBufferMaxW[WINPR_MAX_ENVIRONMENT_LENGTH] = { 0 }; + LPSTR lpTmpBuffer = lpBufferMaxA; + + nSizeW = ARRAYSIZE(lpBufferMaxW); + + result = GetEnvironmentVariableW(lpNameW, lpBufferMaxW, nSizeW); + + SSIZE_T rc = + ConvertWCharNToUtf8(lpBufferMaxW, nSizeW, lpTmpBuffer, ARRAYSIZE(lpBufferMaxA)); + if ((rc < 0) || (rc >= UINT32_MAX)) + goto cleanup; + + result = (DWORD)rc + 1; + } + else + { + nSizeW = nSize; + lpBufferW = calloc(nSizeW + 1, sizeof(WCHAR)); + + if (!lpBufferW) + goto cleanup; + + result = GetEnvironmentVariableW(lpNameW, lpBufferW, nSizeW); + + if (result == 0) + goto cleanup; + + SSIZE_T rc = ConvertWCharNToUtf8(lpBufferW, nSizeW, lpBufferA, nSize); + if ((rc < 0) || (rc > UINT32_MAX)) + goto cleanup; + + result = (DWORD)rc; + } + +cleanup: + free(lpBufferW); + free(lpNameW); + + return result; +} + +#else + +DWORD GetEnvironmentVariableX(const char* lpName, char* lpBuffer, DWORD nSize) +{ + return GetEnvironmentVariableA(lpName, lpBuffer, nSize); +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b207e61ccc98ff9b01e1d4bf82a199d5ae2ce6a6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/CMakeLists.txt @@ -0,0 +1,25 @@ +set(MODULE_NAME "TestEnvironment") +set(MODULE_PREFIX "TEST_ENVIRONMENT") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestEnvironmentGetEnvironmentStrings.c TestEnvironmentSetEnvironmentVariable.c + TestEnvironmentMergeEnvironmentStrings.c TestEnvironmentGetSetEB.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetEnvironmentStrings.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetEnvironmentStrings.c new file mode 100644 index 0000000000000000000000000000000000000000..f7f2435a9fca22a240df19ba097a64312a551041 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetEnvironmentStrings.c @@ -0,0 +1,41 @@ + +#include +#include +#include +#include + +int TestEnvironmentGetEnvironmentStrings(int argc, char* argv[]) +{ + int r = -1; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + LPTCH lpszEnvironmentBlock = GetEnvironmentStrings(); + if (!lpszEnvironmentBlock) + goto fail; + + TCHAR* p = lpszEnvironmentBlock; + while (p[0] && p[1]) + { + const size_t max = _tcslen(p); + const int rc = _sntprintf(NULL, 0, _T("%s\n"), p); + if (rc < 1) + { + _tprintf(_T("test failed: return %d\n"), rc); + goto fail; + } + if (max != (size_t)(rc - 1)) + { + _tprintf(_T("test failed: length %") _T(PRIuz) _T(" != %d [%s]\n"), max, rc - 1, p); + goto fail; + } + p += (max + 1); + } + + r = 0; +fail: + FreeEnvironmentStrings(lpszEnvironmentBlock); + + return r; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetSetEB.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetSetEB.c new file mode 100644 index 0000000000000000000000000000000000000000..603b4c2f09dc7eee9037017ab26209556a04ebef --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentGetSetEB.c @@ -0,0 +1,138 @@ + +#include +#include +#include +#include + +int TestEnvironmentGetSetEB(int argc, char* argv[]) +{ + int rc = 0; +#ifndef _WIN32 + char test[1024]; + TCHAR* p = NULL; + DWORD length = 0; + LPTCH lpszEnvironmentBlock = "SHELL=123\0test=1\0test1=2\0DISPLAY=WINPR_TEST_VALUE\0\0"; + LPTCH lpszEnvironmentBlockNew = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + rc = -1; + /* Get length of an variable */ + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "DISPLAY", NULL, 0); + + if (0 == length) + return -1; + + /* Get the variable itself */ + p = (LPSTR)malloc(length); + + if (!p) + goto fail; + + if (GetEnvironmentVariableEBA(lpszEnvironmentBlock, "DISPLAY", p, length) != length - 1) + goto fail; + + printf("GetEnvironmentVariableA(WINPR_TEST_VARIABLE) = %s\n", p); + + if (strcmp(p, "WINPR_TEST_VALUE") != 0) + goto fail; + + /* Get length of an non-existing variable */ + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "BLA", NULL, 0); + + if (0 != length) + { + printf("Unset variable returned\n"); + goto fail; + } + + /* Get length of an similar called variables */ + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "XDISPLAY", NULL, 0); + + if (0 != length) + { + printf("Similar named variable returned (XDISPLAY, length %d)\n", length); + goto fail; + } + + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "DISPLAYX", NULL, 0); + + if (0 != length) + { + printf("Similar named variable returned (DISPLAYX, length %d)\n", length); + goto fail; + } + + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "DISPLA", NULL, 0); + + if (0 != length) + { + printf("Similar named variable returned (DISPLA, length %d)\n", length); + goto fail; + } + + length = GetEnvironmentVariableEBA(lpszEnvironmentBlock, "ISPLAY", NULL, 0); + + if (0 != length) + { + printf("Similar named variable returned (ISPLAY, length %d)\n", length); + goto fail; + } + + /* Set variable in empty environment block */ + if (SetEnvironmentVariableEBA(&lpszEnvironmentBlockNew, "test", "5")) + { + if (GetEnvironmentVariableEBA(lpszEnvironmentBlockNew, "test", test, 1023)) + { + if (strcmp(test, "5") != 0) + goto fail; + } + else + goto fail; + } + + /* Clear variable */ + if (SetEnvironmentVariableEBA(&lpszEnvironmentBlockNew, "test", NULL)) + { + if (GetEnvironmentVariableEBA(lpszEnvironmentBlockNew, "test", test, 1023)) + goto fail; + else + { + // not found .. this is expected + } + } + + free(lpszEnvironmentBlockNew); + lpszEnvironmentBlockNew = (LPTCH)calloc(1024, sizeof(TCHAR)); + + if (!lpszEnvironmentBlockNew) + goto fail; + + memcpy(lpszEnvironmentBlockNew, lpszEnvironmentBlock, length); + + /* Set variable in empty environment block */ + if (SetEnvironmentVariableEBA(&lpszEnvironmentBlockNew, "test", "5")) + { + if (0 != GetEnvironmentVariableEBA(lpszEnvironmentBlockNew, "testr", test, 1023)) + { + printf("GetEnvironmentVariableEBA returned unset variable\n"); + goto fail; + } + + if (GetEnvironmentVariableEBA(lpszEnvironmentBlockNew, "test", test, 1023)) + { + if (strcmp(test, "5") != 0) + goto fail; + } + else + goto fail; + } + + rc = 0; +fail: + free(p); + free(lpszEnvironmentBlockNew); +#endif + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentMergeEnvironmentStrings.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentMergeEnvironmentStrings.c new file mode 100644 index 0000000000000000000000000000000000000000..428418d2b2234b27da807242a8c0ba2339dc0fa8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentMergeEnvironmentStrings.c @@ -0,0 +1,34 @@ + +#include +#include +#include +#include + +int TestEnvironmentMergeEnvironmentStrings(int argc, char* argv[]) +{ +#ifndef _WIN32 + TCHAR* p = NULL; + size_t length = 0; + LPTCH lpszEnvironmentBlock = NULL; + LPTCH lpsz2Merge = "SHELL=123\0test=1\0test1=2\0DISPLAY=:77\0\0"; + LPTCH lpszMergedEnvironmentBlock = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + lpszEnvironmentBlock = GetEnvironmentStrings(); + lpszMergedEnvironmentBlock = MergeEnvironmentStrings(lpszEnvironmentBlock, lpsz2Merge); + p = (TCHAR*)lpszMergedEnvironmentBlock; + + while (p[0] && p[1]) + { + printf("%s\n", p); + length = strlen(p); + p += (length + 1); + } + + FreeEnvironmentStrings(lpszMergedEnvironmentBlock); + FreeEnvironmentStrings(lpszEnvironmentBlock); +#endif + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentSetEnvironmentVariable.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentSetEnvironmentVariable.c new file mode 100644 index 0000000000000000000000000000000000000000..04b706411a0fbd8437ca18cd86d5ef26d2b578f3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/environment/test/TestEnvironmentSetEnvironmentVariable.c @@ -0,0 +1,72 @@ + +#include +#include +#include +#include +#include + +#define TEST_NAME "WINPR_TEST_VARIABLE" +#define TEST_VALUE "WINPR_TEST_VALUE" +int TestEnvironmentSetEnvironmentVariable(int argc, char* argv[]) +{ + int rc = -1; + DWORD nSize = 0; + LPSTR lpBuffer = NULL; + DWORD error = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + SetEnvironmentVariableA(TEST_NAME, TEST_VALUE); + nSize = GetEnvironmentVariableA(TEST_NAME, NULL, 0); + + /* check if value returned is len + 1 ) */ + if (nSize != strnlen(TEST_VALUE, sizeof(TEST_VALUE)) + 1) + { + printf("GetEnvironmentVariableA not found error\n"); + return -1; + } + + lpBuffer = (LPSTR)malloc(nSize); + + if (!lpBuffer) + return -1; + + nSize = GetEnvironmentVariableA(TEST_NAME, lpBuffer, nSize); + + if (nSize != strnlen(TEST_VALUE, sizeof(TEST_VALUE))) + { + printf("GetEnvironmentVariableA wrong size returned\n"); + goto fail; + } + + if (strcmp(lpBuffer, TEST_VALUE) != 0) + { + printf("GetEnvironmentVariableA returned value doesn't match\n"); + goto fail; + } + + nSize = GetEnvironmentVariableA("__xx__notset_", lpBuffer, nSize); + error = GetLastError(); + + if (0 != nSize || ERROR_ENVVAR_NOT_FOUND != error) + { + printf("GetEnvironmentVariableA not found error\n"); + goto fail; + } + + /* clear variable */ + SetEnvironmentVariableA(TEST_NAME, NULL); + nSize = GetEnvironmentVariableA(TEST_VALUE, NULL, 0); + + if (0 != nSize) + { + printf("SetEnvironmentVariableA failed to clear variable\n"); + goto fail; + } + + rc = 0; +fail: + free(lpBuffer); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9d9bffcbd23ab9128f923666824e9edad114062 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-error cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(error.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ff50ca63afadf0cfd40a591a7a560d0aa9fd1b94 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "1") +set(MINWIN_SHORT_NAME "errorhandling") +set(MINWIN_LONG_NAME "Error Handling Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/error.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/error.c new file mode 100644 index 0000000000000000000000000000000000000000..7746d02395f9f9c977c9a1676daf51ae5b8827ea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/error.c @@ -0,0 +1,99 @@ +/** + * WinPR: Windows Portable Runtime + * Error Handling Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#ifndef _WIN32 + +#include + +#include + +UINT GetErrorMode(void) +{ + return 0; +} + +UINT SetErrorMode(UINT uMode) +{ + return 0; +} + +DWORD GetLastError(VOID) +{ + PTEB pt = NtCurrentTeb(); + if (pt) + { + return pt->LastErrorValue; + } + return ERROR_OUTOFMEMORY; +} + +VOID SetLastError(DWORD dwErrCode) +{ + PTEB pt = NtCurrentTeb(); + if (pt) + { + pt->LastErrorValue = dwErrCode; + } +} + +VOID RestoreLastError(DWORD dwErrCode) +{ +} + +VOID RaiseException(DWORD dwExceptionCode, DWORD dwExceptionFlags, DWORD nNumberOfArguments, + CONST ULONG_PTR* lpArguments) +{ +} + +LONG UnhandledExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) +{ + return 0; +} + +LPTOP_LEVEL_EXCEPTION_FILTER +SetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) +{ + return NULL; +} + +PVOID AddVectoredExceptionHandler(ULONG First, PVECTORED_EXCEPTION_HANDLER Handler) +{ + return NULL; +} + +ULONG RemoveVectoredExceptionHandler(PVOID Handle) +{ + return 0; +} + +PVOID AddVectoredContinueHandler(ULONG First, PVECTORED_EXCEPTION_HANDLER Handler) +{ + return NULL; +} + +ULONG RemoveVectoredContinueHandler(PVOID Handle) +{ + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..578d06e1f530a0ded793f1fa339c264ead320542 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestError") +set(MODULE_PREFIX "TEST_ERROR") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestErrorSetLastError.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/TestErrorSetLastError.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/TestErrorSetLastError.c new file mode 100644 index 0000000000000000000000000000000000000000..b274addc6d225824c34e77277d0c057ca846caad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/error/test/TestErrorSetLastError.c @@ -0,0 +1,145 @@ +/** + * CTest for winpr's SetLastError/GetLastError + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2013 Thincast Technologies GmbH + * Copyright 2013 Norbert Federa + * + * 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 +#include +#include +#include +#include +#include + +#include + +static int status = 0; + +static LONG* pLoopCount = NULL; +static BOOL bStopTest = FALSE; + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +static DWORD WINAPI test_error_thread(LPVOID arg) +{ + int id = 0; + DWORD dwErrorSet = 0; + DWORD dwErrorGet = 0; + + id = (int)(size_t)arg; + + do + { + dwErrorSet = prand(UINT32_MAX - 1) + 1; + SetLastError(dwErrorSet); + if ((dwErrorGet = GetLastError()) != dwErrorSet) + { + printf("GetLastError() failure (thread %d): Expected: 0x%08" PRIX32 + ", Actual: 0x%08" PRIX32 "\n", + id, dwErrorSet, dwErrorGet); + if (!status) + status = -1; + break; + } + InterlockedIncrement(pLoopCount); + } while (!status && !bStopTest); + + return 0; +} + +int TestErrorSetLastError(int argc, char* argv[]) +{ + DWORD error = 0; + HANDLE threads[4]; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* We must initialize WLog here. It will check for settings + * in the environment and if the variables are not set, the last + * error state is changed... */ + WLog_GetRoot(); + + SetLastError(ERROR_ACCESS_DENIED); + + error = GetLastError(); + + if (error != ERROR_ACCESS_DENIED) + { + printf("GetLastError() failure: Expected: 0x%08X, Actual: 0x%08" PRIX32 "\n", + ERROR_ACCESS_DENIED, error); + return -1; + } + + pLoopCount = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + if (!pLoopCount) + { + printf("Unable to allocate memory\n"); + return -1; + } + *pLoopCount = 0; + + for (int i = 0; i < 4; i++) + { + if (!(threads[i] = CreateThread(NULL, 0, test_error_thread, (void*)(size_t)0, 0, NULL))) + { + printf("Failed to create thread #%d\n", i); + return -1; + } + } + + // let the threads run for at least 0.2 seconds + Sleep(200); + bStopTest = TRUE; + + (void)WaitForSingleObject(threads[0], INFINITE); + (void)WaitForSingleObject(threads[1], INFINITE); + (void)WaitForSingleObject(threads[2], INFINITE); + (void)WaitForSingleObject(threads[3], INFINITE); + + (void)CloseHandle(threads[0]); + (void)CloseHandle(threads[1]); + (void)CloseHandle(threads[2]); + (void)CloseHandle(threads[3]); + + error = GetLastError(); + + if (error != ERROR_ACCESS_DENIED) + { + printf("GetLastError() failure: Expected: 0x%08X, Actual: 0x%08" PRIX32 "\n", + ERROR_ACCESS_DENIED, error); + return -1; + } + + if (*pLoopCount < 4) + { + printf("Error: unexpected loop count\n"); + return -1; + } + + printf("Completed %" PRId32 " iterations.\n", *pLoopCount); + winpr_aligned_free(pLoopCount); + + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c3f8606e16dd31c77e0baef614bcd83e6cc2b946 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-file cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(generic.c namedPipeClient.c namedPipeClient.h pattern.c file.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..1830cd7cc3742f853d454ab0d8505b14f732d41b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "file") +set(MINWIN_LONG_NAME "File Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.c new file mode 100644 index 0000000000000000000000000000000000000000..657d1f37cebe7b608cc40ab6a9c1818c2bc5d159 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.c @@ -0,0 +1,1496 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 Bernhard Miklautz + * Copyright 2016 David PHAM-VAN + * + * 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 +#include +#include + +#include +#include +#include + +#ifdef _WIN32 + +#include + +#else /* _WIN32 */ + +#include "../log.h" +#define TAG WINPR_TAG("file") + +#include +#include + +#include "file.h" +#include +#include +#include +#include +#include + +#ifdef ANDROID +#include +#else +#include +#endif + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +static BOOL FileIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_FILE, FALSE); +} + +static int FileGetFd(HANDLE handle) +{ + WINPR_FILE* file = (WINPR_FILE*)handle; + + if (!FileIsHandled(handle)) + return -1; + + return fileno(file->fp); +} + +static BOOL FileCloseHandle(HANDLE handle) +{ + WINPR_FILE* file = (WINPR_FILE*)handle; + + if (!FileIsHandled(handle)) + return FALSE; + + if (file->fp) + { + /* Don't close stdin/stdout/stderr */ + if (fileno(file->fp) > 2) + { + (void)fclose(file->fp); + file->fp = NULL; + } + } + + free(file->lpFileName); + free(file); + return TRUE; +} + +static BOOL FileSetEndOfFile(HANDLE hFile) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + + if (!hFile) + return FALSE; + + const INT64 size = _ftelli64(pFile->fp); + if (size < 0) + return FALSE; + + if (ftruncate(fileno(pFile->fp), (off_t)size) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "ftruncate %s failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + SetLastError(map_posix_err(errno)); + return FALSE; + } + + return TRUE; +} + +// NOLINTBEGIN(readability-non-const-parameter) +static DWORD FileSetFilePointer(HANDLE hFile, LONG lDistanceToMove, + const PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod) +// NOLINTEND(readability-non-const-parameter) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + INT64 offset = 0; + int whence = 0; + + if (!hFile) + return INVALID_SET_FILE_POINTER; + + /* If there is a high part, the sign is contained in that + * and the low integer must be interpreted as unsigned. */ + if (lpDistanceToMoveHigh) + { + offset = (INT64)(((UINT64)*lpDistanceToMoveHigh << 32U) | (UINT64)lDistanceToMove); + } + else + offset = lDistanceToMove; + + switch (dwMoveMethod) + { + case FILE_BEGIN: + whence = SEEK_SET; + break; + case FILE_END: + whence = SEEK_END; + break; + case FILE_CURRENT: + whence = SEEK_CUR; + break; + default: + return INVALID_SET_FILE_POINTER; + } + + if (_fseeki64(pFile->fp, offset, whence)) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return INVALID_SET_FILE_POINTER; + } + + return (DWORD)_ftelli64(pFile->fp); +} + +static BOOL FileSetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove, + PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + int whence = 0; + + if (!hFile) + return FALSE; + + switch (dwMoveMethod) + { + case FILE_BEGIN: + whence = SEEK_SET; + break; + case FILE_END: + whence = SEEK_END; + break; + case FILE_CURRENT: + whence = SEEK_CUR; + break; + default: + return FALSE; + } + + if (_fseeki64(pFile->fp, liDistanceToMove.QuadPart, whence)) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } + + if (lpNewFilePointer) + lpNewFilePointer->QuadPart = _ftelli64(pFile->fp); + + return TRUE; +} + +static BOOL FileRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) +{ + size_t io_status = 0; + WINPR_FILE* file = NULL; + BOOL status = TRUE; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (!Object) + return FALSE; + + file = (WINPR_FILE*)Object; + clearerr(file->fp); + io_status = fread(lpBuffer, 1, nNumberOfBytesToRead, file->fp); + + if (io_status == 0 && ferror(file->fp)) + { + status = FALSE; + + switch (errno) + { + case EWOULDBLOCK: + SetLastError(ERROR_NO_DATA); + break; + default: + SetLastError(map_posix_err(errno)); + } + } + + if (lpNumberOfBytesRead) + *lpNumberOfBytesRead = (DWORD)io_status; + + return status; +} + +static BOOL FileWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) +{ + size_t io_status = 0; + WINPR_FILE* file = NULL; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (!Object) + return FALSE; + + file = (WINPR_FILE*)Object; + + clearerr(file->fp); + io_status = fwrite(lpBuffer, 1, nNumberOfBytesToWrite, file->fp); + if (io_status == 0 && ferror(file->fp)) + { + SetLastError(map_posix_err(errno)); + return FALSE; + } + + *lpNumberOfBytesWritten = (DWORD)io_status; + return TRUE; +} + +static DWORD FileGetFileSize(HANDLE Object, LPDWORD lpFileSizeHigh) +{ + WINPR_FILE* file = NULL; + INT64 cur = 0; + INT64 size = 0; + + if (!Object) + return 0; + + file = (WINPR_FILE*)Object; + + cur = _ftelli64(file->fp); + + if (cur < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return INVALID_FILE_SIZE; + } + + if (_fseeki64(file->fp, 0, SEEK_END) != 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", file->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return INVALID_FILE_SIZE; + } + + size = _ftelli64(file->fp); + + if (size < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return INVALID_FILE_SIZE; + } + + if (_fseeki64(file->fp, cur, SEEK_SET) != 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return INVALID_FILE_SIZE; + } + + if (lpFileSizeHigh) + *lpFileSizeHigh = (UINT32)(size >> 32); + + return (UINT32)(size & 0xFFFFFFFF); +} + +static BOOL FileGetFileInformationByHandle(HANDLE hFile, + LPBY_HANDLE_FILE_INFORMATION lpFileInformation) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + struct stat st; + UINT64 ft = 0; + const char* lastSep = NULL; + + if (!pFile) + return FALSE; + if (!lpFileInformation) + return FALSE; + + if (fstat(fileno(pFile->fp), &st) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "fstat failed with %s [%#08X]", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return FALSE; + } + + lpFileInformation->dwFileAttributes = 0; + + if (S_ISDIR(st.st_mode)) + lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; + + if (lpFileInformation->dwFileAttributes == 0) + lpFileInformation->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE; + + lastSep = strrchr(pFile->lpFileName, '/'); + + if (lastSep) + { + const char* name = lastSep + 1; + const size_t namelen = strlen(name); + + if ((namelen > 1) && (name[0] == '.') && (name[1] != '.')) + lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; + } + + if (!(st.st_mode & S_IWUSR)) + lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; + +#ifdef _DARWIN_FEATURE_64_BIT_INODE + ft = STAT_TIME_TO_FILETIME(st.st_birthtime); +#else + ft = STAT_TIME_TO_FILETIME(st.st_ctime); +#endif + lpFileInformation->ftCreationTime.dwHighDateTime = (ft) >> 32ULL; + lpFileInformation->ftCreationTime.dwLowDateTime = ft & 0xFFFFFFFF; + ft = STAT_TIME_TO_FILETIME(st.st_mtime); + lpFileInformation->ftLastWriteTime.dwHighDateTime = (ft) >> 32ULL; + lpFileInformation->ftLastWriteTime.dwLowDateTime = ft & 0xFFFFFFFF; + ft = STAT_TIME_TO_FILETIME(st.st_atime); + lpFileInformation->ftLastAccessTime.dwHighDateTime = (ft) >> 32ULL; + lpFileInformation->ftLastAccessTime.dwLowDateTime = ft & 0xFFFFFFFF; + lpFileInformation->nFileSizeHigh = ((UINT64)st.st_size) >> 32ULL; + lpFileInformation->nFileSizeLow = st.st_size & 0xFFFFFFFF; + lpFileInformation->dwVolumeSerialNumber = (UINT32)st.st_dev; + lpFileInformation->nNumberOfLinks = (UINT32)st.st_nlink; + lpFileInformation->nFileIndexHigh = (st.st_ino >> 4) & 0xFFFFFFFF; + lpFileInformation->nFileIndexLow = st.st_ino & 0xFFFFFFFF; + return TRUE; +} + +static BOOL FileLockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, + DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh, + LPOVERLAPPED lpOverlapped) +{ +#ifdef __sun + struct flock lock; + int lckcmd; +#else + int lock = 0; +#endif + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (!hFile) + return FALSE; + + if (pFile->bLocked) + { + WLog_ERR(TAG, "File %s already locked!", pFile->lpFileName); + return FALSE; + } + +#ifdef __sun + lock.l_start = 0; + lock.l_len = 0; + lock.l_whence = SEEK_SET; + + if (dwFlags & LOCKFILE_EXCLUSIVE_LOCK) + lock.l_type = F_WRLCK; + else + lock.l_type = F_WRLCK; + + if (dwFlags & LOCKFILE_FAIL_IMMEDIATELY) + lckcmd = F_SETLK; + else + lckcmd = F_SETLKW; + + if (fcntl(fileno(pFile->fp), lckcmd, &lock) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "F_SETLK failed with %s [0x%08X]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } +#else + if (dwFlags & LOCKFILE_EXCLUSIVE_LOCK) + lock = LOCK_EX; + else + lock = LOCK_SH; + + if (dwFlags & LOCKFILE_FAIL_IMMEDIATELY) + lock |= LOCK_NB; + + if (flock(fileno(pFile->fp), lock) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "flock failed with %s [0x%08X]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } +#endif + + pFile->bLocked = TRUE; + + return TRUE; +} + +static BOOL FileUnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; +#ifdef __sun + struct flock lock; +#endif + + if (!hFile) + return FALSE; + + if (!pFile->bLocked) + { + WLog_ERR(TAG, "File %s is not locked!", pFile->lpFileName); + return FALSE; + } + +#ifdef __sun + lock.l_start = 0; + lock.l_len = 0; + lock.l_whence = SEEK_SET; + lock.l_type = F_UNLCK; + if (fcntl(fileno(pFile->fp), F_GETLK, &lock) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "F_UNLCK on %s failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } + +#else + if (flock(fileno(pFile->fp), LOCK_UN) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "flock(LOCK_UN) %s failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } +#endif + + return TRUE; +} + +static BOOL FileUnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow, + DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; +#ifdef __sun + struct flock lock; +#endif + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (!hFile) + return FALSE; + + if (!pFile->bLocked) + { + WLog_ERR(TAG, "File %s is not locked!", pFile->lpFileName); + return FALSE; + } + +#ifdef __sun + lock.l_start = 0; + lock.l_len = 0; + lock.l_whence = SEEK_SET; + lock.l_type = F_UNLCK; + if (fcntl(fileno(pFile->fp), F_GETLK, &lock) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "F_UNLCK on %s failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } +#else + if (flock(fileno(pFile->fp), LOCK_UN) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "flock(LOCK_UN) %s failed with %s [0x%08X]", pFile->lpFileName, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } +#endif + + return TRUE; +} + +static INT64 FileTimeToUS(const FILETIME* ft) +{ + const INT64 EPOCH_DIFF_US = EPOCH_DIFF * 1000000LL; + INT64 tmp = ((INT64)ft->dwHighDateTime) << 32 | ft->dwLowDateTime; + tmp /= 10; /* 100ns steps to 1us step */ + tmp -= EPOCH_DIFF_US; + return tmp; +} + +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) +static struct timespec filetimeToTimespec(const FILETIME* ftime) +{ + WINPR_ASSERT(ftime); + INT64 tmp = FileTimeToUS(ftime); + struct timespec ts = { 0 }; + ts.tv_sec = tmp / 1000000LL; + ts.tv_nsec = (tmp % 1000000LL) * 1000LL; + return ts; +} + +static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime, + const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime) +{ + struct timespec times[2] = { { UTIME_OMIT, UTIME_OMIT }, + { UTIME_OMIT, UTIME_OMIT } }; /* last access, last modification */ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + + if (!hFile) + return FALSE; + + if (lpLastAccessTime) + times[0] = filetimeToTimespec(lpLastAccessTime); + + if (lpLastWriteTime) + times[1] = filetimeToTimespec(lpLastWriteTime); + + // TODO: Creation time can not be handled! + const int rc = futimens(fileno(pFile->fp), times); + if (rc != 0) + return FALSE; + + return TRUE; +} +#elif defined(__APPLE__) || defined(ANDROID) || defined(__FreeBSD__) || defined(KFREEBSD) +static struct timeval filetimeToTimeval(const FILETIME* ftime) +{ + WINPR_ASSERT(ftime); + UINT64 tmp = FileTimeToUS(ftime); + struct timeval tv = { 0 }; + tv.tv_sec = tmp / 1000000ULL; + tv.tv_usec = tmp % 1000000ULL; + return tv; +} + +static struct timeval statToTimeval(const struct stat* sval) +{ + WINPR_ASSERT(sval); + struct timeval tv = { 0 }; +#if defined(__FreeBSD__) || defined(__APPLE__) || defined(KFREEBSD) + tv.tv_sec = sval->st_atime; +#ifdef _POSIX_SOURCE + TIMESPEC_TO_TIMEVAL(&tv, &sval->st_atim); +#else + TIMESPEC_TO_TIMEVAL(&tv, &sval->st_atimespec); +#endif +#elif defined(ANDROID) + tv.tv_sec = sval->st_atime; + tv.tv_usec = sval->st_atimensec / 1000UL; +#endif + return tv; +} + +static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime, + const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime) +{ + struct stat buf = { 0 }; + /* OpenBSD, NetBSD and DragonflyBSD support POSIX futimens */ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + + if (!hFile) + return FALSE; + + const int rc = fstat(fileno(pFile->fp), &buf); + if (rc < 0) + return FALSE; + + struct timeval timevals[2] = { statToTimeval(&buf), statToTimeval(&buf) }; + if (lpLastAccessTime) + timevals[0] = filetimeToTimeval(lpLastAccessTime); + + if (lpLastWriteTime) + timevals[1] = filetimeToTimeval(lpLastWriteTime); + + // TODO: Creation time can not be handled! + { + const int res = utimes(pFile->lpFileName, timevals); + if (res != 0) + return FALSE; + } + + return TRUE; +} +#else +static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime, + const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime) +{ + WINPR_FILE* pFile = (WINPR_FILE*)hFile; + + if (!hFile) + return FALSE; + + WLog_WARN(TAG, "TODO: Creation, Access and Write time can not be handled!"); + WLog_WARN(TAG, + "TODO: Define _POSIX_C_SOURCE >= 200809L or implement a platform specific handler!"); + return TRUE; +} +#endif + +static HANDLE_OPS fileOps = { + FileIsHandled, + FileCloseHandle, + FileGetFd, + NULL, /* CleanupHandle */ + FileRead, + NULL, /* FileReadEx */ + NULL, /* FileReadScatter */ + FileWrite, + NULL, /* FileWriteEx */ + NULL, /* FileWriteGather */ + FileGetFileSize, + NULL, /* FlushFileBuffers */ + FileSetEndOfFile, + FileSetFilePointer, + FileSetFilePointerEx, + NULL, /* FileLockFile */ + FileLockFileEx, + FileUnlockFile, + FileUnlockFileEx, + FileSetFileTime, + FileGetFileInformationByHandle, +}; + +static HANDLE_OPS shmOps = { + FileIsHandled, + FileCloseHandle, + FileGetFd, + NULL, /* CleanupHandle */ + FileRead, + NULL, /* FileReadEx */ + NULL, /* FileReadScatter */ + FileWrite, + NULL, /* FileWriteEx */ + NULL, /* FileWriteGather */ + NULL, /* FileGetFileSize */ + NULL, /* FlushFileBuffers */ + NULL, /* FileSetEndOfFile */ + NULL, /* FileSetFilePointer */ + NULL, /* SetFilePointerEx */ + NULL, /* FileLockFile */ + NULL, /* FileLockFileEx */ + NULL, /* FileUnlockFile */ + NULL, /* FileUnlockFileEx */ + NULL, /* FileSetFileTime */ + FileGetFileInformationByHandle, +}; + +static const char* FileGetMode(DWORD dwDesiredAccess, DWORD dwCreationDisposition, BOOL* create) +{ + BOOL writeable = (dwDesiredAccess & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0; + + switch (dwCreationDisposition) + { + case CREATE_ALWAYS: + *create = TRUE; + return (writeable) ? "wb+" : "rwb"; + case CREATE_NEW: + *create = TRUE; + return "wb+"; + case OPEN_ALWAYS: + *create = TRUE; + return "rb+"; + case OPEN_EXISTING: + *create = FALSE; + return (writeable) ? "rb+" : "rb"; + case TRUNCATE_EXISTING: + *create = FALSE; + return "wb+"; + default: + *create = FALSE; + return ""; + } +} + +UINT32 map_posix_err(int fs_errno) +{ + NTSTATUS rc = 0; + + /* try to return NTSTATUS version of error code */ + + switch (fs_errno) + { + case 0: + rc = STATUS_SUCCESS; + break; + + case ENOTCONN: + case ENODEV: + case ENOTDIR: + case ENXIO: + rc = ERROR_FILE_NOT_FOUND; + break; + + case EROFS: + case EPERM: + case EACCES: + rc = ERROR_ACCESS_DENIED; + break; + + case ENOENT: + rc = ERROR_FILE_NOT_FOUND; + break; + + case EBUSY: + rc = ERROR_BUSY_DRIVE; + break; + + case EEXIST: + rc = ERROR_FILE_EXISTS; + break; + + case EISDIR: + rc = STATUS_FILE_IS_A_DIRECTORY; + break; + + case ENOTEMPTY: + rc = STATUS_DIRECTORY_NOT_EMPTY; + break; + + case EMFILE: + rc = STATUS_TOO_MANY_OPENED_FILES; + break; + + default: + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "Missing ERRNO mapping %s [%d]", + winpr_strerror(fs_errno, ebuffer, sizeof(ebuffer)), fs_errno); + rc = STATUS_UNSUCCESSFUL; + } + break; + } + + return (UINT32)rc; +} + +static HANDLE FileCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) +{ + WINPR_FILE* pFile = NULL; + BOOL create = 0; + const char* mode = FileGetMode(dwDesiredAccess, dwCreationDisposition, &create); +#ifdef __sun + struct flock lock; +#else + int lock = 0; +#endif + FILE* fp = NULL; + struct stat st; + + if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED) + { + WLog_ERR(TAG, "WinPR does not support the FILE_FLAG_OVERLAPPED flag"); + SetLastError(ERROR_NOT_SUPPORTED); + return INVALID_HANDLE_VALUE; + } + + pFile = (WINPR_FILE*)calloc(1, sizeof(WINPR_FILE)); + if (!pFile) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return INVALID_HANDLE_VALUE; + } + + WINPR_HANDLE_SET_TYPE_AND_MODE(pFile, HANDLE_TYPE_FILE, WINPR_FD_READ); + pFile->common.ops = &fileOps; + + pFile->lpFileName = _strdup(lpFileName); + if (!pFile->lpFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + free(pFile); + return INVALID_HANDLE_VALUE; + } + + pFile->dwOpenMode = dwDesiredAccess; + pFile->dwShareMode = dwShareMode; + pFile->dwFlagsAndAttributes = dwFlagsAndAttributes; + pFile->lpSecurityAttributes = lpSecurityAttributes; + pFile->dwCreationDisposition = dwCreationDisposition; + pFile->hTemplateFile = hTemplateFile; + + if (create) + { + if (dwCreationDisposition == CREATE_NEW) + { + if (stat(pFile->lpFileName, &st) == 0) + { + SetLastError(ERROR_FILE_EXISTS); + free(pFile->lpFileName); + free(pFile); + return INVALID_HANDLE_VALUE; + } + } + + fp = winpr_fopen(pFile->lpFileName, "ab"); + if (!fp) + { + SetLastError(map_posix_err(errno)); + free(pFile->lpFileName); + free(pFile); + return INVALID_HANDLE_VALUE; + } + + fp = freopen(pFile->lpFileName, mode, fp); + } + else + { + if (stat(pFile->lpFileName, &st) != 0) + { + SetLastError(map_posix_err(errno)); + free(pFile->lpFileName); + free(pFile); + return INVALID_HANDLE_VALUE; + } + + /* FIFO (named pipe) would block the following fopen + * call if not connected. This renders the channel unusable, + * therefore abort early. */ + if (S_ISFIFO(st.st_mode)) + { + SetLastError(ERROR_FILE_NOT_FOUND); + free(pFile->lpFileName); + free(pFile); + return INVALID_HANDLE_VALUE; + } + } + + if (NULL == fp) + fp = winpr_fopen(pFile->lpFileName, mode); + + pFile->fp = fp; + if (!pFile->fp) + { + /* This case can occur when trying to open a + * not existing file without create flag. */ + SetLastError(map_posix_err(errno)); + free(pFile->lpFileName); + free(pFile); + return INVALID_HANDLE_VALUE; + } + + (void)setvbuf(fp, NULL, _IONBF, 0); + +#ifdef __sun + lock.l_start = 0; + lock.l_len = 0; + lock.l_whence = SEEK_SET; + + if (dwShareMode & FILE_SHARE_READ) + lock.l_type = F_RDLCK; + if (dwShareMode & FILE_SHARE_WRITE) + lock.l_type = F_RDLCK; +#else + if (dwShareMode & FILE_SHARE_READ) + lock = LOCK_SH; + if (dwShareMode & FILE_SHARE_WRITE) + lock = LOCK_EX; +#endif + + if (dwShareMode & (FILE_SHARE_READ | FILE_SHARE_WRITE)) + { +#ifdef __sun + if (fcntl(fileno(pFile->fp), F_SETLKW, &lock) == -1) +#else + if (flock(fileno(pFile->fp), lock) < 0) +#endif + { + char ebuffer[256] = { 0 }; +#ifdef __sun + WLog_ERR(TAG, "F_SETLKW failed with %s [0x%08X]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); +#else + WLog_ERR(TAG, "flock failed with %s [0x%08X]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); +#endif + + SetLastError(map_posix_err(errno)); + FileCloseHandle(pFile); + return INVALID_HANDLE_VALUE; + } + + pFile->bLocked = TRUE; + } + + if (fstat(fileno(pFile->fp), &st) == 0 && dwFlagsAndAttributes & FILE_ATTRIBUTE_READONLY) + { + st.st_mode &= WINPR_ASSERTING_INT_CAST(mode_t, ~(S_IWUSR | S_IWGRP | S_IWOTH)); + fchmod(fileno(pFile->fp), st.st_mode); + } + + SetLastError(STATUS_SUCCESS); + return pFile; +} + +static BOOL IsFileDevice(LPCTSTR lpDeviceName) +{ + return TRUE; +} + +static const HANDLE_CREATOR FileHandleCreator = { IsFileDevice, FileCreateFileA }; + +const HANDLE_CREATOR* GetFileHandleCreator(void) +{ + return &FileHandleCreator; +} + +static WINPR_FILE* FileHandle_New(FILE* fp) +{ + WINPR_FILE* pFile = NULL; + char name[MAX_PATH] = { 0 }; + + (void)_snprintf(name, sizeof(name), "device_%d", fileno(fp)); + pFile = (WINPR_FILE*)calloc(1, sizeof(WINPR_FILE)); + if (!pFile) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return NULL; + } + pFile->fp = fp; + pFile->common.ops = &shmOps; + pFile->lpFileName = _strdup(name); + + WINPR_HANDLE_SET_TYPE_AND_MODE(pFile, HANDLE_TYPE_FILE, WINPR_FD_READ); + return pFile; +} + +HANDLE GetStdHandle(DWORD nStdHandle) +{ + FILE* fp = NULL; + WINPR_FILE* pFile = NULL; + + switch (nStdHandle) + { + case STD_INPUT_HANDLE: + fp = stdin; + break; + case STD_OUTPUT_HANDLE: + fp = stdout; + break; + case STD_ERROR_HANDLE: + fp = stderr; + break; + default: + return INVALID_HANDLE_VALUE; + } + pFile = FileHandle_New(fp); + if (!pFile) + return INVALID_HANDLE_VALUE; + + return (HANDLE)pFile; +} + +BOOL SetStdHandle(DWORD nStdHandle, HANDLE hHandle) +{ + return FALSE; +} + +BOOL SetStdHandleEx(DWORD dwStdHandle, HANDLE hNewHandle, HANDLE* phOldHandle) +{ + return FALSE; +} + +BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector, + LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters) +{ +#if defined(ANDROID) +#define STATVFS statfs +#else +#define STATVFS statvfs +#endif + + struct STATVFS svfst = { 0 }; + STATVFS(lpRootPathName, &svfst); + *lpSectorsPerCluster = (UINT32)MIN(svfst.f_frsize, UINT32_MAX); + *lpBytesPerSector = 1; + *lpNumberOfFreeClusters = (UINT32)MIN(svfst.f_bavail, UINT32_MAX); + *lpTotalNumberOfClusters = (UINT32)MIN(svfst.f_blocks, UINT32_MAX); + return TRUE; +} + +BOOL GetDiskFreeSpaceW(LPCWSTR lpRootPathName, LPDWORD lpSectorsPerCluster, + LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters, + LPDWORD lpTotalNumberOfClusters) +{ + BOOL ret = 0; + if (!lpRootPathName) + return FALSE; + + char* rootPathName = ConvertWCharToUtf8Alloc(lpRootPathName, NULL); + if (!rootPathName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + ret = GetDiskFreeSpaceA(rootPathName, lpSectorsPerCluster, lpBytesPerSector, + lpNumberOfFreeClusters, lpTotalNumberOfClusters); + free(rootPathName); + return ret; +} + +#endif /* _WIN32 */ + +/** + * Check if a file name component is valid. + * + * Some file names are not valid on Windows. See "Naming Files, Paths, and Namespaces": + * https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx + */ +BOOL ValidFileNameComponent(LPCWSTR lpFileName) +{ + if (!lpFileName) + return FALSE; + + /* CON */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'C' || lpFileName[0] == L'c')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'O' || lpFileName[1] == L'o')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'N' || lpFileName[2] == L'n')) && + (lpFileName[3] == L'\0')) + { + return FALSE; + } + + /* PRN */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'P' || lpFileName[0] == L'p')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'R' || lpFileName[1] == L'r')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'N' || lpFileName[2] == L'n')) && + (lpFileName[3] == L'\0')) + { + return FALSE; + } + + /* AUX */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'A' || lpFileName[0] == L'a')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'U' || lpFileName[1] == L'u')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'X' || lpFileName[2] == L'x')) && + (lpFileName[3] == L'\0')) + { + return FALSE; + } + + /* NUL */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'N' || lpFileName[0] == L'n')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'U' || lpFileName[1] == L'u')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'L' || lpFileName[2] == L'l')) && + (lpFileName[3] == L'\0')) + { + return FALSE; + } + + /* LPT0-9 */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'L' || lpFileName[0] == L'l')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'P' || lpFileName[1] == L'p')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'T' || lpFileName[2] == L't')) && + (lpFileName[3] != L'\0' && (L'0' <= lpFileName[3] && lpFileName[3] <= L'9')) && + (lpFileName[4] == L'\0')) + { + return FALSE; + } + + /* COM0-9 */ + if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'C' || lpFileName[0] == L'c')) && + (lpFileName[1] != L'\0' && (lpFileName[1] == L'O' || lpFileName[1] == L'o')) && + (lpFileName[2] != L'\0' && (lpFileName[2] == L'M' || lpFileName[2] == L'm')) && + (lpFileName[3] != L'\0' && (L'0' <= lpFileName[3] && lpFileName[3] <= L'9')) && + (lpFileName[4] == L'\0')) + { + return FALSE; + } + + /* Reserved characters */ + for (LPCWSTR c = lpFileName; *c; c++) + { + if ((*c == L'<') || (*c == L'>') || (*c == L':') || (*c == L'"') || (*c == L'/') || + (*c == L'\\') || (*c == L'|') || (*c == L'?') || (*c == L'*')) + { + return FALSE; + } + } + + return TRUE; +} + +#ifdef _UWP + +HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + HANDLE hFile; + CREATEFILE2_EXTENDED_PARAMETERS params = { 0 }; + + params.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); + + if (dwFlagsAndAttributes & FILE_FLAG_BACKUP_SEMANTICS) + params.dwFileFlags |= FILE_FLAG_BACKUP_SEMANTICS; + if (dwFlagsAndAttributes & FILE_FLAG_DELETE_ON_CLOSE) + params.dwFileFlags |= FILE_FLAG_DELETE_ON_CLOSE; + if (dwFlagsAndAttributes & FILE_FLAG_NO_BUFFERING) + params.dwFileFlags |= FILE_FLAG_NO_BUFFERING; + if (dwFlagsAndAttributes & FILE_FLAG_OPEN_NO_RECALL) + params.dwFileFlags |= FILE_FLAG_OPEN_NO_RECALL; + if (dwFlagsAndAttributes & FILE_FLAG_OPEN_REPARSE_POINT) + params.dwFileFlags |= FILE_FLAG_OPEN_REPARSE_POINT; + if (dwFlagsAndAttributes & FILE_FLAG_OPEN_REQUIRING_OPLOCK) + params.dwFileFlags |= FILE_FLAG_OPEN_REQUIRING_OPLOCK; + if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED) + params.dwFileFlags |= FILE_FLAG_OVERLAPPED; + if (dwFlagsAndAttributes & FILE_FLAG_POSIX_SEMANTICS) + params.dwFileFlags |= FILE_FLAG_POSIX_SEMANTICS; + if (dwFlagsAndAttributes & FILE_FLAG_RANDOM_ACCESS) + params.dwFileFlags |= FILE_FLAG_RANDOM_ACCESS; + if (dwFlagsAndAttributes & FILE_FLAG_SESSION_AWARE) + params.dwFileFlags |= FILE_FLAG_SESSION_AWARE; + if (dwFlagsAndAttributes & FILE_FLAG_SEQUENTIAL_SCAN) + params.dwFileFlags |= FILE_FLAG_SEQUENTIAL_SCAN; + if (dwFlagsAndAttributes & FILE_FLAG_WRITE_THROUGH) + params.dwFileFlags |= FILE_FLAG_WRITE_THROUGH; + + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_ARCHIVE) + params.dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_COMPRESSED) + params.dwFileAttributes |= FILE_ATTRIBUTE_COMPRESSED; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_DEVICE) + params.dwFileAttributes |= FILE_ATTRIBUTE_DEVICE; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_DIRECTORY) + params.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_ENCRYPTED) + params.dwFileAttributes |= FILE_ATTRIBUTE_ENCRYPTED; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_HIDDEN) + params.dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) + params.dwFileAttributes |= FILE_ATTRIBUTE_INTEGRITY_STREAM; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NORMAL) + params.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) + params.dwFileAttributes |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) + params.dwFileAttributes |= FILE_ATTRIBUTE_NO_SCRUB_DATA; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_OFFLINE) + params.dwFileAttributes |= FILE_ATTRIBUTE_OFFLINE; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_READONLY) + params.dwFileAttributes |= FILE_ATTRIBUTE_READONLY; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_REPARSE_POINT) + params.dwFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_SPARSE_FILE) + params.dwFileAttributes |= FILE_ATTRIBUTE_SPARSE_FILE; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_SYSTEM) + params.dwFileAttributes |= FILE_ATTRIBUTE_SYSTEM; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_TEMPORARY) + params.dwFileAttributes |= FILE_ATTRIBUTE_TEMPORARY; + if (dwFlagsAndAttributes & FILE_ATTRIBUTE_VIRTUAL) + params.dwFileAttributes |= FILE_ATTRIBUTE_VIRTUAL; + + if (dwFlagsAndAttributes & SECURITY_ANONYMOUS) + params.dwSecurityQosFlags |= SECURITY_ANONYMOUS; + if (dwFlagsAndAttributes & SECURITY_CONTEXT_TRACKING) + params.dwSecurityQosFlags |= SECURITY_CONTEXT_TRACKING; + if (dwFlagsAndAttributes & SECURITY_DELEGATION) + params.dwSecurityQosFlags |= SECURITY_DELEGATION; + if (dwFlagsAndAttributes & SECURITY_EFFECTIVE_ONLY) + params.dwSecurityQosFlags |= SECURITY_EFFECTIVE_ONLY; + if (dwFlagsAndAttributes & SECURITY_IDENTIFICATION) + params.dwSecurityQosFlags |= SECURITY_IDENTIFICATION; + if (dwFlagsAndAttributes & SECURITY_IMPERSONATION) + params.dwSecurityQosFlags |= SECURITY_IMPERSONATION; + + params.lpSecurityAttributes = lpSecurityAttributes; + params.hTemplateFile = hTemplateFile; + + hFile = CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ¶ms); + + return hFile; +} + +HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + HANDLE hFile; + if (!lpFileName) + return NULL; + + WCHAR* lpFileNameW = ConvertUtf8ToWCharAlloc(lpFileName, NULL); + + if (!lpFileNameW) + return NULL; + + hFile = CreateFileW(lpFileNameW, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + + free(lpFileNameW); + + return hFile; +} + +DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) +{ + BOOL status; + LARGE_INTEGER fileSize = { 0, 0 }; + + if (!lpFileSizeHigh) + return INVALID_FILE_SIZE; + + status = GetFileSizeEx(hFile, &fileSize); + + if (!status) + return INVALID_FILE_SIZE; + + *lpFileSizeHigh = fileSize.HighPart; + + return fileSize.LowPart; +} + +DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, + DWORD dwMoveMethod) +{ + BOOL status; + LARGE_INTEGER liDistanceToMove = { 0, 0 }; + LARGE_INTEGER liNewFilePointer = { 0, 0 }; + + liDistanceToMove.LowPart = lDistanceToMove; + + status = SetFilePointerEx(hFile, liDistanceToMove, &liNewFilePointer, dwMoveMethod); + + if (!status) + return INVALID_SET_FILE_POINTER; + + if (lpDistanceToMoveHigh) + *lpDistanceToMoveHigh = liNewFilePointer.HighPart; + + return liNewFilePointer.LowPart; +} + +HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData) +{ + return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindFileData, FindExSearchNameMatch, + NULL, 0); +} + +HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData) +{ + return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindFileData, FindExSearchNameMatch, + NULL, 0); +} + +DWORD GetFullPathNameA(LPCSTR lpFileName, DWORD nBufferLength, LPSTR lpBuffer, LPSTR* lpFilePart) +{ + DWORD dwStatus; + WCHAR* lpFileNameW = NULL; + WCHAR* lpBufferW = NULL; + WCHAR* lpFilePartW = NULL; + DWORD nBufferLengthW = nBufferLength * sizeof(WCHAR); + + if (!lpFileName || (nBufferLength < 1)) + return 0; + + lpFileNameW = ConvertUtf8ToWCharAlloc(lpFileName, NULL); + if (!lpFileNameW) + return 0; + + lpBufferW = (WCHAR*)malloc(nBufferLengthW); + + if (!lpBufferW) + return 0; + + dwStatus = GetFullPathNameW(lpFileNameW, nBufferLengthW, lpBufferW, &lpFilePartW); + + (void)ConvertWCharNToUtf8(lpBufferW, nBufferLengthW / sizeof(WCHAR), lpBuffer, nBufferLength); + + if (lpFilePart) + lpFilePart = lpBuffer + (lpFilePartW - lpBufferW); + + free(lpFileNameW); + free(lpBufferW); + + return dwStatus * 2; +} + +BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector, + LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters) +{ + BOOL status; + ULARGE_INTEGER FreeBytesAvailableToCaller = { 0, 0 }; + ULARGE_INTEGER TotalNumberOfBytes = { 0, 0 }; + ULARGE_INTEGER TotalNumberOfFreeBytes = { 0, 0 }; + + status = GetDiskFreeSpaceExA(lpRootPathName, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, + &TotalNumberOfFreeBytes); + + if (!status) + return FALSE; + + *lpBytesPerSector = 1; + *lpSectorsPerCluster = TotalNumberOfBytes.LowPart; + *lpNumberOfFreeClusters = FreeBytesAvailableToCaller.LowPart; + *lpTotalNumberOfClusters = TotalNumberOfFreeBytes.LowPart; + + return TRUE; +} + +BOOL GetDiskFreeSpaceW(LPCWSTR lpRootPathName, LPDWORD lpSectorsPerCluster, + LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters, + LPDWORD lpTotalNumberOfClusters) +{ + BOOL status; + ULARGE_INTEGER FreeBytesAvailableToCaller = { 0, 0 }; + ULARGE_INTEGER TotalNumberOfBytes = { 0, 0 }; + ULARGE_INTEGER TotalNumberOfFreeBytes = { 0, 0 }; + + status = GetDiskFreeSpaceExW(lpRootPathName, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, + &TotalNumberOfFreeBytes); + + if (!status) + return FALSE; + + *lpBytesPerSector = 1; + *lpSectorsPerCluster = TotalNumberOfBytes.LowPart; + *lpNumberOfFreeClusters = FreeBytesAvailableToCaller.LowPart; + *lpTotalNumberOfClusters = TotalNumberOfFreeBytes.LowPart; + + return TRUE; +} + +DWORD GetLogicalDriveStringsA(DWORD nBufferLength, LPSTR lpBuffer) +{ + SetLastError(ERROR_INVALID_FUNCTION); + return 0; +} + +DWORD GetLogicalDriveStringsW(DWORD nBufferLength, LPWSTR lpBuffer) +{ + SetLastError(ERROR_INVALID_FUNCTION); + return 0; +} + +BOOL PathIsDirectoryEmptyA(LPCSTR pszPath) +{ + return FALSE; +} + +UINT GetACP(void) +{ + return CP_UTF8; +} + +#endif + +/* Extended API */ + +#ifdef _WIN32 +#include +#endif + +HANDLE GetFileHandleForFileDescriptor(int fd) +{ +#ifdef _WIN32 + return (HANDLE)_get_osfhandle(fd); +#else /* _WIN32 */ + WINPR_FILE* pFile = NULL; + FILE* fp = NULL; + int flags = 0; + + /* Make sure it's a valid fd */ + if (fcntl(fd, F_GETFD) == -1 && errno == EBADF) + return INVALID_HANDLE_VALUE; + + flags = fcntl(fd, F_GETFL); + if (flags == -1) + return INVALID_HANDLE_VALUE; + + if (flags & O_WRONLY) + fp = fdopen(fd, "wb"); + else + fp = fdopen(fd, "rb"); + + if (!fp) + return INVALID_HANDLE_VALUE; + + (void)setvbuf(fp, NULL, _IONBF, 0); + + // NOLINTNEXTLINE(clang-analyzer-unix.Stream) + pFile = FileHandle_New(fp); + if (!pFile) + return INVALID_HANDLE_VALUE; + + return (HANDLE)pFile; +#endif /* _WIN32 */ +} + +FILE* winpr_fopen(const char* path, const char* mode) +{ +#ifndef _WIN32 + return fopen(path, mode); +#else + LPWSTR lpPathW = NULL; + LPWSTR lpModeW = NULL; + FILE* result = NULL; + + if (!path || !mode) + return NULL; + + lpPathW = ConvertUtf8ToWCharAlloc(path, NULL); + if (!lpPathW) + goto cleanup; + + lpModeW = ConvertUtf8ToWCharAlloc(mode, NULL); + if (!lpModeW) + goto cleanup; + + result = _wfopen(lpPathW, lpModeW); + +cleanup: + free(lpPathW); + free(lpModeW); + return result; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.h new file mode 100644 index 0000000000000000000000000000000000000000..ce6b852d37e668a74f6c0a94c2714955e24f7f9e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/file.h @@ -0,0 +1,66 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2015 Armin Novak + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2016 David PHAM-VAN + * + * 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_PRIV_H +#define WINPR_FILE_PRIV_H + +#include +#include + +#include +#include +#include + +#ifndef _WIN32 + +#include +#include "../handle/handle.h" + +#define EPOCH_DIFF 11644473600LL +#define STAT_TIME_TO_FILETIME(_t) (((UINT64)(_t) + EPOCH_DIFF) * 10000000LL) + +struct winpr_file +{ + WINPR_HANDLE common; + + FILE* fp; + + char* lpFileName; + + DWORD dwOpenMode; + DWORD dwShareMode; + DWORD dwFlagsAndAttributes; + + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + DWORD dwCreationDisposition; + HANDLE hTemplateFile; + + BOOL bLocked; +}; +typedef struct winpr_file WINPR_FILE; + +const HANDLE_CREATOR* GetFileHandleCreator(void); + +UINT32 map_posix_err(int fs_errno); + +#endif /* _WIN32 */ + +#endif /* WINPR_FILE_PRIV_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/generic.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/generic.c new file mode 100644 index 0000000000000000000000000000000000000000..de743531185168299e36ca3ea2a2424fc05ba4b7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/generic.c @@ -0,0 +1,1384 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Hewlett-Packard Development Company, L.P. + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include +#include +#include +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifdef WINPR_HAVE_FCNTL_H +#include +#endif + +#include "../log.h" +#define TAG WINPR_TAG("file") + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef WINPR_HAVE_AIO_H +#undef WINPR_HAVE_AIO_H /* disable for now, incomplete */ +#endif + +#ifdef WINPR_HAVE_AIO_H +#include +#endif + +#ifdef ANDROID +#include +#else +#include +#endif + +#include "../handle/handle.h" + +#include "../pipe/pipe.h" + +#include "file.h" + +/** + * api-ms-win-core-file-l1-2-0.dll: + * + * CreateFileA + * CreateFileW + * CreateFile2 + * DeleteFileA + * DeleteFileW + * CreateDirectoryA + * CreateDirectoryW + * RemoveDirectoryA + * RemoveDirectoryW + * CompareFileTime + * DefineDosDeviceW + * DeleteVolumeMountPointW + * FileTimeToLocalFileTime + * LocalFileTimeToFileTime + * FindClose + * FindCloseChangeNotification + * FindFirstChangeNotificationA + * FindFirstChangeNotificationW + * FindFirstFileA + * FindFirstFileExA + * FindFirstFileExW + * FindFirstFileW + * FindFirstVolumeW + * FindNextChangeNotification + * FindNextFileA + * FindNextFileW + * FindNextVolumeW + * FindVolumeClose + * GetDiskFreeSpaceA + * GetDiskFreeSpaceExA + * GetDiskFreeSpaceExW + * GetDiskFreeSpaceW + * GetDriveTypeA + * GetDriveTypeW + * GetFileAttributesA + * GetFileAttributesExA + * GetFileAttributesExW + * GetFileAttributesW + * GetFileInformationByHandle + * GetFileSize + * GetFileSizeEx + * GetFileTime + * GetFileType + * GetFinalPathNameByHandleA + * GetFinalPathNameByHandleW + * GetFullPathNameA + * GetFullPathNameW + * GetLogicalDrives + * GetLogicalDriveStringsW + * GetLongPathNameA + * GetLongPathNameW + * GetShortPathNameW + * GetTempFileNameW + * GetTempPathW + * GetVolumeInformationByHandleW + * GetVolumeInformationW + * GetVolumeNameForVolumeMountPointW + * GetVolumePathNamesForVolumeNameW + * GetVolumePathNameW + * QueryDosDeviceW + * SetFileAttributesA + * SetFileAttributesW + * SetFileTime + * SetFileValidData + * SetFileInformationByHandle + * ReadFile + * ReadFileEx + * ReadFileScatter + * WriteFile + * WriteFileEx + * WriteFileGather + * FlushFileBuffers + * SetEndOfFile + * SetFilePointer + * SetFilePointerEx + * LockFile + * LockFileEx + * UnlockFile + * UnlockFileEx + */ + +/** + * File System Behavior in the Microsoft Windows Environment: + * http://download.microsoft.com/download/4/3/8/43889780-8d45-4b2e-9d3a-c696a890309f/File%20System%20Behavior%20Overview.pdf + */ + +/** + * Asynchronous I/O - The GNU C Library: + * http://www.gnu.org/software/libc/manual/html_node/Asynchronous-I_002fO.html + */ + +/** + * aio.h - asynchronous input and output: + * http://pubs.opengroup.org/onlinepubs/009695399/basedefs/aio.h.html + */ + +/** + * Asynchronous I/O User Guide: + * http://code.google.com/p/kernel/wiki/AIOUserGuide + */ +static wArrayList* HandleCreators; + +static pthread_once_t HandleCreatorsInitialized = PTHREAD_ONCE_INIT; + +#include "../comm/comm.h" +#include "namedPipeClient.h" + +static void HandleCreatorsInit(void) +{ + WINPR_ASSERT(HandleCreators == NULL); + HandleCreators = ArrayList_New(TRUE); + + if (!HandleCreators) + return; + + /* + * Register all file handle creators. + */ + ArrayList_Append(HandleCreators, GetNamedPipeClientHandleCreator()); + const HANDLE_CREATOR* serial = GetCommHandleCreator(); + if (serial) + ArrayList_Append(HandleCreators, serial); + ArrayList_Append(HandleCreators, GetFileHandleCreator()); +} + +#ifdef WINPR_HAVE_AIO_H + +static BOOL g_AioSignalHandlerInstalled = FALSE; + +void AioSignalHandler(int signum, siginfo_t* siginfo, void* arg) +{ + WLog_INFO("%d", signum); +} + +int InstallAioSignalHandler() +{ + if (!g_AioSignalHandlerInstalled) + { + struct sigaction action; + sigemptyset(&action.sa_mask); + sigaddset(&action.sa_mask, SIGIO); + action.sa_flags = SA_SIGINFO; + action.sa_sigaction = (void*)&AioSignalHandler; + sigaction(SIGIO, &action, NULL); + g_AioSignalHandlerInstalled = TRUE; + } + + return 0; +} + +#endif /* WINPR_HAVE_AIO_H */ + +HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + if (!lpFileName) + return INVALID_HANDLE_VALUE; + + if (pthread_once(&HandleCreatorsInitialized, HandleCreatorsInit) != 0) + { + SetLastError(ERROR_DLL_INIT_FAILED); + return INVALID_HANDLE_VALUE; + } + + if (HandleCreators == NULL) + { + SetLastError(ERROR_DLL_INIT_FAILED); + return INVALID_HANDLE_VALUE; + } + + ArrayList_Lock(HandleCreators); + + for (size_t i = 0; i <= ArrayList_Count(HandleCreators); i++) + { + const HANDLE_CREATOR* creator = ArrayList_GetItem(HandleCreators, i); + + if (creator && creator->IsHandled(lpFileName)) + { + HANDLE newHandle = + creator->CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + ArrayList_Unlock(HandleCreators); + return newHandle; + } + } + + ArrayList_Unlock(HandleCreators); + return INVALID_HANDLE_VALUE; +} + +HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +{ + HANDLE hdl = NULL; + if (!lpFileName) + return NULL; + char* lpFileNameA = ConvertWCharToUtf8Alloc(lpFileName, NULL); + + if (!lpFileNameA) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + goto fail; + } + + hdl = CreateFileA(lpFileNameA, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +fail: + free(lpFileNameA); + return hdl; +} + +BOOL DeleteFileA(LPCSTR lpFileName) +{ + int status = 0; + status = unlink(lpFileName); + return (status != -1) ? TRUE : FALSE; +} + +BOOL DeleteFileW(LPCWSTR lpFileName) +{ + if (!lpFileName) + return FALSE; + LPSTR lpFileNameA = ConvertWCharToUtf8Alloc(lpFileName, NULL); + BOOL rc = FALSE; + + if (!lpFileNameA) + goto fail; + + rc = DeleteFileA(lpFileNameA); +fail: + free(lpFileNameA); + return rc; +} + +BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + /* + * from http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx + * lpNumberOfBytesRead can be NULL only when the lpOverlapped parameter is not NULL. + */ + + if (!lpNumberOfBytesRead && !lpOverlapped) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->ReadFile) + return handle->ops->ReadFile(handle, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, + lpOverlapped); + + WLog_ERR(TAG, "ReadFile operation not implemented"); + return FALSE; +} + +BOOL ReadFileEx(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->ReadFileEx) + return handle->ops->ReadFileEx(handle, lpBuffer, nNumberOfBytesToRead, lpOverlapped, + lpCompletionRoutine); + + WLog_ERR(TAG, "ReadFileEx operation not implemented"); + return FALSE; +} + +BOOL ReadFileScatter(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[], DWORD nNumberOfBytesToRead, + LPDWORD lpReserved, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->ReadFileScatter) + return handle->ops->ReadFileScatter(handle, aSegmentArray, nNumberOfBytesToRead, lpReserved, + lpOverlapped); + + WLog_ERR(TAG, "ReadFileScatter operation not implemented"); + return FALSE; +} + +BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->WriteFile) + return handle->ops->WriteFile(handle, lpBuffer, nNumberOfBytesToWrite, + lpNumberOfBytesWritten, lpOverlapped); + + WLog_ERR(TAG, "WriteFile operation not implemented"); + return FALSE; +} + +BOOL WriteFileEx(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->WriteFileEx) + return handle->ops->WriteFileEx(handle, lpBuffer, nNumberOfBytesToWrite, lpOverlapped, + lpCompletionRoutine); + + WLog_ERR(TAG, "WriteFileEx operation not implemented"); + return FALSE; +} + +BOOL WriteFileGather(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[], + DWORD nNumberOfBytesToWrite, LPDWORD lpReserved, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->WriteFileGather) + return handle->ops->WriteFileGather(handle, aSegmentArray, nNumberOfBytesToWrite, + lpReserved, lpOverlapped); + + WLog_ERR(TAG, "WriteFileGather operation not implemented"); + return FALSE; +} + +BOOL FlushFileBuffers(HANDLE hFile) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->FlushFileBuffers) + return handle->ops->FlushFileBuffers(handle); + + WLog_ERR(TAG, "FlushFileBuffers operation not implemented"); + return FALSE; +} + +BOOL WINAPI GetFileAttributesExA(LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, + LPVOID lpFileInformation) +{ + LPWIN32_FILE_ATTRIBUTE_DATA fd = lpFileInformation; + WIN32_FIND_DATAA findFileData = { 0 }; + + if (!fd) + return FALSE; + + HANDLE hFind = FindFirstFileA(lpFileName, &findFileData); + if (hFind == INVALID_HANDLE_VALUE) + return FALSE; + + FindClose(hFind); + fd->dwFileAttributes = findFileData.dwFileAttributes; + fd->ftCreationTime = findFileData.ftCreationTime; + fd->ftLastAccessTime = findFileData.ftLastAccessTime; + fd->ftLastWriteTime = findFileData.ftLastWriteTime; + fd->nFileSizeHigh = findFileData.nFileSizeHigh; + fd->nFileSizeLow = findFileData.nFileSizeLow; + return TRUE; +} + +BOOL WINAPI GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, + LPVOID lpFileInformation) +{ + BOOL ret = 0; + if (!lpFileName) + return FALSE; + LPSTR lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, NULL); + + if (!lpCFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + ret = GetFileAttributesExA(lpCFileName, fInfoLevelId, lpFileInformation); + free(lpCFileName); + return ret; +} + +DWORD WINAPI GetFileAttributesA(LPCSTR lpFileName) +{ + WIN32_FIND_DATAA findFileData = { 0 }; + HANDLE hFind = FindFirstFileA(lpFileName, &findFileData); + + if (hFind == INVALID_HANDLE_VALUE) + return INVALID_FILE_ATTRIBUTES; + + FindClose(hFind); + return findFileData.dwFileAttributes; +} + +DWORD WINAPI GetFileAttributesW(LPCWSTR lpFileName) +{ + DWORD ret = 0; + if (!lpFileName) + return FALSE; + LPSTR lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, NULL); + if (!lpCFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + ret = GetFileAttributesA(lpCFileName); + free(lpCFileName); + return ret; +} + +BOOL GetFileInformationByHandle(HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->GetFileInformationByHandle) + return handle->ops->GetFileInformationByHandle(handle, lpFileInformation); + + WLog_ERR(TAG, "GetFileInformationByHandle operation not implemented"); + return 0; +} + +static char* append(char* buffer, size_t size, const char* append) +{ + winpr_str_append(append, buffer, size, "|"); + return buffer; +} + +static const char* flagsToStr(char* buffer, size_t size, DWORD flags) +{ + char strflags[32] = { 0 }; + if (flags & FILE_ATTRIBUTE_READONLY) + append(buffer, size, "FILE_ATTRIBUTE_READONLY"); + if (flags & FILE_ATTRIBUTE_HIDDEN) + append(buffer, size, "FILE_ATTRIBUTE_HIDDEN"); + if (flags & FILE_ATTRIBUTE_SYSTEM) + append(buffer, size, "FILE_ATTRIBUTE_SYSTEM"); + if (flags & FILE_ATTRIBUTE_DIRECTORY) + append(buffer, size, "FILE_ATTRIBUTE_DIRECTORY"); + if (flags & FILE_ATTRIBUTE_ARCHIVE) + append(buffer, size, "FILE_ATTRIBUTE_ARCHIVE"); + if (flags & FILE_ATTRIBUTE_DEVICE) + append(buffer, size, "FILE_ATTRIBUTE_DEVICE"); + if (flags & FILE_ATTRIBUTE_NORMAL) + append(buffer, size, "FILE_ATTRIBUTE_NORMAL"); + if (flags & FILE_ATTRIBUTE_TEMPORARY) + append(buffer, size, "FILE_ATTRIBUTE_TEMPORARY"); + if (flags & FILE_ATTRIBUTE_SPARSE_FILE) + append(buffer, size, "FILE_ATTRIBUTE_SPARSE_FILE"); + if (flags & FILE_ATTRIBUTE_REPARSE_POINT) + append(buffer, size, "FILE_ATTRIBUTE_REPARSE_POINT"); + if (flags & FILE_ATTRIBUTE_COMPRESSED) + append(buffer, size, "FILE_ATTRIBUTE_COMPRESSED"); + if (flags & FILE_ATTRIBUTE_OFFLINE) + append(buffer, size, "FILE_ATTRIBUTE_OFFLINE"); + if (flags & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) + append(buffer, size, "FILE_ATTRIBUTE_NOT_CONTENT_INDEXED"); + if (flags & FILE_ATTRIBUTE_ENCRYPTED) + append(buffer, size, "FILE_ATTRIBUTE_ENCRYPTED"); + if (flags & FILE_ATTRIBUTE_VIRTUAL) + append(buffer, size, "FILE_ATTRIBUTE_VIRTUAL"); + + (void)_snprintf(strflags, sizeof(strflags), " [0x%08" PRIx32 "]", flags); + winpr_str_append(strflags, buffer, size, NULL); + return buffer; +} + +BOOL SetFileAttributesA(LPCSTR lpFileName, DWORD dwFileAttributes) +{ + BOOL rc = FALSE; +#ifdef WINPR_HAVE_FCNTL_H + struct stat st = { 0 }; + int fd = 0; + + if (dwFileAttributes & ~FILE_ATTRIBUTE_READONLY) + { + char buffer[8192] = { 0 }; + const char* flags = + flagsToStr(buffer, sizeof(buffer), dwFileAttributes & ~FILE_ATTRIBUTE_READONLY); + WLog_WARN(TAG, "Unsupported flags %s, ignoring!", flags); + } + + fd = open(lpFileName, O_RDONLY); + if (fd < 0) + return FALSE; + + if (fstat(fd, &st) != 0) + goto fail; + + if (dwFileAttributes & FILE_ATTRIBUTE_READONLY) + { + st.st_mode &= WINPR_ASSERTING_INT_CAST(mode_t, (mode_t)(~(S_IWUSR | S_IWGRP | S_IWOTH))); + } + else + { + st.st_mode |= S_IWUSR; + } + + if (fchmod(fd, st.st_mode) != 0) + goto fail; + + rc = TRUE; +fail: + close(fd); +#endif + return rc; +} + +BOOL SetFileAttributesW(LPCWSTR lpFileName, DWORD dwFileAttributes) +{ + BOOL ret = 0; + LPSTR lpCFileName = NULL; + + if (!lpFileName) + return FALSE; + + if (dwFileAttributes & ~FILE_ATTRIBUTE_READONLY) + { + char buffer[8192] = { 0 }; + const char* flags = + flagsToStr(buffer, sizeof(buffer), dwFileAttributes & ~FILE_ATTRIBUTE_READONLY); + WLog_WARN(TAG, "Unsupported flags %s, ignoring!", flags); + } + + lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, NULL); + if (!lpCFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + ret = SetFileAttributesA(lpCFileName, dwFileAttributes); + free(lpCFileName); + return ret; +} + +BOOL SetEndOfFile(HANDLE hFile) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->SetEndOfFile) + return handle->ops->SetEndOfFile(handle); + + WLog_ERR(TAG, "SetEndOfFile operation not implemented"); + return FALSE; +} + +DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->GetFileSize) + return handle->ops->GetFileSize(handle, lpFileSizeHigh); + + WLog_ERR(TAG, "GetFileSize operation not implemented"); + return 0; +} + +DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, + DWORD dwMoveMethod) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->SetFilePointer) + return handle->ops->SetFilePointer(handle, lDistanceToMove, lpDistanceToMoveHigh, + dwMoveMethod); + + WLog_ERR(TAG, "SetFilePointer operation not implemented"); + return 0; +} + +BOOL SetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove, PLARGE_INTEGER lpNewFilePointer, + DWORD dwMoveMethod) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->SetFilePointerEx) + return handle->ops->SetFilePointerEx(handle, liDistanceToMove, lpNewFilePointer, + dwMoveMethod); + + WLog_ERR(TAG, "SetFilePointerEx operation not implemented"); + return 0; +} + +BOOL LockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->LockFile) + return handle->ops->LockFile(handle, dwFileOffsetLow, dwFileOffsetHigh, + nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh); + + WLog_ERR(TAG, "LockFile operation not implemented"); + return FALSE; +} + +BOOL LockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, DWORD nNumberOfBytesToLockLow, + DWORD nNumberOfBytesToLockHigh, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->LockFileEx) + return handle->ops->LockFileEx(handle, dwFlags, dwReserved, nNumberOfBytesToLockLow, + nNumberOfBytesToLockHigh, lpOverlapped); + + WLog_ERR(TAG, "LockFileEx operation not implemented"); + return FALSE; +} + +BOOL UnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->UnlockFile) + return handle->ops->UnlockFile(handle, dwFileOffsetLow, dwFileOffsetHigh, + nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh); + + WLog_ERR(TAG, "UnLockFile operation not implemented"); + return FALSE; +} + +BOOL UnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow, + DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->UnlockFileEx) + return handle->ops->UnlockFileEx(handle, dwReserved, nNumberOfBytesToUnlockLow, + nNumberOfBytesToUnlockHigh, lpOverlapped); + + WLog_ERR(TAG, "UnLockFileEx operation not implemented"); + return FALSE; +} + +BOOL WINAPI SetFileTime(HANDLE hFile, const FILETIME* lpCreationTime, + const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime) +{ + ULONG Type = 0; + WINPR_HANDLE* handle = NULL; + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) + return FALSE; + + handle = (WINPR_HANDLE*)hFile; + + if (handle->ops->SetFileTime) + return handle->ops->SetFileTime(handle, lpCreationTime, lpLastAccessTime, lpLastWriteTime); + + WLog_ERR(TAG, "operation not implemented"); + return FALSE; +} + +typedef struct +{ + char magic[16]; + LPSTR lpPath; + LPSTR lpPattern; + DIR* pDir; +} WIN32_FILE_SEARCH; + +static const char file_search_magic[] = "file_srch_magic"; + +WINPR_ATTR_MALLOC(FindClose, 1) +static WIN32_FILE_SEARCH* file_search_new(const char* name, size_t namelen, const char* pattern, + size_t patternlen) +{ + WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)calloc(1, sizeof(WIN32_FILE_SEARCH)); + if (!pFileSearch) + return NULL; + WINPR_ASSERT(sizeof(file_search_magic) == sizeof(pFileSearch->magic)); + memcpy(pFileSearch->magic, file_search_magic, sizeof(pFileSearch->magic)); + + pFileSearch->lpPath = strndup(name, namelen); + pFileSearch->lpPattern = strndup(pattern, patternlen); + if (!pFileSearch->lpPath || !pFileSearch->lpPattern) + goto fail; + + pFileSearch->pDir = opendir(pFileSearch->lpPath); + if (!pFileSearch->pDir) + { + /* Work around for android: + * parent directories are not accessible, so if we have a directory without pattern + * try to open it directly and set pattern to '*' + */ + struct stat fileStat = { 0 }; + if (stat(name, &fileStat) == 0) + { + if (S_ISDIR(fileStat.st_mode)) + { + pFileSearch->pDir = opendir(name); + if (pFileSearch->pDir) + { + free(pFileSearch->lpPath); + free(pFileSearch->lpPattern); + pFileSearch->lpPath = _strdup(name); + pFileSearch->lpPattern = _strdup("*"); + if (!pFileSearch->lpPath || !pFileSearch->lpPattern) + { + closedir(pFileSearch->pDir); + pFileSearch->pDir = NULL; + } + } + } + } + } + if (!pFileSearch->pDir) + goto fail; + + return pFileSearch; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + FindClose(pFileSearch); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +static BOOL is_valid_file_search_handle(HANDLE handle) +{ + WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)handle; + if (!pFileSearch) + return FALSE; + if (pFileSearch == INVALID_HANDLE_VALUE) + return FALSE; + if (strncmp(file_search_magic, pFileSearch->magic, sizeof(file_search_magic)) != 0) + return FALSE; + return TRUE; +} +static BOOL FindDataFromStat(const char* path, const struct stat* fileStat, + LPWIN32_FIND_DATAA lpFindFileData) +{ + UINT64 ft = 0; + char* lastSep = NULL; + lpFindFileData->dwFileAttributes = 0; + + if (S_ISDIR(fileStat->st_mode)) + lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; + + if (lpFindFileData->dwFileAttributes == 0) + lpFindFileData->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE; + + lastSep = strrchr(path, '/'); + + if (lastSep) + { + const char* name = lastSep + 1; + const size_t namelen = strlen(name); + + if ((namelen > 1) && (name[0] == '.') && (name[1] != '.')) + lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; + } + + if (!(fileStat->st_mode & S_IWUSR)) + lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; + +#ifdef _DARWIN_FEATURE_64_BIT_INODE + ft = STAT_TIME_TO_FILETIME(fileStat->st_birthtime); +#else + ft = STAT_TIME_TO_FILETIME(fileStat->st_ctime); +#endif + lpFindFileData->ftCreationTime.dwHighDateTime = (ft) >> 32ULL; + lpFindFileData->ftCreationTime.dwLowDateTime = ft & 0xFFFFFFFF; + ft = STAT_TIME_TO_FILETIME(fileStat->st_mtime); + lpFindFileData->ftLastWriteTime.dwHighDateTime = (ft) >> 32ULL; + lpFindFileData->ftLastWriteTime.dwLowDateTime = ft & 0xFFFFFFFF; + ft = STAT_TIME_TO_FILETIME(fileStat->st_atime); + lpFindFileData->ftLastAccessTime.dwHighDateTime = (ft) >> 32ULL; + lpFindFileData->ftLastAccessTime.dwLowDateTime = ft & 0xFFFFFFFF; + lpFindFileData->nFileSizeHigh = ((UINT64)fileStat->st_size) >> 32ULL; + lpFindFileData->nFileSizeLow = fileStat->st_size & 0xFFFFFFFF; + return TRUE; +} + +HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData) +{ + if (!lpFindFileData || !lpFileName) + { + SetLastError(ERROR_BAD_ARGUMENTS); + return INVALID_HANDLE_VALUE; + } + + const WIN32_FIND_DATAA empty = { 0 }; + *lpFindFileData = empty; + + WIN32_FILE_SEARCH* pFileSearch = NULL; + size_t patternlen = 0; + const size_t flen = strlen(lpFileName); + const char sep = PathGetSeparatorA(PATH_STYLE_NATIVE); + const char* ptr = strrchr(lpFileName, sep); + if (!ptr) + goto fail; + patternlen = strlen(ptr + 1); + if (patternlen == 0) + goto fail; + + pFileSearch = file_search_new(lpFileName, flen - patternlen, ptr + 1, patternlen); + + if (!pFileSearch) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return INVALID_HANDLE_VALUE; + } + + if (FindNextFileA((HANDLE)pFileSearch, lpFindFileData)) + return (HANDLE)pFileSearch; + +fail: + FindClose(pFileSearch); + return INVALID_HANDLE_VALUE; +} + +static BOOL ConvertFindDataAToW(LPWIN32_FIND_DATAA lpFindFileDataA, + LPWIN32_FIND_DATAW lpFindFileDataW) +{ + if (!lpFindFileDataA || !lpFindFileDataW) + return FALSE; + + lpFindFileDataW->dwFileAttributes = lpFindFileDataA->dwFileAttributes; + lpFindFileDataW->ftCreationTime = lpFindFileDataA->ftCreationTime; + lpFindFileDataW->ftLastAccessTime = lpFindFileDataA->ftLastAccessTime; + lpFindFileDataW->ftLastWriteTime = lpFindFileDataA->ftLastWriteTime; + lpFindFileDataW->nFileSizeHigh = lpFindFileDataA->nFileSizeHigh; + lpFindFileDataW->nFileSizeLow = lpFindFileDataA->nFileSizeLow; + lpFindFileDataW->dwReserved0 = lpFindFileDataA->dwReserved0; + lpFindFileDataW->dwReserved1 = lpFindFileDataA->dwReserved1; + + if (ConvertUtf8NToWChar(lpFindFileDataA->cFileName, ARRAYSIZE(lpFindFileDataA->cFileName), + lpFindFileDataW->cFileName, ARRAYSIZE(lpFindFileDataW->cFileName)) < 0) + return FALSE; + + return ConvertUtf8NToWChar(lpFindFileDataA->cAlternateFileName, + ARRAYSIZE(lpFindFileDataA->cAlternateFileName), + lpFindFileDataW->cAlternateFileName, + ARRAYSIZE(lpFindFileDataW->cAlternateFileName)) >= 0; +} + +HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData) +{ + LPSTR utfFileName = NULL; + HANDLE h = NULL; + if (!lpFileName) + return FALSE; + LPWIN32_FIND_DATAA fd = (LPWIN32_FIND_DATAA)calloc(1, sizeof(WIN32_FIND_DATAA)); + + if (!fd) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return INVALID_HANDLE_VALUE; + } + + utfFileName = ConvertWCharToUtf8Alloc(lpFileName, NULL); + if (!utfFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + free(fd); + return INVALID_HANDLE_VALUE; + } + + h = FindFirstFileA(utfFileName, fd); + free(utfFileName); + + if (h != INVALID_HANDLE_VALUE) + { + if (!ConvertFindDataAToW(fd, lpFindFileData)) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + FindClose(h); + h = INVALID_HANDLE_VALUE; + goto out; + } + } + +out: + free(fd); + return h; +} + +HANDLE FindFirstFileExA(LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, LPVOID lpFindFileData, + FINDEX_SEARCH_OPS fSearchOp, LPVOID lpSearchFilter, DWORD dwAdditionalFlags) +{ + return INVALID_HANDLE_VALUE; +} + +HANDLE FindFirstFileExW(LPCWSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, LPVOID lpFindFileData, + FINDEX_SEARCH_OPS fSearchOp, LPVOID lpSearchFilter, DWORD dwAdditionalFlags) +{ + return INVALID_HANDLE_VALUE; +} + +BOOL FindNextFileA(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData) +{ + if (!lpFindFileData) + return FALSE; + + const WIN32_FIND_DATAA empty = { 0 }; + *lpFindFileData = empty; + + if (!is_valid_file_search_handle(hFindFile)) + return FALSE; + + WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)hFindFile; + struct dirent* pDirent = NULL; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + while ((pDirent = readdir(pFileSearch->pDir)) != NULL) + { + if (FilePatternMatchA(pDirent->d_name, pFileSearch->lpPattern)) + { + BOOL success = FALSE; + + strncpy(lpFindFileData->cFileName, pDirent->d_name, MAX_PATH); + const size_t namelen = strnlen(lpFindFileData->cFileName, MAX_PATH); + size_t pathlen = strlen(pFileSearch->lpPath); + char* fullpath = (char*)malloc(pathlen + namelen + 2); + + if (fullpath == NULL) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + memcpy(fullpath, pFileSearch->lpPath, pathlen); + /* Ensure path is terminated with a separator, but prevent + * duplicate separators */ + if (fullpath[pathlen - 1] != '/') + fullpath[pathlen++] = '/'; + memcpy(fullpath + pathlen, pDirent->d_name, namelen); + fullpath[pathlen + namelen] = 0; + + struct stat fileStat = { 0 }; + if (stat(fullpath, &fileStat) != 0) + { + free(fullpath); + SetLastError(map_posix_err(errno)); + errno = 0; + continue; + } + + /* Skip FIFO entries. */ + if (S_ISFIFO(fileStat.st_mode)) + { + free(fullpath); + continue; + } + + success = FindDataFromStat(fullpath, &fileStat, lpFindFileData); + free(fullpath); + return success; + } + } + + SetLastError(ERROR_NO_MORE_FILES); + return FALSE; +} + +BOOL FindNextFileW(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData) +{ + LPWIN32_FIND_DATAA fd = (LPWIN32_FIND_DATAA)calloc(1, sizeof(WIN32_FIND_DATAA)); + + if (!fd) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + if (FindNextFileA(hFindFile, fd)) + { + if (!ConvertFindDataAToW(fd, lpFindFileData)) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + free(fd); + return FALSE; + } + + free(fd); + return TRUE; + } + + free(fd); + return FALSE; +} + +BOOL FindClose(HANDLE hFindFile) +{ + WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)hFindFile; + if (!pFileSearch) + return FALSE; + + /* Since INVALID_HANDLE_VALUE != NULL the analyzer guesses that there + * is a initialized HANDLE that is not freed properly. + * Disable this return to stop confusing the analyzer. */ +#ifndef __clang_analyzer__ + if (!is_valid_file_search_handle(hFindFile)) + return FALSE; +#endif + + free(pFileSearch->lpPath); + free(pFileSearch->lpPattern); + + if (pFileSearch->pDir) + closedir(pFileSearch->pDir); + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + free(pFileSearch); + return TRUE; +} + +BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) +{ + if (!mkdir(lpPathName, S_IRUSR | S_IWUSR | S_IXUSR)) + return TRUE; + + return FALSE; +} + +BOOL CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) +{ + if (!lpPathName) + return FALSE; + char* utfPathName = ConvertWCharToUtf8Alloc(lpPathName, NULL); + BOOL ret = FALSE; + + if (!utfPathName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + goto fail; + } + + ret = CreateDirectoryA(utfPathName, lpSecurityAttributes); +fail: + free(utfPathName); + return ret; +} + +BOOL RemoveDirectoryA(LPCSTR lpPathName) +{ + int ret = rmdir(lpPathName); + + if (ret != 0) + SetLastError(map_posix_err(errno)); + else + SetLastError(STATUS_SUCCESS); + + return ret == 0; +} + +BOOL RemoveDirectoryW(LPCWSTR lpPathName) +{ + if (!lpPathName) + return FALSE; + char* utfPathName = ConvertWCharToUtf8Alloc(lpPathName, NULL); + BOOL ret = FALSE; + + if (!utfPathName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + goto fail; + } + + ret = RemoveDirectoryA(utfPathName); +fail: + free(utfPathName); + return ret; +} + +BOOL MoveFileExA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags) +{ + struct stat st; + int ret = 0; + ret = stat(lpNewFileName, &st); + + if ((dwFlags & MOVEFILE_REPLACE_EXISTING) == 0) + { + if (ret == 0) + { + SetLastError(ERROR_ALREADY_EXISTS); + return FALSE; + } + } + else + { + if (ret == 0 && (st.st_mode & S_IWUSR) == 0) + { + SetLastError(ERROR_ACCESS_DENIED); + return FALSE; + } + } + + ret = rename(lpExistingFileName, lpNewFileName); + + if (ret != 0) + SetLastError(map_posix_err(errno)); + + return ret == 0; +} + +BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags) +{ + if (!lpExistingFileName || !lpNewFileName) + return FALSE; + + LPSTR lpCExistingFileName = ConvertWCharToUtf8Alloc(lpExistingFileName, NULL); + LPSTR lpCNewFileName = ConvertWCharToUtf8Alloc(lpNewFileName, NULL); + BOOL ret = FALSE; + + if (!lpCExistingFileName || !lpCNewFileName) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + goto fail; + } + + ret = MoveFileExA(lpCExistingFileName, lpCNewFileName, dwFlags); +fail: + free(lpCNewFileName); + free(lpCExistingFileName); + return ret; +} + +BOOL MoveFileA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName) +{ + return MoveFileExA(lpExistingFileName, lpNewFileName, 0); +} + +BOOL MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName) +{ + return MoveFileExW(lpExistingFileName, lpNewFileName, 0); +} + +#endif + +/* Extended API */ + +int UnixChangeFileMode(const char* filename, int flags) +{ + if (!filename) + return -1; +#ifndef _WIN32 + mode_t fl = 0; + fl |= (flags & 0x4000) ? S_ISUID : 0; + fl |= (flags & 0x2000) ? S_ISGID : 0; + fl |= (flags & 0x1000) ? S_ISVTX : 0; + fl |= (flags & 0x0400) ? S_IRUSR : 0; + fl |= (flags & 0x0200) ? S_IWUSR : 0; + fl |= (flags & 0x0100) ? S_IXUSR : 0; + fl |= (flags & 0x0040) ? S_IRGRP : 0; + fl |= (flags & 0x0020) ? S_IWGRP : 0; + fl |= (flags & 0x0010) ? S_IXGRP : 0; + fl |= (flags & 0x0004) ? S_IROTH : 0; + fl |= (flags & 0x0002) ? S_IWOTH : 0; + fl |= (flags & 0x0001) ? S_IXOTH : 0; + return chmod(filename, fl); +#else + int rc; + WCHAR* wfl = ConvertUtf8ToWCharAlloc(filename, NULL); + + if (!wfl) + return -1; + + /* Check for unsupported flags. */ + if (flags & ~(_S_IREAD | _S_IWRITE)) + WLog_WARN(TAG, "Unsupported file mode %d for _wchmod", flags); + + rc = _wchmod(wfl, flags); + free(wfl); + return rc; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.c new file mode 100644 index 0000000000000000000000000000000000000000..ad83589fd1d636e686ebeedb067218ae7f9a20ba --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.c @@ -0,0 +1,293 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Hewlett-Packard Development Company, L.P. + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 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. + */ + +#include + +#include +#include +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include "../log.h" +#define TAG WINPR_TAG("file") + +#ifndef _WIN32 + +#ifdef ANDROID +#include +#else +#include +#endif + +#include "../handle/handle.h" + +#include "../pipe/pipe.h" +#include "namedPipeClient.h" + +static BOOL NamedPipeClientIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_NAMED_PIPE, TRUE); +} + +static BOOL NamedPipeClientCloseHandle(HANDLE handle) +{ + WINPR_NAMED_PIPE* pNamedPipe = (WINPR_NAMED_PIPE*)handle; + + if (!NamedPipeClientIsHandled(handle)) + return FALSE; + + if (pNamedPipe->clientfd != -1) + { + // WLOG_DBG(TAG, "closing clientfd %d", pNamedPipe->clientfd); + close(pNamedPipe->clientfd); + } + + if (pNamedPipe->serverfd != -1) + { + // WLOG_DBG(TAG, "closing serverfd %d", pNamedPipe->serverfd); + close(pNamedPipe->serverfd); + } + + if (pNamedPipe->pfnUnrefNamedPipe) + pNamedPipe->pfnUnrefNamedPipe(pNamedPipe); + + free(pNamedPipe->lpFileName); + free(pNamedPipe->lpFilePath); + free(pNamedPipe->name); + free(pNamedPipe); + return TRUE; +} + +static int NamedPipeClientGetFd(HANDLE handle) +{ + WINPR_NAMED_PIPE* file = (WINPR_NAMED_PIPE*)handle; + + if (!NamedPipeClientIsHandled(handle)) + return -1; + + if (file->ServerMode) + return file->serverfd; + else + return file->clientfd; +} + +static HANDLE_OPS ops = { + NamedPipeClientIsHandled, + NamedPipeClientCloseHandle, + NamedPipeClientGetFd, + NULL, /* CleanupHandle */ + NamedPipeRead, + NULL, /* FileReadEx */ + NULL, /* FileReadScatter */ + NamedPipeWrite, + NULL, /* FileWriteEx */ + NULL, /* FileWriteGather */ + NULL, /* FileGetFileSize */ + NULL, /* FlushFileBuffers */ + NULL, /* FileSetEndOfFile */ + NULL, /* FileSetFilePointer */ + NULL, /* SetFilePointerEx */ + NULL, /* FileLockFile */ + NULL, /* FileLockFileEx */ + NULL, /* FileUnlockFile */ + NULL, /* FileUnlockFileEx */ + NULL, /* SetFileTime */ + NULL, /* FileGetFileInformationByHandle */ +}; + +static HANDLE NamedPipeClientCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, + DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) +{ + int status = 0; + struct sockaddr_un s = { 0 }; + + if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED) + { + WLog_ERR(TAG, "WinPR does not support the FILE_FLAG_OVERLAPPED flag"); + SetLastError(ERROR_NOT_SUPPORTED); + return INVALID_HANDLE_VALUE; + } + + if (!lpFileName) + return INVALID_HANDLE_VALUE; + + if (!IsNamedPipeFileNameA(lpFileName)) + return INVALID_HANDLE_VALUE; + + WINPR_NAMED_PIPE* pNamedPipe = (WINPR_NAMED_PIPE*)calloc(1, sizeof(WINPR_NAMED_PIPE)); + + if (!pNamedPipe) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return INVALID_HANDLE_VALUE; + } + + HANDLE hNamedPipe = (HANDLE)pNamedPipe; + WINPR_HANDLE_SET_TYPE_AND_MODE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE, WINPR_FD_READ); + pNamedPipe->name = _strdup(lpFileName); + + if (!pNamedPipe->name) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + goto fail; + } + + pNamedPipe->dwOpenMode = 0; + pNamedPipe->dwPipeMode = 0; + pNamedPipe->nMaxInstances = 0; + pNamedPipe->nOutBufferSize = 0; + pNamedPipe->nInBufferSize = 0; + pNamedPipe->nDefaultTimeOut = 0; + pNamedPipe->dwFlagsAndAttributes = dwFlagsAndAttributes; + pNamedPipe->lpFileName = GetNamedPipeNameWithoutPrefixA(lpFileName); + + if (!pNamedPipe->lpFileName) + goto fail; + + pNamedPipe->lpFilePath = GetNamedPipeUnixDomainSocketFilePathA(lpFileName); + + if (!pNamedPipe->lpFilePath) + goto fail; + + pNamedPipe->clientfd = socket(PF_LOCAL, SOCK_STREAM, 0); + if (pNamedPipe->clientfd < 0) + goto fail; + + pNamedPipe->serverfd = -1; + pNamedPipe->ServerMode = FALSE; + s.sun_family = AF_UNIX; + (void)sprintf_s(s.sun_path, ARRAYSIZE(s.sun_path), "%s", pNamedPipe->lpFilePath); + status = connect(pNamedPipe->clientfd, (struct sockaddr*)&s, sizeof(struct sockaddr_un)); + pNamedPipe->common.ops = &ops; + + if (status != 0) + goto fail; + + if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED) + { +#if 0 + int flags = fcntl(pNamedPipe->clientfd, F_GETFL); + + if (flags != -1) + (void)fcntl(pNamedPipe->clientfd, F_SETFL, flags | O_NONBLOCK); + +#endif + } + + return hNamedPipe; + +fail: + if (pNamedPipe) + { + if (pNamedPipe->clientfd >= 0) + close(pNamedPipe->clientfd); + free(pNamedPipe->name); + free(pNamedPipe->lpFileName); + free(pNamedPipe->lpFilePath); + free(pNamedPipe); + } + return INVALID_HANDLE_VALUE; +} + +const HANDLE_CREATOR* GetNamedPipeClientHandleCreator(void) +{ + static const HANDLE_CREATOR NamedPipeClientHandleCreator = { .IsHandled = IsNamedPipeFileNameA, + .CreateFileA = + NamedPipeClientCreateFileA }; + return &NamedPipeClientHandleCreator; +} + +#endif + +/* Extended API */ + +#define NAMED_PIPE_PREFIX_PATH "\\\\.\\pipe\\" + +BOOL IsNamedPipeFileNameA(LPCSTR lpName) +{ + if (strncmp(lpName, NAMED_PIPE_PREFIX_PATH, sizeof(NAMED_PIPE_PREFIX_PATH) - 1) != 0) + return FALSE; + + return TRUE; +} + +char* GetNamedPipeNameWithoutPrefixA(LPCSTR lpName) +{ + char* lpFileName = NULL; + + if (!lpName) + return NULL; + + if (!IsNamedPipeFileNameA(lpName)) + return NULL; + + lpFileName = _strdup(&lpName[strnlen(NAMED_PIPE_PREFIX_PATH, sizeof(NAMED_PIPE_PREFIX_PATH))]); + return lpFileName; +} + +char* GetNamedPipeUnixDomainSocketBaseFilePathA(void) +{ + char* lpTempPath = NULL; + char* lpPipePath = NULL; + lpTempPath = GetKnownPath(KNOWN_PATH_TEMP); + + if (!lpTempPath) + return NULL; + + lpPipePath = GetCombinedPath(lpTempPath, ".pipe"); + free(lpTempPath); + return lpPipePath; +} + +char* GetNamedPipeUnixDomainSocketFilePathA(LPCSTR lpName) +{ + char* lpPipePath = NULL; + char* lpFileName = NULL; + char* lpFilePath = NULL; + lpPipePath = GetNamedPipeUnixDomainSocketBaseFilePathA(); + lpFileName = GetNamedPipeNameWithoutPrefixA(lpName); + lpFilePath = GetCombinedPath(lpPipePath, lpFileName); + free(lpPipePath); + free(lpFileName); + return lpFilePath; +} + +int GetNamePipeFileDescriptor(HANDLE hNamedPipe) +{ +#ifndef _WIN32 + int fd = 0; + WINPR_NAMED_PIPE* pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; + + if (!NamedPipeClientIsHandled(hNamedPipe)) + return -1; + + fd = (pNamedPipe->ServerMode) ? pNamedPipe->serverfd : pNamedPipe->clientfd; + return fd; +#else + return -1; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.h new file mode 100644 index 0000000000000000000000000000000000000000..a01b62c2cb8f9376b0ac60db5f0362d245276341 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/namedPipeClient.h @@ -0,0 +1,25 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2024 Armin Novak + * 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 + +extern const HANDLE_CREATOR* GetNamedPipeClientHandleCreator(void); diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/pattern.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/pattern.c new file mode 100644 index 0000000000000000000000000000000000000000..cb4d61806fcba9ba76294b7559c69846616fc584 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/pattern.c @@ -0,0 +1,373 @@ +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifdef WINPR_HAVE_FCNTL_H +#include +#endif + +#include "../log.h" +#define TAG WINPR_TAG("file") + +/** + * File System Behavior in the Microsoft Windows Environment: + * http://download.microsoft.com/download/4/3/8/43889780-8d45-4b2e-9d3a-c696a890309f/File%20System%20Behavior%20Overview.pdf + */ + +LPSTR FilePatternFindNextWildcardA(LPCSTR lpPattern, DWORD* pFlags) +{ + LPSTR lpWildcard = NULL; + *pFlags = 0; + lpWildcard = strpbrk(lpPattern, "*?~"); + + if (lpWildcard) + { + if (*lpWildcard == '*') + { + *pFlags = WILDCARD_STAR; + return lpWildcard; + } + else if (*lpWildcard == '?') + { + *pFlags = WILDCARD_QM; + return lpWildcard; + } + else if (*lpWildcard == '~') + { + if (lpWildcard[1] == '*') + { + *pFlags = WILDCARD_DOS_STAR; + return lpWildcard; + } + else if (lpWildcard[1] == '?') + { + *pFlags = WILDCARD_DOS_QM; + return lpWildcard; + } + else if (lpWildcard[1] == '.') + { + *pFlags = WILDCARD_DOS_DOT; + return lpWildcard; + } + } + } + + return NULL; +} + +static BOOL FilePatternMatchSubExpressionA(LPCSTR lpFileName, size_t cchFileName, LPCSTR lpX, + size_t cchX, LPCSTR lpY, size_t cchY, LPCSTR lpWildcard, + LPCSTR* ppMatchEnd) +{ + LPCSTR lpMatch = NULL; + + if (!lpFileName) + return FALSE; + + if (*lpWildcard == '*') + { + /* + * S + * <-----< + * X | | e Y + * X * Y == (0)----->-(1)->-----(2)-----(3) + */ + + /* + * State 0: match 'X' + */ + if (_strnicmp(lpFileName, lpX, cchX) != 0) + return FALSE; + + /* + * State 1: match 'S' or 'e' + * + * We use 'e' to transition to state 2 + */ + + /** + * State 2: match Y + */ + + if (cchY != 0) + { + /* TODO: case insensitive character search */ + lpMatch = strchr(&lpFileName[cchX], *lpY); + + if (!lpMatch) + return FALSE; + + if (_strnicmp(lpMatch, lpY, cchY) != 0) + return FALSE; + } + else + { + lpMatch = &lpFileName[cchFileName]; + } + + /** + * State 3: final state + */ + *ppMatchEnd = &lpMatch[cchY]; + return TRUE; + } + else if (*lpWildcard == '?') + { + /** + * X S Y + * X ? Y == (0)---(1)---(2)---(3) + */ + + /* + * State 0: match 'X' + */ + if (cchFileName < cchX) + return FALSE; + + if (_strnicmp(lpFileName, lpX, cchX) != 0) + return FALSE; + + /* + * State 1: match 'S' + */ + + /** + * State 2: match Y + */ + + if (cchY != 0) + { + /* TODO: case insensitive character search */ + lpMatch = strchr(&lpFileName[cchX + 1], *lpY); + + if (!lpMatch) + return FALSE; + + if (_strnicmp(lpMatch, lpY, cchY) != 0) + return FALSE; + } + else + { + if ((cchX + 1) > cchFileName) + return FALSE; + + lpMatch = &lpFileName[cchX + 1]; + } + + /** + * State 3: final state + */ + *ppMatchEnd = &lpMatch[cchY]; + return TRUE; + } + else if (*lpWildcard == '~') + { + WLog_ERR(TAG, "warning: unimplemented '~' pattern match"); + return TRUE; + } + + return FALSE; +} + +BOOL FilePatternMatchA(LPCSTR lpFileName, LPCSTR lpPattern) +{ + BOOL match = 0; + LPCSTR lpTail = NULL; + size_t cchTail = 0; + size_t cchPattern = 0; + size_t cchFileName = 0; + DWORD dwFlags = 0; + DWORD dwNextFlags = 0; + LPSTR lpWildcard = NULL; + LPSTR lpNextWildcard = NULL; + + /** + * Wild Card Matching + * + * '*' matches 0 or more characters + * '?' matches exactly one character + * + * '~*' DOS_STAR - matches 0 or more characters until encountering and matching final '.' + * + * '~?' DOS_QM - matches any single character, or upon encountering a period or end of name + * string, advances the expression to the end of the set of contiguous DOS_QMs. + * + * '~.' DOS_DOT - matches either a '.' or zero characters beyond name string. + */ + + if (!lpPattern) + return FALSE; + + if (!lpFileName) + return FALSE; + + cchPattern = strlen(lpPattern); + cchFileName = strlen(lpFileName); + + /** + * First and foremost the file system starts off name matching with the expression “*”. + * If the expression contains a single wild card character ‘*’ all matches are satisfied + * immediately. This is the most common wild card character used in Windows and expression + * evaluation is optimized by looking for this character first. + */ + + if ((lpPattern[0] == '*') && (cchPattern == 1)) + return TRUE; + + /** + * Subsequently evaluation of the “*X” expression is performed. This is a case where + * the expression starts off with a wild card character and contains some non-wild card + * characters towards the tail end of the name. This is evaluated by making sure the + * expression starts off with the character ‘*’ and does not contain any wildcards in + * the latter part of the expression. The tail part of the expression beyond the first + * character ‘*’ is matched against the file name at the end uppercasing each character + * if necessary during the comparison. + */ + + if (lpPattern[0] == '*') + { + lpTail = &lpPattern[1]; + cchTail = strlen(lpTail); + + if (!FilePatternFindNextWildcardA(lpTail, &dwFlags)) + { + /* tail contains no wildcards */ + if (cchFileName < cchTail) + return FALSE; + + if (_stricmp(&lpFileName[cchFileName - cchTail], lpTail) == 0) + return TRUE; + + return FALSE; + } + } + + /** + * The remaining expressions are evaluated in a non deterministic + * finite order as listed below, where: + * + * 'S' is any single character + * 'S-.' is any single character except the final '.' + * 'e' is a null character transition + * 'EOF' is the end of the name string + * + * S + * <-----< + * X | | e Y + * X * Y == (0)----->-(1)->-----(2)-----(3) + * + * + * S-. + * <-----< + * X | | e Y + * X ~* Y == (0)----->-(1)->-----(2)-----(3) + * + * + * X S S Y + * X ?? Y == (0)---(1)---(2)---(3)---(4) + * + * + * X S-. S-. Y + * X ~?~? == (0)---(1)-----(2)-----(3)---(4) + * | |_______| + * | ^ | + * |_______________| + * ^EOF of .^ + * + */ + lpWildcard = FilePatternFindNextWildcardA(lpPattern, &dwFlags); + + if (lpWildcard) + { + LPCSTR lpX = NULL; + LPCSTR lpY = NULL; + size_t cchX = 0; + size_t cchY = 0; + LPCSTR lpMatchEnd = NULL; + LPCSTR lpSubPattern = NULL; + size_t cchSubPattern = 0; + LPCSTR lpSubFileName = NULL; + size_t cchSubFileName = 0; + size_t cchWildcard = 0; + size_t cchNextWildcard = 0; + cchSubPattern = cchPattern; + lpSubPattern = lpPattern; + cchSubFileName = cchFileName; + lpSubFileName = lpFileName; + cchWildcard = ((dwFlags & WILDCARD_DOS) ? 2 : 1); + lpNextWildcard = FilePatternFindNextWildcardA(&lpWildcard[cchWildcard], &dwNextFlags); + + if (!lpNextWildcard) + { + lpX = lpSubPattern; + cchX = WINPR_ASSERTING_INT_CAST(size_t, (lpWildcard - lpSubPattern)); + lpY = &lpSubPattern[cchX + cchWildcard]; + cchY = (cchSubPattern - WINPR_ASSERTING_INT_CAST(size_t, (lpY - lpSubPattern))); + match = FilePatternMatchSubExpressionA(lpSubFileName, cchSubFileName, lpX, cchX, lpY, + cchY, lpWildcard, &lpMatchEnd); + return match; + } + else + { + while (lpNextWildcard) + { + cchSubFileName = + cchFileName - WINPR_ASSERTING_INT_CAST(size_t, (lpSubFileName - lpFileName)); + cchNextWildcard = ((dwNextFlags & WILDCARD_DOS) ? 2 : 1); + lpX = lpSubPattern; + cchX = WINPR_ASSERTING_INT_CAST(size_t, (lpWildcard - lpSubPattern)); + lpY = &lpSubPattern[cchX + cchWildcard]; + cchY = + WINPR_ASSERTING_INT_CAST(size_t, (lpNextWildcard - lpWildcard)) - cchWildcard; + match = FilePatternMatchSubExpressionA(lpSubFileName, cchSubFileName, lpX, cchX, + lpY, cchY, lpWildcard, &lpMatchEnd); + + if (!match) + return FALSE; + + lpSubFileName = lpMatchEnd; + cchWildcard = cchNextWildcard; + lpWildcard = lpNextWildcard; + dwFlags = dwNextFlags; + lpNextWildcard = + FilePatternFindNextWildcardA(&lpWildcard[cchWildcard], &dwNextFlags); + } + + return TRUE; + } + } + else + { + /* no wildcard characters */ + if (_stricmp(lpFileName, lpPattern) == 0) + return TRUE; + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d72f70fd22c84329cf0784bbe2f9e2c37b14a7d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/CMakeLists.txt @@ -0,0 +1,57 @@ +if(NOT WIN32) + set(MODULE_NAME "TestFile") + set(MODULE_PREFIX "TEST_FILE") + + disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + + set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + + set(${MODULE_PREFIX}_TESTS + TestFileCreateFile.c + TestFileDeleteFile.c + TestFileReadFile.c + TestSetFileAttributes.c + TestFileWriteFile.c + TestFilePatternMatch.c + TestFileFindFirstFile.c + TestFileFindFirstFileEx.c + TestFileFindNextFile.c + TestFileGetStdHandle.c + ) + + create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + + add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + + target_link_libraries(${MODULE_NAME} winpr) + + set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + + if(NOT MSVC) + set(TEST_AREA "${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME}Area") + else() + set(TEST_AREA "${TESTING_OUTPUT_DIRECTORY}/${CMAKE_BUILD_TYPE}/${MODULE_NAME}Area") + endif() + + file(MAKE_DIRECTORY "${TEST_AREA}") + file(WRITE "${TEST_AREA}/TestFile1" "TestFile1") + file(WRITE "${TEST_AREA}/TestFile2" "TestFile2") + file(WRITE "${TEST_AREA}/TestFile3" "TestFile3") + file(MAKE_DIRECTORY "${TEST_AREA}/TestDirectory1") + file(WRITE "${TEST_AREA}/TestDirectory1/TestDirectory1File1" "TestDirectory1File1") + file(MAKE_DIRECTORY "${TEST_AREA}/TestDirectory2") + file(WRITE "${TEST_AREA}/TestDirectory2/TestDirectory2File1" "TestDirectory2File1") + file(WRITE "${TEST_AREA}/TestDirectory2/TestDirectory2File2" "TestDirectory2File2") + file(MAKE_DIRECTORY "${TEST_AREA}/TestDirectory3") + file(WRITE "${TEST_AREA}/TestDirectory3/TestDirectory3File1" "TestDirectory3File1") + file(WRITE "${TEST_AREA}/TestDirectory3/TestDirectory3File2" "TestDirectory3File2") + file(WRITE "${TEST_AREA}/TestDirectory3/TestDirectory3File3" "TestDirectory3File3") + + foreach(test ${${MODULE_PREFIX}_TESTS}) + get_filename_component(TestName ${test} NAME_WE) + add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName} ${TEST_AREA}) + endforeach() + + set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test") + +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileCreateFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileCreateFile.c new file mode 100644 index 0000000000000000000000000000000000000000..0e62891116462fa476c496ad115456e894746660 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileCreateFile.c @@ -0,0 +1,94 @@ + +#include +#include +#include +#include +#include +#include +#include + +int TestFileCreateFile(int argc, char* argv[]) +{ + HANDLE handle = NULL; + HRESULT hr = 0; + DWORD written = 0; + const char buffer[] = "Some random text\r\njust want it done."; + char cmp[sizeof(buffer)]; + char sname[8192]; + LPSTR name = NULL; + int rc = 0; + SYSTEMTIME systemTime; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + GetSystemTime(&systemTime); + (void)sprintf_s(sname, sizeof(sname), + "CreateFile-%04" PRIu16 "%02" PRIu16 "%02" PRIu16 "%02" PRIu16 "%02" PRIu16 + "%02" PRIu16 "%04" PRIu16, + systemTime.wYear, systemTime.wMonth, systemTime.wDay, systemTime.wHour, + systemTime.wMinute, systemTime.wSecond, systemTime.wMilliseconds); + name = GetKnownSubPath(KNOWN_PATH_TEMP, sname); + + if (!name) + return -1; + + /* On windows we would need '\\' or '/' as separator. + * Single '\' do not work. */ + hr = PathCchConvertStyleA(name, strlen(name), PATH_STYLE_UNIX); + + if (FAILED(hr)) + rc = -1; + + handle = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, NULL); + + if (!handle) + { + free(name); + return -1; + } + + if (!winpr_PathFileExists(name)) + rc = -1; + + if (!WriteFile(handle, buffer, sizeof(buffer), &written, NULL)) + rc = -1; + + if (written != sizeof(buffer)) + rc = -1; + + written = SetFilePointer(handle, 5, NULL, FILE_BEGIN); + + if (written != 5) + rc = -1; + + written = SetFilePointer(handle, 0, NULL, FILE_CURRENT); + + if (written != 5) + rc = -1; + + written = SetFilePointer(handle, -5, NULL, FILE_CURRENT); + + if (written != 0) + rc = -1; + + if (!ReadFile(handle, cmp, sizeof(cmp), &written, NULL)) + rc = -1; + + if (written != sizeof(cmp)) + rc = -1; + + if (memcmp(buffer, cmp, sizeof(buffer)) != 0) + rc = -1; + + if (!CloseHandle(handle)) + rc = -1; + + if (!winpr_DeleteFile(name)) + rc = -1; + + if (winpr_PathFileExists(name)) + rc = -1; + + free(name); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileDeleteFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileDeleteFile.c new file mode 100644 index 0000000000000000000000000000000000000000..50069313365668c55139d5b9b9c339013cf9f780 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileDeleteFile.c @@ -0,0 +1,50 @@ + +#include +#include +#include +#include +#include + +int TestFileDeleteFile(int argc, char* argv[]) +{ + BOOL rc = FALSE; + int fd = 0; + char validA[] = "/tmp/valid-test-file-XXXXXX"; + char validW[] = "/tmp/valid-test-file-XXXXXX"; + WCHAR* validWW = NULL; + const char invalidA[] = "/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + WCHAR invalidW[sizeof(invalidA)] = { 0 }; + + (void)ConvertUtf8NToWChar(invalidA, ARRAYSIZE(invalidA), invalidW, ARRAYSIZE(invalidW)); + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + rc = DeleteFileA(invalidA); + if (rc) + return -1; + + rc = DeleteFileW(invalidW); + if (rc) + return -1; + + fd = mkstemp(validA); + if (fd < 0) + return -1; + + rc = DeleteFileA(validA); + if (!rc) + return -1; + + fd = mkstemp(validW); + if (fd < 0) + return -1; + + validWW = ConvertUtf8NToWCharAlloc(validW, ARRAYSIZE(validW), NULL); + if (validWW) + rc = DeleteFileW(validWW); + free(validWW); + if (!rc) + return -1; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFile.c new file mode 100644 index 0000000000000000000000000000000000000000..2be310853c32e4465e190e60074f8c47f8d8f296 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFile.c @@ -0,0 +1,327 @@ + +#include +#include +#include +#include +#include +#include +#include +#include + +static const CHAR testFile1A[] = "TestFile1A"; + +static BOOL create_layout_files(size_t level, const char* BasePath, wArrayList* files) +{ + for (size_t x = 0; x < 10; x++) + { + CHAR FilePath[PATHCCH_MAX_CCH] = { 0 }; + strncpy(FilePath, BasePath, ARRAYSIZE(FilePath)); + + CHAR name[64] = { 0 }; + (void)_snprintf(name, ARRAYSIZE(name), "%zd-TestFile%zd", level, x); + NativePathCchAppendA(FilePath, PATHCCH_MAX_CCH, name); + + HANDLE hdl = + CreateFileA(FilePath, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hdl == INVALID_HANDLE_VALUE) + return FALSE; + ArrayList_Append(files, FilePath); + (void)CloseHandle(hdl); + } + return TRUE; +} + +static BOOL create_layout_directories(size_t level, size_t max_level, const char* BasePath, + wArrayList* files) +{ + if (level >= max_level) + return TRUE; + + CHAR FilePath[PATHCCH_MAX_CCH] = { 0 }; + strncpy(FilePath, BasePath, ARRAYSIZE(FilePath)); + PathCchConvertStyleA(FilePath, ARRAYSIZE(FilePath), PATH_STYLE_NATIVE); + if (!winpr_PathMakePath(FilePath, NULL)) + return FALSE; + ArrayList_Append(files, FilePath); + + if (!create_layout_files(level + 1, BasePath, files)) + return FALSE; + + for (size_t x = 0; x < 10; x++) + { + CHAR CurFilePath[PATHCCH_MAX_CCH] = { 0 }; + strncpy(CurFilePath, FilePath, ARRAYSIZE(CurFilePath)); + + PathCchConvertStyleA(CurFilePath, ARRAYSIZE(CurFilePath), PATH_STYLE_NATIVE); + + CHAR name[64] = { 0 }; + (void)_snprintf(name, ARRAYSIZE(name), "%zd-TestPath%zd", level, x); + NativePathCchAppendA(CurFilePath, PATHCCH_MAX_CCH, name); + + if (!create_layout_directories(level + 1, max_level, CurFilePath, files)) + return FALSE; + } + return TRUE; +} + +static BOOL create_layout(const char* BasePath, wArrayList* files) +{ + CHAR BasePathNative[PATHCCH_MAX_CCH] = { 0 }; + memcpy(BasePathNative, BasePath, sizeof(BasePathNative)); + PathCchConvertStyleA(BasePathNative, ARRAYSIZE(BasePathNative), PATH_STYLE_NATIVE); + + return create_layout_directories(0, 3, BasePathNative, files); +} + +static void cleanup_layout(const char* BasePath) +{ + winpr_RemoveDirectory_RecursiveA(BasePath); +} + +static BOOL find_first_file_success(const char* FilePath) +{ + BOOL rc = FALSE; + WIN32_FIND_DATAA FindData = { 0 }; + HANDLE hFind = FindFirstFileA(FilePath, &FindData); + if (hFind == INVALID_HANDLE_VALUE) + { + printf("FindFirstFile failure: %s (INVALID_HANDLE_VALUE -1)\n", FilePath); + goto fail; + } + + printf("FindFirstFile: %s", FindData.cFileName); + + if (strcmp(FindData.cFileName, testFile1A) != 0) + { + printf("FindFirstFile failure: Expected: %s, Actual: %s\n", testFile1A, FindData.cFileName); + goto fail; + } + rc = TRUE; +fail: + if (hFind != INVALID_HANDLE_VALUE) + FindClose(hFind); + return rc; +} + +static BOOL list_directory_dot(const char* BasePath, wArrayList* files) +{ + BOOL rc = FALSE; + CHAR BasePathDot[PATHCCH_MAX_CCH] = { 0 }; + memcpy(BasePathDot, BasePath, ARRAYSIZE(BasePathDot)); + PathCchConvertStyleA(BasePathDot, ARRAYSIZE(BasePathDot), PATH_STYLE_NATIVE); + NativePathCchAppendA(BasePathDot, PATHCCH_MAX_CCH, "."); + WIN32_FIND_DATAA FindData = { 0 }; + HANDLE hFind = FindFirstFileA(BasePathDot, &FindData); + if (hFind == INVALID_HANDLE_VALUE) + return FALSE; + size_t count = 0; + do + { + count++; + if (strcmp(FindData.cFileName, ".") != 0) + goto fail; + } while (FindNextFile(hFind, &FindData)); + + rc = TRUE; +fail: + FindClose(hFind); + + if (count != 1) + return FALSE; + return rc; +} + +static BOOL list_directory_star(const char* BasePath, wArrayList* files) +{ + CHAR BasePathDot[PATHCCH_MAX_CCH] = { 0 }; + memcpy(BasePathDot, BasePath, ARRAYSIZE(BasePathDot)); + PathCchConvertStyleA(BasePathDot, ARRAYSIZE(BasePathDot), PATH_STYLE_NATIVE); + NativePathCchAppendA(BasePathDot, PATHCCH_MAX_CCH, "*"); + WIN32_FIND_DATAA FindData = { 0 }; + HANDLE hFind = FindFirstFileA(BasePathDot, &FindData); + if (hFind == INVALID_HANDLE_VALUE) + return FALSE; + size_t count = 0; + size_t dotcount = 0; + size_t dotdotcount = 0; + do + { + if (strcmp(FindData.cFileName, ".") == 0) + dotcount++; + else if (strcmp(FindData.cFileName, "..") == 0) + dotdotcount++; + else + count++; + } while (FindNextFile(hFind, &FindData)); + FindClose(hFind); + + const char sep = PathGetSeparatorA(PATH_STYLE_NATIVE); + size_t fcount = 0; + const size_t baselen = strlen(BasePath); + const size_t total = ArrayList_Count(files); + for (size_t x = 0; x < total; x++) + { + const char* path = ArrayList_GetItem(files, x); + const size_t pathlen = strlen(path); + if (pathlen < baselen) + continue; + const char* skip = &path[baselen]; + if (*skip == sep) + skip++; + const char* end = strrchr(skip, sep); + if (end) + continue; + fcount++; + } + + if (fcount != count) + return FALSE; + return TRUE; +} + +static BOOL find_first_file_fail(const char* FilePath) +{ + WIN32_FIND_DATAA FindData = { 0 }; + HANDLE hFind = FindFirstFileA(FilePath, &FindData); + if (hFind == INVALID_HANDLE_VALUE) + return TRUE; + + FindClose(hFind); + return FALSE; +} + +static int TestFileFindFirstFileA(const char* str) +{ + int rc = -1; + if (!str) + return -1; + + CHAR BasePath[PATHCCH_MAX_CCH] = { 0 }; + + strncpy(BasePath, str, ARRAYSIZE(BasePath)); + + const size_t length = strnlen(BasePath, PATHCCH_MAX_CCH - 1); + + CHAR FilePath[PATHCCH_MAX_CCH] = { 0 }; + CopyMemory(FilePath, BasePath, length * sizeof(CHAR)); + + PathCchConvertStyleA(BasePath, length, PATH_STYLE_WINDOWS); + + wArrayList* files = ArrayList_New(FALSE); + if (!files) + return -3; + wObject* obj = ArrayList_Object(files); + obj->fnObjectFree = winpr_ObjectStringFree; + obj->fnObjectNew = winpr_ObjectStringClone; + + if (!create_layout(BasePath, files)) + goto fail; + + NativePathCchAppendA(FilePath, PATHCCH_MAX_CCH, testFile1A); + + printf("Finding file: %s\n", FilePath); + + if (!find_first_file_fail(FilePath)) + goto fail; + + HANDLE hdl = + CreateFileA(FilePath, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hdl == INVALID_HANDLE_VALUE) + goto fail; + (void)CloseHandle(hdl); + + if (!find_first_file_success(FilePath)) + goto fail; + + CHAR BasePathInvalid[PATHCCH_MAX_CCH] = { 0 }; + memcpy(BasePathInvalid, BasePath, ARRAYSIZE(BasePathInvalid)); + PathCchAddBackslashA(BasePathInvalid, PATHCCH_MAX_CCH); + + if (!find_first_file_fail(BasePathInvalid)) + goto fail; + + if (!list_directory_dot(BasePath, files)) + goto fail; + + if (!list_directory_star(BasePath, files)) + goto fail; + + rc = 0; +fail: + DeleteFileA(FilePath); + cleanup_layout(BasePath); + ArrayList_Free(files); + return rc; +} + +static int TestFileFindFirstFileW(const char* str) +{ + WCHAR buffer[32] = { 0 }; + const WCHAR* testFile1W = InitializeConstWCharFromUtf8("TestFile1W", buffer, ARRAYSIZE(buffer)); + int rc = -1; + if (!str) + return -1; + + WCHAR BasePath[PATHCCH_MAX_CCH] = { 0 }; + + (void)ConvertUtf8ToWChar(str, BasePath, ARRAYSIZE(BasePath)); + + const size_t length = _wcsnlen(BasePath, PATHCCH_MAX_CCH - 1); + + WCHAR FilePath[PATHCCH_MAX_CCH] = { 0 }; + CopyMemory(FilePath, BasePath, length * sizeof(WCHAR)); + + PathCchConvertStyleW(BasePath, length, PATH_STYLE_WINDOWS); + NativePathCchAppendW(FilePath, PATHCCH_MAX_CCH, testFile1W); + + CHAR FilePathA[PATHCCH_MAX_CCH] = { 0 }; + (void)ConvertWCharNToUtf8(FilePath, ARRAYSIZE(FilePath), FilePathA, ARRAYSIZE(FilePathA)); + printf("Finding file: %s\n", FilePathA); + + WIN32_FIND_DATAW FindData = { 0 }; + HANDLE hFind = FindFirstFileW(FilePath, &FindData); + + if (hFind == INVALID_HANDLE_VALUE) + { + printf("FindFirstFile failure: %s (INVALID_HANDLE_VALUE -1)\n", FilePathA); + goto fail; + } + + CHAR cFileName[MAX_PATH] = { 0 }; + (void)ConvertWCharNToUtf8(FindData.cFileName, ARRAYSIZE(FindData.cFileName), cFileName, + ARRAYSIZE(cFileName)); + + printf("FindFirstFile: %s", cFileName); + + if (_wcscmp(FindData.cFileName, testFile1W) != 0) + { + printf("FindFirstFile failure: Expected: %s, Actual: %s\n", testFile1A, cFileName); + goto fail; + } + + rc = 0; +fail: + DeleteFileW(FilePath); + FindClose(hFind); + return rc; +} + +int TestFileFindFirstFile(int argc, char* argv[]) +{ + char* str = GetKnownSubPath(KNOWN_PATH_TEMP, "TestFileFindFirstFile"); + if (!str) + return -23; + + cleanup_layout(str); + + int rc1 = -1; + int rc2 = -1; + if (winpr_PathMakePath(str, NULL)) + { + rc1 = TestFileFindFirstFileA(str); + rc2 = 0; // TestFileFindFirstFileW(str); + winpr_RemoveDirectory(str); + } + free(str); + return rc1 + rc2; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFileEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFileEx.c new file mode 100644 index 0000000000000000000000000000000000000000..b8a7683d41f9938e03f4ad91321785d83bac4103 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindFirstFileEx.c @@ -0,0 +1,10 @@ + +#include +#include +#include +#include + +int TestFileFindFirstFileEx(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindNextFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindNextFile.c new file mode 100644 index 0000000000000000000000000000000000000000..c1d2c1b6d5c8235b41e3a982220df91d0d3cfc31 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileFindNextFile.c @@ -0,0 +1,99 @@ + +#include +#include +#include +#include +#include +#include + +static TCHAR testDirectory2File1[] = _T("TestDirectory2File1"); +static TCHAR testDirectory2File2[] = _T("TestDirectory2File2"); + +int TestFileFindNextFile(int argc, char* argv[]) +{ + char* str = NULL; + size_t length = 0; + BOOL status = 0; + HANDLE hFind = NULL; + LPTSTR BasePath = NULL; + WIN32_FIND_DATA FindData; + TCHAR FilePath[PATHCCH_MAX_CCH] = { 0 }; + WINPR_UNUSED(argc); + str = argv[1]; +#ifdef UNICODE + BasePath = ConvertUtf8ToWChar(str, &length); + + if (!BasePath) + { + _tprintf(_T("Unable to allocate memory")); + return -1; + } +#else + BasePath = _strdup(str); + + if (!BasePath) + { + printf("Unable to allocate memory"); + return -1; + } + + length = strlen(BasePath); +#endif + /* Simple filter matching all files inside current directory */ + CopyMemory(FilePath, BasePath, length * sizeof(TCHAR)); + FilePath[length] = 0; + PathCchConvertStyle(BasePath, length, PATH_STYLE_WINDOWS); + NativePathCchAppend(FilePath, PATHCCH_MAX_CCH, _T("TestDirectory2")); + NativePathCchAppend(FilePath, PATHCCH_MAX_CCH, _T("TestDirectory2File*")); + free(BasePath); + _tprintf(_T("Finding file: %s\n"), FilePath); + hFind = FindFirstFile(FilePath, &FindData); + + if (hFind == INVALID_HANDLE_VALUE) + { + _tprintf(_T("FindFirstFile failure: %s\n"), FilePath); + return -1; + } + + _tprintf(_T("FindFirstFile: %s"), FindData.cFileName); + + /** + * The current implementation does not enforce a particular order + */ + + if ((_tcsncmp(FindData.cFileName, testDirectory2File1, ARRAYSIZE(testDirectory2File1)) != 0) && + (_tcsncmp(FindData.cFileName, testDirectory2File2, ARRAYSIZE(testDirectory2File2)) != 0)) + { + _tprintf(_T("FindFirstFile failure: Expected: %s, Actual: %s\n"), testDirectory2File1, + FindData.cFileName); + return -1; + } + + status = FindNextFile(hFind, &FindData); + + if (!status) + { + _tprintf(_T("FindNextFile failure: Expected: TRUE, Actual: %") _T(PRId32) _T("\n"), status); + return -1; + } + + if ((_tcsncmp(FindData.cFileName, testDirectory2File1, ARRAYSIZE(testDirectory2File1)) != 0) && + (_tcsncmp(FindData.cFileName, testDirectory2File2, ARRAYSIZE(testDirectory2File2)) != 0)) + { + _tprintf(_T("FindNextFile failure: Expected: %s, Actual: %s\n"), testDirectory2File2, + FindData.cFileName); + return -1; + } + + status = FindNextFile(hFind, &FindData); + + if (status) + { + _tprintf(_T("FindNextFile failure: Expected: FALSE, Actual: %") _T(PRId32) _T("\n"), + status); + return -1; + } + + FindClose(hFind); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileGetStdHandle.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileGetStdHandle.c new file mode 100644 index 0000000000000000000000000000000000000000..7728f8418960676fe89241d6772d8043d4792d5f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileGetStdHandle.c @@ -0,0 +1,49 @@ + +/** + * WinPR: Windows Portable Runtime + * File Functions + * + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 Bernhard Miklautz + * + * 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 +#include +#include +#include + +int TestFileGetStdHandle(int argc, char* argv[]) +{ + HANDLE so = NULL; + const char buf[] = "happy happy"; + DWORD bytesWritten = 0; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + so = GetStdHandle(STD_OUTPUT_HANDLE); + if (so == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "GetStdHandle failed ;(\n"); + return -1; + } + WriteFile(so, buf, strnlen(buf, sizeof(buf)), &bytesWritten, FALSE); + if (bytesWritten != strnlen(buf, sizeof(buf))) + { + (void)fprintf(stderr, "write failed\n"); + return -1; + } + (void)CloseHandle(so); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFilePatternMatch.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFilePatternMatch.c new file mode 100644 index 0000000000000000000000000000000000000000..8f7a2fb335d9c74e519599087160221b121d535e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFilePatternMatch.c @@ -0,0 +1,182 @@ + +#include +#include +#include +#include + +int TestFilePatternMatch(int argc, char* argv[]) +{ + /* '*' expression */ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + if (!FilePatternMatchA("document.txt", "*")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "*"); + return -1; + } + + /* '*X' expression */ + + if (!FilePatternMatchA("document.txt", "*.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "*.txt"); + return -1; + } + + if (FilePatternMatchA("document.docx", "*.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.docx", "*.txt"); + return -1; + } + + if (FilePatternMatchA("document.txt.bak", "*.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt.bak", "*.txt"); + return -1; + } + + if (FilePatternMatchA("bak", "*.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "bak", "*.txt"); + return -1; + } + + /* 'X*' expression */ + + if (!FilePatternMatchA("document.txt", "document.*")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", "document.*"); + return -1; + } + + /* 'X?' expression */ + + if (!FilePatternMatchA("document.docx", "document.doc?")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.docx", + "document.doc?"); + return -1; + } + + if (FilePatternMatchA("document.doc", "document.doc?")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.doc", + "document.doc?"); + return -1; + } + + /* no wildcards expression */ + + if (!FilePatternMatchA("document.txt", "document.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "document.txt", + "document.txt"); + return -1; + } + + /* 'X * Y' expression */ + + if (!FilePatternMatchA("X123Y.txt", "X*Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y.txt", "X*Y.txt"); + return -1; + } + + if (!FilePatternMatchA("XY.txt", "X*Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XY.txt", "X*Y.txt"); + return -1; + } + + if (FilePatternMatchA("XZ.txt", "X*Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XZ.txt", "X*Y.txt"); + return -1; + } + + if (FilePatternMatchA("X123Z.txt", "X*Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Z.txt", "X*Y.txt"); + return -1; + } + + /* 'X * Y * Z' expression */ + + if (!FilePatternMatchA("X123Y456Z.txt", "X*Y*Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456Z.txt", "X*Y*Z.txt"); + return -1; + } + + if (!FilePatternMatchA("XYZ.txt", "X*Y*Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYZ.txt", "X*Y*Z.txt"); + return -1; + } + + if (!FilePatternMatchA("X123Y456W.txt", "X*Y*Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456W.txt", "X*Y*Z.txt"); + return -1; + } + + if (!FilePatternMatchA("XYW.txt", "X*Y*Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYW.txt", "X*Y*Z.txt"); + return -1; + } + + /* 'X ? Y' expression */ + + if (!FilePatternMatchA("X1Y.txt", "X?Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X1Y.txt", "X?Y.txt"); + return -1; + } + + if (FilePatternMatchA("XY.txt", "X?Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XY.txt", "X?Y.txt"); + return -1; + } + + if (FilePatternMatchA("XZ.txt", "X?Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XZ.txt", "X?Y.txt"); + return -1; + } + + if (FilePatternMatchA("X123Z.txt", "X?Y.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Z.txt", "X?Y.txt"); + return -1; + } + + /* 'X ? Y ? Z' expression */ + + if (!FilePatternMatchA("X123Y456Z.txt", "X?Y?Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456Z.txt", "X?Y?Z.txt"); + return -1; + } + + if (FilePatternMatchA("XYZ.txt", "X?Y?Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYZ.txt", "X?Y?Z.txt"); + return -1; + } + + if (!FilePatternMatchA("X123Y456W.txt", "X?Y?Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "X123Y456W.txt", "X?Y?Z.txt"); + return -1; + } + + if (FilePatternMatchA("XYW.txt", "X?Y?Z.txt")) + { + printf("FilePatternMatchA error: FileName: %s Pattern: %s\n", "XYW.txt", "X?Y?Z.txt"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileReadFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileReadFile.c new file mode 100644 index 0000000000000000000000000000000000000000..936881a4ed027c1bf6acdc586e4c2620e99a2876 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileReadFile.c @@ -0,0 +1,10 @@ + +#include +#include +#include +#include + +int TestFileReadFile(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileWriteFile.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileWriteFile.c new file mode 100644 index 0000000000000000000000000000000000000000..a8283ee6db8078d1342bb9e2f424f5baa6e98c80 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestFileWriteFile.c @@ -0,0 +1,10 @@ + +#include +#include +#include +#include + +int TestFileWriteFile(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestSetFileAttributes.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestSetFileAttributes.c new file mode 100644 index 0000000000000000000000000000000000000000..b00c2ce1a4ce17c42c3891b3ebeef96ba3dcdf7a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/file/test/TestSetFileAttributes.c @@ -0,0 +1,152 @@ + +#include +#include +#include +#include +#include +#include +#include + +static const DWORD allflags[] = { + 0, + FILE_ATTRIBUTE_READONLY, + FILE_ATTRIBUTE_HIDDEN, + FILE_ATTRIBUTE_SYSTEM, + FILE_ATTRIBUTE_DIRECTORY, + FILE_ATTRIBUTE_ARCHIVE, + FILE_ATTRIBUTE_DEVICE, + FILE_ATTRIBUTE_NORMAL, + FILE_ATTRIBUTE_TEMPORARY, + FILE_ATTRIBUTE_SPARSE_FILE, + FILE_ATTRIBUTE_REPARSE_POINT, + FILE_ATTRIBUTE_COMPRESSED, + FILE_ATTRIBUTE_OFFLINE, + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, + FILE_ATTRIBUTE_ENCRYPTED, + FILE_ATTRIBUTE_VIRTUAL, + FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM, + FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DEVICE | + FILE_ATTRIBUTE_NORMAL, + FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_SPARSE_FILE | FILE_ATTRIBUTE_REPARSE_POINT | + FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_OFFLINE, + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_ENCRYPTED | FILE_ATTRIBUTE_VIRTUAL +}; + +static BOOL test_SetFileAttributesA(void) +{ + BOOL rc = FALSE; + HANDLE handle = NULL; + const DWORD flags[] = { 0, FILE_ATTRIBUTE_READONLY }; + char* name = GetKnownSubPath(KNOWN_PATH_TEMP, "afsklhjwe4oq5iu432oijrlkejadlkhjaklhfdkahfd"); + if (!name) + goto fail; + + for (size_t x = 0; x < ARRAYSIZE(allflags); x++) + { + const DWORD flag = allflags[x]; + const BOOL brc = SetFileAttributesA(NULL, flag); + if (brc) + goto fail; + + const BOOL crc = SetFileAttributesA(name, flag); + if (crc) + goto fail; + } + + handle = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, NULL); + if (handle == INVALID_HANDLE_VALUE) + goto fail; + (void)CloseHandle(handle); + + for (size_t x = 0; x < ARRAYSIZE(flags); x++) + { + DWORD attr = 0; + const DWORD flag = flags[x]; + const BOOL brc = SetFileAttributesA(name, flag); + if (!brc) + goto fail; + + attr = GetFileAttributesA(name); + if (flag != 0) + { + if ((attr & flag) == 0) + goto fail; + } + } + + rc = TRUE; + +fail: + DeleteFileA(name); + free(name); + return rc; +} + +static BOOL test_SetFileAttributesW(void) +{ + BOOL rc = FALSE; + WCHAR* name = NULL; + HANDLE handle = NULL; + const DWORD flags[] = { 0, FILE_ATTRIBUTE_READONLY }; + char* base = GetKnownSubPath(KNOWN_PATH_TEMP, "afsklhjwe4oq5iu432oijrlkejadlkhjaklhfdkahfd"); + if (!base) + goto fail; + + name = ConvertUtf8ToWCharAlloc(base, NULL); + if (!name) + goto fail; + + for (size_t x = 0; x < ARRAYSIZE(allflags); x++) + { + const DWORD flag = allflags[x]; + const BOOL brc = SetFileAttributesW(NULL, flag); + if (brc) + goto fail; + + const BOOL crc = SetFileAttributesW(name, flag); + if (crc) + goto fail; + } + + handle = CreateFileW(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, NULL); + if (handle == INVALID_HANDLE_VALUE) + goto fail; + (void)CloseHandle(handle); + + for (size_t x = 0; x < ARRAYSIZE(flags); x++) + { + DWORD attr = 0; + const DWORD flag = flags[x]; + const BOOL brc = SetFileAttributesW(name, flag); + if (!brc) + goto fail; + + attr = GetFileAttributesW(name); + if (flag != 0) + { + if ((attr & flag) == 0) + goto fail; + } + } + + rc = TRUE; +fail: + DeleteFileW(name); + free(name); + free(base); + return rc; +} + +int TestSetFileAttributes(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_SetFileAttributesA()) + return -1; + if (!test_SetFileAttributesW()) + return -1; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e70981551d9282ecf5d8d69cf6442e2115175deb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/CMakeLists.txt @@ -0,0 +1,19 @@ +# WinPR: Windows Portable Runtime +# libwinpr-handle cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2014 DI (FH) Martin Haimberger +# +# 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(handle.c handle.h nonehandle.c nonehandle.h) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..4a571ba66af43092d6644e1335fd45db6efb9a46 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/ModuleOptions.cmake @@ -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 "handle") +set(MINWIN_LONG_NAME "Handle and Object Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.c new file mode 100644 index 0000000000000000000000000000000000000000..5c35d42adbf88f7ecd8356615237197c3a8b74bc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.c @@ -0,0 +1,81 @@ +/** + * WinPR: Windows Portable Runtime + * Handle Management + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 DI (FH) Martin Haimberger + * + * 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 + +#include + +#ifndef _WIN32 + +#include + +#include "../synch/synch.h" +#include "../thread/thread.h" +#include "../pipe/pipe.h" +#include "../comm/comm.h" +#include "../security/security.h" + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include + +#include "../handle/handle.h" + +BOOL CloseHandle(HANDLE hObject) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + + if (!winpr_Handle_GetInfo(hObject, &Type, &Object)) + return FALSE; + + if (!Object) + return FALSE; + + if (!Object->ops) + return FALSE; + + if (Object->ops->CloseHandle) + return Object->ops->CloseHandle(hObject); + + return FALSE; +} + +BOOL DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, + LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, + DWORD dwOptions) +{ + *((ULONG_PTR*)lpTargetHandle) = (ULONG_PTR)hSourceHandle; + return TRUE; +} + +BOOL GetHandleInformation(HANDLE hObject, LPDWORD lpdwFlags) +{ + return TRUE; +} + +BOOL SetHandleInformation(HANDLE hObject, DWORD dwMask, DWORD dwFlags) +{ + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.h new file mode 100644 index 0000000000000000000000000000000000000000..5abe218dc41d010a185e44ac834fa5419e910e06 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/handle.h @@ -0,0 +1,198 @@ +/** + * WinPR: Windows Portable Runtime + * Handle Management + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_HANDLE_PRIVATE_H + +#include +#include +#include +#include + +#define HANDLE_TYPE_NONE 0 +#define HANDLE_TYPE_PROCESS 1 +#define HANDLE_TYPE_THREAD 2 +#define HANDLE_TYPE_EVENT 3 +#define HANDLE_TYPE_MUTEX 4 +#define HANDLE_TYPE_SEMAPHORE 5 +#define HANDLE_TYPE_TIMER 6 +#define HANDLE_TYPE_NAMED_PIPE 7 +#define HANDLE_TYPE_ANONYMOUS_PIPE 8 +#define HANDLE_TYPE_ACCESS_TOKEN 9 +#define HANDLE_TYPE_FILE 10 +#define HANDLE_TYPE_TIMER_QUEUE 11 +#define HANDLE_TYPE_TIMER_QUEUE_TIMER 12 +#define HANDLE_TYPE_COMM 13 + +typedef BOOL (*pcIsHandled)(HANDLE handle); +typedef BOOL (*pcCloseHandle)(HANDLE handle); +typedef int (*pcGetFd)(HANDLE handle); +typedef DWORD (*pcCleanupHandle)(HANDLE handle); +typedef BOOL (*pcReadFile)(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); +typedef BOOL (*pcReadFileEx)(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPOVERLAPPED lpOverlapped, + LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); +typedef BOOL (*pcReadFileScatter)(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[], + DWORD nNumberOfBytesToRead, LPDWORD lpReserved, + LPOVERLAPPED lpOverlapped); +typedef BOOL (*pcWriteFile)(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); +typedef BOOL (*pcWriteFileEx)(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPOVERLAPPED lpOverlapped, + LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); +typedef BOOL (*pcWriteFileGather)(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[], + DWORD nNumberOfBytesToWrite, LPDWORD lpReserved, + LPOVERLAPPED lpOverlapped); +typedef DWORD (*pcGetFileSize)(HANDLE handle, LPDWORD lpFileSizeHigh); +typedef BOOL (*pcGetFileInformationByHandle)(HANDLE handle, + LPBY_HANDLE_FILE_INFORMATION lpFileInformation); +typedef BOOL (*pcFlushFileBuffers)(HANDLE hFile); +typedef BOOL (*pcSetEndOfFile)(HANDLE handle); +typedef DWORD (*pcSetFilePointer)(HANDLE handle, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, + DWORD dwMoveMethod); +typedef BOOL (*pcSetFilePointerEx)(HANDLE hFile, LARGE_INTEGER liDistanceToMove, + PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod); +typedef BOOL (*pcLockFile)(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh); +typedef BOOL (*pcLockFileEx)(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, + DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh, + LPOVERLAPPED lpOverlapped); +typedef BOOL (*pcUnlockFile)(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh); +typedef BOOL (*pcUnlockFileEx)(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow, + DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped); +typedef BOOL (*pcSetFileTime)(HANDLE hFile, const FILETIME* lpCreationTime, + const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime); + +typedef struct +{ + pcIsHandled IsHandled; + pcCloseHandle CloseHandle; + pcGetFd GetFd; + pcCleanupHandle CleanupHandle; + pcReadFile ReadFile; + pcReadFileEx ReadFileEx; + pcReadFileScatter ReadFileScatter; + pcWriteFile WriteFile; + pcWriteFileEx WriteFileEx; + pcWriteFileGather WriteFileGather; + pcGetFileSize GetFileSize; + pcFlushFileBuffers FlushFileBuffers; + pcSetEndOfFile SetEndOfFile; + pcSetFilePointer SetFilePointer; + pcSetFilePointerEx SetFilePointerEx; + pcLockFile LockFile; + pcLockFileEx LockFileEx; + pcUnlockFile UnlockFile; + pcUnlockFileEx UnlockFileEx; + pcSetFileTime SetFileTime; + pcGetFileInformationByHandle GetFileInformationByHandle; +} HANDLE_OPS; + +typedef struct +{ + ULONG Type; + ULONG Mode; + HANDLE_OPS* ops; +} WINPR_HANDLE; + +static INLINE BOOL WINPR_HANDLE_IS_HANDLED(HANDLE handle, ULONG type, BOOL invalidValue) +{ + WINPR_HANDLE* pWinprHandle = (WINPR_HANDLE*)handle; + BOOL invalid = !pWinprHandle; + + if (invalidValue) + { + if (INVALID_HANDLE_VALUE == pWinprHandle) + invalid = TRUE; + } + + if (invalid || (pWinprHandle->Type != type)) + { + SetLastError(ERROR_INVALID_HANDLE); + return FALSE; + } + + return TRUE; +} + +static INLINE void WINPR_HANDLE_SET_TYPE_AND_MODE(void* _handle, ULONG _type, ULONG _mode) +{ + WINPR_HANDLE* hdl = (WINPR_HANDLE*)_handle; + + hdl->Type = _type; + hdl->Mode = _mode; +} + +static INLINE BOOL winpr_Handle_GetInfo(HANDLE handle, ULONG* pType, WINPR_HANDLE** pObject) +{ + WINPR_HANDLE* wHandle = NULL; + + if (handle == NULL) + return FALSE; + + /* INVALID_HANDLE_VALUE is an invalid value for every handle, but it + * confuses the clang scanbuild analyzer. */ +#ifndef __clang_analyzer__ + if (handle == INVALID_HANDLE_VALUE) + return FALSE; +#endif + + wHandle = (WINPR_HANDLE*)handle; + + *pType = wHandle->Type; + *pObject = handle; + + return TRUE; +} + +static INLINE int winpr_Handle_getFd(HANDLE handle) +{ + WINPR_HANDLE* hdl = NULL; + ULONG type = 0; + + if (!winpr_Handle_GetInfo(handle, &type, &hdl)) + return -1; + + if (!hdl || !hdl->ops || !hdl->ops->GetFd) + return -1; + + return hdl->ops->GetFd(handle); +} + +static INLINE DWORD winpr_Handle_cleanup(HANDLE handle) +{ + WINPR_HANDLE* hdl = NULL; + ULONG type = 0; + + if (!winpr_Handle_GetInfo(handle, &type, &hdl)) + return WAIT_FAILED; + + if (!hdl || !hdl->ops) + return WAIT_FAILED; + + /* If there is no cleanup function, assume all ok. */ + if (!hdl->ops->CleanupHandle) + return WAIT_OBJECT_0; + + return hdl->ops->CleanupHandle(handle); +} + +#endif /* WINPR_HANDLE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.c new file mode 100644 index 0000000000000000000000000000000000000000..1fe54b8af0fa023120ee50d74fc6392578eca058 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.c @@ -0,0 +1,82 @@ +/** + * WinPR: Windows Portable Runtime + * NoneHandle a.k.a. brathandle should be used where a handle is needed, but + * functionality is not implemented yet or not implementable. + * + * Copyright 2014 DI (FH) Martin Haimberger + * + * 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 + +#include "nonehandle.h" + +#ifndef _WIN32 + +#include + +static BOOL NoneHandleCloseHandle(HANDLE handle) +{ + WINPR_NONE_HANDLE* none = (WINPR_NONE_HANDLE*)handle; + free(none); + return TRUE; +} + +static BOOL NoneHandleIsHandle(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_NONE, FALSE); +} + +static int NoneHandleGetFd(HANDLE handle) +{ + if (!NoneHandleIsHandle(handle)) + return -1; + + return -1; +} + +static HANDLE_OPS ops = { NoneHandleIsHandle, + NoneHandleCloseHandle, + NoneHandleGetFd, + NULL, /* CleanupHandle */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +HANDLE CreateNoneHandle(void) +{ + WINPR_NONE_HANDLE* none = (WINPR_NONE_HANDLE*)calloc(1, sizeof(WINPR_NONE_HANDLE)); + + if (!none) + return NULL; + + none->common.ops = &ops; + return (HANDLE)none; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.h new file mode 100644 index 0000000000000000000000000000000000000000..50e224cbdf893d525f55634d00ebd788fc553c52 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/handle/nonehandle.h @@ -0,0 +1,40 @@ +/** + * WinPR: Windows Portable Runtime + * NoneHandle a.k.a. brathandle should be used where a handle is needed, but + * functionality is not implemented yet or not implementable. + * + * Copyright 2014 DI (FH) Martin Haimberger + * + * 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_NONE_HANDLE_PRIVATE_H +#define WINPR_NONE_HANDLE_PRIVATE_H + +#ifndef _WIN32 + +#include +#include "handle.h" + +struct winpr_none_handle +{ + WINPR_HANDLE common; +}; + +typedef struct winpr_none_handle WINPR_NONE_HANDLE; + +HANDLE CreateNoneHandle(void); + +#endif /*_WIN32*/ + +#endif /* WINPR_NONE_HANDLE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5eba25e113a1e77eaedf95d0330f793b788f9386 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/CMakeLists.txt @@ -0,0 +1,18 @@ +# WinPR: Windows Portable Runtime +# libwinpr-input cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(virtualkey.c scancode.c keycode.c) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..4531e43861ee6835d870177b843175df879ea91a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/ModuleOptions.cmake @@ -0,0 +1,7 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "input") +set(MINWIN_LONG_NAME "Input Functions") +set(MODULE_LIBRARY_NAME "input") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/keycode.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/keycode.c new file mode 100644 index 0000000000000000000000000000000000000000..a7867138afd534114d7c09b4bc5bf8cc57d1667b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/keycode.c @@ -0,0 +1,910 @@ +/** + * WinPR: Windows Portable Runtime + * Keyboard Input + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +/** + * X11 Keycodes + */ + +/** + * Mac OS X + */ + +static DWORD KEYCODE_TO_VKCODE_APPLE[256] = { + VK_KEY_A, /* APPLE_VK_ANSI_A (0x00) */ + VK_KEY_S, /* APPLE_VK_ANSI_S (0x01) */ + VK_KEY_D, /* APPLE_VK_ANSI_D (0x02) */ + VK_KEY_F, /* APPLE_VK_ANSI_F (0x03) */ + VK_KEY_H, /* APPLE_VK_ANSI_H (0x04) */ + VK_KEY_G, /* APPLE_VK_ANSI_G (0x05) */ + VK_KEY_Z, /* APPLE_VK_ANSI_Z (0x06) */ + VK_KEY_X, /* APPLE_VK_ANSI_X (0x07) */ + VK_KEY_C, /* APPLE_VK_ANSI_C (0x08) */ + VK_KEY_V, /* APPLE_VK_ANSI_V (0x09) */ + VK_OEM_102, /* APPLE_VK_ISO_Section (0x0A) */ + VK_KEY_B, /* APPLE_VK_ANSI_B (0x0B) */ + VK_KEY_Q, /* APPLE_VK_ANSI_Q (0x0C) */ + VK_KEY_W, /* APPLE_VK_ANSI_W (0x0D) */ + VK_KEY_E, /* APPLE_VK_ANSI_E (0x0E) */ + VK_KEY_R, /* APPLE_VK_ANSI_R (0x0F) */ + VK_KEY_Y, /* APPLE_VK_ANSI_Y (0x10) */ + VK_KEY_T, /* APPLE_VK_ANSI_T (0x11) */ + VK_KEY_1, /* APPLE_VK_ANSI_1 (0x12) */ + VK_KEY_2, /* APPLE_VK_ANSI_2 (0x13) */ + VK_KEY_3, /* APPLE_VK_ANSI_3 (0x14) */ + VK_KEY_4, /* APPLE_VK_ANSI_4 (0x15) */ + VK_KEY_6, /* APPLE_VK_ANSI_6 (0x16) */ + VK_KEY_5, /* APPLE_VK_ANSI_5 (0x17) */ + VK_OEM_PLUS, /* APPLE_VK_ANSI_Equal (0x18) */ + VK_KEY_9, /* APPLE_VK_ANSI_9 (0x19) */ + VK_KEY_7, /* APPLE_VK_ANSI_7 (0x1A) */ + VK_OEM_MINUS, /* APPLE_VK_ANSI_Minus (0x1B) */ + VK_KEY_8, /* APPLE_VK_ANSI_8 (0x1C) */ + VK_KEY_0, /* APPLE_VK_ANSI_0 (0x1D) */ + VK_OEM_6, /* APPLE_VK_ANSI_RightBracket (0x1E) */ + VK_KEY_O, /* APPLE_VK_ANSI_O (0x1F) */ + VK_KEY_U, /* APPLE_VK_ANSI_U (0x20) */ + VK_OEM_4, /* APPLE_VK_ANSI_LeftBracket (0x21) */ + VK_KEY_I, /* APPLE_VK_ANSI_I (0x22) */ + VK_KEY_P, /* APPLE_VK_ANSI_P (0x23) */ + VK_RETURN, /* APPLE_VK_Return (0x24) */ + VK_KEY_L, /* APPLE_VK_ANSI_L (0x25) */ + VK_KEY_J, /* APPLE_VK_ANSI_J (0x26) */ + VK_OEM_7, /* APPLE_VK_ANSI_Quote (0x27) */ + VK_KEY_K, /* APPLE_VK_ANSI_K (0x28) */ + VK_OEM_1, /* APPLE_VK_ANSI_Semicolon (0x29) */ + VK_OEM_5, /* APPLE_VK_ANSI_Backslash (0x2A) */ + VK_OEM_COMMA, /* APPLE_VK_ANSI_Comma (0x2B) */ + VK_OEM_2, /* APPLE_VK_ANSI_Slash (0x2C) */ + VK_KEY_N, /* APPLE_VK_ANSI_N (0x2D) */ + VK_KEY_M, /* APPLE_VK_ANSI_M (0x2E) */ + VK_OEM_PERIOD, /* APPLE_VK_ANSI_Period (0x2F) */ + VK_TAB, /* APPLE_VK_Tab (0x30) */ + VK_SPACE, /* APPLE_VK_Space (0x31) */ + VK_OEM_3, /* APPLE_VK_ANSI_Grave (0x32) */ + VK_BACK, /* APPLE_VK_Delete (0x33) */ + 0, /* APPLE_VK_0x34 (0x34) */ + VK_ESCAPE, /* APPLE_VK_Escape (0x35) */ + VK_RWIN | KBDEXT, /* APPLE_VK_RightCommand (0x36) */ + VK_LWIN | KBDEXT, /* APPLE_VK_Command (0x37) */ + VK_LSHIFT, /* APPLE_VK_Shift (0x38) */ + VK_CAPITAL, /* APPLE_VK_CapsLock (0x39) */ + VK_LMENU, /* APPLE_VK_Option (0x3A) */ + VK_LCONTROL, /* APPLE_VK_Control (0x3B) */ + VK_RSHIFT, /* APPLE_VK_RightShift (0x3C) */ + VK_RMENU | KBDEXT, /* APPLE_VK_RightOption (0x3D) */ + VK_RWIN | KBDEXT, /* APPLE_VK_RightControl (0x3E) */ + VK_RWIN | KBDEXT, /* APPLE_VK_Function (0x3F) */ + VK_F17, /* APPLE_VK_F17 (0x40) */ + VK_DECIMAL, /* APPLE_VK_ANSI_KeypadDecimal (0x41) */ + 0, /* APPLE_VK_0x42 (0x42) */ + VK_MULTIPLY, /* APPLE_VK_ANSI_KeypadMultiply (0x43) */ + 0, /* APPLE_VK_0x44 (0x44) */ + VK_ADD, /* APPLE_VK_ANSI_KeypadPlus (0x45) */ + 0, /* APPLE_VK_0x46 (0x46) */ + VK_NUMLOCK, /* APPLE_VK_ANSI_KeypadClear (0x47) */ + VK_VOLUME_UP, /* APPLE_VK_VolumeUp (0x48) */ + VK_VOLUME_DOWN, /* APPLE_VK_VolumeDown (0x49) */ + VK_VOLUME_MUTE, /* APPLE_VK_Mute (0x4A) */ + VK_DIVIDE | KBDEXT, /* APPLE_VK_ANSI_KeypadDivide (0x4B) */ + VK_RETURN | KBDEXT, /* APPLE_VK_ANSI_KeypadEnter (0x4C) */ + 0, /* APPLE_VK_0x4D (0x4D) */ + VK_SUBTRACT, /* APPLE_VK_ANSI_KeypadMinus (0x4E) */ + VK_F18, /* APPLE_VK_F18 (0x4F) */ + VK_F19, /* APPLE_VK_F19 (0x50) */ + VK_CLEAR | KBDEXT, /* APPLE_VK_ANSI_KeypadEquals (0x51) */ + VK_NUMPAD0, /* APPLE_VK_ANSI_Keypad0 (0x52) */ + VK_NUMPAD1, /* APPLE_VK_ANSI_Keypad1 (0x53) */ + VK_NUMPAD2, /* APPLE_VK_ANSI_Keypad2 (0x54) */ + VK_NUMPAD3, /* APPLE_VK_ANSI_Keypad3 (0x55) */ + VK_NUMPAD4, /* APPLE_VK_ANSI_Keypad4 (0x56) */ + VK_NUMPAD5, /* APPLE_VK_ANSI_Keypad5 (0x57) */ + VK_NUMPAD6, /* APPLE_VK_ANSI_Keypad6 (0x58) */ + VK_NUMPAD7, /* APPLE_VK_ANSI_Keypad7 (0x59) */ + VK_F20, /* APPLE_VK_F20 (0x5A) */ + VK_NUMPAD8, /* APPLE_VK_ANSI_Keypad8 (0x5B) */ + VK_NUMPAD9, /* APPLE_VK_ANSI_Keypad9 (0x5C) */ + 0, /* APPLE_VK_JIS_Yen (0x5D) */ + 0, /* APPLE_VK_JIS_Underscore (0x5E) */ + VK_DECIMAL, /* APPLE_VK_JIS_KeypadComma (0x5F) */ + VK_F5, /* APPLE_VK_F5 (0x60) */ + VK_F6, /* APPLE_VK_F6 (0x61) */ + VK_F7, /* APPLE_VK_F7 (0x62) */ + VK_F3, /* APPLE_VK_F3 (0x63) */ + VK_F8, /* APPLE_VK_F8 (0x64) */ + VK_F9, /* APPLE_VK_F9 (0x65) */ + 0, /* APPLE_VK_JIS_Eisu (0x66) */ + VK_F11, /* APPLE_VK_F11 (0x67) */ + 0, /* APPLE_VK_JIS_Kana (0x68) */ + VK_SNAPSHOT | KBDEXT, /* APPLE_VK_F13 (0x69) */ + VK_F16, /* APPLE_VK_F16 (0x6A) */ + VK_F14, /* APPLE_VK_F14 (0x6B) */ + 0, /* APPLE_VK_0x6C (0x6C) */ + VK_F10, /* APPLE_VK_F10 (0x6D) */ + 0, /* APPLE_VK_0x6E (0x6E) */ + VK_F12, /* APPLE_VK_F12 (0x6F) */ + 0, /* APPLE_VK_0x70 (0x70) */ + VK_PAUSE | KBDEXT, /* APPLE_VK_F15 (0x71) */ + VK_INSERT | KBDEXT, /* APPLE_VK_Help (0x72) */ + VK_HOME | KBDEXT, /* APPLE_VK_Home (0x73) */ + VK_PRIOR | KBDEXT, /* APPLE_VK_PageUp (0x74) */ + VK_DELETE | KBDEXT, /* APPLE_VK_ForwardDelete (0x75) */ + VK_F4, /* APPLE_VK_F4 (0x76) */ + VK_END | KBDEXT, /* APPLE_VK_End (0x77) */ + VK_F2, /* APPLE_VK_F2 (0x78) */ + VK_NEXT | KBDEXT, /* APPLE_VK_PageDown (0x79) */ + VK_F1, /* APPLE_VK_F1 (0x7A) */ + VK_LEFT | KBDEXT, /* APPLE_VK_LeftArrow (0x7B) */ + VK_RIGHT | KBDEXT, /* APPLE_VK_RightArrow (0x7C) */ + VK_DOWN | KBDEXT, /* APPLE_VK_DownArrow (0x7D) */ + VK_UP | KBDEXT, /* APPLE_VK_UpArrow (0x7E) */ + 0, /* 127 */ + 0, /* 128 */ + 0, /* 129 */ + 0, /* 130 */ + 0, /* 131 */ + 0, /* 132 */ + 0, /* 133 */ + 0, /* 134 */ + 0, /* 135 */ + 0, /* 136 */ + 0, /* 137 */ + 0, /* 138 */ + 0, /* 139 */ + 0, /* 140 */ + 0, /* 141 */ + 0, /* 142 */ + 0, /* 143 */ + 0, /* 144 */ + 0, /* 145 */ + 0, /* 146 */ + 0, /* 147 */ + 0, /* 148 */ + 0, /* 149 */ + 0, /* 150 */ + 0, /* 151 */ + 0, /* 152 */ + 0, /* 153 */ + 0, /* 154 */ + 0, /* 155 */ + 0, /* 156 */ + 0, /* 157 */ + 0, /* 158 */ + 0, /* 159 */ + 0, /* 160 */ + 0, /* 161 */ + 0, /* 162 */ + 0, /* 163 */ + 0, /* 164 */ + 0, /* 165 */ + 0, /* 166 */ + 0, /* 167 */ + 0, /* 168 */ + 0, /* 169 */ + 0, /* 170 */ + 0, /* 171 */ + 0, /* 172 */ + 0, /* 173 */ + 0, /* 174 */ + 0, /* 175 */ + 0, /* 176 */ + 0, /* 177 */ + 0, /* 178 */ + 0, /* 179 */ + 0, /* 180 */ + 0, /* 181 */ + 0, /* 182 */ + 0, /* 183 */ + 0, /* 184 */ + 0, /* 185 */ + 0, /* 186 */ + 0, /* 187 */ + 0, /* 188 */ + 0, /* 189 */ + 0, /* 190 */ + 0, /* 191 */ + 0, /* 192 */ + 0, /* 193 */ + 0, /* 194 */ + 0, /* 195 */ + 0, /* 196 */ + 0, /* 197 */ + 0, /* 198 */ + 0, /* 199 */ + 0, /* 200 */ + 0, /* 201 */ + 0, /* 202 */ + 0, /* 203 */ + 0, /* 204 */ + 0, /* 205 */ + 0, /* 206 */ + 0, /* 207 */ + 0, /* 208 */ + 0, /* 209 */ + 0, /* 210 */ + 0, /* 211 */ + 0, /* 212 */ + 0, /* 213 */ + 0, /* 214 */ + 0, /* 215 */ + 0, /* 216 */ + 0, /* 217 */ + 0, /* 218 */ + 0, /* 219 */ + 0, /* 220 */ + 0, /* 221 */ + 0, /* 222 */ + 0, /* 223 */ + 0, /* 224 */ + 0, /* 225 */ + 0, /* 226 */ + 0, /* 227 */ + 0, /* 228 */ + 0, /* 229 */ + 0, /* 230 */ + 0, /* 231 */ + 0, /* 232 */ + 0, /* 233 */ + 0, /* 234 */ + 0, /* 235 */ + 0, /* 236 */ + 0, /* 237 */ + 0, /* 238 */ + 0, /* 239 */ + 0, /* 240 */ + 0, /* 241 */ + 0, /* 242 */ + 0, /* 243 */ + 0, /* 244 */ + 0, /* 245 */ + 0, /* 246 */ + 0, /* 247 */ + 0, /* 248 */ + 0, /* 249 */ + 0, /* 250 */ + 0, /* 251 */ + 0, /* 252 */ + 0, /* 253 */ + 0, /* 254 */ + 0 /* 255 */ +}; + +/** + * evdev (Linux) + * + * Refer to linux/input-event-codes.h + */ + +static DWORD KEYCODE_TO_VKCODE_EVDEV[256] = { + 0, /* KEY_RESERVED (0) */ + VK_ESCAPE, /* KEY_ESC (1) */ + VK_KEY_1, /* KEY_1 (2) */ + VK_KEY_2, /* KEY_2 (3) */ + VK_KEY_3, /* KEY_3 (4) */ + VK_KEY_4, /* KEY_4 (5) */ + VK_KEY_5, /* KEY_5 (6) */ + VK_KEY_6, /* KEY_6 (7) */ + VK_KEY_7, /* KEY_7 (8) */ + VK_KEY_8, /* KEY_8 (9) */ + VK_KEY_9, /* KEY_9 (10) */ + VK_KEY_0, /* KEY_0 (11) */ + VK_OEM_MINUS, /* KEY_MINUS (12) */ + VK_OEM_PLUS, /* KEY_EQUAL (13) */ + VK_BACK, /* KEY_BACKSPACE (14) */ + VK_TAB, /* KEY_TAB (15) */ + VK_KEY_Q, /* KEY_Q (16) */ + VK_KEY_W, /* KEY_W (17) */ + VK_KEY_E, /* KEY_E (18) */ + VK_KEY_R, /* KEY_R (19) */ + VK_KEY_T, /* KEY_T (20) */ + VK_KEY_Y, /* KEY_Y (21) */ + VK_KEY_U, /* KEY_U (22) */ + VK_KEY_I, /* KEY_I (23) */ + VK_KEY_O, /* KEY_O (24) */ + VK_KEY_P, /* KEY_P (25) */ + VK_OEM_4, /* KEY_LEFTBRACE (26) */ + VK_OEM_6, /* KEY_RIGHTBRACE (27) */ + VK_RETURN, /* KEY_ENTER (28) */ + VK_LCONTROL, /* KEY_LEFTCTRL (29) */ + VK_KEY_A, /* KEY_A (30) */ + VK_KEY_S, /* KEY_S (31) */ + VK_KEY_D, /* KEY_D (32) */ + VK_KEY_F, /* KEY_F (33) */ + VK_KEY_G, /* KEY_G (34) */ + VK_KEY_H, /* KEY_H (35) */ + VK_KEY_J, /* KEY_J (36) */ + VK_KEY_K, /* KEY_K (37) */ + VK_KEY_L, /* KEY_L (38) */ + VK_OEM_1, /* KEY_SEMICOLON (39) */ + VK_OEM_7, /* KEY_APOSTROPHE (40) */ + VK_OEM_3, /* KEY_GRAVE (41) */ + VK_LSHIFT, /* KEY_LEFTSHIFT (42) */ + VK_OEM_5, /* KEY_BACKSLASH (43) */ + VK_KEY_Z, /* KEY_Z (44) */ + VK_KEY_X, /* KEY_X (45) */ + VK_KEY_C, /* KEY_C (46) */ + VK_KEY_V, /* KEY_V (47) */ + VK_KEY_B, /* KEY_B (48) */ + VK_KEY_N, /* KEY_N (49) */ + VK_KEY_M, /* KEY_M (50) */ + VK_OEM_COMMA, /* KEY_COMMA (51) */ + VK_OEM_PERIOD, /* KEY_DOT (52) */ + VK_OEM_2, /* KEY_SLASH (53) */ + VK_RSHIFT, /* KEY_RIGHTSHIFT (54) */ + VK_MULTIPLY, /* KEY_KPASTERISK (55) */ + VK_LMENU, /* KEY_LEFTALT (56) */ + VK_SPACE, /* KEY_SPACE (57) */ + VK_CAPITAL, /* KEY_CAPSLOCK (58) */ + VK_F1, /* KEY_F1 (59) */ + VK_F2, /* KEY_F2 (60) */ + VK_F3, /* KEY_F3 (61) */ + VK_F4, /* KEY_F4 (62) */ + VK_F5, /* KEY_F5 (63) */ + VK_F6, /* KEY_F6 (64) */ + VK_F7, /* KEY_F7 (65) */ + VK_F8, /* KEY_F8 (66) */ + VK_F9, /* KEY_F9 (67) */ + VK_F10, /* KEY_F10 (68) */ + VK_NUMLOCK, /* KEY_NUMLOCK (69) */ + VK_SCROLL, /* KEY_SCROLLLOCK (70) */ + VK_NUMPAD7, /* KEY_KP7 (71) */ + VK_NUMPAD8, /* KEY_KP8 (72) */ + VK_NUMPAD9, /* KEY_KP9 (73) */ + VK_SUBTRACT, /* KEY_KPMINUS (74) */ + VK_NUMPAD4, /* KEY_KP4 (75) */ + VK_NUMPAD5, /* KEY_KP5 (76) */ + VK_NUMPAD6, /* KEY_KP6 (77) */ + VK_ADD, /* KEY_KPPLUS (78) */ + VK_NUMPAD1, /* KEY_KP1 (79) */ + VK_NUMPAD2, /* KEY_KP2 (80) */ + VK_NUMPAD3, /* KEY_KP3 (81) */ + VK_NUMPAD0, /* KEY_KP0 (82) */ + VK_DECIMAL, /* KEY_KPDOT (83) */ + 0, /* (84) */ + 0, /* KEY_ZENKAKUHANKAKU (85) */ + VK_OEM_102, /* KEY_102ND (86) */ + VK_F11, /* KEY_F11 (87) */ + VK_F12, /* KEY_F12 (88) */ + VK_ABNT_C1, /* KEY_RO (89) */ + VK_DBE_KATAKANA, /* KEY_KATAKANA (90) */ + VK_DBE_HIRAGANA, /* KEY_HIRAGANA (91) */ + VK_CONVERT, /* KEY_HENKAN (92) */ + VK_HKTG, /* KEY_KATAKANAHIRAGANA (93) */ + VK_NONCONVERT, /* KEY_MUHENKAN (94) */ + 0, /* KEY_KPJPCOMMA (95) */ + VK_RETURN | KBDEXT, /* KEY_KPENTER (96) */ + VK_RCONTROL | KBDEXT, /* KEY_RIGHTCTRL (97) */ + VK_DIVIDE | KBDEXT, /* KEY_KPSLASH (98) */ + VK_SNAPSHOT | KBDEXT, /* KEY_SYSRQ (99) */ + VK_RMENU | KBDEXT, /* KEY_RIGHTALT (100) */ + 0, /* KEY_LINEFEED (101) */ + VK_HOME | KBDEXT, /* KEY_HOME (102) */ + VK_UP | KBDEXT, /* KEY_UP (103) */ + VK_PRIOR | KBDEXT, /* KEY_PAGEUP (104) */ + VK_LEFT | KBDEXT, /* KEY_LEFT (105) */ + VK_RIGHT | KBDEXT, /* KEY_RIGHT (106) */ + VK_END | KBDEXT, /* KEY_END (107) */ + VK_DOWN | KBDEXT, /* KEY_DOWN (108) */ + VK_NEXT | KBDEXT, /* KEY_PAGEDOWN (109) */ + VK_INSERT | KBDEXT, /* KEY_INSERT (110) */ + VK_DELETE | KBDEXT, /* KEY_DELETE (111) */ + 0, /* KEY_MACRO (112) */ + VK_VOLUME_MUTE | KBDEXT, /* KEY_MUTE (113) */ + VK_VOLUME_DOWN | KBDEXT, /* KEY_VOLUMEDOWN (114) */ + VK_VOLUME_UP | KBDEXT, /* KEY_VOLUMEUP (115) */ + 0, /* KEY_POWER (SC System Power Down) (116) */ + 0, /* KEY_KPEQUAL (117) */ + 0, /* KEY_KPPLUSMINUS (118) */ + VK_PAUSE | KBDEXT, /* KEY_PAUSE (119) */ + 0, /* KEY_SCALE (AL Compiz Scale (Expose)) (120) */ + VK_ABNT_C2, /* KEY_KPCOMMA (121) */ + VK_HANGUL, /* KEY_HANGEUL, KEY_HANGUEL (122) */ + VK_HANJA, /* KEY_HANJA (123) */ + VK_OEM_8, /* KEY_YEN (124) */ + VK_LWIN | KBDEXT, /* KEY_LEFTMETA (125) */ + VK_RWIN | KBDEXT, /* KEY_RIGHTMETA (126) */ + 0, /* KEY_COMPOSE (127) */ + 0, /* KEY_STOP (AC Stop) (128) */ + 0, /* KEY_AGAIN (AC Properties) (129) */ + 0, /* KEY_PROPS (AC Undo) (130) */ + 0, /* KEY_UNDO (131) */ + 0, /* KEY_FRONT (132) */ + 0, /* KEY_COPY (AC Copy) (133) */ + 0, /* KEY_OPEN (AC Open) (134) */ + 0, /* KEY_PASTE (AC Paste) (135) */ + 0, /* KEY_FIND (AC Search) (136) */ + 0, /* KEY_CUT (AC Cut) (137) */ + VK_HELP, /* KEY_HELP (AL Integrated Help Center) (138) */ + VK_APPS | KBDEXT, /* KEY_MENU (Menu (show menu)) (139) */ + 0, /* KEY_CALC (AL Calculator) (140) */ + 0, /* KEY_SETUP (141) */ + VK_SLEEP, /* KEY_SLEEP (SC System Sleep) (142) */ + 0, /* KEY_WAKEUP (System Wake Up) (143) */ + 0, /* KEY_FILE (AL Local Machine Browser) (144) */ + 0, /* KEY_SENDFILE (145) */ + 0, /* KEY_DELETEFILE (146) */ + VK_CONVERT, /* KEY_XFER (147) */ + VK_LAUNCH_APP1, /* KEY_PROG1 (148) */ + VK_LAUNCH_APP2, /* KEY_PROG2 (149) */ + 0, /* KEY_WWW (AL Internet Browser) (150) */ + 0, /* KEY_MSDOS (151) */ + 0, /* KEY_COFFEE, KEY_SCREENLOCK + * (AL Terminal Lock/Screensaver) (152) */ + 0, /* KEY_ROTATE_DISPLAY, KEY_DIRECTION + * (Display orientation for e.g. tablets) (153) */ + 0, /* KEY_CYCLEWINDOWS (154) */ + VK_LAUNCH_MAIL | KBDEXT, /* KEY_MAIL (155) */ + VK_BROWSER_FAVORITES | KBDEXT, /* KEY_BOOKMARKS (AC Bookmarks) (156) */ + 0, /* KEY_COMPUTER (157) */ + VK_BROWSER_BACK | KBDEXT, /* KEY_BACK (AC Back) (158) */ + VK_BROWSER_FORWARD | KBDEXT, /* KEY_FORWARD (AC Forward) (159) */ + 0, /* KEY_CLOSECD (160) */ + 0, /* KEY_EJECTCD (161) */ + 0, /* KEY_EJECTCLOSECD (162) */ + VK_MEDIA_NEXT_TRACK | KBDEXT, /* KEY_NEXTSONG (163) */ + VK_MEDIA_PLAY_PAUSE | KBDEXT, /* KEY_PLAYPAUSE (164) */ + VK_MEDIA_PREV_TRACK | KBDEXT, /* KEY_PREVIOUSSONG (165) */ + VK_MEDIA_STOP | KBDEXT, /* KEY_STOPCD (166) */ + 0, /* KEY_RECORD (167) */ + 0, /* KEY_REWIND (168) */ + 0, /* KEY_PHONE (Media Select Telephone) (169) */ + 0, /* KEY_ISO (170) */ + 0, /* KEY_CONFIG (AL Consumer Control Configuration) (171) */ + VK_BROWSER_HOME | KBDEXT, /* KEY_HOMEPAGE (AC Home) (172) */ + VK_BROWSER_REFRESH | KBDEXT, /* KEY_REFRESH (AC Refresh) (173) */ + 0, /* KEY_EXIT (AC Exit) (174) */ + 0, /* KEY_MOVE (175) */ + 0, /* KEY_EDIT (176) */ + 0, /* KEY_SCROLLUP (177) */ + 0, /* KEY_SCROLLDOWN (178) */ + 0, /* KEY_KPLEFTPAREN (179) */ + 0, /* KEY_KPRIGHTPAREN (180) */ + 0, /* KEY_NEW (AC New) (181) */ + 0, /* KEY_REDO (AC Redo/Repeat) (182) */ + VK_F13, /* KEY_F13 (183) */ + VK_F14, /* KEY_F14 (184) */ + VK_F15, /* KEY_F15 (185) */ + VK_F16, /* KEY_F16 (186) */ + VK_F17, /* KEY_F17 (187) */ + VK_F18, /* KEY_F18 (188) */ + VK_F19, /* KEY_F19 (189) */ + VK_F20, /* KEY_F20 (190) */ + VK_F21, /* KEY_F21 (191) */ + VK_F22, /* KEY_F22 (192) */ + VK_F23, /* KEY_F23 (193) */ + VK_F24, /* KEY_F24 (194) */ + 0, /* (195) */ + 0, /* (196) */ + 0, /* (197) */ + 0, /* (198) */ + 0, /* (199) */ + VK_PLAY, /* KEY_PLAYCD (200) */ + 0, /* KEY_PAUSECD (201) */ + 0, /* KEY_PROG3 (202) */ + 0, /* KEY_PROG4 (203) */ + 0, /* KEY_ALL_APPLICATIONS, KEY_DASHBOARD + * (AC Desktop Show All Applications) (204) */ + 0, /* KEY_SUSPEND (205) */ + 0, /* KEY_CLOSE (AC Close) (206) */ + VK_PLAY, /* KEY_PLAY (207) */ + 0, /* KEY_FASTFORWARD (208) */ + 0, /* KEY_BASSBOOST (209) */ + VK_PRINT | KBDEXT, /* KEY_PRINT (AC Print) (210) */ + 0, /* KEY_HP (211) */ + 0, /* KEY_CAMERA (212) */ + 0, /* KEY_SOUND (213) */ + 0, /* KEY_QUESTION (214) */ + 0, /* KEY_EMAIL (215) */ + 0, /* KEY_CHAT (216) */ + VK_BROWSER_SEARCH | KBDEXT, /* KEY_SEARCH (217) */ + 0, /* KEY_CONNECT (218) */ + 0, /* KEY_FINANCE (AL Checkbook/Finance) (219) */ + 0, /* KEY_SPORT (220) */ + 0, /* KEY_SHOP (221) */ + 0, /* KEY_ALTERASE (222) */ + 0, /* KEY_CANCEL (AC Cancel) (223) */ + 0, /* KEY_BRIGHTNESSDOWN (224) */ + 0, /* KEY_BRIGHTNESSUP (225) */ + 0, /* KEY_MEDIA (226) */ + 0, /* KEY_SWITCHVIDEOMODE + * (Cycle between available video outputs + * (Monitor/LCD/TV-out/etc)) (227) */ + 0, /* KEY_KBDILLUMTOGGLE (228) */ + 0, /* KEY_KBDILLUMDOWN (229) */ + 0, /* KEY_KBDILLUMUP (230) */ + 0, /* KEY_SEND (AC Send) (231) */ + 0, /* KEY_REPLY (AC Reply) (232) */ + 0, /* KEY_FORWARDMAIL (AC Forward Msg) (233) */ + 0, /* KEY_SAVE (AC Save) (234) */ + 0, /* KEY_DOCUMENTS (235) */ + 0, /* KEY_BATTERY (236) */ + 0, /* KEY_BLUETOOTH (237) */ + 0, /* KEY_WLAN (238) */ + 0, /* KEY_UWB (239) */ + 0, /* KEY_UNKNOWN (240) */ + 0, /* KEY_VIDEO_NEXT (drive next video source) (241) */ + 0, /* KEY_VIDEO_PREV (drive previous video source) (242) */ + 0, /* KEY_BRIGHTNESS_CYCLE + * (brightness up, after max is min) (243) */ + 0, /* KEY_BRIGHTNESS_AUTO, KEY_BRIGHTNESS_ZERO + * (Set Auto Brightness: manual brightness control is off, + * rely on ambient) (244) */ + 0, /* KEY_DISPLAY_OFF (display device to off state) (245) */ + 0, /* KEY_WWAN, KEY_WIMAX + * (Wireless WAN (LTE, UMTS, GSM, etc.)) (246) */ + 0, /* KEY_RFKILL (Key that controls all radios) (247) */ + 0, /* KEY_MICMUTE (Mute / unmute the microphone) (248) */ + 0, /* (249) */ + 0, /* (250) */ + 0, /* (251) */ + 0, /* (252) */ + 0, /* (253) */ + 0, /* (254) */ + 0, /* (255) */ +}; + +/** + * XKB + * + * Refer to X Keyboard Configuration Database: + * http://www.freedesktop.org/wiki/Software/XKeyboardConfig + */ + +/* TODO: Finish Japanese Keyboard */ + +static DWORD KEYCODE_TO_VKCODE_XKB[256] = { + 0, /* 0 */ + 0, /* 1 */ + 0, /* 2 */ + 0, /* 3 */ + 0, /* 4 */ + 0, /* 5 */ + 0, /* 6 */ + 0, /* 7 */ + 0, /* 8 */ + VK_ESCAPE, /* 9 */ + VK_KEY_1, /* 10 */ + VK_KEY_2, /* 11 */ + VK_KEY_3, /* 12 */ + VK_KEY_4, /* 13 */ + VK_KEY_5, /* 14 */ + VK_KEY_6, /* 15 */ + VK_KEY_7, /* 16 */ + VK_KEY_8, /* 17 */ + VK_KEY_9, /* 18 */ + VK_KEY_0, /* 19 */ + VK_OEM_MINUS, /* 20 */ + VK_OEM_PLUS, /* 21 */ + VK_BACK, /* 22 */ + VK_TAB, /* 23 */ + VK_KEY_Q, /* 24 */ + VK_KEY_W, /* 25 */ + VK_KEY_E, /* 26 */ + VK_KEY_R, /* 27 */ + VK_KEY_T, /* 28 */ + VK_KEY_Y, /* 29 */ + VK_KEY_U, /* 30 */ + VK_KEY_I, /* 31 */ + VK_KEY_O, /* 32 */ + VK_KEY_P, /* 33 */ + VK_OEM_4, /* 34 */ + VK_OEM_6, /* 35 */ + VK_RETURN, /* 36 */ + VK_LCONTROL, /* 37 */ + VK_KEY_A, /* 38 */ + VK_KEY_S, /* 39 */ + VK_KEY_D, /* 40 */ + VK_KEY_F, /* 41 */ + VK_KEY_G, /* 42 */ + VK_KEY_H, /* 43 */ + VK_KEY_J, /* 44 */ + VK_KEY_K, /* 45 */ + VK_KEY_L, /* 46 */ + VK_OEM_1, /* 47 */ + VK_OEM_7, /* 48 */ + VK_OEM_3, /* 49 */ + VK_LSHIFT, /* 50 */ + VK_OEM_5, /* 51 */ + VK_KEY_Z, /* 52 */ + VK_KEY_X, /* 53 */ + VK_KEY_C, /* 54 */ + VK_KEY_V, /* 55 */ + VK_KEY_B, /* 56 */ + VK_KEY_N, /* 57 */ + VK_KEY_M, /* 58 */ + VK_OEM_COMMA, /* 59 */ + VK_OEM_PERIOD, /* 60 */ + VK_OEM_2, /* 61 */ + VK_RSHIFT, /* 62 */ + VK_MULTIPLY, /* 63 */ + VK_LMENU, /* 64 */ + VK_SPACE, /* 65 */ + VK_CAPITAL, /* 66 */ + VK_F1, /* 67 */ + VK_F2, /* 68 */ + VK_F3, /* 69 */ + VK_F4, /* 70 */ + VK_F5, /* 71 */ + VK_F6, /* 72 */ + VK_F7, /* 73 */ + VK_F8, /* 74 */ + VK_F9, /* 75 */ + VK_F10, /* 76 */ + VK_NUMLOCK, /* 77 */ + VK_SCROLL, /* 78 */ + VK_NUMPAD7, /* 79 */ + VK_NUMPAD8, /* 80 */ + VK_NUMPAD9, /* 81 */ + VK_SUBTRACT, /* 82 */ + VK_NUMPAD4, /* 83 */ + VK_NUMPAD5, /* 84 */ + VK_NUMPAD6, /* 85 */ + VK_ADD, /* 86 */ + VK_NUMPAD1, /* 87 */ + VK_NUMPAD2, /* 88 */ + VK_NUMPAD3, /* 89 */ + VK_NUMPAD0, /* 90 */ + VK_DECIMAL, /* 91 */ + 0, /* 92 */ + 0, /* 93 */ + VK_OEM_102, /* 94 */ + VK_F11, /* 95 */ + VK_F12, /* 96 */ +#ifdef __sun + VK_HOME | KBDEXT, /* 97 */ + VK_UP | KBDEXT, /* 98 */ + VK_PRIOR | KBDEXT, /* 99 */ + VK_LEFT | KBDEXT, /* 100 */ + VK_HKTG, /* 101 */ + VK_RIGHT | KBDEXT, /* 102 */ + VK_END | KBDEXT, /* 103 */ + VK_DOWN | KBDEXT, /* 104 */ + VK_NEXT | KBDEXT, /* 105 */ + VK_INSERT | KBDEXT, /* 106 */ + VK_DELETE | KBDEXT, /* 107 */ + VK_RETURN | KBDEXT, /* 108 */ +#else + VK_ABNT_C1, /* 97 */ + VK_DBE_KATAKANA, /* 98 */ + VK_DBE_HIRAGANA, /* 99 */ + VK_CONVERT, /* 100 */ + VK_HKTG, /* 101 */ + VK_NONCONVERT, /* 102 */ + 0, /* 103 */ + VK_RETURN | KBDEXT, /* 104 */ + VK_RCONTROL | KBDEXT, /* 105 */ + VK_DIVIDE | KBDEXT, /* 106 */ + VK_SNAPSHOT | KBDEXT, /* 107 */ + VK_RMENU | KBDEXT, /* 108 */ +#endif + 0, /* KEY_LINEFEED 109 */ + VK_HOME | KBDEXT, /* 110 */ + VK_UP | KBDEXT, /* 111 */ + VK_PRIOR | KBDEXT, /* 112 */ + VK_LEFT | KBDEXT, /* 113 */ + VK_RIGHT | KBDEXT, /* 114 */ + VK_END | KBDEXT, /* 115 */ + VK_DOWN | KBDEXT, /* 116 */ + VK_NEXT | KBDEXT, /* 117 */ + VK_INSERT | KBDEXT, /* 118 */ + VK_DELETE | KBDEXT, /* 119 */ + 0, /* KEY_MACRO 120 */ + VK_VOLUME_MUTE | KBDEXT, /* 121 */ + VK_VOLUME_DOWN | KBDEXT, /* 122 */ + VK_VOLUME_UP | KBDEXT, /* 123 */ + 0, /* 124 */ + 0, /* 125 */ + 0, /* KEY_KPPLUSMINUS 126 */ + VK_PAUSE | KBDEXT, /* 127 */ + 0, /* KEY_SCALE 128 */ + VK_ABNT_C2, /* KEY_KPCOMMA 129 */ + VK_HANGUL, /* 130 */ + VK_HANJA, /* 131 */ + VK_OEM_8, /* 132 */ + VK_LWIN | KBDEXT, /* 133 */ + VK_RWIN | KBDEXT, /* 134 */ + VK_APPS | KBDEXT, /* 135 */ + 0, /* 136 */ + 0, /* 137 */ + 0, /* 138 */ + 0, /* 139 */ + 0, /* 140 */ + 0, /* 141 */ + 0, /* 142 */ + 0, /* 143 */ + 0, /* 144 */ + 0, /* 145 */ + VK_HELP, /* 146 */ + VK_APPS | KBDEXT, /* KEY_MENU 147 */ + 0, /* KEY_CALC 148 */ + 0, /* KEY_SETUP 149 */ + VK_SLEEP, /* KEY_SLEEP 150 */ + 0, /* KEY_WAKEUP 151 */ + 0, /* KEY_FILE 152 */ + 0, /* KEY_SEND 153 */ + 0, /* KEY_DELETEFILE 154 */ + VK_CONVERT, /* KEY_XFER 155 */ + VK_LAUNCH_APP1, /* KEY_PROG1 156 */ + VK_LAUNCH_APP2, /* KEY_PROG2 157 */ + 0, /* KEY_WWW 158 */ + 0, /* KEY_MSDOS 159 */ + 0, /* KEY_COFFEE 160 */ + 0, /* KEY_DIRECTION 161 */ + 0, /* KEY_CYCLEWINDOWS 162 */ + VK_LAUNCH_MAIL | KBDEXT, /* KEY_MAIL 163 */ + VK_BROWSER_FAVORITES | KBDEXT, /* KEY_BOOKMARKS 164 */ + 0, /* KEY_COMPUTER 165 */ + VK_BROWSER_BACK | KBDEXT, /* KEY_BACK 166 */ + VK_BROWSER_FORWARD | KBDEXT, /* KEY_FORWARD 167 */ + 0, /* KEY_CLOSECD 168 */ + 0, /* KEY_EJECTCD 169 */ + 0, /* KEY_EJECTCLOSECD 170 */ + VK_MEDIA_NEXT_TRACK | KBDEXT, /* KEY_NEXTSONG 171 */ + VK_MEDIA_PLAY_PAUSE | KBDEXT, /* KEY_PLAYPAUSE 172 */ + VK_MEDIA_PREV_TRACK | KBDEXT, /* KEY_PREVIOUSSONG 173 */ + VK_MEDIA_STOP | KBDEXT, /* KEY_STOPCD 174 */ + 0, /* KEY_RECORD 175 */ + 0, /* KEY_REWIND 176 */ + 0, /* KEY_PHONE 177 */ + 0, /* KEY_ISO 178 */ + 0, /* KEY_CONFIG 179 */ + VK_BROWSER_HOME | KBDEXT, /* KEY_HOMEPAGE 180 */ + VK_BROWSER_REFRESH | KBDEXT, /* KEY_REFRESH 181 */ + 0, /* KEY_EXIT 182 */ + 0, /* KEY_MOVE 183 */ + 0, /* KEY_EDIT 184 */ + 0, /* KEY_SCROLLUP 185 */ + 0, /* KEY_SCROLLDOWN 186 */ + 0, /* KEY_KPLEFTPAREN 187 */ + 0, /* KEY_KPRIGHTPAREN 188 */ + 0, /* KEY_NEW 189 */ + 0, /* KEY_REDO 190 */ + VK_F13, /* 191 */ + VK_F14, /* 192 */ + VK_F15, /* 193 */ + VK_F16, /* 194 */ + VK_F17, /* 195 */ + VK_F18, /* 196 */ + VK_F19, /* 197 */ + VK_F20, /* 198 */ + VK_F21, /* 199 */ + VK_F22, /* 200 */ + VK_F23, /* 201 */ + VK_F24, /* 202 */ + 0, /* 203 */ + 0, /* 204 */ + 0, /* 205 */ + VK_LWIN, /* 206 */ + 0, /* 207 */ + VK_PLAY, /* KEY_PLAYCD 208 */ + VK_PAUSE, /* KEY_PAUSECD 209 */ + 0, /* KEY_PROG3 210 */ + 0, /* KEY_PROG4 211 */ + 0, /* KEY_DASHBOARD 212 */ + 0, /* KEY_SUSPEND 213 */ + 0, /* KEY_CLOSE 214 */ + VK_PLAY, /* KEY_PLAY 215 */ + 0, /* KEY_FASTFORWARD 216 */ + 0, /* KEY_BASSBOOST 217 */ + VK_PRINT | KBDEXT, /* KEY_PRINT 218 */ + 0, /* KEY_HP 219 */ + 0, /* KEY_CAMERA 220 */ + 0, /* KEY_SOUND 221 */ + 0, /* KEY_QUESTION 222 */ + 0, /* KEY_EMAIL 223 */ + 0, /* KEY_CHAT 224 */ + VK_BROWSER_SEARCH | KBDEXT, /* KEY_SEARCH 225 */ + 0, /* KEY_CONNECT 226 */ + 0, /* KEY_FINANCE 227 */ + 0, /* KEY_SPORT 228 */ + 0, /* KEY_SHOP 229 */ + 0, /* KEY_ALTERASE 230 */ + 0, /* KEY_CANCEL 231 */ + 0, /* KEY_BRIGHTNESSDOWN 232 */ + 0, /* KEY_BRIGHTNESSUP 233 */ + 0, /* KEY_MEDIA 234 */ + 0, /* KEY_SWITCHVIDEOMODE 235 */ + 0, /* KEY_KBDILLUMTOGGLE 236 */ + 0, /* KEY_KBDILLUMDOWN 237 */ + 0, /* KEY_KBDILLUMUP 238 */ + 0, /* KEY_SEND 239 */ + 0, /* KEY_REPLY 240 */ + 0, /* KEY_FORWARDMAIL 241 */ + 0, /* KEY_SAVE 242 */ + 0, /* KEY_DOCUMENTS 243 */ + 0, /* KEY_BATTERY 244 */ + 0, /* KEY_BLUETOOTH 245 */ + 0, /* KEY_WLAN 246 */ + 0, /* KEY_UWB 247 */ + 0, /* KEY_UNKNOWN 248 */ + 0, /* KEY_VIDEO_NEXT 249 */ + 0, /* KEY_VIDEO_PREV 250 */ + 0, /* KEY_BRIGHTNESS_CYCLE 251 */ + 0, /* KEY_BRIGHTNESS_ZERO 252 */ + 0, /* KEY_DISPLAY_OFF 253 */ + 0, /* 254 */ + 0 /* 255 */ +}; + +DWORD GetVirtualKeyCodeFromKeycode(DWORD keycode, WINPR_KEYCODE_TYPE type) +{ + DWORD vkcode = 0; + + vkcode = VK_NONE; + + switch (type) + { + case WINPR_KEYCODE_TYPE_APPLE: + if (keycode < 0xFF) + vkcode = KEYCODE_TO_VKCODE_APPLE[keycode & 0xFF]; + break; + case WINPR_KEYCODE_TYPE_EVDEV: + if (keycode < 0xFF) + vkcode = KEYCODE_TO_VKCODE_EVDEV[keycode & 0xFF]; + break; + case WINPR_KEYCODE_TYPE_XKB: + if (keycode < 0xFF) + vkcode = KEYCODE_TO_VKCODE_XKB[keycode & 0xFF]; + break; + default: + break; + } + + if (!vkcode) + vkcode = VK_NONE; + + return vkcode; +} + +DWORD GetKeycodeFromVirtualKeyCode(DWORD keycode, WINPR_KEYCODE_TYPE type) +{ + DWORD* targetArray = NULL; + size_t targetSize = 0; + + switch (type) + { + case WINPR_KEYCODE_TYPE_APPLE: + targetArray = KEYCODE_TO_VKCODE_APPLE; + targetSize = ARRAYSIZE(KEYCODE_TO_VKCODE_APPLE); + break; + case WINPR_KEYCODE_TYPE_EVDEV: + targetArray = KEYCODE_TO_VKCODE_EVDEV; + targetSize = ARRAYSIZE(KEYCODE_TO_VKCODE_EVDEV); + break; + case WINPR_KEYCODE_TYPE_XKB: + targetArray = KEYCODE_TO_VKCODE_XKB; + targetSize = ARRAYSIZE(KEYCODE_TO_VKCODE_XKB); + break; + default: + return 0; + } + + for (DWORD index = 0; index < targetSize; index++) + { + if (keycode == targetArray[index]) + return index; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/scancode.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/scancode.c new file mode 100644 index 0000000000000000000000000000000000000000..bcf24b9ae8fe32015b035de25dc2497e508d9e0c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/scancode.c @@ -0,0 +1,328 @@ +/** + * WinPR: Windows Portable Runtime + * Keyboard Input + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include + +#include "../log.h" +#define TAG WINPR_TAG("input.scancode") + +/** + * Virtual Scan Codes + */ + +/** + * Keyboard Type 4 + * WINPR_KBD_TYPE_IBM_ENHANCED + * + * https://kbdlayout.info/KBDUSX/virtualkeys + */ + +static const DWORD KBD4T[128] = { + KBD4_T00, KBD4_T01, KBD4_T02, KBD4_T03, KBD4_T04, KBD4_T05, KBD4_T06, KBD4_T07, KBD4_T08, + KBD4_T09, KBD4_T0A, KBD4_T0B, KBD4_T0C, KBD4_T0D, KBD4_T0E, KBD4_T0F, KBD4_T10, KBD4_T11, + KBD4_T12, KBD4_T13, KBD4_T14, KBD4_T15, KBD4_T16, KBD4_T17, KBD4_T18, KBD4_T19, KBD4_T1A, + KBD4_T1B, KBD4_T1C, KBD4_T1D, KBD4_T1E, KBD4_T1F, KBD4_T20, KBD4_T21, KBD4_T22, KBD4_T23, + KBD4_T24, KBD4_T25, KBD4_T26, KBD4_T27, KBD4_T28, KBD4_T29, KBD4_T2A, KBD4_T2B, KBD4_T2C, + KBD4_T2D, KBD4_T2E, KBD4_T2F, KBD4_T30, KBD4_T31, KBD4_T32, KBD4_T33, KBD4_T34, KBD4_T35, + KBD4_T36, KBD4_T37, KBD4_T38, KBD4_T39, KBD4_T3A, KBD4_T3B, KBD4_T3C, KBD4_T3D, KBD4_T3E, + KBD4_T3F, KBD4_T40, KBD4_T41, KBD4_T42, KBD4_T43, KBD4_T44, KBD4_T45, KBD4_T46, KBD4_T47, + KBD4_T48, KBD4_T49, KBD4_T4A, KBD4_T4B, KBD4_T4C, KBD4_T4D, KBD4_T4E, KBD4_T4F, KBD4_T50, + KBD4_T51, KBD4_T52, KBD4_T53, KBD4_T54, KBD4_T55, KBD4_T56, KBD4_T57, KBD4_T58, KBD4_T59, + KBD4_T5A, KBD4_T5B, KBD4_T5C, KBD4_T5D, KBD4_T5E, KBD4_T5F, KBD4_T60, KBD4_T61, KBD4_T62, + KBD4_T63, KBD4_T64, KBD4_T65, KBD4_T66, KBD4_T67, KBD4_T68, KBD4_T69, KBD4_T6A, KBD4_T6B, + KBD4_T6C, KBD4_T6D, KBD4_T6E, KBD4_T6F, KBD4_T70, KBD4_T71, KBD4_T72, KBD4_T73, KBD4_T74, + KBD4_T75, KBD4_T76, KBD4_T77, KBD4_T78, KBD4_T79, KBD4_T7A, KBD4_T7B, KBD4_T7C, KBD4_T7D, + KBD4_T7E, KBD4_T7F +}; + +static const DWORD KBD4X[128] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, KBD4_X10, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, KBD4_X19, VK_NONE, + VK_NONE, KBD4_X1C, KBD4_X1D, VK_NONE, VK_NONE, KBD4_X20, KBD4_X21, KBD4_X22, VK_NONE, + KBD4_X24, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, KBD4_X2E, VK_NONE, KBD4_X30, VK_NONE, KBD4_X32, VK_NONE, VK_NONE, KBD4_X35, + VK_NONE, KBD4_X37, KBD4_X38, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, KBD4_X46, KBD4_X47, + KBD4_X48, KBD4_X49, VK_NONE, KBD4_X4B, VK_NONE, KBD4_X4D, VK_NONE, KBD4_X4F, KBD4_X50, + KBD4_X51, KBD4_X52, KBD4_X53, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, KBD4_X5B, KBD4_X5C, KBD4_X5D, KBD4_X5E, KBD4_X5F, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, KBD4_X65, KBD4_X66, KBD4_X67, KBD4_X68, KBD4_X69, KBD4_X6A, KBD4_X6B, + KBD4_X6C, KBD4_X6D, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, +}; + +static const DWORD KBD4X_1[128] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_PAUSE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE +}; + +/** + * Keyboard Type 7 + * WINPR_KBD_TYPE_JAPANESE + * + * https://kbdlayout.info/KBDJAV/virtualkeys + */ + +static const DWORD KBD7T[128] = { + KBD7_T00, KBD7_T01, KBD7_T02, KBD7_T03, KBD7_T04, KBD7_T05, KBD7_T06, KBD7_T07, KBD7_T08, + KBD7_T09, KBD7_T0A, KBD7_T0B, KBD7_T0C, KBD7_T0D, KBD7_T0E, KBD7_T0F, KBD7_T10, KBD7_T11, + KBD7_T12, KBD7_T13, KBD7_T14, KBD7_T15, KBD7_T16, KBD7_T17, KBD7_T18, KBD7_T19, KBD7_T1A, + KBD7_T1B, KBD7_T1C, KBD7_T1D, KBD7_T1E, KBD7_T1F, KBD7_T20, KBD7_T21, KBD7_T22, KBD7_T23, + KBD7_T24, KBD7_T25, KBD7_T26, KBD7_T27, KBD7_T28, KBD7_T29, KBD7_T2A, KBD7_T2B, KBD7_T2C, + KBD7_T2D, KBD7_T2E, KBD7_T2F, KBD7_T30, KBD7_T31, KBD7_T32, KBD7_T33, KBD7_T34, KBD7_T35, + KBD7_T36, KBD7_T37, KBD7_T38, KBD7_T39, KBD7_T3A, KBD7_T3B, KBD7_T3C, KBD7_T3D, KBD7_T3E, + KBD7_T3F, KBD7_T40, KBD7_T41, KBD7_T42, KBD7_T43, KBD7_T44, KBD7_T45, KBD7_T46, KBD7_T47, + KBD7_T48, KBD7_T49, KBD7_T4A, KBD7_T4B, KBD7_T4C, KBD7_T4D, KBD7_T4E, KBD7_T4F, KBD7_T50, + KBD7_T51, KBD7_T52, KBD7_T53, KBD7_T54, KBD7_T55, KBD7_T56, KBD7_T57, KBD7_T58, KBD7_T59, + KBD7_T5A, KBD7_T5B, KBD7_T5C, KBD7_T5D, KBD7_T5E, KBD7_T5F, KBD7_T60, KBD7_T61, KBD7_T62, + KBD7_T63, KBD7_T64, KBD7_T65, KBD7_T66, KBD7_T67, KBD7_T68, KBD7_T69, KBD7_T6A, KBD7_T6B, + KBD7_T6C, KBD7_T6D, KBD7_T6E, KBD7_T6F, KBD7_T70, KBD7_T71, KBD7_T72, KBD7_T73, KBD7_T74, + KBD7_T75, KBD7_T76, KBD7_T77, KBD7_T78, KBD7_T79, KBD7_T7A, KBD7_T7B, KBD7_T7C, KBD7_T7D, + KBD7_T7E, KBD7_T7F +}; + +static const DWORD KBD7X[256] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, KBD7_X10, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, KBD7_X19, VK_NONE, + VK_NONE, KBD7_X1C, KBD7_X1D, VK_NONE, VK_NONE, KBD7_X20, KBD7_X21, KBD7_X22, VK_NONE, + KBD7_X24, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, KBD7_X2E, VK_NONE, KBD7_X30, VK_NONE, KBD7_X32, KBD7_X33, VK_NONE, KBD7_X35, + VK_NONE, KBD7_X37, KBD7_X38, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, KBD7_X42, KBD7_X43, KBD7_X44, VK_NONE, KBD7_X46, KBD7_X47, + KBD7_X48, KBD7_X49, VK_NONE, KBD7_X4B, VK_NONE, KBD7_X4D, VK_NONE, KBD7_X4F, KBD7_X50, + KBD7_X51, KBD7_X52, KBD7_X53, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, KBD7_X5B, KBD7_X5C, KBD7_X5D, KBD7_X5E, KBD7_X5F, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, KBD7_X65, KBD7_X66, KBD7_X67, KBD7_X68, KBD7_X69, KBD7_X6A, KBD7_X6B, + KBD7_X6C, KBD7_X6D, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + KBD7_XF1, KBD7_XF2, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE +}; + +static const DWORD KBD7X_1[128] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_PAUSE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE +}; + +/** + * Keyboard Type 8 + * WINPR_KBD_TYPE_KOREAN + * + * https://kbdlayout.info/kbdkor/virtualkeys + */ +// clang-format off +static const DWORD KBD8T[128] = { + VK_NONE, VK_ESCAPE, VK_KEY_1, VK_KEY_3, VK_KEY_4, VK_KEY_5, VK_KEY_6, + VK_KEY_7, VK_KEY_8, VK_KEY_9, VK_KEY_0, VK_OEM_MINUS, VK_OEM_PLUS, VK_BACK, + VK_TAB, VK_KEY_Q, VK_KEY_W, VK_KEY_E, VK_KEY_R, VK_KEY_T, VK_KEY_Y, + VK_KEY_U, VK_KEY_I, VK_KEY_O, VK_KEY_P, VK_OEM_4, VK_OEM_6, VK_RETURN, + VK_LCONTROL, VK_KEY_A, VK_KEY_S, VK_KEY_D, VK_KEY_F, VK_KEY_G, VK_KEY_H, + VK_KEY_J, VK_KEY_K, VK_KEY_L, VK_OEM_1, VK_OEM_7, VK_OEM_3, VK_LSHIFT, + VK_OEM_5, VK_KEY_Z, VK_KEY_X, VK_KEY_C, VK_KEY_V, VK_KEY_B, VK_KEY_N, + VK_KEY_M, VK_OEM_COMMA, VK_OEM_PERIOD, VK_OEM_2, VK_RSHIFT, VK_MULTIPLY, VK_LMENU, + VK_SPACE, VK_CAPITAL, VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, + VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_NUMLOCK, VK_SCROLL, + VK_HOME, VK_UP, VK_PRIOR, VK_SUBTRACT, VK_LEFT, VK_CLEAR, VK_RIGHT, + VK_ADD, VK_END, VK_DOWN, VK_NEXT, VK_INSERT, VK_DELETE, VK_SNAPSHOT, + VK_NONE, VK_OEM_102, VK_F11, VK_F12, VK_CLEAR, VK_OEM_WSCTRL,VK_DBE_KATAKANA, + VK_OEM_JUMP, VK_DBE_FLUSHSTRING,VK_OEM_BACKTAB,VK_OEM_AUTO, VK_NONE, VK_DBE_NOCODEINPUT,VK_HELP, + VK_NONE, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, + VK_F19, VK_F20, VK_F21, VK_F22, VK_F23, VK_OEM_PA3, VK_NONE, + VK_OEM_RESET,VK_NONE, VK_ABNT_C1, VK_NONE, VK_NONE, VK_F24, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_OEM_PA1, VK_TAB, VK_NONE, VK_ABNT_C2, + VK_OEM_PA2 +}; + +static const DWORD KBD8X[256] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_MEDIA_PREV_TRACK, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_MEDIA_NEXT_TRACK, + VK_NONE, VK_NONE, VK_RETURN, VK_HANJA, VK_NONE, VK_NONE, VK_VOLUME_MUTE, VK_LAUNCH_APP2, + VK_MEDIA_PLAY_PAUSE, VK_NONE, VK_MEDIA_STOP, VK_NONE, VK_NONE, VK_NONE, VK_NONE,VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_VOLUME_DOWN, VK_NONE, VK_VOLUME_UP, VK_NONE, + VK_BROWSER_HOME, VK_NONE, VK_NONE, VK_DIVIDE, VK_NONE, VK_SNAPSHOT, VK_KANA, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_CANCEL, VK_HOME, VK_UP, VK_PRIOR, VK_NONE, VK_LEFT, VK_NONE, VK_RIGHT, VK_NONE, + VK_END, VK_DOWN,VK_NEXT, VK_INSERT, VK_DELETE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_LWIN, VK_RWIN, VK_APPS, VK_NONE, VK_SLEEP, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_BROWSER_SEARCH, VK_BROWSER_FAVORITES, VK_BROWSER_REFRESH, + VK_BROWSER_STOP, VK_BROWSER_FORWARD, VK_BROWSER_BACK,VK_LAUNCH_APP1, VK_LAUNCH_MAIL, + VK_LAUNCH_MEDIA_SELECT, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_HANJA, + VK_KANA, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE +}; +// clang-format on + +static const DWORD KBD8X_1[128] = { + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_PAUSE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, + VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE, VK_NONE +}; + +DWORD GetVirtualKeyCodeFromVirtualScanCode(DWORD scancode, DWORD dwKeyboardType) +{ + const DWORD codeIndex = scancode & 0xFF; + + if (codeIndex > 127) + return VK_NONE; + + switch (dwKeyboardType) + { + /* IBM and compatible */ + case WINPR_KBD_TYPE_IBM_PC_XT: + case WINPR_KBD_TYPE_OLIVETTI_ICO: + case WINPR_KBD_TYPE_IBM_PC_AT: + case WINPR_KBD_TYPE_IBM_ENHANCED: + if (scancode & KBDMULTIVK) + return KBD4X_1[codeIndex]; + if (scancode & KBDEXT) + return KBD4X[codeIndex]; + return KBD4T[codeIndex]; + + case WINPR_KBD_TYPE_JAPANESE: + if (scancode & KBDMULTIVK) + return KBD7X_1[codeIndex]; + if (scancode & KBDEXT) + return KBD7X[codeIndex]; + return KBD7T[codeIndex]; + case WINPR_KBD_TYPE_KOREAN: + if (scancode & KBDMULTIVK) + return KBD8X_1[codeIndex]; + if (scancode & KBDEXT) + return KBD8X[codeIndex]; + return KBD8T[codeIndex]; + case WINPR_KBD_TYPE_NOKIA_1050: + case WINPR_KBD_TYPE_NOKIA_9140: + default: + WLog_ERR(TAG, "dwKeyboardType=0x%08" PRIx32 " not supported", dwKeyboardType); + return VK_NONE; + } +} + +static DWORD get_scancode(DWORD vkcode, const DWORD* array, size_t arraysize, DWORD flag) +{ + WINPR_ASSERT(array); + for (size_t x = 0; x < arraysize; x++) + { + const DWORD cur = array[x]; + if (cur == vkcode) + return WINPR_ASSERTING_INT_CAST(DWORD, x) | flag; + } + return VK_NONE; +} + +DWORD GetVirtualScanCodeFromVirtualKeyCode(DWORD vkcode, DWORD dwKeyboardType) +{ + DWORD codeIndex = vkcode & 0xFF; + + switch (dwKeyboardType) + { + case WINPR_KBD_TYPE_IBM_PC_XT: + case WINPR_KBD_TYPE_OLIVETTI_ICO: + case WINPR_KBD_TYPE_IBM_PC_AT: + case WINPR_KBD_TYPE_IBM_ENHANCED: + if (vkcode & KBDMULTIVK) + return get_scancode(codeIndex, KBD4X_1, ARRAYSIZE(KBD4X_1), KBDMULTIVK); + if (vkcode & KBDEXT) + return get_scancode(codeIndex, KBD4X, ARRAYSIZE(KBD4X), KBDEXT); + else + return get_scancode(codeIndex, KBD4T, ARRAYSIZE(KBD4T), 0); + + case WINPR_KBD_TYPE_JAPANESE: + if (vkcode & KBDMULTIVK) + return get_scancode(codeIndex, KBD7X_1, ARRAYSIZE(KBD7X_1), KBDMULTIVK); + if (vkcode & KBDEXT) + return get_scancode(codeIndex, KBD7X, ARRAYSIZE(KBD7X), KBDEXT); + else + return get_scancode(codeIndex, KBD7T, ARRAYSIZE(KBD7T), 0); + case WINPR_KBD_TYPE_KOREAN: + if (vkcode & KBDMULTIVK) + return get_scancode(codeIndex, KBD8X_1, ARRAYSIZE(KBD8X_1), KBDMULTIVK); + if (vkcode & KBDEXT) + return get_scancode(codeIndex, KBD8X, ARRAYSIZE(KBD8X), KBDEXT); + else + return get_scancode(codeIndex, KBD8T, ARRAYSIZE(KBD8T), 0); + case WINPR_KBD_TYPE_NOKIA_1050: + case WINPR_KBD_TYPE_NOKIA_9140: + default: + WLog_ERR(TAG, "dwKeyboardType=0x%08" PRIx32 " not supported", dwKeyboardType); + return 0; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/virtualkey.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/virtualkey.c new file mode 100644 index 0000000000000000000000000000000000000000..66f9b0951d3bd7663bb7b2e700d40fa9af3bbac6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/input/virtualkey.c @@ -0,0 +1,459 @@ +/** + * WinPR: Windows Portable Runtime + * Keyboard Input + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +/** + * Virtual Key Codes + */ + +typedef struct +{ + DWORD code; /* Windows Virtual Key Code */ + const char* name; /* Virtual Key Code Name */ +} VIRTUAL_KEY_CODE; + +static const VIRTUAL_KEY_CODE VIRTUAL_KEY_CODE_TABLE[256] = { + { 0, NULL }, + { VK_LBUTTON, "VK_LBUTTON" }, + { VK_RBUTTON, "VK_RBUTTON" }, + { VK_CANCEL, "VK_CANCEL" }, + { VK_MBUTTON, "VK_MBUTTON" }, + { VK_XBUTTON1, "VK_XBUTTON1" }, + { VK_XBUTTON2, "VK_XBUTTON2" }, + { 0, NULL }, + { VK_BACK, "VK_BACK" }, + { VK_TAB, "VK_TAB" }, + { 0, NULL }, + { 0, NULL }, + { VK_CLEAR, "VK_CLEAR" }, + { VK_RETURN, "VK_RETURN" }, + { 0, NULL }, + { 0, NULL }, + { VK_SHIFT, "VK_SHIFT" }, + { VK_CONTROL, "VK_CONTROL" }, + { VK_MENU, "VK_MENU" }, + { VK_PAUSE, "VK_PAUSE" }, + { VK_CAPITAL, "VK_CAPITAL" }, + { VK_KANA, "VK_KANA" }, /* also VK_HANGUL */ + { 0, NULL }, + { VK_JUNJA, "VK_JUNJA" }, + { VK_FINAL, "VK_FINAL" }, + { VK_KANJI, "VK_KANJI" }, /* also VK_HANJA */ + { VK_HKTG, "VK_HKTG" }, + { VK_ESCAPE, "VK_ESCAPE" }, + { VK_CONVERT, "VK_CONVERT" }, + { VK_NONCONVERT, "VK_NONCONVERT" }, + { VK_ACCEPT, "VK_ACCEPT" }, + { VK_MODECHANGE, "VK_MODECHANGE" }, + { VK_SPACE, "VK_SPACE" }, + { VK_PRIOR, "VK_PRIOR" }, + { VK_NEXT, "VK_NEXT" }, + { VK_END, "VK_END" }, + { VK_HOME, "VK_HOME" }, + { VK_LEFT, "VK_LEFT" }, + { VK_UP, "VK_UP" }, + { VK_RIGHT, "VK_RIGHT" }, + { VK_DOWN, "VK_DOWN" }, + { VK_SELECT, "VK_SELECT" }, + { VK_PRINT, "VK_PRINT" }, + { VK_EXECUTE, "VK_EXECUTE" }, + { VK_SNAPSHOT, "VK_SNAPSHOT" }, + { VK_INSERT, "VK_INSERT" }, + { VK_DELETE, "VK_DELETE" }, + { VK_HELP, "VK_HELP" }, + { VK_KEY_0, "VK_KEY_0" }, + { VK_KEY_1, "VK_KEY_1" }, + { VK_KEY_2, "VK_KEY_2" }, + { VK_KEY_3, "VK_KEY_3" }, + { VK_KEY_4, "VK_KEY_4" }, + { VK_KEY_5, "VK_KEY_5" }, + { VK_KEY_6, "VK_KEY_6" }, + { VK_KEY_7, "VK_KEY_7" }, + { VK_KEY_8, "VK_KEY_8" }, + { VK_KEY_9, "VK_KEY_9" }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { VK_KEY_A, "VK_KEY_A" }, + { VK_KEY_B, "VK_KEY_B" }, + { VK_KEY_C, "VK_KEY_C" }, + { VK_KEY_D, "VK_KEY_D" }, + { VK_KEY_E, "VK_KEY_E" }, + { VK_KEY_F, "VK_KEY_F" }, + { VK_KEY_G, "VK_KEY_G" }, + { VK_KEY_H, "VK_KEY_H" }, + { VK_KEY_I, "VK_KEY_I" }, + { VK_KEY_J, "VK_KEY_J" }, + { VK_KEY_K, "VK_KEY_K" }, + { VK_KEY_L, "VK_KEY_L" }, + { VK_KEY_M, "VK_KEY_M" }, + { VK_KEY_N, "VK_KEY_N" }, + { VK_KEY_O, "VK_KEY_O" }, + { VK_KEY_P, "VK_KEY_P" }, + { VK_KEY_Q, "VK_KEY_Q" }, + { VK_KEY_R, "VK_KEY_R" }, + { VK_KEY_S, "VK_KEY_S" }, + { VK_KEY_T, "VK_KEY_T" }, + { VK_KEY_U, "VK_KEY_U" }, + { VK_KEY_V, "VK_KEY_V" }, + { VK_KEY_W, "VK_KEY_W" }, + { VK_KEY_X, "VK_KEY_X" }, + { VK_KEY_Y, "VK_KEY_Y" }, + { VK_KEY_Z, "VK_KEY_Z" }, + { VK_LWIN, "VK_LWIN" }, + { VK_RWIN, "VK_RWIN" }, + { VK_APPS, "VK_APPS" }, + { 0, NULL }, + { VK_SLEEP, "VK_SLEEP" }, + { VK_NUMPAD0, "VK_NUMPAD0" }, + { VK_NUMPAD1, "VK_NUMPAD1" }, + { VK_NUMPAD2, "VK_NUMPAD2" }, + { VK_NUMPAD3, "VK_NUMPAD3" }, + { VK_NUMPAD4, "VK_NUMPAD4" }, + { VK_NUMPAD5, "VK_NUMPAD5" }, + { VK_NUMPAD6, "VK_NUMPAD6" }, + { VK_NUMPAD7, "VK_NUMPAD7" }, + { VK_NUMPAD8, "VK_NUMPAD8" }, + { VK_NUMPAD9, "VK_NUMPAD9" }, + { VK_MULTIPLY, "VK_MULTIPLY" }, + { VK_ADD, "VK_ADD" }, + { VK_SEPARATOR, "VK_SEPARATOR" }, + { VK_SUBTRACT, "VK_SUBTRACT" }, + { VK_DECIMAL, "VK_DECIMAL" }, + { VK_DIVIDE, "VK_DIVIDE" }, + { VK_F1, "VK_F1" }, + { VK_F2, "VK_F2" }, + { VK_F3, "VK_F3" }, + { VK_F4, "VK_F4" }, + { VK_F5, "VK_F5" }, + { VK_F6, "VK_F6" }, + { VK_F7, "VK_F7" }, + { VK_F8, "VK_F8" }, + { VK_F9, "VK_F9" }, + { VK_F10, "VK_F10" }, + { VK_F11, "VK_F11" }, + { VK_F12, "VK_F12" }, + { VK_F13, "VK_F13" }, + { VK_F14, "VK_F14" }, + { VK_F15, "VK_F15" }, + { VK_F16, "VK_F16" }, + { VK_F17, "VK_F17" }, + { VK_F18, "VK_F18" }, + { VK_F19, "VK_F19" }, + { VK_F20, "VK_F20" }, + { VK_F21, "VK_F21" }, + { VK_F22, "VK_F22" }, + { VK_F23, "VK_F23" }, + { VK_F24, "VK_F24" }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { VK_NUMLOCK, "VK_NUMLOCK" }, + { VK_SCROLL, "VK_SCROLL" }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { VK_LSHIFT, "VK_LSHIFT" }, + { VK_RSHIFT, "VK_RSHIFT" }, + { VK_LCONTROL, "VK_LCONTROL" }, + { VK_RCONTROL, "VK_RCONTROL" }, + { VK_LMENU, "VK_LMENU" }, + { VK_RMENU, "VK_RMENU" }, + { VK_BROWSER_BACK, "VK_BROWSER_BACK" }, + { VK_BROWSER_FORWARD, "VK_BROWSER_FORWARD" }, + { VK_BROWSER_REFRESH, "VK_BROWSER_REFRESH" }, + { VK_BROWSER_STOP, "VK_BROWSER_STOP" }, + { VK_BROWSER_SEARCH, "VK_BROWSER_SEARCH" }, + { VK_BROWSER_FAVORITES, "VK_BROWSER_FAVORITES" }, + { VK_BROWSER_HOME, "VK_BROWSER_HOME" }, + { VK_VOLUME_MUTE, "VK_VOLUME_MUTE" }, + { VK_VOLUME_DOWN, "VK_VOLUME_DOWN" }, + { VK_VOLUME_UP, "VK_VOLUME_UP" }, + { VK_MEDIA_NEXT_TRACK, "VK_MEDIA_NEXT_TRACK" }, + { VK_MEDIA_PREV_TRACK, "VK_MEDIA_PREV_TRACK" }, + { VK_MEDIA_STOP, "VK_MEDIA_STOP" }, + { VK_MEDIA_PLAY_PAUSE, "VK_MEDIA_PLAY_PAUSE" }, + { VK_LAUNCH_MAIL, "VK_LAUNCH_MAIL" }, + { VK_MEDIA_SELECT, "VK_MEDIA_SELECT" }, + { VK_LAUNCH_APP1, "VK_LAUNCH_APP1" }, + { VK_LAUNCH_APP2, "VK_LAUNCH_APP2" }, + { 0, NULL }, + { 0, NULL }, + { VK_OEM_1, "VK_OEM_1" }, + { VK_OEM_PLUS, "VK_OEM_PLUS" }, + { VK_OEM_COMMA, "VK_OEM_COMMA" }, + { VK_OEM_MINUS, "VK_OEM_MINUS" }, + { VK_OEM_PERIOD, "VK_OEM_PERIOD" }, + { VK_OEM_2, "VK_OEM_2" }, + { VK_OEM_3, "VK_OEM_3" }, + { VK_ABNT_C1, "VK_ABNT_C1" }, + { VK_ABNT_C2, "VK_ABNT_C2" }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { VK_OEM_4, "VK_OEM_4" }, + { VK_OEM_5, "VK_OEM_5" }, + { VK_OEM_6, "VK_OEM_6" }, + { VK_OEM_7, "VK_OEM_7" }, + { VK_OEM_8, "VK_OEM_8" }, + { 0, NULL }, + { 0, NULL }, + { VK_OEM_102, "VK_OEM_102" }, + { 0, NULL }, + { 0, NULL }, + { VK_PROCESSKEY, "VK_PROCESSKEY" }, + { 0, NULL }, + { VK_PACKET, "VK_PACKET" }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { 0, NULL }, + { VK_ATTN, "VK_ATTN" }, + { VK_CRSEL, "VK_CRSEL" }, + { VK_EXSEL, "VK_EXSEL" }, + { VK_EREOF, "VK_EREOF" }, + { VK_PLAY, "VK_PLAY" }, + { VK_ZOOM, "VK_ZOOM" }, + { VK_NONAME, "VK_NONAME" }, + { VK_PA1, "VK_PA1" }, + { VK_OEM_CLEAR, "VK_OEM_CLEAR" }, + { 0, NULL } +}; + +typedef struct +{ + const char* name; + DWORD vkcode; +} XKB_KEYNAME; + +static XKB_KEYNAME XKB_KEYNAME_TABLE[] = { + { "BKSP", VK_BACK }, + { "TAB", VK_TAB }, + { "RTRN", VK_RETURN }, + { "LFSH", VK_LSHIFT }, + { "LALT", VK_LMENU }, + { "CAPS", VK_CAPITAL }, + { "ESC", VK_ESCAPE }, + { "SPCE", VK_SPACE }, + { "AE10", VK_KEY_0 }, + { "AE01", VK_KEY_1 }, + { "AE02", VK_KEY_2 }, + { "AE03", VK_KEY_3 }, + { "AE04", VK_KEY_4 }, + { "AE05", VK_KEY_5 }, + { "AE06", VK_KEY_6 }, + { "AE07", VK_KEY_7 }, + { "AE08", VK_KEY_8 }, + { "AE09", VK_KEY_9 }, + { "AC01", VK_KEY_A }, + { "AB05", VK_KEY_B }, + { "AB03", VK_KEY_C }, + { "AC03", VK_KEY_D }, + { "AD03", VK_KEY_E }, + { "AC04", VK_KEY_F }, + { "AC05", VK_KEY_G }, + { "AC06", VK_KEY_H }, + { "AD08", VK_KEY_I }, + { "AC07", VK_KEY_J }, + { "AC08", VK_KEY_K }, + { "AC09", VK_KEY_L }, + { "AB07", VK_KEY_M }, + { "AB06", VK_KEY_N }, + { "AD09", VK_KEY_O }, + { "AD10", VK_KEY_P }, + { "AD01", VK_KEY_Q }, + { "AD04", VK_KEY_R }, + { "AC02", VK_KEY_S }, + { "AD05", VK_KEY_T }, + { "AD07", VK_KEY_U }, + { "AB04", VK_KEY_V }, + { "AD02", VK_KEY_W }, + { "AB02", VK_KEY_X }, + { "AD06", VK_KEY_Y }, + { "AB01", VK_KEY_Z }, + { "KP0", VK_NUMPAD0 }, + { "KP1", VK_NUMPAD1 }, + { "KP2", VK_NUMPAD2 }, + { "KP3", VK_NUMPAD3 }, + { "KP4", VK_NUMPAD4 }, + { "KP5", VK_NUMPAD5 }, + { "KP6", VK_NUMPAD6 }, + { "KP7", VK_NUMPAD7 }, + { "KP8", VK_NUMPAD8 }, + { "KP9", VK_NUMPAD9 }, + { "KPMU", VK_MULTIPLY }, + { "KPAD", VK_ADD }, + { "KPSU", VK_SUBTRACT }, + { "KPDL", VK_DECIMAL }, + { "AB10", VK_OEM_2 }, + { "FK01", VK_F1 }, + { "FK02", VK_F2 }, + { "FK03", VK_F3 }, + { "FK04", VK_F4 }, + { "FK05", VK_F5 }, + { "FK06", VK_F6 }, + { "FK07", VK_F7 }, + { "FK08", VK_F8 }, + { "FK09", VK_F9 }, + { "FK10", VK_F10 }, + { "FK11", VK_F11 }, + { "FK12", VK_F12 }, + { "NMLK", VK_NUMLOCK }, + { "SCLK", VK_SCROLL }, + { "RTSH", VK_RSHIFT }, + { "LCTL", VK_LCONTROL }, + { "AC10", VK_OEM_1 }, + { "AE12", VK_OEM_PLUS }, + { "AB08", VK_OEM_COMMA }, + { "AE11", VK_OEM_MINUS }, + { "AB09", VK_OEM_PERIOD }, + { "TLDE", VK_OEM_3 }, + { "AB11", VK_ABNT_C1 }, + { "I129", VK_ABNT_C2 }, + { "AD11", VK_OEM_4 }, + { "BKSL", VK_OEM_5 }, + { "AD12", VK_OEM_6 }, + { "AC11", VK_OEM_7 }, + { "LSGT", VK_OEM_102 }, + { "KPEN", VK_RETURN | KBDEXT }, + { "PAUS", VK_PAUSE | KBDEXT }, + { "PGUP", VK_PRIOR | KBDEXT }, + { "PGDN", VK_NEXT | KBDEXT }, + { "END", VK_END | KBDEXT }, + { "HOME", VK_HOME | KBDEXT }, + { "LEFT", VK_LEFT | KBDEXT }, + { "UP", VK_UP | KBDEXT }, + { "RGHT", VK_RIGHT | KBDEXT }, + { "DOWN", VK_DOWN | KBDEXT }, + { "PRSC", VK_SNAPSHOT | KBDEXT }, + { "INS", VK_INSERT | KBDEXT }, + { "DELE", VK_DELETE | KBDEXT }, + { "LWIN", VK_LWIN | KBDEXT }, + { "RWIN", VK_RWIN | KBDEXT }, + { "COMP", VK_APPS | KBDEXT }, + { "KPDV", VK_DIVIDE | KBDEXT }, + { "RCTL", VK_RCONTROL | KBDEXT }, + { "RALT", VK_RMENU | KBDEXT }, + + /* Japanese */ + + { "HENK", VK_CONVERT }, + { "MUHE", VK_NONCONVERT }, + { "HKTG", VK_HKTG }, + + // { "AE13", VK_BACKSLASH_JP }, // JP + // { "LVL3", 0x54} +}; + +const char* GetVirtualKeyName(DWORD vkcode) +{ + const char* vkname = NULL; + + if (vkcode < ARRAYSIZE(VIRTUAL_KEY_CODE_TABLE)) + vkname = VIRTUAL_KEY_CODE_TABLE[vkcode].name; + + if (!vkname) + vkname = "VK_NONE"; + + return vkname; +} + +DWORD GetVirtualKeyCodeFromName(const char* vkname) +{ + for (size_t i = 0; i < ARRAYSIZE(VIRTUAL_KEY_CODE_TABLE); i++) + { + if (VIRTUAL_KEY_CODE_TABLE[i].name) + { + if (strcmp(vkname, VIRTUAL_KEY_CODE_TABLE[i].name) == 0) + return VIRTUAL_KEY_CODE_TABLE[i].code; + } + } + + return VK_NONE; +} + +DWORD GetVirtualKeyCodeFromXkbKeyName(const char* xkbname) +{ + for (size_t i = 0; i < ARRAYSIZE(XKB_KEYNAME_TABLE); i++) + { + if (XKB_KEYNAME_TABLE[i].name) + { + if (strcmp(xkbname, XKB_KEYNAME_TABLE[i].name) == 0) + return XKB_KEYNAME_TABLE[i].vkcode; + } + } + + return VK_NONE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..296cf8c2711d5e8ac264fa794b048152bab3a093 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-interlocked cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(interlocked.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..90767f3c69470010b6e96f7f2d9df17a5f86e292 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "interlocked") +set(MINWIN_LONG_NAME "Interlocked Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/interlocked.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/interlocked.c new file mode 100644 index 0000000000000000000000000000000000000000..eb11709048a72800b912459836c64611f388ee16 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/interlocked.c @@ -0,0 +1,534 @@ +/** + * WinPR: Windows Portable Runtime + * Interlocked Singly-Linked Lists + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include + +/* Singly-Linked List */ + +#ifndef _WIN32 + +#include +#include + +VOID InitializeSListHead(WINPR_PSLIST_HEADER ListHead) +{ + WINPR_ASSERT(ListHead); +#ifdef _WIN64 + ListHead->s.Alignment = 0; + ListHead->s.Region = 0; + ListHead->Header8.Init = 1; +#else + ListHead->Alignment = 0; +#endif +} + +WINPR_PSLIST_ENTRY InterlockedPushEntrySList(WINPR_PSLIST_HEADER ListHead, + WINPR_PSLIST_ENTRY ListEntry) +{ + WINPR_SLIST_HEADER old = { 0 }; + WINPR_SLIST_HEADER newHeader = { 0 }; + + WINPR_ASSERT(ListHead); + WINPR_ASSERT(ListEntry); +#ifdef _WIN64 + newHeader.HeaderX64.NextEntry = (((ULONG_PTR)ListEntry) >> 4); + + while (1) + { + old = *ListHead; + + ListEntry->Next = (PSLIST_ENTRY)(((ULONG_PTR)old.HeaderX64.NextEntry) << 4); + + newHeader.HeaderX64.Depth = old.HeaderX64.Depth + 1; + newHeader.HeaderX64.Sequence = old.HeaderX64.Sequence + 1; + + if (InterlockedCompareExchange64((LONGLONG*)ListHead, newHeader).Alignment, old).Alignment)) + { + InterlockedCompareExchange64(&((LONGLONG*)ListHead)[1], newHeader).Region, + old).Region); + break; + } + } + + return (PSLIST_ENTRY)((ULONG_PTR)old.HeaderX64.NextEntry << 4); +#else + newHeader.s.Next.Next = ListEntry; + + do + { + old = *ListHead; + ListEntry->Next = old.s.Next.Next; + newHeader.s.Depth = old.s.Depth + 1; + newHeader.s.Sequence = old.s.Sequence + 1; + if (old.Alignment > INT64_MAX) + return NULL; + if (newHeader.Alignment > INT64_MAX) + return NULL; + if (ListHead->Alignment > INT64_MAX) + return NULL; + } while (InterlockedCompareExchange64((LONGLONG*)&ListHead->Alignment, + (LONGLONG)newHeader.Alignment, + (LONGLONG)old.Alignment) != (LONGLONG)old.Alignment); + + return old.s.Next.Next; +#endif +} + +WINPR_PSLIST_ENTRY InterlockedPushListSListEx(WINPR_PSLIST_HEADER ListHead, WINPR_PSLIST_ENTRY List, + WINPR_PSLIST_ENTRY ListEnd, ULONG Count) +{ + WINPR_ASSERT(ListHead); + WINPR_ASSERT(List); + WINPR_ASSERT(ListEnd); + +#ifdef _WIN64 + +#else + +#endif + return NULL; +} + +WINPR_PSLIST_ENTRY InterlockedPopEntrySList(WINPR_PSLIST_HEADER ListHead) +{ + WINPR_SLIST_HEADER old = { 0 }; + WINPR_SLIST_HEADER newHeader = { 0 }; + WINPR_PSLIST_ENTRY entry = NULL; + + WINPR_ASSERT(ListHead); + +#ifdef _WIN64 + while (1) + { + old = *ListHead; + + entry = (PSLIST_ENTRY)(((ULONG_PTR)old.HeaderX64.NextEntry) << 4); + + if (!entry) + return NULL; + + newHeader.HeaderX64.NextEntry = ((ULONG_PTR)entry->Next) >> 4; + newHeader.HeaderX64.Depth = old.HeaderX64.Depth - 1; + newHeader.HeaderX64.Sequence = old.HeaderX64.Sequence - 1; + + if (InterlockedCompareExchange64((LONGLONG*)ListHead, newHeader).Alignment, old).Alignment)) + { + InterlockedCompareExchange64(&((LONGLONG*)ListHead)[1], newHeader).Region, + old).Region); + break; + } + } +#else + do + { + old = *ListHead; + + entry = old.s.Next.Next; + + if (!entry) + return NULL; + + newHeader.s.Next.Next = entry->Next; + newHeader.s.Depth = old.s.Depth - 1; + newHeader.s.Sequence = old.s.Sequence + 1; + + if (old.Alignment > INT64_MAX) + return NULL; + if (newHeader.Alignment > INT64_MAX) + return NULL; + if (ListHead->Alignment > INT64_MAX) + return NULL; + } while (InterlockedCompareExchange64((LONGLONG*)&ListHead->Alignment, + (LONGLONG)newHeader.Alignment, + (LONGLONG)old.Alignment) != (LONGLONG)old.Alignment); +#endif + return entry; +} + +WINPR_PSLIST_ENTRY InterlockedFlushSList(WINPR_PSLIST_HEADER ListHead) +{ + WINPR_SLIST_HEADER old = { 0 }; + WINPR_SLIST_HEADER newHeader = { 0 }; + + WINPR_ASSERT(ListHead); + if (!QueryDepthSList(ListHead)) + return NULL; + +#ifdef _WIN64 + newHeader).Alignment = 0; + newHeader).Region = 0; + newHeader.HeaderX64.HeaderType = 1; + + while (1) + { + old = *ListHead; + newHeader.HeaderX64.Sequence = old.HeaderX64.Sequence + 1; + + if (InterlockedCompareExchange64((LONGLONG*)ListHead, newHeader).Alignment, old).Alignment)) + { + InterlockedCompareExchange64(&((LONGLONG*)ListHead)[1], newHeader).Region, + old).Region); + break; + } + } + + return (PSLIST_ENTRY)(((ULONG_PTR)old.HeaderX64.NextEntry) << 4); +#else + newHeader.Alignment = 0; + + do + { + old = *ListHead; + newHeader.s.Sequence = old.s.Sequence + 1; + + if (old.Alignment > INT64_MAX) + return NULL; + if (newHeader.Alignment > INT64_MAX) + return NULL; + if (ListHead->Alignment > INT64_MAX) + return NULL; + } while (InterlockedCompareExchange64((LONGLONG*)&ListHead->Alignment, + (LONGLONG)newHeader.Alignment, + (LONGLONG)old.Alignment) != (LONGLONG)old.Alignment); + + return old.s.Next.Next; +#endif +} + +USHORT QueryDepthSList(WINPR_PSLIST_HEADER ListHead) +{ + WINPR_ASSERT(ListHead); + +#ifdef _WIN64 + return ListHead->HeaderX64.Depth; +#else + return ListHead->s.Depth; +#endif +} + +LONG InterlockedIncrement(LONG volatile* Addend) +{ + WINPR_ASSERT(Addend); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_add_and_fetch(Addend, 1); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +LONG InterlockedDecrement(LONG volatile* Addend) +{ + WINPR_ASSERT(Addend); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_sub_and_fetch(Addend, 1); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +LONG InterlockedExchange(LONG volatile* Target, LONG Value) +{ + WINPR_ASSERT(Target); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_val_compare_and_swap(Target, *Target, Value); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +LONG InterlockedExchangeAdd(LONG volatile* Addend, LONG Value) +{ + WINPR_ASSERT(Addend); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_fetch_and_add(Addend, Value); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +LONG InterlockedCompareExchange(LONG volatile* Destination, LONG Exchange, LONG Comperand) +{ + WINPR_ASSERT(Destination); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_val_compare_and_swap(Destination, Comperand, Exchange); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +PVOID InterlockedCompareExchangePointer(PVOID volatile* Destination, PVOID Exchange, + PVOID Comperand) +{ + WINPR_ASSERT(Destination); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_val_compare_and_swap(Destination, Comperand, Exchange); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +#endif /* _WIN32 */ + +#if defined(_WIN32) && !defined(WINPR_INTERLOCKED_COMPARE_EXCHANGE64) + +/* InterlockedCompareExchange64 already defined */ + +#elif defined(_WIN32) && defined(WINPR_INTERLOCKED_COMPARE_EXCHANGE64) + +static volatile HANDLE mutex = NULL; + +BOOL static_mutex_lock(volatile HANDLE* static_mutex) +{ + if (*static_mutex == NULL) + { + HANDLE handle; + + if (!(handle = CreateMutex(NULL, FALSE, NULL))) + return FALSE; + + if (InterlockedCompareExchangePointer((PVOID*)static_mutex, (PVOID)handle, NULL) != NULL) + (void)CloseHandle(handle); + } + + return (WaitForSingleObject(*static_mutex, INFINITE) == WAIT_OBJECT_0); +} + +LONGLONG InterlockedCompareExchange64(LONGLONG volatile* Destination, LONGLONG Exchange, + LONGLONG Comperand) +{ + LONGLONG previousValue = 0; + BOOL locked = static_mutex_lock(&mutex); + + previousValue = *Destination; + + if (*Destination == Comperand) + *Destination = Exchange; + + if (locked) + (void)ReleaseMutex(mutex); + else + (void)fprintf(stderr, + "WARNING: InterlockedCompareExchange64 operation might have failed\n"); + + return previousValue; +} + +#elif (defined(ANDROID) && ANDROID) || \ + (defined(__GNUC__) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) + +#include + +static pthread_mutex_t mutex; + +LONGLONG InterlockedCompareExchange64(LONGLONG volatile* Destination, LONGLONG Exchange, + LONGLONG Comperand) +{ + LONGLONG previousValue = 0; + + pthread_mutex_lock(&mutex); + + previousValue = *Destination; + + if (*Destination == Comperand) + *Destination = Exchange; + + pthread_mutex_unlock(&mutex); + + return previousValue; +} + +#else + +LONGLONG InterlockedCompareExchange64(LONGLONG volatile* Destination, LONGLONG Exchange, + LONGLONG Comperand) +{ + WINPR_ASSERT(Destination); + +#if defined(__GNUC__) || defined(__clang__) + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST + return __sync_val_compare_and_swap(Destination, Comperand, Exchange); + WINPR_PRAGMA_DIAG_POP +#else + return 0; +#endif +} + +#endif + +/* Doubly-Linked List */ + +/** + * Kernel-Mode Basics: Windows Linked Lists: + * http://www.osronline.com/article.cfm?article=499 + * + * Singly and Doubly Linked Lists: + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff563802/ + */ + +VOID InitializeListHead(WINPR_PLIST_ENTRY ListHead) +{ + WINPR_ASSERT(ListHead); + ListHead->Flink = ListHead->Blink = ListHead; +} + +BOOL IsListEmpty(const WINPR_LIST_ENTRY* ListHead) +{ + WINPR_ASSERT(ListHead); + return (BOOL)(ListHead->Flink == ListHead); +} + +BOOL RemoveEntryList(WINPR_PLIST_ENTRY Entry) +{ + WINPR_ASSERT(Entry); + WINPR_PLIST_ENTRY OldFlink = Entry->Flink; + WINPR_ASSERT(OldFlink); + + WINPR_PLIST_ENTRY OldBlink = Entry->Blink; + WINPR_ASSERT(OldBlink); + + OldFlink->Blink = OldBlink; + OldBlink->Flink = OldFlink; + + return (BOOL)(OldFlink == OldBlink); +} + +VOID InsertHeadList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY Entry) +{ + WINPR_ASSERT(ListHead); + WINPR_ASSERT(Entry); + + WINPR_PLIST_ENTRY OldFlink = ListHead->Flink; + WINPR_ASSERT(OldFlink); + + Entry->Flink = OldFlink; + Entry->Blink = ListHead; + OldFlink->Blink = Entry; + ListHead->Flink = Entry; +} + +WINPR_PLIST_ENTRY RemoveHeadList(WINPR_PLIST_ENTRY ListHead) +{ + WINPR_ASSERT(ListHead); + + WINPR_PLIST_ENTRY Entry = ListHead->Flink; + WINPR_ASSERT(Entry); + + WINPR_PLIST_ENTRY Flink = Entry->Flink; + WINPR_ASSERT(Flink); + + ListHead->Flink = Flink; + Flink->Blink = ListHead; + + return Entry; +} + +VOID InsertTailList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY Entry) +{ + WINPR_ASSERT(ListHead); + WINPR_ASSERT(Entry); + + WINPR_PLIST_ENTRY OldBlink = ListHead->Blink; + WINPR_ASSERT(OldBlink); + + Entry->Flink = ListHead; + Entry->Blink = OldBlink; + OldBlink->Flink = Entry; + ListHead->Blink = Entry; +} + +WINPR_PLIST_ENTRY RemoveTailList(WINPR_PLIST_ENTRY ListHead) +{ + WINPR_ASSERT(ListHead); + + WINPR_PLIST_ENTRY Entry = ListHead->Blink; + WINPR_ASSERT(Entry); + + WINPR_PLIST_ENTRY Blink = Entry->Blink; + WINPR_ASSERT(Blink); + + ListHead->Blink = Blink; + Blink->Flink = ListHead; + + return Entry; +} + +VOID AppendTailList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY ListToAppend) +{ + WINPR_ASSERT(ListHead); + WINPR_ASSERT(ListToAppend); + + WINPR_PLIST_ENTRY ListEnd = ListHead->Blink; + + ListHead->Blink->Flink = ListToAppend; + ListHead->Blink = ListToAppend->Blink; + ListToAppend->Blink->Flink = ListHead; + ListToAppend->Blink = ListEnd; +} + +VOID PushEntryList(WINPR_PSINGLE_LIST_ENTRY ListHead, WINPR_PSINGLE_LIST_ENTRY Entry) +{ + WINPR_ASSERT(ListHead); + WINPR_ASSERT(Entry); + + Entry->Next = ListHead->Next; + ListHead->Next = Entry; +} + +WINPR_PSINGLE_LIST_ENTRY PopEntryList(WINPR_PSINGLE_LIST_ENTRY ListHead) +{ + WINPR_ASSERT(ListHead); + WINPR_PSINGLE_LIST_ENTRY FirstEntry = ListHead->Next; + + if (FirstEntry != NULL) + ListHead->Next = FirstEntry->Next; + + return FirstEntry; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/module_5.1.def b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/module_5.1.def new file mode 100644 index 0000000000000000000000000000000000000000..160c9de80da638dfb2e9fab12992146c168f9cea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/module_5.1.def @@ -0,0 +1,13 @@ +LIBRARY "libwinpr-interlocked" +EXPORTS + InterlockedCompareExchange64 @1 + InitializeListHead @2 + IsListEmpty @3 + RemoveEntryList @4 + InsertHeadList @5 + RemoveHeadList @6 + InsertTailList @7 + RemoveTailList @8 + AppendTailList @9 + PushEntryList @10 + PopEntryList @11 diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4afb6542baf31274c875b39f6bfdfeca34052e7a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestInterlocked") +set(MODULE_PREFIX "TEST_INTERLOCKED") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestInterlockedAccess.c TestInterlockedSList.c TestInterlockedDList.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedAccess.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedAccess.c new file mode 100644 index 0000000000000000000000000000000000000000..1d00d7a008cd03aaa19e4b0c74a8b0dab717d48d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedAccess.c @@ -0,0 +1,200 @@ +#include +#include +#include +#include + +int TestInterlockedAccess(int argc, char* argv[]) +{ + LONG* Addend = NULL; + LONG* Target = NULL; + LONG oldValue = 0; + LONG* Destination = NULL; + LONGLONG oldValue64 = 0; + LONGLONG* Destination64 = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + /* InterlockedIncrement */ + + Addend = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + if (!Addend) + { + printf("Failed to allocate memory\n"); + return -1; + } + + *Addend = 0; + + for (int index = 0; index < 10; index++) + InterlockedIncrement(Addend); + + if (*Addend != 10) + { + printf("InterlockedIncrement failure: Actual: %" PRId32 ", Expected: 10\n", *Addend); + return -1; + } + + /* InterlockedDecrement */ + + for (int index = 0; index < 10; index++) + (void)InterlockedDecrement(Addend); + + if (*Addend != 0) + { + printf("InterlockedDecrement failure: Actual: %" PRId32 ", Expected: 0\n", *Addend); + return -1; + } + + /* InterlockedExchange */ + + Target = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + + if (!Target) + { + printf("Failed to allocate memory\n"); + return -1; + } + + *Target = 0xAA; + + oldValue = InterlockedExchange(Target, 0xFF); + + if (oldValue != 0xAA) + { + printf("InterlockedExchange failure: Actual: 0x%08" PRIX32 ", Expected: 0xAA\n", oldValue); + return -1; + } + + if (*Target != 0xFF) + { + printf("InterlockedExchange failure: Actual: 0x%08" PRIX32 ", Expected: 0xFF\n", *Target); + return -1; + } + + /* InterlockedExchangeAdd */ + + *Addend = 25; + + oldValue = InterlockedExchangeAdd(Addend, 100); + + if (oldValue != 25) + { + printf("InterlockedExchangeAdd failure: Actual: %" PRId32 ", Expected: 25\n", oldValue); + return -1; + } + + if (*Addend != 125) + { + printf("InterlockedExchangeAdd failure: Actual: %" PRId32 ", Expected: 125\n", *Addend); + return -1; + } + + /* InterlockedCompareExchange (*Destination == Comparand) */ + + Destination = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + if (!Destination) + { + printf("Failed to allocate memory\n"); + return -1; + } + + *Destination = (LONG)0xAABBCCDDL; + + oldValue = InterlockedCompareExchange(Destination, (LONG)0xCCDDEEFFL, (LONG)0xAABBCCDDL); + + if (oldValue != (LONG)0xAABBCCDDL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%08" PRIX32 + ", Expected: 0xAABBCCDD\n", + oldValue); + return -1; + } + + if ((*Destination) != (LONG)0xCCDDEEFFL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%08" PRIX32 + ", Expected: 0xCCDDEEFF\n", + *Destination); + return -1; + } + + /* InterlockedCompareExchange (*Destination != Comparand) */ + + *Destination = (LONG)0xAABBCCDDL; + + oldValue = InterlockedCompareExchange(Destination, -857870593L, 0x66778899L); + + if (oldValue != (LONG)0xAABBCCDDL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%08" PRIX32 + ", Expected: 0xAABBCCDD\n", + oldValue); + return -1; + } + + if ((*Destination) != (LONG)0xAABBCCDDL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%08" PRIX32 + ", Expected: 0xAABBCCDD\n", + *Destination); + return -1; + } + + /* InterlockedCompareExchange64 (*Destination == Comparand) */ + + Destination64 = winpr_aligned_malloc(sizeof(LONGLONG), sizeof(LONGLONG)); + if (!Destination64) + { + printf("Failed to allocate memory\n"); + return -1; + } + + *Destination64 = 0x66778899AABBCCDD; + + oldValue64 = + InterlockedCompareExchange64(Destination64, 0x0899AABBCCDDEEFFLL, 0x66778899AABBCCDD); + + if (oldValue64 != 0x66778899AABBCCDD) + { + printf("InterlockedCompareExchange failure: Actual: 0x%016" PRIX64 + ", Expected: 0x66778899AABBCCDD\n", + oldValue64); + return -1; + } + + if ((*Destination64) != 0x0899AABBCCDDEEFFLL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%016" PRIX64 + ", Expected: 0x0899AABBCCDDEEFFLL\n", + *Destination64); + return -1; + } + + /* InterlockedCompareExchange64 (*Destination != Comparand) */ + + *Destination64 = 0x66778899AABBCCDDLL; + + oldValue64 = InterlockedCompareExchange64(Destination64, 0x0899AABBCCDDEEFFLL, 12345); + + if (oldValue64 != 0x66778899AABBCCDDLL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%016" PRIX64 + ", Expected: 0x66778899AABBCCDD\n", + oldValue64); + return -1; + } + + if (*Destination64 != 0x66778899AABBCCDDLL) + { + printf("InterlockedCompareExchange failure: Actual: 0x%016" PRIX64 + ", Expected: 0x66778899AABBCCDD\n", + *Destination64); + return -1; + } + + winpr_aligned_free(Addend); + winpr_aligned_free(Target); + winpr_aligned_free(Destination); + winpr_aligned_free(Destination64); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedDList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedDList.c new file mode 100644 index 0000000000000000000000000000000000000000..f49e37d9cfb03fc9c1d9485c0a1b2f809f5023c1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedDList.c @@ -0,0 +1,79 @@ + +#include +#include +#include +#include + +typedef struct +{ + WINPR_LIST_ENTRY ItemEntry; + ULONG Signature; +} LIST_ITEM, *PLIST_ITEM; + +int TestInterlockedDList(int argc, char* argv[]) +{ + ULONG Count = 0; + PLIST_ITEM pListItem = NULL; + WINPR_PLIST_ENTRY pListHead = NULL; + WINPR_PLIST_ENTRY pListEntry = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + pListHead = (WINPR_PLIST_ENTRY)winpr_aligned_malloc(sizeof(WINPR_LIST_ENTRY), + MEMORY_ALLOCATION_ALIGNMENT); + + if (!pListHead) + { + printf("Memory allocation failed.\n"); + return -1; + } + + InitializeListHead(pListHead); + + if (!IsListEmpty(pListHead)) + { + printf("Expected empty list\n"); + return -1; + } + + /* InsertHeadList / RemoveHeadList */ + + printf("InsertHeadList / RemoveHeadList\n"); + + for (Count = 1; Count <= 10; Count += 1) + { + pListItem = + (PLIST_ITEM)winpr_aligned_malloc(sizeof(LIST_ITEM), MEMORY_ALLOCATION_ALIGNMENT); + pListItem->Signature = Count; + InsertHeadList(pListHead, &(pListItem->ItemEntry)); + } + + for (Count = 10; Count >= 1; Count -= 1) + { + pListEntry = RemoveHeadList(pListHead); + pListItem = (PLIST_ITEM)pListEntry; + winpr_aligned_free(pListItem); + } + + /* InsertTailList / RemoveTailList */ + + printf("InsertTailList / RemoveTailList\n"); + + for (Count = 1; Count <= 10; Count += 1) + { + pListItem = + (PLIST_ITEM)winpr_aligned_malloc(sizeof(LIST_ITEM), MEMORY_ALLOCATION_ALIGNMENT); + pListItem->Signature = Count; + InsertTailList(pListHead, &(pListItem->ItemEntry)); + } + + for (Count = 10; Count >= 1; Count -= 1) + { + pListEntry = RemoveTailList(pListHead); + pListItem = (PLIST_ITEM)pListEntry; + winpr_aligned_free(pListItem); + } + + winpr_aligned_free(pListHead); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedSList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedSList.c new file mode 100644 index 0000000000000000000000000000000000000000..09969f2ee2d2e2d3cb605571cb2ee29e0ad86678 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/interlocked/test/TestInterlockedSList.c @@ -0,0 +1,95 @@ + +#include +#include +#include +#include + +#define ITEM_COUNT 23 + +typedef struct +{ + WINPR_SLIST_ENTRY ItemEntry; + ULONG Signature; +} PROGRAM_ITEM, *PPROGRAM_ITEM; + +int TestInterlockedSList(int argc, char* argv[]) +{ + int rc = -1; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Initialize the list header to a MEMORY_ALLOCATION_ALIGNMENT boundary. */ + WINPR_PSLIST_HEADER pListHead = (WINPR_PSLIST_HEADER)winpr_aligned_malloc( + sizeof(WINPR_SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT); + + if (!pListHead) + { + printf("Memory allocation failed.\n"); + return -1; + } + + InitializeSListHead(pListHead); + + /* Insert 10 items into the list. */ + for (ULONG Count = 0; Count < ITEM_COUNT; Count++) + { + PPROGRAM_ITEM pProgramItem = + (PPROGRAM_ITEM)winpr_aligned_malloc(sizeof(PROGRAM_ITEM), MEMORY_ALLOCATION_ALIGNMENT); + + if (!pProgramItem) + { + printf("Memory allocation failed.\n"); + goto fail; + } + + pProgramItem->Signature = Count + 1UL; + WINPR_PSLIST_ENTRY pFirstEntry = + InterlockedPushEntrySList(pListHead, &(pProgramItem->ItemEntry)); + if (((Count == 0) && pFirstEntry) || ((Count != 0) && !pFirstEntry)) + { + printf("Error: List is empty.\n"); + winpr_aligned_free(pProgramItem); + goto fail; + } + } + + /* Remove 10 items from the list and display the signature. */ + for (ULONG Count = 0; Count < ITEM_COUNT; Count++) + { + WINPR_PSLIST_ENTRY pListEntry = InterlockedPopEntrySList(pListHead); + + if (!pListEntry) + { + printf("List is empty.\n"); + goto fail; + } + + PPROGRAM_ITEM pProgramItem = (PPROGRAM_ITEM)pListEntry; + printf("Signature is %" PRIu32 "\n", pProgramItem->Signature); + + /* + * This example assumes that the SLIST_ENTRY structure is the + * first member of the structure. If your structure does not + * follow this convention, you must compute the starting address + * of the structure before calling the free function. + */ + + winpr_aligned_free(pListEntry); + } + + /* Flush the list and verify that the items are gone. */ + WINPR_PSLIST_ENTRY pFirstEntry = InterlockedPopEntrySList(pListHead); + + if (pFirstEntry) + { + printf("Error: List is not empty.\n"); + goto fail; + } + + rc = 0; +fail: + winpr_aligned_free(pListHead); + + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8fdcab3d9695026467813a8830ef529522daab9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-io cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(device.c io.c io.h) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..9e7ac864ed933b522cc063618fcfff3eef6f75fd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "1") +set(MINWIN_SHORT_NAME "io") +set(MINWIN_LONG_NAME "Asynchronous I/O Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/device.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/device.c new file mode 100644 index 0000000000000000000000000000000000000000..b8aabfc0dbc0ac8cef174d2e2421c7f1b846fd2d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/device.c @@ -0,0 +1,234 @@ +/** + * WinPR: Windows Portable Runtime + * Asynchronous I/O Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#ifndef _WIN32 + +#include "io.h" + +#include +#include +#include +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include +#include + +#include +#include +#include + +/** + * I/O Manager Routines + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff551797/ + * + * These routines are only accessible to kernel drivers, but we need + * similar functionality in WinPR in user space. + * + * This is a best effort non-conflicting port of this API meant for + * non-Windows, WinPR usage only. + * + * References: + * + * Device Objects and Device Stacks: + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff543153/ + * + * Driver Development Part 1: Introduction to Drivers: + * http://www.codeproject.com/Articles/9504/Driver-Development-Part-1-Introduction-to-Drivers/ + */ + +#define DEVICE_FILE_PREFIX_PATH "\\Device\\" + +static char* GetDeviceFileNameWithoutPrefixA(LPCSTR lpName) +{ + char* lpFileName = NULL; + + if (!lpName) + return NULL; + + if (strncmp(lpName, DEVICE_FILE_PREFIX_PATH, sizeof(DEVICE_FILE_PREFIX_PATH) - 1) != 0) + return NULL; + + lpFileName = + _strdup(&lpName[strnlen(DEVICE_FILE_PREFIX_PATH, sizeof(DEVICE_FILE_PREFIX_PATH))]); + return lpFileName; +} + +static char* GetDeviceFileUnixDomainSocketBaseFilePathA(void) +{ + char* lpTempPath = NULL; + char* lpPipePath = NULL; + lpTempPath = GetKnownPath(KNOWN_PATH_TEMP); + + if (!lpTempPath) + return NULL; + + lpPipePath = GetCombinedPath(lpTempPath, ".device"); + free(lpTempPath); + return lpPipePath; +} + +static char* GetDeviceFileUnixDomainSocketFilePathA(LPCSTR lpName) +{ + char* lpPipePath = NULL; + char* lpFileName = NULL; + char* lpFilePath = NULL; + lpPipePath = GetDeviceFileUnixDomainSocketBaseFilePathA(); + + if (!lpPipePath) + return NULL; + + lpFileName = GetDeviceFileNameWithoutPrefixA(lpName); + + if (!lpFileName) + { + free(lpPipePath); + return NULL; + } + + lpFilePath = GetCombinedPath(lpPipePath, lpFileName); + free(lpPipePath); + free(lpFileName); + return lpFilePath; +} + +/** + * IoCreateDevice: + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff548397/ + */ + +NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtensionSize, + PUNICODE_STRING DeviceName, DEVICE_TYPE DeviceType, + ULONG DeviceCharacteristics, BOOLEAN Exclusive, + PDEVICE_OBJECT_EX* DeviceObject) +{ + int status = 0; + char* DeviceBasePath = NULL; + DEVICE_OBJECT_EX* pDeviceObjectEx = NULL; + DeviceBasePath = GetDeviceFileUnixDomainSocketBaseFilePathA(); + + if (!DeviceBasePath) + return STATUS_NO_MEMORY; + + if (!winpr_PathFileExists(DeviceBasePath)) + { + if (mkdir(DeviceBasePath, S_IRUSR | S_IWUSR | S_IXUSR) != 0) + { + free(DeviceBasePath); + return STATUS_ACCESS_DENIED; + } + } + + free(DeviceBasePath); + pDeviceObjectEx = (DEVICE_OBJECT_EX*)calloc(1, sizeof(DEVICE_OBJECT_EX)); + + if (!pDeviceObjectEx) + return STATUS_NO_MEMORY; + + pDeviceObjectEx->DeviceName = + ConvertWCharNToUtf8Alloc(DeviceName->Buffer, DeviceName->Length / sizeof(WCHAR), NULL); + if (!pDeviceObjectEx->DeviceName) + { + free(pDeviceObjectEx); + return STATUS_NO_MEMORY; + } + + pDeviceObjectEx->DeviceFileName = + GetDeviceFileUnixDomainSocketFilePathA(pDeviceObjectEx->DeviceName); + + if (!pDeviceObjectEx->DeviceFileName) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx); + return STATUS_NO_MEMORY; + } + + if (winpr_PathFileExists(pDeviceObjectEx->DeviceFileName)) + { + if (unlink(pDeviceObjectEx->DeviceFileName) == -1) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx); + return STATUS_ACCESS_DENIED; + } + } + + status = mkfifo(pDeviceObjectEx->DeviceFileName, 0666); + + if (status != 0) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx); + + switch (errno) + { + case EACCES: + return STATUS_ACCESS_DENIED; + + case EEXIST: + return STATUS_OBJECT_NAME_EXISTS; + + case ENAMETOOLONG: + return STATUS_NAME_TOO_LONG; + + case ENOENT: + case ENOTDIR: + return STATUS_NOT_A_DIRECTORY; + + case ENOSPC: + return STATUS_DISK_FULL; + + default: + return STATUS_INTERNAL_ERROR; + } + } + + *((ULONG_PTR*)(DeviceObject)) = (ULONG_PTR)pDeviceObjectEx; + return STATUS_SUCCESS; +} + +/** + * IoDeleteDevice: + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff549083/ + */ + +VOID _IoDeleteDeviceEx(PDEVICE_OBJECT_EX DeviceObject) +{ + DEVICE_OBJECT_EX* pDeviceObjectEx = NULL; + pDeviceObjectEx = (DEVICE_OBJECT_EX*)DeviceObject; + + if (!pDeviceObjectEx) + return; + + unlink(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx); +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.c new file mode 100644 index 0000000000000000000000000000000000000000..2df20be192a01ef52fd97cc3d33b619b642fdb43 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.c @@ -0,0 +1,276 @@ +/** + * WinPR: Windows Portable Runtime + * Asynchronous I/O Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#ifndef _WIN32 + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "../handle/handle.h" +#include "../pipe/pipe.h" +#include "../log.h" + +#define TAG WINPR_TAG("io") + +BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped, + LPDWORD lpNumberOfBytesTransferred, BOOL bWait) +{ +#if 1 + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +#else + ULONG Type; + WINPR_HANDLE* Object; + + if (!winpr_Handle_GetInfo(hFile, &Type, &Object)) + return FALSE; + + else if (Type == HANDLE_TYPE_NAMED_PIPE) + { + int status = -1; + DWORD request; + PVOID lpBuffer; + DWORD nNumberOfBytes; + WINPR_NAMED_PIPE* pipe; + + pipe = (WINPR_NAMED_PIPE*)Object; + + if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) + return FALSE; + + lpBuffer = lpOverlapped->Pointer; + request = (DWORD)lpOverlapped->Internal; + nNumberOfBytes = (DWORD)lpOverlapped->InternalHigh; + + if (request == 0) + { + if (pipe->clientfd == -1) + return FALSE; + + status = read(pipe->clientfd, lpBuffer, nNumberOfBytes); + } + else if (request == 1) + { + if (pipe->clientfd == -1) + return FALSE; + + status = write(pipe->clientfd, lpBuffer, nNumberOfBytes); + } + else if (request == 2) + { + socklen_t length; + struct sockaddr_un s = { 0 }; + + if (pipe->serverfd == -1) + return FALSE; + + length = sizeof(struct sockaddr_un); + + status = accept(pipe->serverfd, (struct sockaddr*)&s, &length); + + if (status < 0) + return FALSE; + + pipe->clientfd = status; + pipe->ServerMode = FALSE; + + status = 0; + } + + if (status < 0) + { + *lpNumberOfBytesTransferred = 0; + return FALSE; + } + + *lpNumberOfBytesTransferred = status; + } + + return TRUE; +#endif +} + +BOOL GetOverlappedResultEx(HANDLE hFile, LPOVERLAPPED lpOverlapped, + LPDWORD lpNumberOfBytesTransferred, DWORD dwMilliseconds, + BOOL bAlertable) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, + LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, + LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +HANDLE CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort, + ULONG_PTR CompletionKey, DWORD NumberOfConcurrentThreads) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +BOOL GetQueuedCompletionStatus(HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred, + PULONG_PTR lpCompletionKey, LPOVERLAPPED* lpOverlapped, + DWORD dwMilliseconds) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetQueuedCompletionStatusEx(HANDLE CompletionPort, LPOVERLAPPED_ENTRY lpCompletionPortEntries, + ULONG ulCount, PULONG ulNumEntriesRemoved, DWORD dwMilliseconds, + BOOL fAlertable) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL PostQueuedCompletionStatus(HANDLE CompletionPort, DWORD dwNumberOfBytesTransferred, + ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CancelIo(HANDLE hFile) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CancelIoEx(HANDLE hFile, LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CancelSynchronousIo(HANDLE hThread) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +#endif + +#ifdef _UWP + +#include +#include + +#include "../log.h" + +#define TAG WINPR_TAG("io") + +BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped, + LPDWORD lpNumberOfBytesTransferred, BOOL bWait) +{ + return GetOverlappedResultEx(hFile, lpOverlapped, lpNumberOfBytesTransferred, + bWait ? INFINITE : 0, TRUE); +} + +BOOL DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, + LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, + LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +HANDLE CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort, + ULONG_PTR CompletionKey, DWORD NumberOfConcurrentThreads) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +BOOL GetQueuedCompletionStatus(HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred, + PULONG_PTR lpCompletionKey, LPOVERLAPPED* lpOverlapped, + DWORD dwMilliseconds) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetQueuedCompletionStatusEx(HANDLE CompletionPort, LPOVERLAPPED_ENTRY lpCompletionPortEntries, + ULONG ulCount, PULONG ulNumEntriesRemoved, DWORD dwMilliseconds, + BOOL fAlertable) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL PostQueuedCompletionStatus(HANDLE CompletionPort, DWORD dwNumberOfBytesTransferred, + ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL CancelIo(HANDLE hFile) +{ + return CancelIoEx(hFile, NULL); +} + +BOOL CancelSynchronousIo(HANDLE hThread) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.h new file mode 100644 index 0000000000000000000000000000000000000000..17d00139583ae96ea745ada5230df6c0cd8ae4e4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/io.h @@ -0,0 +1,37 @@ +/** + * WinPR: Windows Portable Runtime + * Asynchronous I/O Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_IO_PRIVATE_H + +#ifndef _WIN32 + +#include + +#include "../handle/handle.h" + +typedef struct +{ + char* DeviceName; + char* DeviceFileName; +} DEVICE_OBJECT_EX; + +#endif + +#endif /* WINPR_IO_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e13785522ffaa00a3bd54f84e0e5d9ad686510bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestIo") +set(MODULE_PREFIX "TEST_IO") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestIoGetOverlappedResult.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/TestIoGetOverlappedResult.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/TestIoGetOverlappedResult.c new file mode 100644 index 0000000000000000000000000000000000000000..044eb11ccb20fe5add8d53cad0b0c318fb60fc09 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/io/test/TestIoGetOverlappedResult.c @@ -0,0 +1,10 @@ + +#include +#include +#include +#include + +int TestIoGetOverlappedResult(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..264864bf1dc1a9a97b9a7d14e24fb7cd7e25bc90 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-library cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(library.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..b1dcf644b1cda1ed148ff2d6c4d309848f9eac71 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "1") +set(MINWIN_SHORT_NAME "libraryloader") +set(MINWIN_LONG_NAME "Dynamic-Link Library Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/library.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/library.c new file mode 100644 index 0000000000000000000000000000000000000000..7c51a2f5b810a9ea4a77933d6ae887bba44e48cf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/library.c @@ -0,0 +1,431 @@ +/** + * WinPR: Windows Portable Runtime + * Library Loader + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#include "../log.h" +#define TAG WINPR_TAG("library") + +/** + * api-ms-win-core-libraryloader-l1-1-1.dll: + * + * AddDllDirectory + * RemoveDllDirectory + * SetDefaultDllDirectories + * DisableThreadLibraryCalls + * EnumResourceLanguagesExA + * EnumResourceLanguagesExW + * EnumResourceNamesExA + * EnumResourceNamesExW + * EnumResourceTypesExA + * EnumResourceTypesExW + * FindResourceExW + * FindStringOrdinal + * FreeLibrary + * FreeLibraryAndExitThread + * FreeResource + * GetModuleFileNameA + * GetModuleFileNameW + * GetModuleHandleA + * GetModuleHandleExA + * GetModuleHandleExW + * GetModuleHandleW + * GetProcAddress + * LoadLibraryExA + * LoadLibraryExW + * LoadResource + * LoadStringA + * LoadStringW + * LockResource + * QueryOptionalDelayLoadedAPI + * SizeofResource + */ + +#if !defined(_WIN32) || defined(_UWP) + +#ifndef _WIN32 + +#include +#include +#include +#include +#include +#include + +#ifdef __MACOSX__ +#include +#endif + +#if defined(__FreeBSD__) +#include +#endif + +#endif + +DLL_DIRECTORY_COOKIE AddDllDirectory(PCWSTR NewDirectory) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +BOOL RemoveDllDirectory(DLL_DIRECTORY_COOKIE Cookie) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL SetDefaultDllDirectories(DWORD DirectoryFlags) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +HMODULE LoadLibraryA(LPCSTR lpLibFileName) +{ +#if defined(_UWP) + int status; + HMODULE hModule = NULL; + WCHAR* filenameW = NULL; + + if (!lpLibFileName) + return NULL; + + filenameW = ConvertUtf8ToWCharAlloc(lpLibFileName, NULL); + if (filenameW) + return NULL; + + hModule = LoadLibraryW(filenameW); + free(filenameW); + return hModule; +#else + HMODULE library = NULL; + library = dlopen(lpLibFileName, RTLD_LOCAL | RTLD_LAZY); + + if (!library) + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + const char* err = dlerror(); + WLog_ERR(TAG, "failed with %s", err); + return NULL; + } + + return library; +#endif +} + +HMODULE LoadLibraryW(LPCWSTR lpLibFileName) +{ + if (!lpLibFileName) + return NULL; +#if defined(_UWP) + return LoadPackagedLibrary(lpLibFileName, 0); +#else + HMODULE module = NULL; + char* name = ConvertWCharToUtf8Alloc(lpLibFileName, NULL); + if (!name) + return NULL; + + module = LoadLibraryA(name); + free(name); + return module; +#endif +} + +HMODULE LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) +{ + if (dwFlags != 0) + WLog_WARN(TAG, "does not support dwFlags 0x%08" PRIx32, dwFlags); + + if (hFile) + WLog_WARN(TAG, "does not support hFile != NULL"); + + return LoadLibraryA(lpLibFileName); +} + +HMODULE LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) +{ + if (dwFlags != 0) + WLog_WARN(TAG, "does not support dwFlags 0x%08" PRIx32, dwFlags); + + if (hFile) + WLog_WARN(TAG, "does not support hFile != NULL"); + + return LoadLibraryW(lpLibFileName); +} + +#endif + +#if !defined(_WIN32) && !defined(__CYGWIN__) + +FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName) +{ + FARPROC proc = NULL; + proc = dlsym(hModule, lpProcName); + + if (proc == NULL) + { + // NOLINTNEXTLINE(concurrency-mt-unsafe) + WLog_ERR(TAG, "GetProcAddress: could not find procedure %s: %s", lpProcName, dlerror()); + return (FARPROC)NULL; + } + + return proc; +} + +BOOL FreeLibrary(HMODULE hLibModule) +{ + int status = 0; + status = dlclose(hLibModule); + + if (status != 0) + return FALSE; + + return TRUE; +} + +HMODULE GetModuleHandleA(LPCSTR lpModuleName) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +HMODULE GetModuleHandleW(LPCWSTR lpModuleName) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +/** + * GetModuleFileName: + * http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197/ + * + * Finding current executable's path without /proc/self/exe: + * http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe + */ + +DWORD GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize) +{ + DWORD status = 0; + if (!lpFilename) + { + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + + char* name = calloc(nSize, sizeof(char)); + if (!name) + { + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + status = GetModuleFileNameA(hModule, name, nSize); + + if ((status > INT_MAX) || (nSize > INT_MAX)) + { + SetLastError(ERROR_INTERNAL_ERROR); + status = 0; + } + + if (status > 0) + { + if (ConvertUtf8NToWChar(name, status, lpFilename, nSize) < 0) + { + free(name); + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + } + + free(name); + return status; +} + +#if defined(__linux__) || defined(__NetBSD__) || defined(__DragonFly__) +static DWORD module_from_proc(const char* proc, LPSTR lpFilename, DWORD nSize) +{ + char buffer[8192] = { 0 }; + ssize_t status = readlink(proc, buffer, ARRAYSIZE(buffer) - 1); + + if ((status < 0) || ((size_t)status >= ARRAYSIZE(buffer))) + { + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + + const size_t length = strnlen(buffer, ARRAYSIZE(buffer)); + + if (length < nSize) + { + CopyMemory(lpFilename, buffer, length); + lpFilename[length] = '\0'; + return (DWORD)length; + } + + CopyMemory(lpFilename, buffer, nSize - 1); + lpFilename[nSize - 1] = '\0'; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return nSize; +} +#endif + +DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize) +{ + if (hModule) + { + WLog_ERR(TAG, "is not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return 0; + } + +#if defined(__linux__) + return module_from_proc("/proc/self/exe", lpFilename, nSize); +#elif defined(__FreeBSD__) + int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; + size_t cb = nSize; + + { + const int rc = sysctl(mib, ARRAYSIZE(mib), NULL, &cb, NULL, 0); + if (rc != 0) + { + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + } + + char* fullname = calloc(cb + 1, sizeof(char)); + if (!fullname) + { + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + + { + size_t cb2 = cb; + const int rc = sysctl(mib, ARRAYSIZE(mib), fullname, &cb2, NULL, 0); + if ((rc != 0) || (cb2 != cb)) + { + SetLastError(ERROR_INTERNAL_ERROR); + free(fullname); + return 0; + } + } + + if (nSize > 0) + { + strncpy(lpFilename, fullname, nSize - 1); + lpFilename[nSize - 1] = '\0'; + } + free(fullname); + + if (nSize < cb) + SetLastError(ERROR_INSUFFICIENT_BUFFER); + + return (DWORD)MIN(nSize, cb); +#elif defined(__NetBSD__) + return module_from_proc("/proc/curproc/exe", lpFilename, nSize); +#elif defined(__DragonFly__) + return module_from_proc("/proc/curproc/file", lpFilename, nSize); +#elif defined(__MACOSX__) + char path[4096] = { 0 }; + char buffer[4096] = { 0 }; + uint32_t size = sizeof(path); + const int status = _NSGetExecutablePath(path, &size); + + if (status != 0) + { + /* path too small */ + SetLastError(ERROR_INTERNAL_ERROR); + return 0; + } + + /* + * _NSGetExecutablePath may not return the canonical path, + * so use realpath to find the absolute, canonical path. + */ + realpath(path, buffer); + const size_t length = strnlen(buffer, sizeof(buffer)); + + if (length < nSize) + { + CopyMemory(lpFilename, buffer, length); + lpFilename[length] = '\0'; + return (DWORD)length; + } + + CopyMemory(lpFilename, buffer, nSize - 1); + lpFilename[nSize - 1] = '\0'; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return nSize; +#else + WLog_ERR(TAG, "is not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return 0; +#endif +} + +#endif + +HMODULE LoadLibraryX(LPCSTR lpLibFileName) +{ + if (!lpLibFileName) + return NULL; + +#if defined(_WIN32) + HMODULE hm = NULL; + WCHAR* wstr = ConvertUtf8ToWCharAlloc(lpLibFileName, NULL); + + if (wstr) + hm = LoadLibraryW(wstr); + free(wstr); + return hm; +#else + return LoadLibraryA(lpLibFileName); +#endif +} + +HMODULE LoadLibraryExX(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) +{ + if (!lpLibFileName) + return NULL; +#if defined(_WIN32) + HMODULE hm = NULL; + WCHAR* wstr = ConvertUtf8ToWCharAlloc(lpLibFileName, NULL); + if (wstr) + hm = LoadLibraryExW(wstr, hFile, dwFlags); + free(wstr); + return hm; +#else + return LoadLibraryExA(lpLibFileName, hFile, dwFlags); +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0c001ad9b7cc7c0dc5f7bc808832cfab337dd30 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/CMakeLists.txt @@ -0,0 +1,30 @@ +add_subdirectory(TestLibraryA) +add_subdirectory(TestLibraryB) + +set(MODULE_NAME "TestLibrary") +set(MODULE_PREFIX "TEST_LIBRARY") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestLibraryLoadLibrary.c TestLibraryGetProcAddress.c TestLibraryGetModuleFileName.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +add_dependencies(${MODULE_NAME} TestLibraryA TestLibraryB) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +set(TEST_AREA "${MODULE_NAME}Area") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..45bb563834e0e5b5960a660c218d2edc516a53ac --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/CMakeLists.txt @@ -0,0 +1,30 @@ +# WinPR: Windows Portable Runtime +# libwinpr-library cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "TestLibraryA") +set(MODULE_PREFIX "TEST_LIBRARY_A") + +set(SRCS TestLibraryA.c) + +add_library(${MODULE_NAME} SHARED ${SRCS}) +set_target_properties(${MODULE_NAME} PROPERTIES PREFIX "") +set_target_properties( + ${MODULE_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}" RUNTIME_OUTPUT_DIRECTORY + "${TESTING_OUTPUT_DIRECTORY}" +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test/Extra") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/TestLibraryA.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/TestLibraryA.c new file mode 100644 index 0000000000000000000000000000000000000000..d11bc4d09b29e5e7945ba87b8174e0eb1a13617a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryA/TestLibraryA.c @@ -0,0 +1,14 @@ +#include + +DECLSPEC_EXPORT int FunctionA(int a, int b); +DECLSPEC_EXPORT int FunctionB(int a, int b); + +int FunctionA(int a, int b) +{ + return (a * b); /* multiply */ +} + +int FunctionB(int a, int b) +{ + return (a / b); /* divide */ +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0595336d05c5655e6c74130c334aa43c46e6fc26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/CMakeLists.txt @@ -0,0 +1,31 @@ +# WinPR: Windows Portable Runtime +# libwinpr-library cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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 "TestLibraryB") +set(MODULE_PREFIX "TEST_LIBRARY_B") + +set(SRCS TestLibraryB.c) + +add_library(${MODULE_NAME} SHARED ${SRCS}) + +set_target_properties(${MODULE_NAME} PROPERTIES PREFIX "") +set_target_properties( + ${MODULE_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}" RUNTIME_OUTPUT_DIRECTORY + "${TESTING_OUTPUT_DIRECTORY}" +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test/Extra") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/TestLibraryB.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/TestLibraryB.c new file mode 100644 index 0000000000000000000000000000000000000000..eac586e98dc681d555f162647999a06c219b8efd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryB/TestLibraryB.c @@ -0,0 +1,14 @@ +#include + +DECLSPEC_EXPORT int FunctionA(int a, int b); +DECLSPEC_EXPORT int FunctionB(int a, int b); + +int FunctionA(int a, int b) +{ + return (a + b); /* add */ +} + +int FunctionB(int a, int b) +{ + return (a - b); /* subtract */ +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetModuleFileName.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetModuleFileName.c new file mode 100644 index 0000000000000000000000000000000000000000..714522a0d597b54f3b147eb590af4813096033f1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetModuleFileName.c @@ -0,0 +1,56 @@ + +#include +#include +#include +#include +#include +#include + +int TestLibraryGetModuleFileName(int argc, char* argv[]) +{ + char ModuleFileName[4096]; + DWORD len = 0; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + /* Test insufficient buffer size behaviour */ + SetLastError(ERROR_SUCCESS); + len = GetModuleFileNameA(NULL, ModuleFileName, 2); + if (len != 2) + { + printf("%s: GetModuleFileNameA unexpectedly returned %" PRIu32 " instead of 2\n", __func__, + len); + return -1; + } + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) + { + printf("%s: Invalid last error value: 0x%08" PRIX32 + ". Expected 0x%08X (ERROR_INSUFFICIENT_BUFFER)\n", + __func__, GetLastError(), ERROR_INSUFFICIENT_BUFFER); + return -1; + } + + /* Test with real/sufficient buffer size */ + SetLastError(ERROR_SUCCESS); + len = GetModuleFileNameA(NULL, ModuleFileName, sizeof(ModuleFileName)); + if (len == 0) + { + printf("%s: GetModuleFileNameA failed with error 0x%08" PRIX32 "\n", __func__, + GetLastError()); + return -1; + } + if (len == sizeof(ModuleFileName)) + { + printf("%s: GetModuleFileNameA unexpectedly returned nSize\n", __func__); + return -1; + } + if (GetLastError() != ERROR_SUCCESS) + { + printf("%s: Invalid last error value: 0x%08" PRIX32 ". Expected 0x%08X (ERROR_SUCCESS)\n", + __func__, GetLastError(), ERROR_SUCCESS); + return -1; + } + + printf("GetModuleFileNameA: %s\n", ModuleFileName); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c new file mode 100644 index 0000000000000000000000000000000000000000..ccf542167ddcfaa3071a809de49f0926d35209b1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c @@ -0,0 +1,105 @@ + +#include +#include +#include +#include +#include +#include +#include + +typedef int (*TEST_AB_FN)(int a, int b); + +int TestLibraryGetProcAddress(int argc, char* argv[]) +{ + int a = 0; + int b = 0; + int c = 0; + HINSTANCE library = NULL; + TEST_AB_FN pFunctionA = NULL; + TEST_AB_FN pFunctionB = NULL; + LPCSTR SharedLibraryExtension = NULL; + CHAR LibraryPath[PATHCCH_MAX_CCH] = { 0 }; + PCHAR p = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + if (!GetModuleFileNameA(NULL, LibraryPath, PATHCCH_MAX_CCH)) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: GetModuleFilenameA failed: %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + /* PathCchRemoveFileSpec is not implemented in WinPR */ + + if (!(p = strrchr(LibraryPath, PathGetSeparatorA(PATH_STYLE_NATIVE)))) + { + printf("%s: Error identifying module directory path\n", __func__); + return -1; + } + + *p = 0; + NativePathCchAppendA(LibraryPath, PATHCCH_MAX_CCH, "TestLibraryA"); + SharedLibraryExtension = PathGetSharedLibraryExtensionA(PATH_SHARED_LIB_EXT_WITH_DOT); + NativePathCchAddExtensionA(LibraryPath, PATHCCH_MAX_CCH, SharedLibraryExtension); + printf("%s: Loading Library: '%s'\n", __func__, LibraryPath); + + if (!(library = LoadLibraryA(LibraryPath))) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: LoadLibraryA failure: %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + if (!(pFunctionA = GetProcAddressAs(library, "FunctionA", TEST_AB_FN))) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: GetProcAddress failure (FunctionA) %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + if (!(pFunctionB = GetProcAddressAs(library, "FunctionB", TEST_AB_FN))) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: GetProcAddress failure (FunctionB) %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + a = 2; + b = 3; + c = pFunctionA(a, b); /* LibraryA / FunctionA multiplies a and b */ + + if (c != (a * b)) + { + printf("%s: pFunctionA call failed\n", __func__); + return -1; + } + + a = 10; + b = 5; + c = pFunctionB(a, b); /* LibraryA / FunctionB divides a by b */ + + if (c != (a / b)) + { + printf("%s: pFunctionB call failed\n", __func__); + return -1; + } + + if (!FreeLibrary(library)) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: FreeLibrary failure: %s - %s [0x%08" PRIX32 "]\n", __func__, NtStatus2Tag(herr), + Win32ErrorCode2Tag(err), err); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c new file mode 100644 index 0000000000000000000000000000000000000000..e9d1c8da90ce66795ebb67c087a05bd7c8893934 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c @@ -0,0 +1,61 @@ + +#include +#include +#include +#include +#include +#include +#include + +int TestLibraryLoadLibrary(int argc, char* argv[]) +{ + HINSTANCE library = NULL; + LPCSTR SharedLibraryExtension = NULL; + CHAR LibraryPath[PATHCCH_MAX_CCH] = { 0 }; + PCHAR p = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + if (!GetModuleFileNameA(NULL, LibraryPath, PATHCCH_MAX_CCH)) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: GetModuleFilenameA failed: %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + /* PathCchRemoveFileSpec is not implemented in WinPR */ + + if (!(p = strrchr(LibraryPath, PathGetSeparatorA(PATH_STYLE_NATIVE)))) + { + printf("%s: Error identifying module directory path\n", __func__); + return -1; + } + *p = 0; + + NativePathCchAppendA(LibraryPath, PATHCCH_MAX_CCH, "TestLibraryA"); + SharedLibraryExtension = PathGetSharedLibraryExtensionA(PATH_SHARED_LIB_EXT_WITH_DOT); + NativePathCchAddExtensionA(LibraryPath, PATHCCH_MAX_CCH, SharedLibraryExtension); + + printf("%s: Loading Library: '%s'\n", __func__, LibraryPath); + + if (!(library = LoadLibraryA(LibraryPath))) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: LoadLibraryA failure: %s - %s [0x%08" PRIX32 "]\n", __func__, + NtStatus2Tag(herr), Win32ErrorCode2Tag(err), err); + return -1; + } + + if (!FreeLibrary(library)) + { + const UINT32 err = GetLastError(); + const HRESULT herr = HRESULT_FROM_WIN32(err); + printf("%s: FreeLibrary failure: %s - %s [0x%08" PRIX32 "]\n", __func__, NtStatus2Tag(herr), + Win32ErrorCode2Tag(err), err); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/log.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/log.h new file mode 100644 index 0000000000000000000000000000000000000000..60158aaf423fd95e7cc4982ac813a198ff62c508 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/log.h @@ -0,0 +1,27 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Winpr log defines + * + * Copyright 2014 Armin Novak + * + * 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_PRIV_H +#define WINPR_LOG_PRIV_H + +#include + +#define WINPR_TAG(tag) "com.winpr." tag + +#endif /* WINPR_UTILS_DEBUG_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fad6090e64afbe5eb26a01e3bd727d376f50a3ea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-memory cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(memory.c memory.h) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d5dfca1c83d7922eb27e68106421b8ad7f0d47dd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "2") +set(MINWIN_SHORT_NAME "memory") +set(MINWIN_LONG_NAME "Memory Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.c new file mode 100644 index 0000000000000000000000000000000000000000..5c6f5e042e01edf7a2cb22dac1eaadc066400883 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.c @@ -0,0 +1,128 @@ +/** + * WinPR: Windows Portable Runtime + * Memory Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +/** + * api-ms-win-core-memory-l1-1-2.dll: + * + * AllocateUserPhysicalPages + * AllocateUserPhysicalPagesNuma + * CreateFileMappingFromApp + * CreateFileMappingNumaW + * CreateFileMappingW + * CreateMemoryResourceNotification + * FlushViewOfFile + * FreeUserPhysicalPages + * GetLargePageMinimum + * GetMemoryErrorHandlingCapabilities + * GetProcessWorkingSetSizeEx + * GetSystemFileCacheSize + * GetWriteWatch + * MapUserPhysicalPages + * MapViewOfFile + * MapViewOfFileEx + * MapViewOfFileFromApp + * OpenFileMappingW + * PrefetchVirtualMemory + * QueryMemoryResourceNotification + * ReadProcessMemory + * RegisterBadMemoryNotification + * ResetWriteWatch + * SetProcessWorkingSetSizeEx + * SetSystemFileCacheSize + * UnmapViewOfFile + * UnmapViewOfFileEx + * UnregisterBadMemoryNotification + * VirtualAlloc + * VirtualAllocEx + * VirtualAllocExNuma + * VirtualFree + * VirtualFreeEx + * VirtualLock + * VirtualProtect + * VirtualProtectEx + * VirtualQuery + * VirtualQueryEx + * VirtualUnlock + * WriteProcessMemory + */ + +#ifndef _WIN32 + +#include "memory.h" + +HANDLE CreateFileMappingA(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes, DWORD flProtect, + DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName) +{ + if (hFile != INVALID_HANDLE_VALUE) + { + return NULL; /* not yet implemented */ + } + + return NULL; +} + +HANDLE CreateFileMappingW(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes, DWORD flProtect, + DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCWSTR lpName) +{ + return NULL; +} + +HANDLE OpenFileMappingA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) +{ + return NULL; +} + +HANDLE OpenFileMappingW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName) +{ + return NULL; +} + +LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, + DWORD dwFileOffsetLow, size_t dwNumberOfBytesToMap) +{ + return NULL; +} + +LPVOID MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, + DWORD dwFileOffsetLow, size_t dwNumberOfBytesToMap, LPVOID lpBaseAddress) +{ + return NULL; +} + +BOOL FlushViewOfFile(LPCVOID lpBaseAddress, size_t dwNumberOfBytesToFlush) +{ + return TRUE; +} + +BOOL UnmapViewOfFile(LPCVOID lpBaseAddress) +{ + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.h new file mode 100644 index 0000000000000000000000000000000000000000..cc2492e0d1463b7f3920c67892f68fea3f0adc13 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/memory.h @@ -0,0 +1,30 @@ +/** + * WinPR: Windows Portable Runtime + * Memory Functions + * + * Copyright 2014 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_MEMORY_PRIVATE_H + +#ifndef _WIN32 + +#include +#include + +#endif + +#endif /* WINPR_MEMORY_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b6c502e7909bbcc38d73bd8a2928182cdc04dc1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/CMakeLists.txt @@ -0,0 +1,21 @@ +set(MODULE_NAME "TestMemory") +set(MODULE_PREFIX "TEST_MEMORY") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestMemoryCreateFileMapping.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/TestMemoryCreateFileMapping.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/TestMemoryCreateFileMapping.c new file mode 100644 index 0000000000000000000000000000000000000000..e6e7552e3732786eba4427abe2656ea79f42e1ea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/memory/test/TestMemoryCreateFileMapping.c @@ -0,0 +1,8 @@ + +#include +#include + +int TestMemoryCreateFileMapping(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..825489dbc04fb0c3c5dc900ec91fab2c41d266aa --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/CMakeLists.txt @@ -0,0 +1,30 @@ +# WinPR: Windows Portable Runtime +# libwinpr-ncrypt cmake build script +# +# Copyright 2021 David Fort +# +# 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. + +if(WITH_PKCS11) + winpr_module_add(ncrypt_pkcs11.c pkcs11-headers/pkcs11.h) +endif() + +winpr_module_add(ncrypt.c ncrypt.h) + +if(WIN32) + winpr_library_add_public(ncrypt) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..54df271e4006ebd532686b190b732d15ff98969f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ModuleOptions.cmake @@ -0,0 +1,7 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "ncrypt") +set(MINWIN_LONG_NAME "NCrypt Functions") +set(MODULE_LIBRARY_NAME "ncrypt") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.c new file mode 100644 index 0000000000000000000000000000000000000000..d5b6e5f89644c0d923babe795d1483c25ac3e5c3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.c @@ -0,0 +1,357 @@ +/** + * WinPR: Windows Portable Runtime + * NCrypt library + * + * Copyright 2021 David Fort + * + * 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 +#include +#include + +#ifndef _WIN32 + +#include +#include "../log.h" + +#include "ncrypt.h" + +#define TAG WINPR_TAG("ncrypt") + +const static char NCRYPT_MAGIC[6] = { 'N', 'C', 'R', 'Y', 'P', 'T' }; + +SECURITY_STATUS checkNCryptHandle(NCRYPT_HANDLE handle, NCryptHandleType matchType) +{ + if (!handle) + { + WLog_VRB(TAG, "invalid handle '%p'", handle); + return ERROR_INVALID_PARAMETER; + } + + const NCryptBaseHandle* base = (NCryptBaseHandle*)handle; + if (memcmp(base->magic, NCRYPT_MAGIC, ARRAYSIZE(NCRYPT_MAGIC)) != 0) + { + char magic1[ARRAYSIZE(NCRYPT_MAGIC) + 1] = { 0 }; + char magic2[ARRAYSIZE(NCRYPT_MAGIC) + 1] = { 0 }; + + memcpy(magic1, base->magic, ARRAYSIZE(NCRYPT_MAGIC)); + memcpy(magic2, NCRYPT_MAGIC, ARRAYSIZE(NCRYPT_MAGIC)); + + WLog_VRB(TAG, "handle '%p' invalid magic '%s' instead of '%s'", base, magic1, magic2); + return ERROR_INVALID_PARAMETER; + } + + switch (base->type) + { + case WINPR_NCRYPT_PROVIDER: + case WINPR_NCRYPT_KEY: + break; + default: + WLog_VRB(TAG, "handle '%p' invalid type %d", base, base->type); + return ERROR_INVALID_PARAMETER; + } + + if ((matchType != WINPR_NCRYPT_INVALID) && (base->type != matchType)) + { + WLog_VRB(TAG, "handle '%p' invalid type %d, expected %d", base, base->type, matchType); + return ERROR_INVALID_PARAMETER; + } + return ERROR_SUCCESS; +} + +void* ncrypt_new_handle(NCryptHandleType kind, size_t len, NCryptGetPropertyFn getProp, + NCryptReleaseFn dtor) +{ + NCryptBaseHandle* ret = calloc(1, len); + if (!ret) + return NULL; + + memcpy(ret->magic, NCRYPT_MAGIC, sizeof(ret->magic)); + ret->type = kind; + ret->getPropertyFn = getProp; + ret->releaseFn = dtor; + return ret; +} + +SECURITY_STATUS winpr_NCryptDefault_dtor(NCRYPT_HANDLE handle) +{ + NCryptBaseHandle* h = (NCryptBaseHandle*)handle; + if (h) + { + memset(h->magic, 0, sizeof(h->magic)); + h->type = WINPR_NCRYPT_INVALID; + h->releaseFn = NULL; + free(h); + } + return ERROR_SUCCESS; +} + +SECURITY_STATUS NCryptEnumStorageProviders(DWORD* wProviderCount, + NCryptProviderName** ppProviderList, DWORD dwFlags) +{ + NCryptProviderName* ret = NULL; + size_t stringAllocSize = 0; +#ifdef WITH_PKCS11 + LPWSTR strPtr = NULL; + static const WCHAR emptyComment[] = { 0 }; + size_t copyAmount = 0; +#endif + + *wProviderCount = 0; + *ppProviderList = NULL; + +#ifdef WITH_PKCS11 + *wProviderCount += 1; + stringAllocSize += (_wcslen(MS_SCARD_PROV) + 1) * 2; + stringAllocSize += sizeof(emptyComment); +#endif + + if (!*wProviderCount) + return ERROR_SUCCESS; + + ret = malloc(*wProviderCount * sizeof(NCryptProviderName) + stringAllocSize); + if (!ret) + return NTE_NO_MEMORY; + +#ifdef WITH_PKCS11 + strPtr = (LPWSTR)(ret + *wProviderCount); + + ret->pszName = strPtr; + copyAmount = (_wcslen(MS_SCARD_PROV) + 1) * 2; + memcpy(strPtr, MS_SCARD_PROV, copyAmount); + strPtr += copyAmount / 2; + + ret->pszComment = strPtr; + copyAmount = sizeof(emptyComment); + memcpy(strPtr, emptyComment, copyAmount); + + *ppProviderList = ret; +#endif + + return ERROR_SUCCESS; +} + +SECURITY_STATUS NCryptOpenStorageProvider(NCRYPT_PROV_HANDLE* phProvider, LPCWSTR pszProviderName, + DWORD dwFlags) +{ + return winpr_NCryptOpenStorageProviderEx(phProvider, pszProviderName, dwFlags, NULL); +} + +SECURITY_STATUS winpr_NCryptOpenStorageProviderEx(NCRYPT_PROV_HANDLE* phProvider, + LPCWSTR pszProviderName, DWORD dwFlags, + LPCSTR* modulePaths) +{ +#if defined(WITH_PKCS11) + if (pszProviderName && ((_wcscmp(pszProviderName, MS_SMART_CARD_KEY_STORAGE_PROVIDER) == 0) || + (_wcscmp(pszProviderName, MS_SCARD_PROV) == 0))) + return NCryptOpenP11StorageProviderEx(phProvider, pszProviderName, dwFlags, modulePaths); + + char buffer[128] = { 0 }; + (void)ConvertWCharToUtf8(pszProviderName, buffer, sizeof(buffer)); + WLog_WARN(TAG, "provider '%s' not supported", buffer); + return ERROR_NOT_SUPPORTED; +#else + WLog_WARN(TAG, "rebuild with -DWITH_PKCS11=ON to enable smartcard logon support"); + return ERROR_NOT_SUPPORTED; +#endif +} + +SECURITY_STATUS NCryptEnumKeys(NCRYPT_PROV_HANDLE hProvider, LPCWSTR pszScope, + NCryptKeyName** ppKeyName, PVOID* ppEnumState, DWORD dwFlags) +{ + SECURITY_STATUS ret = 0; + NCryptBaseProvider* provider = (NCryptBaseProvider*)hProvider; + + ret = checkNCryptHandle((NCRYPT_HANDLE)hProvider, WINPR_NCRYPT_PROVIDER); + if (ret != ERROR_SUCCESS) + return ret; + + return provider->enumKeysFn(hProvider, pszScope, ppKeyName, ppEnumState, dwFlags); +} + +SECURITY_STATUS NCryptOpenKey(NCRYPT_PROV_HANDLE hProvider, NCRYPT_KEY_HANDLE* phKey, + LPCWSTR pszKeyName, DWORD dwLegacyKeySpec, DWORD dwFlags) +{ + SECURITY_STATUS ret = 0; + NCryptBaseProvider* provider = (NCryptBaseProvider*)hProvider; + + ret = checkNCryptHandle((NCRYPT_HANDLE)hProvider, WINPR_NCRYPT_PROVIDER); + if (ret != ERROR_SUCCESS) + return ret; + if (!phKey || !pszKeyName) + return ERROR_INVALID_PARAMETER; + + return provider->openKeyFn(hProvider, phKey, pszKeyName, dwLegacyKeySpec, dwFlags); +} + +static NCryptKeyGetPropertyEnum propertyStringToEnum(LPCWSTR pszProperty) +{ + if (_wcscmp(pszProperty, NCRYPT_CERTIFICATE_PROPERTY) == 0) + { + return NCRYPT_PROPERTY_CERTIFICATE; + } + else if (_wcscmp(pszProperty, NCRYPT_READER_PROPERTY) == 0) + { + return NCRYPT_PROPERTY_READER; + } + else if (_wcscmp(pszProperty, NCRYPT_WINPR_SLOTID) == 0) + { + return NCRYPT_PROPERTY_SLOTID; + } + else if (_wcscmp(pszProperty, NCRYPT_NAME_PROPERTY) == 0) + { + return NCRYPT_PROPERTY_NAME; + } + + return NCRYPT_PROPERTY_UNKNOWN; +} + +SECURITY_STATUS NCryptGetProperty(NCRYPT_HANDLE hObject, LPCWSTR pszProperty, PBYTE pbOutput, + DWORD cbOutput, DWORD* pcbResult, DWORD dwFlags) +{ + NCryptKeyGetPropertyEnum property = NCRYPT_PROPERTY_UNKNOWN; + NCryptBaseHandle* base = NULL; + + if (!hObject) + return ERROR_INVALID_PARAMETER; + + base = (NCryptBaseHandle*)hObject; + if (memcmp(base->magic, NCRYPT_MAGIC, 6) != 0) + return ERROR_INVALID_HANDLE; + + property = propertyStringToEnum(pszProperty); + if (property == NCRYPT_PROPERTY_UNKNOWN) + return ERROR_NOT_SUPPORTED; + + return base->getPropertyFn(hObject, property, pbOutput, cbOutput, pcbResult, dwFlags); +} + +SECURITY_STATUS NCryptFreeObject(NCRYPT_HANDLE hObject) +{ + NCryptBaseHandle* base = NULL; + SECURITY_STATUS ret = checkNCryptHandle(hObject, WINPR_NCRYPT_INVALID); + if (ret != ERROR_SUCCESS) + return ret; + + base = (NCryptBaseHandle*)hObject; + if (base->releaseFn) + ret = base->releaseFn(hObject); + + return ret; +} + +SECURITY_STATUS NCryptFreeBuffer(PVOID pvInput) +{ + if (!pvInput) + return ERROR_INVALID_PARAMETER; + + free(pvInput); + return ERROR_SUCCESS; +} + +#else +SECURITY_STATUS winpr_NCryptOpenStorageProviderEx(NCRYPT_PROV_HANDLE* phProvider, + LPCWSTR pszProviderName, DWORD dwFlags, + LPCSTR* modulePaths) +{ + typedef SECURITY_STATUS (*NCryptOpenStorageProviderFn)(NCRYPT_PROV_HANDLE * phProvider, + LPCWSTR pszProviderName, DWORD dwFlags); + SECURITY_STATUS ret = NTE_PROV_DLL_NOT_FOUND; + HANDLE lib = LoadLibraryA("ncrypt.dll"); + if (!lib) + return NTE_PROV_DLL_NOT_FOUND; + + NCryptOpenStorageProviderFn ncryptOpenStorageProviderFn = + GetProcAddressAs(lib, "NCryptOpenStorageProvider", NCryptOpenStorageProviderFn); + if (!ncryptOpenStorageProviderFn) + { + ret = NTE_PROV_DLL_NOT_FOUND; + goto out_free_lib; + } + + ret = ncryptOpenStorageProviderFn(phProvider, pszProviderName, dwFlags); + +out_free_lib: + FreeLibrary(lib); + return ret; +} +#endif /* _WIN32 */ + +const char* winpr_NCryptSecurityStatusError(SECURITY_STATUS status) +{ +#define NTE_CASE(S) \ + case (SECURITY_STATUS)(S): \ + return #S + + switch (status) + { + NTE_CASE(ERROR_SUCCESS); + NTE_CASE(ERROR_INVALID_PARAMETER); + NTE_CASE(ERROR_INVALID_HANDLE); + NTE_CASE(ERROR_NOT_SUPPORTED); + + NTE_CASE(NTE_BAD_UID); + NTE_CASE(NTE_BAD_HASH); + NTE_CASE(NTE_BAD_KEY); + NTE_CASE(NTE_BAD_LEN); + NTE_CASE(NTE_BAD_DATA); + NTE_CASE(NTE_BAD_SIGNATURE); + NTE_CASE(NTE_BAD_VER); + NTE_CASE(NTE_BAD_ALGID); + NTE_CASE(NTE_BAD_FLAGS); + NTE_CASE(NTE_BAD_TYPE); + NTE_CASE(NTE_BAD_KEY_STATE); + NTE_CASE(NTE_BAD_HASH_STATE); + NTE_CASE(NTE_NO_KEY); + NTE_CASE(NTE_NO_MEMORY); + NTE_CASE(NTE_EXISTS); + NTE_CASE(NTE_PERM); + NTE_CASE(NTE_NOT_FOUND); + NTE_CASE(NTE_DOUBLE_ENCRYPT); + NTE_CASE(NTE_BAD_PROVIDER); + NTE_CASE(NTE_BAD_PROV_TYPE); + NTE_CASE(NTE_BAD_PUBLIC_KEY); + NTE_CASE(NTE_BAD_KEYSET); + NTE_CASE(NTE_PROV_TYPE_NOT_DEF); + NTE_CASE(NTE_PROV_TYPE_ENTRY_BAD); + NTE_CASE(NTE_KEYSET_NOT_DEF); + NTE_CASE(NTE_KEYSET_ENTRY_BAD); + NTE_CASE(NTE_PROV_TYPE_NO_MATCH); + NTE_CASE(NTE_SIGNATURE_FILE_BAD); + NTE_CASE(NTE_PROVIDER_DLL_FAIL); + NTE_CASE(NTE_PROV_DLL_NOT_FOUND); + NTE_CASE(NTE_BAD_KEYSET_PARAM); + NTE_CASE(NTE_FAIL); + NTE_CASE(NTE_SYS_ERR); + NTE_CASE(NTE_SILENT_CONTEXT); + NTE_CASE(NTE_TOKEN_KEYSET_STORAGE_FULL); + NTE_CASE(NTE_TEMPORARY_PROFILE); + NTE_CASE(NTE_FIXEDPARAMETER); + + default: + return ""; + } + +#undef NTE_CASE +} + +const char* winpr_NCryptGetModulePath(NCRYPT_PROV_HANDLE phProvider) +{ +#if defined(WITH_PKCS11) + return NCryptGetModulePath(phProvider); +#else + return NULL; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.h new file mode 100644 index 0000000000000000000000000000000000000000..2f3f2d8fe4f53e77ea387b3fdf3e14e4d319cdb9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt.h @@ -0,0 +1,96 @@ +/** + * WinPR: Windows Portable Runtime + * NCrypt library + * + * Copyright 2021 David Fort + * + * 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_LIBWINPR_NCRYPT_NCRYPT_H_ +#define WINPR_LIBWINPR_NCRYPT_NCRYPT_H_ + +#include + +#include +#include +#include +#include +#include + +/** @brief type of ncrypt object */ +typedef enum +{ + WINPR_NCRYPT_INVALID, + WINPR_NCRYPT_PROVIDER, + WINPR_NCRYPT_KEY +} NCryptHandleType; + +/** @brief dtor function for ncrypt object */ +typedef SECURITY_STATUS (*NCryptReleaseFn)(NCRYPT_HANDLE handle); + +/** @brief an enum for the kind of property to retrieve */ +typedef enum +{ + NCRYPT_PROPERTY_CERTIFICATE, + NCRYPT_PROPERTY_READER, + NCRYPT_PROPERTY_SLOTID, + NCRYPT_PROPERTY_NAME, + NCRYPT_PROPERTY_UNKNOWN +} NCryptKeyGetPropertyEnum; + +typedef SECURITY_STATUS (*NCryptGetPropertyFn)(NCRYPT_HANDLE hObject, + NCryptKeyGetPropertyEnum property, PBYTE pbOutput, + DWORD cbOutput, DWORD* pcbResult, DWORD dwFlags); + +/** @brief common ncrypt handle items */ +typedef struct +{ + char magic[6]; + NCryptHandleType type; + NCryptGetPropertyFn getPropertyFn; + NCryptReleaseFn releaseFn; +} NCryptBaseHandle; + +typedef SECURITY_STATUS (*NCryptEnumKeysFn)(NCRYPT_PROV_HANDLE hProvider, LPCWSTR pszScope, + NCryptKeyName** ppKeyName, PVOID* ppEnumState, + DWORD dwFlags); +typedef SECURITY_STATUS (*NCryptOpenKeyFn)(NCRYPT_PROV_HANDLE hProvider, NCRYPT_KEY_HANDLE* phKey, + LPCWSTR pszKeyName, DWORD dwLegacyKeySpec, + DWORD dwFlags); + +/** @brief common ncrypt provider items */ +typedef struct +{ + NCryptBaseHandle baseHandle; + + NCryptEnumKeysFn enumKeysFn; + NCryptOpenKeyFn openKeyFn; +} NCryptBaseProvider; + +SECURITY_STATUS checkNCryptHandle(NCRYPT_HANDLE handle, NCryptHandleType matchType); + +SECURITY_STATUS winpr_NCryptDefault_dtor(NCRYPT_HANDLE handle); + +void* ncrypt_new_handle(NCryptHandleType kind, size_t len, NCryptGetPropertyFn getProp, + NCryptReleaseFn dtor); + +#if defined(WITH_PKCS11) +SECURITY_STATUS NCryptOpenP11StorageProviderEx(NCRYPT_PROV_HANDLE* phProvider, + LPCWSTR pszProviderName, DWORD dwFlags, + LPCSTR* modulePaths); + +const char* NCryptGetModulePath(NCRYPT_PROV_HANDLE phProvider); +#endif + +#endif /* WINPR_LIBWINPR_NCRYPT_NCRYPT_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c new file mode 100644 index 0000000000000000000000000000000000000000..a8cde64ee955f6d534c30e57fe0703d52ed6f4bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c @@ -0,0 +1,1343 @@ +/** + * WinPR: Windows Portable Runtime + * NCrypt pkcs11 provider + * + * Copyright 2021 David Fort + * + * 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 + +#include +#include +#include +#include +#include + +#include "../log.h" +#include "ncrypt.h" + +/* https://github.com/latchset/pkcs11-headers/blob/main/public-domain/3.1/pkcs11.h */ +#include "pkcs11-headers/pkcs11.h" + +#define TAG WINPR_TAG("ncryptp11") + +#define MAX_SLOTS 64 +#define MAX_KEYS 64 +#define MAX_KEYS_PER_SLOT 64 + +/** @brief ncrypt provider handle */ +typedef struct +{ + NCryptBaseProvider baseProvider; + + HANDLE library; + CK_FUNCTION_LIST_PTR p11; + char* modulePath; +} NCryptP11ProviderHandle; + +/** @brief a handle returned by NCryptOpenKey */ +typedef struct +{ + NCryptBaseHandle base; + NCryptP11ProviderHandle* provider; + CK_SLOT_ID slotId; + CK_BYTE keyCertId[64]; + CK_ULONG keyCertIdLen; +} NCryptP11KeyHandle; + +typedef struct +{ + CK_SLOT_ID slotId; + CK_SLOT_INFO slotInfo; + CK_KEY_TYPE keyType; + CK_CHAR keyLabel[256]; + CK_ULONG idLen; + CK_BYTE id[64]; +} NCryptKeyEnum; + +typedef struct +{ + CK_ULONG nslots; + CK_SLOT_ID slots[MAX_SLOTS]; + CK_ULONG nKeys; + NCryptKeyEnum keys[MAX_KEYS]; + CK_ULONG keyIndex; +} P11EnumKeysState; + +typedef struct +{ + const char* label; + BYTE tag[3]; +} piv_cert_tags_t; +static const piv_cert_tags_t piv_cert_tags[] = { + { "Certificate for PIV Authentication", "\x5F\xC1\x05" }, + { "Certificate for Digital Signature", "\x5F\xC1\x0A" }, + { "Certificate for Key Management", "\x5F\xC1\x0B" }, + { "Certificate for Card Authentication", "\x5F\xC1\x01" }, +}; + +static const BYTE APDU_PIV_SELECT_AID[] = { 0x00, 0xA4, 0x04, 0x00, 0x09, 0xA0, 0x00, 0x00, + 0x03, 0x08, 0x00, 0x00, 0x10, 0x00, 0x00 }; +static const BYTE APDU_PIV_GET_CHUID[] = { 0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, + 0x03, 0x5F, 0xC1, 0x02, 0x00 }; +#define PIV_CONTAINER_NAME_LEN 36 + +static CK_OBJECT_CLASS object_class_public_key = CKO_PUBLIC_KEY; +static CK_BBOOL object_verify = CK_TRUE; +static CK_KEY_TYPE object_ktype_rsa = CKK_RSA; + +static CK_ATTRIBUTE public_key_filter[] = { + { CKA_CLASS, &object_class_public_key, sizeof(object_class_public_key) }, + { CKA_VERIFY, &object_verify, sizeof(object_verify) }, + { CKA_KEY_TYPE, &object_ktype_rsa, sizeof(object_ktype_rsa) } +}; + +static const char* CK_RV_error_string(CK_RV rv); + +static SECURITY_STATUS NCryptP11StorageProvider_dtor(NCRYPT_HANDLE handle) +{ + NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)handle; + CK_RV rv = CKR_OK; + + if (provider) + { + if (provider->p11 && provider->p11->C_Finalize) + rv = provider->p11->C_Finalize(NULL); + if (rv != CKR_OK) + WLog_WARN(TAG, "C_Finalize failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv), + rv); + + free(provider->modulePath); + + if (provider->library) + FreeLibrary(provider->library); + } + + return winpr_NCryptDefault_dtor(handle); +} + +static void fix_padded_string(char* str, size_t maxlen) +{ + char* ptr = str + maxlen - 1; + + while (ptr > str && *ptr == ' ') + ptr--; + ptr++; + *ptr = 0; +} + +static BOOL attributes_have_unallocated_buffers(CK_ATTRIBUTE_PTR attributes, CK_ULONG count) +{ + for (CK_ULONG i = 0; i < count; i++) + { + if (!attributes[i].pValue && (attributes[i].ulValueLen != CK_UNAVAILABLE_INFORMATION)) + return TRUE; + } + + return FALSE; +} + +static BOOL attribute_allocate_attribute_array(CK_ATTRIBUTE_PTR attribute) +{ + WINPR_ASSERT(attribute); + attribute->pValue = calloc(attribute->ulValueLen, sizeof(void*)); + return !!attribute->pValue; +} + +static BOOL attribute_allocate_ulong_array(CK_ATTRIBUTE_PTR attribute) +{ + attribute->pValue = calloc(attribute->ulValueLen, sizeof(CK_ULONG)); + return !!attribute->pValue; +} + +static BOOL attribute_allocate_buffer(CK_ATTRIBUTE_PTR attribute) +{ + attribute->pValue = calloc(attribute->ulValueLen, 1); + return !!attribute->pValue; +} + +static BOOL attributes_allocate_buffers(CK_ATTRIBUTE_PTR attributes, CK_ULONG count) +{ + BOOL ret = TRUE; + + for (CK_ULONG i = 0; i < count; i++) + { + if (attributes[i].pValue || (attributes[i].ulValueLen == CK_UNAVAILABLE_INFORMATION)) + continue; + + switch (attributes[i].type) + { + case CKA_WRAP_TEMPLATE: + case CKA_UNWRAP_TEMPLATE: + ret &= attribute_allocate_attribute_array(&attributes[i]); + break; + + case CKA_ALLOWED_MECHANISMS: + ret &= attribute_allocate_ulong_array(&attributes[i]); + break; + + default: + ret &= attribute_allocate_buffer(&attributes[i]); + break; + } + } + + return ret; +} + +static CK_RV object_load_attributes(NCryptP11ProviderHandle* provider, CK_SESSION_HANDLE session, + CK_OBJECT_HANDLE object, CK_ATTRIBUTE_PTR attributes, + CK_ULONG count) +{ + WINPR_ASSERT(provider); + WINPR_ASSERT(provider->p11); + WINPR_ASSERT(provider->p11->C_GetAttributeValue); + + CK_RV rv = provider->p11->C_GetAttributeValue(session, object, attributes, count); + + switch (rv) + { + case CKR_OK: + if (!attributes_have_unallocated_buffers(attributes, count)) + return rv; + /* fallthrough */ + WINPR_FALLTHROUGH + case CKR_ATTRIBUTE_SENSITIVE: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_BUFFER_TOO_SMALL: + /* attributes need some buffers for the result value */ + if (!attributes_allocate_buffers(attributes, count)) + return CKR_HOST_MEMORY; + + rv = provider->p11->C_GetAttributeValue(session, object, attributes, count); + if (rv != CKR_OK) + WLog_WARN(TAG, "C_GetAttributeValue failed with %s [0x%08" PRIx32 "]", + CK_RV_error_string(rv), rv); + break; + default: + WLog_WARN(TAG, "C_GetAttributeValue failed with %s [0x%08" PRIx32 "]", + CK_RV_error_string(rv), rv); + return rv; + } + + switch (rv) + { + case CKR_ATTRIBUTE_SENSITIVE: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_BUFFER_TOO_SMALL: + WLog_ERR(TAG, + "C_GetAttributeValue failed with %s [0x%08" PRIx32 + "] even after buffer allocation", + CK_RV_error_string(rv), rv); + break; + default: + break; + } + return rv; +} + +static const char* CK_RV_error_string(CK_RV rv) +{ + static char generic_buffer[200]; +#define ERR_ENTRY(X) \ + case X: \ + return #X + + switch (rv) + { + ERR_ENTRY(CKR_OK); + ERR_ENTRY(CKR_CANCEL); + ERR_ENTRY(CKR_HOST_MEMORY); + ERR_ENTRY(CKR_SLOT_ID_INVALID); + ERR_ENTRY(CKR_GENERAL_ERROR); + ERR_ENTRY(CKR_FUNCTION_FAILED); + ERR_ENTRY(CKR_ARGUMENTS_BAD); + ERR_ENTRY(CKR_NO_EVENT); + ERR_ENTRY(CKR_NEED_TO_CREATE_THREADS); + ERR_ENTRY(CKR_CANT_LOCK); + ERR_ENTRY(CKR_ATTRIBUTE_READ_ONLY); + ERR_ENTRY(CKR_ATTRIBUTE_SENSITIVE); + ERR_ENTRY(CKR_ATTRIBUTE_TYPE_INVALID); + ERR_ENTRY(CKR_ATTRIBUTE_VALUE_INVALID); + ERR_ENTRY(CKR_DATA_INVALID); + ERR_ENTRY(CKR_DATA_LEN_RANGE); + ERR_ENTRY(CKR_DEVICE_ERROR); + ERR_ENTRY(CKR_DEVICE_MEMORY); + ERR_ENTRY(CKR_DEVICE_REMOVED); + ERR_ENTRY(CKR_ENCRYPTED_DATA_INVALID); + ERR_ENTRY(CKR_ENCRYPTED_DATA_LEN_RANGE); + ERR_ENTRY(CKR_FUNCTION_CANCELED); + ERR_ENTRY(CKR_FUNCTION_NOT_PARALLEL); + ERR_ENTRY(CKR_FUNCTION_NOT_SUPPORTED); + ERR_ENTRY(CKR_KEY_HANDLE_INVALID); + ERR_ENTRY(CKR_KEY_SIZE_RANGE); + ERR_ENTRY(CKR_KEY_TYPE_INCONSISTENT); + ERR_ENTRY(CKR_KEY_NOT_NEEDED); + ERR_ENTRY(CKR_KEY_CHANGED); + ERR_ENTRY(CKR_KEY_NEEDED); + ERR_ENTRY(CKR_KEY_INDIGESTIBLE); + ERR_ENTRY(CKR_KEY_FUNCTION_NOT_PERMITTED); + ERR_ENTRY(CKR_KEY_NOT_WRAPPABLE); + ERR_ENTRY(CKR_KEY_UNEXTRACTABLE); + ERR_ENTRY(CKR_MECHANISM_INVALID); + ERR_ENTRY(CKR_MECHANISM_PARAM_INVALID); + ERR_ENTRY(CKR_OBJECT_HANDLE_INVALID); + ERR_ENTRY(CKR_OPERATION_ACTIVE); + ERR_ENTRY(CKR_OPERATION_NOT_INITIALIZED); + ERR_ENTRY(CKR_PIN_INCORRECT); + ERR_ENTRY(CKR_PIN_INVALID); + ERR_ENTRY(CKR_PIN_LEN_RANGE); + ERR_ENTRY(CKR_PIN_EXPIRED); + ERR_ENTRY(CKR_PIN_LOCKED); + ERR_ENTRY(CKR_SESSION_CLOSED); + ERR_ENTRY(CKR_SESSION_COUNT); + ERR_ENTRY(CKR_SESSION_HANDLE_INVALID); + ERR_ENTRY(CKR_SESSION_PARALLEL_NOT_SUPPORTED); + ERR_ENTRY(CKR_SESSION_READ_ONLY); + ERR_ENTRY(CKR_SESSION_EXISTS); + ERR_ENTRY(CKR_SESSION_READ_ONLY_EXISTS); + ERR_ENTRY(CKR_SESSION_READ_WRITE_SO_EXISTS); + ERR_ENTRY(CKR_SIGNATURE_INVALID); + ERR_ENTRY(CKR_SIGNATURE_LEN_RANGE); + ERR_ENTRY(CKR_TEMPLATE_INCOMPLETE); + ERR_ENTRY(CKR_TEMPLATE_INCONSISTENT); + ERR_ENTRY(CKR_TOKEN_NOT_PRESENT); + ERR_ENTRY(CKR_TOKEN_NOT_RECOGNIZED); + ERR_ENTRY(CKR_TOKEN_WRITE_PROTECTED); + ERR_ENTRY(CKR_UNWRAPPING_KEY_HANDLE_INVALID); + ERR_ENTRY(CKR_UNWRAPPING_KEY_SIZE_RANGE); + ERR_ENTRY(CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT); + ERR_ENTRY(CKR_USER_ALREADY_LOGGED_IN); + ERR_ENTRY(CKR_USER_NOT_LOGGED_IN); + ERR_ENTRY(CKR_USER_PIN_NOT_INITIALIZED); + ERR_ENTRY(CKR_USER_TYPE_INVALID); + ERR_ENTRY(CKR_USER_ANOTHER_ALREADY_LOGGED_IN); + ERR_ENTRY(CKR_USER_TOO_MANY_TYPES); + ERR_ENTRY(CKR_WRAPPED_KEY_INVALID); + ERR_ENTRY(CKR_WRAPPED_KEY_LEN_RANGE); + ERR_ENTRY(CKR_WRAPPING_KEY_HANDLE_INVALID); + ERR_ENTRY(CKR_WRAPPING_KEY_SIZE_RANGE); + ERR_ENTRY(CKR_WRAPPING_KEY_TYPE_INCONSISTENT); + ERR_ENTRY(CKR_RANDOM_SEED_NOT_SUPPORTED); + ERR_ENTRY(CKR_RANDOM_NO_RNG); + ERR_ENTRY(CKR_DOMAIN_PARAMS_INVALID); + ERR_ENTRY(CKR_BUFFER_TOO_SMALL); + ERR_ENTRY(CKR_SAVED_STATE_INVALID); + ERR_ENTRY(CKR_INFORMATION_SENSITIVE); + ERR_ENTRY(CKR_STATE_UNSAVEABLE); + ERR_ENTRY(CKR_CRYPTOKI_NOT_INITIALIZED); + ERR_ENTRY(CKR_CRYPTOKI_ALREADY_INITIALIZED); + ERR_ENTRY(CKR_MUTEX_BAD); + ERR_ENTRY(CKR_MUTEX_NOT_LOCKED); + ERR_ENTRY(CKR_FUNCTION_REJECTED); + default: + (void)snprintf(generic_buffer, sizeof(generic_buffer), "unknown 0x%lx", rv); + return generic_buffer; + } +#undef ERR_ENTRY +} + +#define loge(tag, msg, rv, index, slot) \ + log_((tag), (msg), (rv), (index), (slot), __FILE__, __func__, __LINE__) +static void log_(const char* tag, const char* msg, CK_RV rv, CK_ULONG index, CK_SLOT_ID slot, + const char* file, const char* fkt, size_t line) +{ + const DWORD log_level = WLOG_ERROR; + static wLog* log_cached_ptr = NULL; + if (!log_cached_ptr) + log_cached_ptr = WLog_Get(tag); + if (!WLog_IsLevelActive(log_cached_ptr, log_level)) + return; + + WLog_PrintMessage(log_cached_ptr, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "%s for slot #%" PRIu32 "(%" PRIu32 "), rv=%s", msg, index, slot, + CK_RV_error_string(rv)); +} + +static SECURITY_STATUS collect_keys(NCryptP11ProviderHandle* provider, P11EnumKeysState* state) +{ + CK_OBJECT_HANDLE slotObjects[MAX_KEYS_PER_SLOT] = { 0 }; + + WINPR_ASSERT(provider); + + CK_FUNCTION_LIST_PTR p11 = provider->p11; + WINPR_ASSERT(p11); + + WLog_DBG(TAG, "checking %" PRIu32 " slots for valid keys...", state->nslots); + state->nKeys = 0; + for (CK_ULONG i = 0; i < state->nslots; i++) + { + CK_SESSION_HANDLE session = (CK_SESSION_HANDLE)NULL; + CK_SLOT_INFO slotInfo = { 0 }; + CK_TOKEN_INFO tokenInfo = { 0 }; + + WINPR_ASSERT(p11->C_GetSlotInfo); + CK_RV rv = p11->C_GetSlotInfo(state->slots[i], &slotInfo); + if (rv != CKR_OK) + { + loge(TAG, "unable to retrieve information", rv, i, state->slots[i]); + continue; + } + + fix_padded_string((char*)slotInfo.slotDescription, sizeof(slotInfo.slotDescription)); + WLog_DBG(TAG, "collecting keys for slot #%" PRIu32 "(%" PRIu32 ") descr='%s' flags=0x%x", i, + state->slots[i], slotInfo.slotDescription, slotInfo.flags); + + /* this is a safety guard as we're supposed to have listed only readers with tokens in them + */ + if (!(slotInfo.flags & CKF_TOKEN_PRESENT)) + { + WLog_INFO(TAG, "token not present for slot #%" PRIu32 "(%" PRIu32 ")", i, + state->slots[i]); + continue; + } + + WINPR_ASSERT(p11->C_GetTokenInfo); + rv = p11->C_GetTokenInfo(state->slots[i], &tokenInfo); + if (rv != CKR_OK) + loge(TAG, "unable to retrieve token info", rv, i, state->slots[i]); + else + { + fix_padded_string((char*)tokenInfo.label, sizeof(tokenInfo.label)); + WLog_DBG(TAG, "token, label='%s' flags=0x%x", tokenInfo.label, tokenInfo.flags); + } + + WINPR_ASSERT(p11->C_OpenSession); + rv = p11->C_OpenSession(state->slots[i], CKF_SERIAL_SESSION, NULL, NULL, &session); + if (rv != CKR_OK) + { + WLog_ERR(TAG, + "unable to openSession for slot #%" PRIu32 "(%" PRIu32 "), session=%p rv=%s", + i, state->slots[i], session, CK_RV_error_string(rv)); + continue; + } + + WINPR_ASSERT(p11->C_FindObjectsInit); + rv = p11->C_FindObjectsInit(session, public_key_filter, ARRAYSIZE(public_key_filter)); + if (rv != CKR_OK) + { + // TODO: shall it be fatal ? + loge(TAG, "unable to initiate search", rv, i, state->slots[i]); + goto cleanup_FindObjectsInit; + } + + CK_ULONG nslotObjects = 0; + WINPR_ASSERT(p11->C_FindObjects); + rv = p11->C_FindObjects(session, &slotObjects[0], ARRAYSIZE(slotObjects), &nslotObjects); + if (rv != CKR_OK) + { + loge(TAG, "unable to findObjects", rv, i, state->slots[i]); + goto cleanup_FindObjects; + } + + WLog_DBG(TAG, "slot has %d objects", nslotObjects); + for (CK_ULONG j = 0; j < nslotObjects; j++) + { + NCryptKeyEnum* key = &state->keys[state->nKeys]; + CK_OBJECT_CLASS dataClass = CKO_PUBLIC_KEY; + CK_ATTRIBUTE key_or_certAttrs[] = { + { CKA_ID, &key->id, sizeof(key->id) }, + { CKA_CLASS, &dataClass, sizeof(dataClass) }, + { CKA_LABEL, &key->keyLabel, sizeof(key->keyLabel) }, + { CKA_KEY_TYPE, &key->keyType, sizeof(key->keyType) } + }; + + rv = object_load_attributes(provider, session, slotObjects[j], key_or_certAttrs, + ARRAYSIZE(key_or_certAttrs)); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "error getting attributes, rv=%s", CK_RV_error_string(rv)); + continue; + } + + key->idLen = key_or_certAttrs[0].ulValueLen; + key->slotId = state->slots[i]; + key->slotInfo = slotInfo; + state->nKeys++; + } + + cleanup_FindObjects: + WINPR_ASSERT(p11->C_FindObjectsFinal); + rv = p11->C_FindObjectsFinal(session); + if (rv != CKR_OK) + loge(TAG, "error during C_FindObjectsFinal", rv, i, state->slots[i]); + cleanup_FindObjectsInit: + WINPR_ASSERT(p11->C_CloseSession); + rv = p11->C_CloseSession(session); + if (rv != CKR_OK) + loge(TAG, "error closing session", rv, i, state->slots[i]); + } + + return ERROR_SUCCESS; +} + +static BOOL convertKeyType(CK_KEY_TYPE k, LPWSTR dest, DWORD len, DWORD* outlen) +{ + const WCHAR* r = NULL; + size_t retLen = 0; + +#define ALGO_CASE(V, S) \ + case V: \ + r = S; \ + retLen = _wcsnlen((S), ARRAYSIZE((S))); \ + break + switch (k) + { + ALGO_CASE(CKK_RSA, BCRYPT_RSA_ALGORITHM); + ALGO_CASE(CKK_DSA, BCRYPT_DSA_ALGORITHM); + ALGO_CASE(CKK_DH, BCRYPT_DH_ALGORITHM); + ALGO_CASE(CKK_EC, BCRYPT_ECDSA_ALGORITHM); + ALGO_CASE(CKK_RC2, BCRYPT_RC2_ALGORITHM); + ALGO_CASE(CKK_RC4, BCRYPT_RC4_ALGORITHM); + ALGO_CASE(CKK_DES, BCRYPT_DES_ALGORITHM); + ALGO_CASE(CKK_DES3, BCRYPT_3DES_ALGORITHM); + case CKK_DES2: + case CKK_X9_42_DH: + case CKK_KEA: + case CKK_GENERIC_SECRET: + case CKK_CAST: + case CKK_CAST3: + case CKK_CAST128: + case CKK_RC5: + case CKK_IDEA: + case CKK_SKIPJACK: + case CKK_BATON: + case CKK_JUNIPER: + case CKK_CDMF: + case CKK_AES: + case CKK_BLOWFISH: + case CKK_TWOFISH: + default: + break; + } +#undef ALGO_CASE + + if (retLen > UINT32_MAX) + return FALSE; + + if (outlen) + *outlen = (UINT32)retLen; + + if (!r) + { + if (dest && len > 0) + dest[0] = 0; + return FALSE; + } + else + { + if (retLen + 1 > len) + { + WLog_ERR(TAG, "target buffer is too small for algo name"); + return FALSE; + } + + if (dest) + { + memcpy(dest, r, sizeof(WCHAR) * retLen); + dest[retLen] = 0; + } + } + + return TRUE; +} + +static void wprintKeyName(LPWSTR str, CK_SLOT_ID slotId, CK_BYTE* id, CK_ULONG idLen) +{ + char asciiName[128] = { 0 }; + char* ptr = asciiName; + const CK_BYTE* bytePtr = NULL; + + *ptr = '\\'; + ptr++; + + bytePtr = ((CK_BYTE*)&slotId); + for (CK_ULONG i = 0; i < sizeof(slotId); i++, bytePtr++, ptr += 2) + (void)snprintf(ptr, 3, "%.2x", *bytePtr); + + *ptr = '\\'; + ptr++; + + for (CK_ULONG i = 0; i < idLen; i++, id++, ptr += 2) + (void)snprintf(ptr, 3, "%.2x", *id); + + (void)ConvertUtf8NToWChar(asciiName, ARRAYSIZE(asciiName), str, + strnlen(asciiName, ARRAYSIZE(asciiName)) + 1); +} + +static size_t parseHex(const char* str, const char* end, CK_BYTE* target) +{ + size_t ret = 0; + + for (; str != end && *str; str++, ret++, target++) + { + int v = 0; + if (*str <= '9' && *str >= '0') + { + v = (*str - '0'); + } + else if (*str <= 'f' && *str >= 'a') + { + v = (10 + *str - 'a'); + } + else if (*str <= 'F' && *str >= 'A') + { + v |= (10 + *str - 'A'); + } + else + { + return 0; + } + v <<= 4; + str++; + + if (!*str || str == end) + return 0; + + if (*str <= '9' && *str >= '0') + { + v |= (*str - '0'); + } + else if (*str <= 'f' && *str >= 'a') + { + v |= (10 + *str - 'a'); + } + else if (*str <= 'F' && *str >= 'A') + { + v |= (10 + *str - 'A'); + } + else + { + return 0; + } + + *target = v & 0xFF; + } + return ret; +} + +static SECURITY_STATUS parseKeyName(LPCWSTR pszKeyName, CK_SLOT_ID* slotId, CK_BYTE* id, + CK_ULONG* idLen) +{ + char asciiKeyName[128] = { 0 }; + char* pos = NULL; + + if (ConvertWCharToUtf8(pszKeyName, asciiKeyName, ARRAYSIZE(asciiKeyName)) < 0) + return NTE_BAD_KEY; + + if (*asciiKeyName != '\\') + return NTE_BAD_KEY; + + pos = strchr(&asciiKeyName[1], '\\'); + if (!pos) + return NTE_BAD_KEY; + + if ((size_t)(pos - &asciiKeyName[1]) > sizeof(CK_SLOT_ID) * 2ull) + return NTE_BAD_KEY; + + *slotId = (CK_SLOT_ID)0; + if (parseHex(&asciiKeyName[1], pos, (CK_BYTE*)slotId) != sizeof(CK_SLOT_ID)) + return NTE_BAD_KEY; + + *idLen = parseHex(pos + 1, NULL, id); + if (!*idLen) + return NTE_BAD_KEY; + + return ERROR_SUCCESS; +} + +static SECURITY_STATUS NCryptP11EnumKeys(NCRYPT_PROV_HANDLE hProvider, LPCWSTR pszScope, + NCryptKeyName** ppKeyName, PVOID* ppEnumState, + DWORD dwFlags) +{ + NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)hProvider; + P11EnumKeysState* state = (P11EnumKeysState*)*ppEnumState; + CK_RV rv = { 0 }; + CK_SLOT_ID currentSlot = { 0 }; + CK_SESSION_HANDLE currentSession = (CK_SESSION_HANDLE)NULL; + char slotFilterBuffer[65] = { 0 }; + char* slotFilter = NULL; + size_t slotFilterLen = 0; + + SECURITY_STATUS ret = checkNCryptHandle((NCRYPT_HANDLE)hProvider, WINPR_NCRYPT_PROVIDER); + if (ret != ERROR_SUCCESS) + return ret; + + if (pszScope) + { + /* + * check whether pszScope is of the form \\.\\ for filtering by + * card reader + */ + char asciiScope[128 + 6 + 1] = { 0 }; + size_t asciiScopeLen = 0; + + if (ConvertWCharToUtf8(pszScope, asciiScope, ARRAYSIZE(asciiScope) - 1) < 0) + { + WLog_WARN(TAG, "Invalid scope"); + return NTE_INVALID_PARAMETER; + } + + if (strstr(asciiScope, "\\\\.\\") != asciiScope) + { + WLog_WARN(TAG, "Invalid scope '%s'", asciiScope); + return NTE_INVALID_PARAMETER; + } + + asciiScopeLen = strnlen(asciiScope, ARRAYSIZE(asciiScope)); + if ((asciiScopeLen < 1) || (asciiScope[asciiScopeLen - 1] != '\\')) + { + WLog_WARN(TAG, "Invalid scope '%s'", asciiScope); + return NTE_INVALID_PARAMETER; + } + + asciiScope[asciiScopeLen - 1] = 0; + + strncpy(slotFilterBuffer, &asciiScope[4], sizeof(slotFilterBuffer)); + slotFilter = slotFilterBuffer; + slotFilterLen = asciiScopeLen - 5; + } + + if (!state) + { + state = (P11EnumKeysState*)calloc(1, sizeof(*state)); + if (!state) + return NTE_NO_MEMORY; + + WINPR_ASSERT(provider->p11->C_GetSlotList); + rv = provider->p11->C_GetSlotList(CK_TRUE, NULL, &state->nslots); + if (rv != CKR_OK) + { + free(state); + /* TODO: perhaps convert rv to NTE_*** errors */ + WLog_WARN(TAG, "C_GetSlotList failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv), + rv); + return NTE_FAIL; + } + + if (state->nslots > MAX_SLOTS) + state->nslots = MAX_SLOTS; + + rv = provider->p11->C_GetSlotList(CK_TRUE, state->slots, &state->nslots); + if (rv != CKR_OK) + { + free(state); + /* TODO: perhaps convert rv to NTE_*** errors */ + WLog_WARN(TAG, "C_GetSlotList failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv), + rv); + return NTE_FAIL; + } + + ret = collect_keys(provider, state); + if (ret != ERROR_SUCCESS) + { + free(state); + return ret; + } + + *ppEnumState = state; + } + + for (; state->keyIndex < state->nKeys; state->keyIndex++) + { + NCryptKeyName* keyName = NULL; + NCryptKeyEnum* key = &state->keys[state->keyIndex]; + CK_OBJECT_CLASS oclass = CKO_CERTIFICATE; + CK_CERTIFICATE_TYPE ctype = CKC_X_509; + CK_ATTRIBUTE certificateFilter[] = { { CKA_CLASS, &oclass, sizeof(oclass) }, + { CKA_CERTIFICATE_TYPE, &ctype, sizeof(ctype) }, + { CKA_ID, key->id, key->idLen } }; + CK_ULONG ncertObjects = 0; + CK_OBJECT_HANDLE certObject = 0; + + /* check the reader filter if any */ + if (slotFilter && memcmp(key->slotInfo.slotDescription, slotFilter, slotFilterLen) != 0) + continue; + + if (!currentSession || (currentSlot != key->slotId)) + { + /* if the current session doesn't match the current key's slot, open a new one + */ + if (currentSession) + { + WINPR_ASSERT(provider->p11->C_CloseSession); + rv = provider->p11->C_CloseSession(currentSession); + if (rv != CKR_OK) + WLog_WARN(TAG, "C_CloseSession failed with %s [0x%08" PRIx32 "]", + CK_RV_error_string(rv), rv); + currentSession = (CK_SESSION_HANDLE)NULL; + } + + WINPR_ASSERT(provider->p11->C_OpenSession); + rv = provider->p11->C_OpenSession(key->slotId, CKF_SERIAL_SESSION, NULL, NULL, + ¤tSession); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "C_OpenSession failed with %s [0x%08" PRIx32 "] for slot %d", + CK_RV_error_string(rv), rv, key->slotId); + continue; + } + currentSlot = key->slotId; + } + + /* look if we can find a certificate that matches the key's id */ + WINPR_ASSERT(provider->p11->C_FindObjectsInit); + rv = provider->p11->C_FindObjectsInit(currentSession, certificateFilter, + ARRAYSIZE(certificateFilter)); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "C_FindObjectsInit failed with %s [0x%08" PRIx32 "] for slot %d", + CK_RV_error_string(rv), rv, key->slotId); + continue; + } + + WINPR_ASSERT(provider->p11->C_FindObjects); + rv = provider->p11->C_FindObjects(currentSession, &certObject, 1, &ncertObjects); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "C_FindObjects failed with %s [0x%08" PRIx32 "] for slot %d", + CK_RV_error_string(rv), rv, currentSlot); + goto cleanup_FindObjects; + } + + if (ncertObjects) + { + /* sizeof keyName struct + "\\" + keyName->pszAlgid */ + DWORD algoSz = 0; + size_t KEYNAME_SZ = + (1 + (sizeof(key->slotId) * 2) /*slotId*/ + 1 + (key->idLen * 2) + 1) * 2; + + convertKeyType(key->keyType, NULL, 0, &algoSz); + KEYNAME_SZ += (1ULL + algoSz) * 2ULL; + + keyName = calloc(1, sizeof(*keyName) + KEYNAME_SZ); + if (!keyName) + { + WLog_ERR(TAG, "unable to allocate keyName"); + goto cleanup_FindObjects; + } + keyName->dwLegacyKeySpec = AT_KEYEXCHANGE | AT_SIGNATURE; + keyName->dwFlags = NCRYPT_MACHINE_KEY_FLAG; + keyName->pszName = (LPWSTR)(keyName + 1); + wprintKeyName(keyName->pszName, key->slotId, key->id, key->idLen); + + keyName->pszAlgid = keyName->pszName + _wcslen(keyName->pszName) + 1; + convertKeyType(key->keyType, keyName->pszAlgid, algoSz + 1, NULL); + } + + cleanup_FindObjects: + WINPR_ASSERT(provider->p11->C_FindObjectsFinal); + rv = provider->p11->C_FindObjectsFinal(currentSession); + if (rv != CKR_OK) + WLog_ERR(TAG, "C_FindObjectsFinal failed with %s [0x%08" PRIx32 "]", + CK_RV_error_string(rv), rv); + + if (keyName) + { + *ppKeyName = keyName; + state->keyIndex++; + return ERROR_SUCCESS; + } + } + + return NTE_NO_MORE_ITEMS; +} + +static SECURITY_STATUS get_piv_container_name(NCryptP11KeyHandle* key, const BYTE* piv_tag, + BYTE* output, size_t output_len) +{ + CK_SLOT_INFO slot_info = { 0 }; + CK_FUNCTION_LIST_PTR p11 = NULL; + WCHAR* reader = NULL; + SCARDCONTEXT context = 0; + SCARDHANDLE card = 0; + DWORD proto = 0; + const SCARD_IO_REQUEST* pci = NULL; + BYTE buf[258] = { 0 }; + char container_name[PIV_CONTAINER_NAME_LEN + 1] = { 0 }; + DWORD buf_len = 0; + SECURITY_STATUS ret = NTE_BAD_KEY; + WinPrAsn1Decoder dec = { 0 }; + WinPrAsn1Decoder dec2 = { 0 }; + size_t len = 0; + BYTE tag = 0; + BYTE* p = NULL; + wStream s = { 0 }; + + WINPR_ASSERT(key); + WINPR_ASSERT(piv_tag); + + WINPR_ASSERT(key->provider); + p11 = key->provider->p11; + WINPR_ASSERT(p11); + + /* Get the reader the card is in */ + WINPR_ASSERT(p11->C_GetSlotInfo); + if (p11->C_GetSlotInfo(key->slotId, &slot_info) != CKR_OK) + return NTE_BAD_KEY; + + fix_padded_string((char*)slot_info.slotDescription, sizeof(slot_info.slotDescription)); + reader = ConvertUtf8NToWCharAlloc((char*)slot_info.slotDescription, + ARRAYSIZE(slot_info.slotDescription), NULL); + ret = NTE_NO_MEMORY; + if (!reader) + goto out; + + ret = NTE_BAD_KEY; + if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &context) != SCARD_S_SUCCESS) + goto out; + + if (SCardConnectW(context, reader, SCARD_SHARE_SHARED, SCARD_PROTOCOL_Tx, &card, &proto) != + SCARD_S_SUCCESS) + goto out; + pci = (proto == SCARD_PROTOCOL_T0) ? SCARD_PCI_T0 : SCARD_PCI_T1; + + buf_len = sizeof(buf); + if (SCardTransmit(card, pci, APDU_PIV_SELECT_AID, sizeof(APDU_PIV_SELECT_AID), NULL, buf, + &buf_len) != SCARD_S_SUCCESS) + goto out; + if ((buf[buf_len - 2] != 0x90 || buf[buf_len - 1] != 0) && buf[buf_len - 2] != 0x61) + goto out; + + buf_len = sizeof(buf); + if (SCardTransmit(card, pci, APDU_PIV_GET_CHUID, sizeof(APDU_PIV_GET_CHUID), NULL, buf, + &buf_len) != SCARD_S_SUCCESS) + goto out; + if ((buf[buf_len - 2] != 0x90 || buf[buf_len - 1] != 0) && buf[buf_len - 2] != 0x61) + goto out; + + /* Find the GUID field in the CHUID data object */ + WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_BER, buf, buf_len); + if (!WinPrAsn1DecReadTagAndLen(&dec, &tag, &len) || tag != 0x53) + goto out; + while (WinPrAsn1DecReadTagLenValue(&dec, &tag, &len, &dec2) && tag != 0x34) + ; + if (tag != 0x34 || len != 16) + goto out; + + s = WinPrAsn1DecGetStream(&dec2); + p = Stream_Buffer(&s); + + /* Construct the value Windows would use for a PIV key's container name */ + (void)snprintf(container_name, PIV_CONTAINER_NAME_LEN + 1, + "%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x", p[3], + p[2], p[1], p[0], p[5], p[4], p[7], p[6], p[8], p[9], p[10], p[11], p[12], + piv_tag[0], piv_tag[1], piv_tag[2]); + + /* And convert it to UTF-16 */ + union + { + WCHAR* wc; + BYTE* b; + } cnv; + cnv.b = output; + if (ConvertUtf8NToWChar(container_name, ARRAYSIZE(container_name), cnv.wc, + output_len / sizeof(WCHAR)) > 0) + ret = ERROR_SUCCESS; + +out: + free(reader); + if (card) + SCardDisconnect(card, SCARD_LEAVE_CARD); + if (context) + SCardReleaseContext(context); + return ret; +} + +static SECURITY_STATUS check_for_piv_container_name(NCryptP11KeyHandle* key, BYTE* pbOutput, + DWORD cbOutput, DWORD* pcbResult, char* label, + size_t label_len) +{ + for (size_t i = 0; i < ARRAYSIZE(piv_cert_tags); i++) + { + const piv_cert_tags_t* cur = &piv_cert_tags[i]; + if (strncmp(label, cur->label, label_len) == 0) + { + *pcbResult = (PIV_CONTAINER_NAME_LEN + 1) * sizeof(WCHAR); + if (!pbOutput) + return ERROR_SUCCESS; + else if (cbOutput < (PIV_CONTAINER_NAME_LEN + 1) * sizeof(WCHAR)) + return NTE_NO_MEMORY; + else + return get_piv_container_name(key, cur->tag, pbOutput, cbOutput); + } + } + return NTE_NOT_FOUND; +} + +static SECURITY_STATUS NCryptP11KeyGetProperties(NCryptP11KeyHandle* keyHandle, + NCryptKeyGetPropertyEnum property, PBYTE pbOutput, + DWORD cbOutput, DWORD* pcbResult, DWORD dwFlags) +{ + SECURITY_STATUS ret = NTE_FAIL; + CK_RV rv = 0; + CK_SESSION_HANDLE session = 0; + CK_OBJECT_HANDLE objectHandle = 0; + CK_ULONG objectCount = 0; + NCryptP11ProviderHandle* provider = NULL; + CK_OBJECT_CLASS oclass = CKO_CERTIFICATE; + CK_CERTIFICATE_TYPE ctype = CKC_X_509; + CK_ATTRIBUTE certificateFilter[] = { { CKA_CLASS, &oclass, sizeof(oclass) }, + { CKA_CERTIFICATE_TYPE, &ctype, sizeof(ctype) }, + { CKA_ID, keyHandle->keyCertId, + keyHandle->keyCertIdLen } }; + CK_ATTRIBUTE* objectFilter = certificateFilter; + CK_ULONG objectFilterLen = ARRAYSIZE(certificateFilter); + + WINPR_ASSERT(keyHandle); + provider = keyHandle->provider; + WINPR_ASSERT(provider); + + switch (property) + + { + case NCRYPT_PROPERTY_CERTIFICATE: + case NCRYPT_PROPERTY_NAME: + break; + case NCRYPT_PROPERTY_READER: + { + CK_SLOT_INFO slotInfo; + + WINPR_ASSERT(provider->p11->C_GetSlotInfo); + rv = provider->p11->C_GetSlotInfo(keyHandle->slotId, &slotInfo); + if (rv != CKR_OK) + return NTE_BAD_KEY; + +#define SLOT_DESC_SZ sizeof(slotInfo.slotDescription) + fix_padded_string((char*)slotInfo.slotDescription, SLOT_DESC_SZ); + const size_t len = 2ULL * (strnlen((char*)slotInfo.slotDescription, SLOT_DESC_SZ) + 1); + if (len > UINT32_MAX) + return NTE_BAD_DATA; + *pcbResult = (UINT32)len; + if (pbOutput) + { + union + { + WCHAR* wc; + BYTE* b; + } cnv; + cnv.b = pbOutput; + if (cbOutput < *pcbResult) + return NTE_NO_MEMORY; + + if (ConvertUtf8ToWChar((char*)slotInfo.slotDescription, cnv.wc, + cbOutput / sizeof(WCHAR)) < 0) + return NTE_NO_MEMORY; + } + return ERROR_SUCCESS; + } + case NCRYPT_PROPERTY_SLOTID: + { + *pcbResult = 4; + if (pbOutput) + { + UINT32* ptr = (UINT32*)pbOutput; + + if (cbOutput < 4) + return NTE_NO_MEMORY; + if (keyHandle->slotId > UINT32_MAX) + { + ret = NTE_BAD_DATA; + goto out_final; + } + *ptr = (UINT32)keyHandle->slotId; + } + return ERROR_SUCCESS; + } + case NCRYPT_PROPERTY_UNKNOWN: + default: + return NTE_NOT_SUPPORTED; + } + + WINPR_ASSERT(provider->p11->C_OpenSession); + rv = provider->p11->C_OpenSession(keyHandle->slotId, CKF_SERIAL_SESSION, NULL, NULL, &session); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "error opening session on slot %d", keyHandle->slotId); + return NTE_FAIL; + } + + WINPR_ASSERT(provider->p11->C_FindObjectsInit); + rv = provider->p11->C_FindObjectsInit(session, objectFilter, objectFilterLen); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "unable to initiate search for slot %d", keyHandle->slotId); + goto out; + } + + WINPR_ASSERT(provider->p11->C_FindObjects); + rv = provider->p11->C_FindObjects(session, &objectHandle, 1, &objectCount); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "unable to findObjects for slot %d", keyHandle->slotId); + goto out_final; + } + if (!objectCount) + { + ret = NTE_NOT_FOUND; + goto out_final; + } + + switch (property) + { + case NCRYPT_PROPERTY_CERTIFICATE: + { + CK_ATTRIBUTE certValue = { CKA_VALUE, pbOutput, cbOutput }; + + WINPR_ASSERT(provider->p11->C_GetAttributeValue); + rv = provider->p11->C_GetAttributeValue(session, objectHandle, &certValue, 1); + if (rv != CKR_OK) + { + // TODO: do a kind of translation from CKR_* to NTE_* + } + + if (certValue.ulValueLen > UINT32_MAX) + { + ret = NTE_BAD_DATA; + goto out_final; + } + *pcbResult = (UINT32)certValue.ulValueLen; + ret = ERROR_SUCCESS; + break; + } + case NCRYPT_PROPERTY_NAME: + { + CK_ATTRIBUTE attr = { CKA_LABEL, NULL, 0 }; + char* label = NULL; + + WINPR_ASSERT(provider->p11->C_GetAttributeValue); + rv = provider->p11->C_GetAttributeValue(session, objectHandle, &attr, 1); + if (rv == CKR_OK) + { + label = calloc(1, attr.ulValueLen); + if (!label) + { + ret = NTE_NO_MEMORY; + break; + } + + attr.pValue = label; + rv = provider->p11->C_GetAttributeValue(session, objectHandle, &attr, 1); + } + + if (rv == CKR_OK) + { + /* Check if we have a PIV card */ + ret = check_for_piv_container_name(keyHandle, pbOutput, cbOutput, pcbResult, label, + attr.ulValueLen); + + /* Otherwise, at least for GIDS cards the label will be the correct value */ + if (ret == NTE_NOT_FOUND) + { + union + { + WCHAR* wc; + BYTE* b; + } cnv; + const size_t olen = pbOutput ? cbOutput / sizeof(WCHAR) : 0; + cnv.b = pbOutput; + SSIZE_T size = ConvertUtf8NToWChar(label, attr.ulValueLen, cnv.wc, olen); + if (size < 0) + ret = ERROR_CONVERT_TO_LARGE; + else + ret = ERROR_SUCCESS; + } + } + + free(label); + break; + } + default: + ret = NTE_NOT_SUPPORTED; + break; + } + +out_final: + WINPR_ASSERT(provider->p11->C_FindObjectsFinal); + rv = provider->p11->C_FindObjectsFinal(session); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "error in C_FindObjectsFinal() for slot %d", keyHandle->slotId); + } +out: + WINPR_ASSERT(provider->p11->C_CloseSession); + rv = provider->p11->C_CloseSession(session); + if (rv != CKR_OK) + { + WLog_ERR(TAG, "error in C_CloseSession() for slot %d", keyHandle->slotId); + } + return ret; +} + +static SECURITY_STATUS NCryptP11GetProperty(NCRYPT_HANDLE hObject, NCryptKeyGetPropertyEnum prop, + PBYTE pbOutput, DWORD cbOutput, DWORD* pcbResult, + DWORD dwFlags) +{ + NCryptBaseHandle* base = (NCryptBaseHandle*)hObject; + + WINPR_ASSERT(base); + switch (base->type) + { + case WINPR_NCRYPT_PROVIDER: + return ERROR_CALL_NOT_IMPLEMENTED; + case WINPR_NCRYPT_KEY: + return NCryptP11KeyGetProperties((NCryptP11KeyHandle*)hObject, prop, pbOutput, cbOutput, + pcbResult, dwFlags); + default: + return ERROR_INVALID_HANDLE; + } + return ERROR_SUCCESS; +} + +static SECURITY_STATUS NCryptP11OpenKey(NCRYPT_PROV_HANDLE hProvider, NCRYPT_KEY_HANDLE* phKey, + LPCWSTR pszKeyName, DWORD dwLegacyKeySpec, DWORD dwFlags) +{ + SECURITY_STATUS ret = 0; + CK_SLOT_ID slotId = 0; + CK_BYTE keyCertId[64] = { 0 }; + CK_ULONG keyCertIdLen = 0; + NCryptP11KeyHandle* keyHandle = NULL; + + ret = parseKeyName(pszKeyName, &slotId, keyCertId, &keyCertIdLen); + if (ret != ERROR_SUCCESS) + return ret; + + keyHandle = (NCryptP11KeyHandle*)ncrypt_new_handle( + WINPR_NCRYPT_KEY, sizeof(*keyHandle), NCryptP11GetProperty, winpr_NCryptDefault_dtor); + if (!keyHandle) + return NTE_NO_MEMORY; + + keyHandle->provider = (NCryptP11ProviderHandle*)hProvider; + keyHandle->slotId = slotId; + memcpy(keyHandle->keyCertId, keyCertId, sizeof(keyCertId)); + keyHandle->keyCertIdLen = keyCertIdLen; + *phKey = (NCRYPT_KEY_HANDLE)keyHandle; + return ERROR_SUCCESS; +} + +static SECURITY_STATUS initialize_pkcs11(HANDLE handle, + CK_RV (*c_get_function_list)(CK_FUNCTION_LIST_PTR_PTR), + NCRYPT_PROV_HANDLE* phProvider) +{ + SECURITY_STATUS status = ERROR_SUCCESS; + NCryptP11ProviderHandle* ret = NULL; + CK_RV rv = 0; + + WINPR_ASSERT(c_get_function_list); + WINPR_ASSERT(phProvider); + + ret = (NCryptP11ProviderHandle*)ncrypt_new_handle( + WINPR_NCRYPT_PROVIDER, sizeof(*ret), NCryptP11GetProperty, NCryptP11StorageProvider_dtor); + if (!ret) + return NTE_NO_MEMORY; + + ret->library = handle; + ret->baseProvider.enumKeysFn = NCryptP11EnumKeys; + ret->baseProvider.openKeyFn = NCryptP11OpenKey; + + rv = c_get_function_list(&ret->p11); + if (rv != CKR_OK) + { + status = NTE_PROVIDER_DLL_FAIL; + goto fail; + } + + WINPR_ASSERT(ret->p11); + WINPR_ASSERT(ret->p11->C_Initialize); + rv = ret->p11->C_Initialize(NULL); + if (rv != CKR_OK) + { + status = NTE_PROVIDER_DLL_FAIL; + goto fail; + } + + *phProvider = (NCRYPT_PROV_HANDLE)ret; + +fail: + if (status != ERROR_SUCCESS) + ret->baseProvider.baseHandle.releaseFn((NCRYPT_HANDLE)ret); + return status; +} + +SECURITY_STATUS NCryptOpenP11StorageProviderEx(NCRYPT_PROV_HANDLE* phProvider, + LPCWSTR pszProviderName, DWORD dwFlags, + LPCSTR* modulePaths) +{ + SECURITY_STATUS status = ERROR_INVALID_PARAMETER; + LPCSTR defaultPaths[] = { "p11-kit-proxy.so", "opensc-pkcs11.so", NULL }; + + if (!phProvider) + return ERROR_INVALID_PARAMETER; + + if (!modulePaths) + modulePaths = defaultPaths; + + while (*modulePaths) + { + const char* modulePath = *modulePaths++; + HANDLE library = LoadLibrary(modulePath); + typedef CK_RV (*c_get_function_list_t)(CK_FUNCTION_LIST_PTR_PTR); + NCryptP11ProviderHandle* provider = NULL; + + WLog_DBG(TAG, "Trying pkcs11 module '%s'", modulePath); + if (!library) + { + status = NTE_PROV_DLL_NOT_FOUND; + goto out_load_library; + } + + c_get_function_list_t c_get_function_list = + GetProcAddressAs(library, "C_GetFunctionList", c_get_function_list_t); + + if (!c_get_function_list) + { + status = NTE_PROV_TYPE_ENTRY_BAD; + goto out_load_library; + } + + status = initialize_pkcs11(library, c_get_function_list, phProvider); + if (status != ERROR_SUCCESS) + { + status = NTE_PROVIDER_DLL_FAIL; + goto out_load_library; + } + + provider = (NCryptP11ProviderHandle*)*phProvider; + provider->modulePath = _strdup(modulePath); + if (!provider->modulePath) + { + status = NTE_NO_MEMORY; + goto out_load_library; + } + + WLog_DBG(TAG, "module '%s' loaded", modulePath); + return ERROR_SUCCESS; + + out_load_library: + if (library) + FreeLibrary(library); + } + + return status; +} + +const char* NCryptGetModulePath(NCRYPT_PROV_HANDLE phProvider) +{ + NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)phProvider; + + WINPR_ASSERT(provider); + + return provider->modulePath; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/.clang-format b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..e3845288a2aece185aa94e88e303e0134efde368 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/.clang-format @@ -0,0 +1 @@ +DisableFormat: true diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/pkcs11.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/pkcs11.h new file mode 100644 index 0000000000000000000000000000000000000000..7dd318a03ed5c0dd3f06fb5cb23e2cd322acab47 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/pkcs11-headers/pkcs11.h @@ -0,0 +1,2411 @@ +/* This file is in the Public Domain */ + +#ifndef _PD_PKCS11_ +#define _PD_PKCS11_ + +#define CRYPTOKI_VERSION_MAJOR 3 +#define CRYPTOKI_VERSION_MINOR 1 +#define CRYPTOKI_VERSION_AMENDMENT 0 + +/* Basic types */ +typedef unsigned char CK_BBOOL; +typedef unsigned char CK_BYTE; +typedef unsigned char CK_CHAR; +typedef unsigned char CK_UTF8CHAR; +typedef unsigned long int CK_ULONG; + +typedef CK_BBOOL * CK_BBOOL_PTR; +typedef CK_BYTE * CK_BYTE_PTR; +typedef CK_CHAR * CK_CHAR_PTR; +typedef CK_UTF8CHAR * CK_UTF8CHAR_PTR; +typedef CK_ULONG * CK_ULONG_PTR; + +/* Basic defines */ +#define NULL_PTR ((void *)0) +typedef void * CK_VOID_PTR; +typedef void ** CK_VOID_PTR_PTR; + +#define CK_EFFECTIVELY_INFINITE 0UL +#define CK_UNAVAILABLE_INFORMATION ~0UL +#define CK_INVALID_HANDLE 0UL +#define CK_TRUE 1 +#define CK_FALSE 0 + +/* CK_ types in alphabetical order */ +#define ULONGDEF(__name__) \ +typedef CK_ULONG __name__; \ +typedef __name__ * __name__ ## _PTR; + +ULONGDEF(CK_ATTRIBUTE_TYPE) +ULONGDEF(CK_CERTIFICATE_CATEGORY) +ULONGDEF(CK_CERTIFICATE_TYPE) +ULONGDEF(CK_EC_KDF_TYPE) +ULONGDEF(CK_EXTRACT_PARAMS) +ULONGDEF(CK_FLAGS) +ULONGDEF(CK_GENERATOR_FUNCTION) +ULONGDEF(CK_HSS_LEVELS) +ULONGDEF(CK_HW_FEATURE_TYPE) +ULONGDEF(CK_JAVA_MIDP_SECURITY_DOMAIN) +ULONGDEF(CK_KEY_TYPE) +ULONGDEF(CK_LMS_TYPE) +ULONGDEF(CK_LMOTS_TYPE) +ULONGDEF(CK_MAC_GENERAL_PARAMS) +ULONGDEF(CK_MECHANISM_TYPE) +ULONGDEF(CK_NOTIFICATION) +ULONGDEF(CK_OBJECT_CLASS) +ULONGDEF(CK_OBJECT_HANDLE) +ULONGDEF(CK_OTP_PARAM_TYPE) +ULONGDEF(CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE) +ULONGDEF(CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE) +ULONGDEF(CK_PRF_DATA_TYPE) +ULONGDEF(CK_PROFILE_ID) +ULONGDEF(CK_RC2_PARAMS) +ULONGDEF(CK_RSA_PKCS_MGF_TYPE) +ULONGDEF(CK_RSA_PKCS_OAEP_SOURCE_TYPE) +ULONGDEF(CK_RV) +ULONGDEF(CK_SESSION_HANDLE) +ULONGDEF(CK_SLOT_ID) +ULONGDEF(CK_SP800_108_DKM_LENGTH_METHOD) +ULONGDEF(CK_STATE) +ULONGDEF(CK_USER_TYPE) +ULONGDEF(CK_X2RATCHET_KDF_TYPE) +ULONGDEF(CK_X3DH_KDF_TYPE) +ULONGDEF(CK_X9_42_DH_KDF_TYPE) +ULONGDEF(CK_XEDDSA_HASH_TYPE) + +/* domain specific values and constants */ + +/* CK (certificate) */ +#define CK_CERTIFICATE_CATEGORY_UNSPECIFIED 0UL +#define CK_CERTIFICATE_CATEGORY_TOKEN_USER 1UL +#define CK_CERTIFICATE_CATEGORY_AUTHORITY 2UL +#define CK_CERTIFICATE_CATEGORY_OTHER_ENTITY 3UL + +/* CK (OTP) */ +#define CK_OTP_VALUE 0UL +#define CK_OTP_PIN 1UL +#define CK_OTP_CHALLENGE 2UL +#define CK_OTP_TIME 3UL +#define CK_OTP_COUNTER 4UL +#define CK_OTP_FLAGS 5UL +#define CK_OTP_OUTPUT_LENGTH 6UL +#define CK_OTP_OUTPUT_FORMAT 7UL + +/* CK (OTP format) */ +#define CK_OTP_FORMAT_DECIMAL 0UL +#define CK_OTP_FORMAT_HEXADECIMAL 1UL +#define CK_OTP_FORMAT_ALPHANUMERIC 2UL +#define CK_OTP_FORMAT_BINARY 3UL + +/* CK (OTP requirement) */ +#define CK_OTP_PARAM_IGNORED 0UL +#define CK_OTP_PARAM_OPTIONAL 1UL +#define CK_OTP_PARAM_MANDATORY 2UL + +/* CK (security) */ +#define CK_SECURITY_DOMAIN_UNSPECIFIED 0UL +#define CK_SECURITY_DOMAIN_MANUFACTURER 1UL +#define CK_SECURITY_DOMAIN_OPERATOR 2UL +#define CK_SECURITY_DOMAIN_THIRD_PARTY 3UL + +/* CK (SP800 KDF) */ +#define CK_SP800_108_ITERATION_VARIABLE 0x00000001UL +#define CK_SP800_108_OPTIONAL_COUNTER 0x00000002UL +#define CK_SP800_108_COUNTER 0x00000002UL +#define CK_SP800_108_DKM_LENGTH 0x00000003UL +#define CK_SP800_108_BYTE_ARRAY 0x00000004UL + +/* CK (SP800 DKM) */ +#define CK_SP800_108_DKM_LENGTH_SUM_OF_KEYS 0x00000001UL +#define CK_SP800_108_DKM_LENGTH_SUM_OF_SEGMENTS 0x00000002UL + +/* CKA */ +#define CKA_CLASS 0x00000000UL +#define CKA_TOKEN 0x00000001UL +#define CKA_PRIVATE 0x00000002UL +#define CKA_LABEL 0x00000003UL +#define CKA_UNIQUE_ID 0x00000004UL +#define CKA_APPLICATION 0x00000010UL +#define CKA_VALUE 0x00000011UL +#define CKA_OBJECT_ID 0x00000012UL +#define CKA_CERTIFICATE_TYPE 0x00000080UL +#define CKA_ISSUER 0x00000081UL +#define CKA_SERIAL_NUMBER 0x00000082UL +#define CKA_AC_ISSUER 0x00000083UL +#define CKA_OWNER 0x00000084UL +#define CKA_ATTR_TYPES 0x00000085UL +#define CKA_TRUSTED 0x00000086UL +#define CKA_CERTIFICATE_CATEGORY 0x00000087UL +#define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088UL +#define CKA_URL 0x00000089UL +#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008AUL +#define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008BUL +#define CKA_NAME_HASH_ALGORITHM 0x0000008CUL +#define CKA_CHECK_VALUE 0x00000090UL +#define CKA_KEY_TYPE 0x00000100UL +#define CKA_SUBJECT 0x00000101UL +#define CKA_ID 0x00000102UL +#define CKA_SENSITIVE 0x00000103UL +#define CKA_ENCRYPT 0x00000104UL +#define CKA_DECRYPT 0x00000105UL +#define CKA_WRAP 0x00000106UL +#define CKA_UNWRAP 0x00000107UL +#define CKA_SIGN 0x00000108UL +#define CKA_SIGN_RECOVER 0x00000109UL +#define CKA_VERIFY 0x0000010AUL +#define CKA_VERIFY_RECOVER 0x0000010BUL +#define CKA_DERIVE 0x0000010CUL +#define CKA_START_DATE 0x00000110UL +#define CKA_END_DATE 0x00000111UL +#define CKA_MODULUS 0x00000120UL +#define CKA_MODULUS_BITS 0x00000121UL +#define CKA_PUBLIC_EXPONENT 0x00000122UL +#define CKA_PRIVATE_EXPONENT 0x00000123UL +#define CKA_PRIME_1 0x00000124UL +#define CKA_PRIME_2 0x00000125UL +#define CKA_EXPONENT_1 0x00000126UL +#define CKA_EXPONENT_2 0x00000127UL +#define CKA_COEFFICIENT 0x00000128UL +#define CKA_PUBLIC_KEY_INFO 0x00000129UL +#define CKA_PRIME 0x00000130UL +#define CKA_SUBPRIME 0x00000131UL +#define CKA_BASE 0x00000132UL +#define CKA_PRIME_BITS 0x00000133UL +#define CKA_SUBPRIME_BITS 0x00000134UL +#define CKA_SUB_PRIME_BITS 0x00000134UL +#define CKA_VALUE_BITS 0x00000160UL +#define CKA_VALUE_LEN 0x00000161UL +#define CKA_EXTRACTABLE 0x00000162UL +#define CKA_LOCAL 0x00000163UL +#define CKA_NEVER_EXTRACTABLE 0x00000164UL +#define CKA_ALWAYS_SENSITIVE 0x00000165UL +#define CKA_KEY_GEN_MECHANISM 0x00000166UL +#define CKA_MODIFIABLE 0x00000170UL +#define CKA_COPYABLE 0x00000171UL +#define CKA_DESTROYABLE 0x00000172UL +#define CKA_EC_PARAMS 0x00000180UL +#define CKA_EC_POINT 0x00000181UL +#define CKA_ALWAYS_AUTHENTICATE 0x00000202UL +#define CKA_WRAP_WITH_TRUSTED 0x00000210UL +#define CKA_OTP_FORMAT 0x00000220UL +#define CKA_OTP_LENGTH 0x00000221UL +#define CKA_OTP_TIME_INTERVAL 0x00000222UL +#define CKA_OTP_USER_FRIENDLY_MODE 0x00000223UL +#define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224UL +#define CKA_OTP_TIME_REQUIREMENT 0x00000225UL +#define CKA_OTP_COUNTER_REQUIREMENT 0x00000226UL +#define CKA_OTP_PIN_REQUIREMENT 0x00000227UL +#define CKA_OTP_COUNTER 0x0000022EUL +#define CKA_OTP_TIME 0x0000022FUL +#define CKA_OTP_USER_IDENTIFIER 0x0000022AUL +#define CKA_OTP_SERVICE_IDENTIFIER 0x0000022BUL +#define CKA_OTP_SERVICE_LOGO 0x0000022CUL +#define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022DUL +#define CKA_GOSTR3410_PARAMS 0x00000250UL +#define CKA_GOSTR3411_PARAMS 0x00000251UL +#define CKA_GOST28147_PARAMS 0x00000252UL +#define CKA_HW_FEATURE_TYPE 0x00000300UL +#define CKA_RESET_ON_INIT 0x00000301UL +#define CKA_HAS_RESET 0x00000302UL +#define CKA_PIXEL_X 0x00000400UL +#define CKA_PIXEL_Y 0x00000401UL +#define CKA_RESOLUTION 0x00000402UL +#define CKA_CHAR_ROWS 0x00000403UL +#define CKA_CHAR_COLUMNS 0x00000404UL +#define CKA_COLOR 0x00000405UL +#define CKA_BITS_PER_PIXEL 0x00000406UL +#define CKA_CHAR_SETS 0x00000480UL +#define CKA_ENCODING_METHODS 0x00000481UL +#define CKA_MIME_TYPES 0x00000482UL +#define CKA_MECHANISM_TYPE 0x00000500UL +#define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501UL +#define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502UL +#define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503UL +#define CKA_PROFILE_ID 0x00000601UL +#define CKA_X2RATCHET_BAG 0x00000602UL +#define CKA_X2RATCHET_BAGSIZE 0x00000603UL +#define CKA_X2RATCHET_BOBS1STMSG 0x00000604UL +#define CKA_X2RATCHET_CKR 0x00000605UL +#define CKA_X2RATCHET_CKS 0x00000606UL +#define CKA_X2RATCHET_DHP 0x00000607UL +#define CKA_X2RATCHET_DHR 0x00000608UL +#define CKA_X2RATCHET_DHS 0x00000609UL +#define CKA_X2RATCHET_HKR 0x0000060AUL +#define CKA_X2RATCHET_HKS 0x0000060BUL +#define CKA_X2RATCHET_ISALICE 0x0000060CUL +#define CKA_X2RATCHET_NHKR 0x0000060DUL +#define CKA_X2RATCHET_NHKS 0x0000060EUL +#define CKA_X2RATCHET_NR 0x0000060FUL +#define CKA_X2RATCHET_NS 0x00000610UL +#define CKA_X2RATCHET_PNS 0x00000611UL +#define CKA_X2RATCHET_RK 0x00000612UL +#define CKA_HSS_LEVELS 0x00000617UL +#define CKA_HSS_LMS_TYPE 0x00000618UL +#define CKA_HSS_LMOTS_TYPE 0x00000619UL +#define CKA_HSS_LMS_TYPES 0x0000061AUL +#define CKA_HSS_LMOTS_TYPES 0x0000061BUL +#define CKA_HSS_KEYS_REMAINING 0x0000061CUL +#define CKA_VENDOR_DEFINED 0x80000000UL +/* Array attributes */ +#define CKA_WRAP_TEMPLATE 0x40000211UL +#define CKA_UNWRAP_TEMPLATE 0x40000212UL +#define CKA_DERIVE_TEMPLATE 0x40000213UL +#define CKA_ALLOWED_MECHANISMS 0x40000600UL +/* Deprecated */ +#ifdef PKCS11_DEPRECATED +#define CKA_ECDSA_PARAMS 0x00000180UL +#define CKA_SECONDARY_AUTH 0x00000200UL +#define CKA_AUTH_PIN_FLAGS 0x00000201UL +#endif + +/* CKC */ +#define CKC_X_509 0x00000000UL +#define CKC_X_509_ATTR_CERT 0x00000001UL +#define CKC_WTLS 0x00000002UL +#define CKC_VENDOR_DEFINED 0x80000000UL + +/* CKD */ +#define CKD_NULL 0x00000001UL +#define CKD_SHA1_KDF 0x00000002UL +#define CKD_SHA1_KDF_ASN1 0x00000003UL +#define CKD_SHA1_KDF_CONCATENATE 0x00000004UL +#define CKD_SHA224_KDF 0x00000005UL +#define CKD_SHA256_KDF 0x00000006UL +#define CKD_SHA384_KDF 0x00000007UL +#define CKD_SHA512_KDF 0x00000008UL +#define CKD_CPDIVERSIFY_KDF 0x00000009UL +#define CKD_SHA3_224_KDF 0x0000000AUL +#define CKD_SHA3_256_KDF 0x0000000BUL +#define CKD_SHA3_384_KDF 0x0000000CUL +#define CKD_SHA3_512_KDF 0x0000000DUL +#define CKD_SHA1_KDF_SP800 0x0000000EUL +#define CKD_SHA224_KDF_SP800 0x0000000FUL +#define CKD_SHA256_KDF_SP800 0x00000010UL +#define CKD_SHA384_KDF_SP800 0x00000011UL +#define CKD_SHA512_KDF_SP800 0x00000012UL +#define CKD_SHA3_224_KDF_SP800 0x00000013UL +#define CKD_SHA3_256_KDF_SP800 0x00000014UL +#define CKD_SHA3_384_KDF_SP800 0x00000015UL +#define CKD_SHA3_512_KDF_SP800 0x00000016UL +#define CKD_BLAKE2B_160_KDF 0x00000017UL +#define CKD_BLAKE2B_256_KDF 0x00000018UL +#define CKD_BLAKE2B_384_KDF 0x00000019UL +#define CKD_BLAKE2B_512_KDF 0x0000001AUL + +/* CFK (array attributes) */ +#define CKF_ARRAY_ATTRIBUTE 0x40000000UL + +/* CKF (capabilities) */ +#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001UL +#define CKF_OS_LOCKING_OK 0x00000002UL + +/* CKF (HKDF) */ +#define CKF_HKDF_SALT_NULL 0x00000001UL +#define CKF_HKDF_SALT_DATA 0x00000002UL +#define CKF_HKDF_SALT_KEY 0x00000004UL + +/* CKF (interface) */ +#define CKF_INTERFACE_FORK_SAFE 0x00000001UL + +/* CKF (mechanism) */ +#define CKF_HW 0x00000001UL +#define CKF_MESSAGE_ENCRYPT 0x00000002UL +#define CKF_MESSAGE_DECRYPT 0x00000004UL +#define CKF_MESSAGE_SIGN 0x00000008UL +#define CKF_MESSAGE_VERIFY 0x00000010UL +#define CKF_MULTI_MESSAGE 0x00000020UL +#define CKF_MULTI_MESSGE 0x00000020UL +#define CKF_FIND_OBJECTS 0x00000040UL +#define CKF_ENCRYPT 0x00000100UL +#define CKF_DECRYPT 0x00000200UL +#define CKF_DIGEST 0x00000400UL +#define CKF_SIGN 0x00000800UL +#define CKF_SIGN_RECOVER 0x00001000UL +#define CKF_VERIFY 0x00002000UL +#define CKF_VERIFY_RECOVER 0x00004000UL +#define CKF_GENERATE 0x00008000UL +#define CKF_GENERATE_KEY_PAIR 0x00010000UL +#define CKF_WRAP 0x00020000UL +#define CKF_UNWRAP 0x00040000UL +#define CKF_DERIVE 0x00080000UL +#define CKF_EC_F_P 0x00100000UL +#define CKF_EC_F_2M 0x00200000UL +#define CKF_EC_ECPARAMETERS 0x00400000UL +#define CKF_EC_OID 0x00800000UL +#define CKF_EC_UNCOMPRESS 0x01000000UL +#define CKF_EC_COMPRESS 0x02000000UL +#define CKF_EC_CURVENAME 0x04000000UL +#define CKF_EXTENSION 0x80000000UL +/* Deprecated */ +#ifdef PKCS11_DEPRECATED +#define CKF_EC_NAMEDCURVE 0x00800000U +#endif + +/* CKF (message) */ +#define CKF_END_OF_MESSAGE 0x00000001UL + +/* CKF (OTP) */ +#define CKF_NEXT_OTP 0x00000001UL +#define CKF_EXCLUDE_TIME 0x00000002UL +#define CKF_EXCLUDE_COUNTER 0x00000004UL +#define CKF_EXCLUDE_CHALLENGE 0x00000008UL +#define CKF_EXCLUDE_PIN 0x00000010UL +#define CKF_USER_FRIENDLY_OTP 0x00000020UL + +/* CKF (parameters to functions) */ +#define CKF_DONT_BLOCK 1 + +/* CKF (session) */ +#define CKF_RW_SESSION 0x00000002UL +#define CKF_SERIAL_SESSION 0x00000004UL + +/* CFK (slot) */ +#define CKF_TOKEN_PRESENT 0x00000001UL +#define CKF_REMOVABLE_DEVICE 0x00000002UL +#define CKF_HW_SLOT 0x00000004UL + +/* CKF (token) */ +#define CKF_RNG 0x00000001UL +#define CKF_WRITE_PROTECTED 0x00000002UL +#define CKF_LOGIN_REQUIRED 0x00000004UL +#define CKF_USER_PIN_INITIALIZED 0x00000008UL +#define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020UL +#define CKF_CLOCK_ON_TOKEN 0x00000040UL +#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100UL +#define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200UL +#define CKF_TOKEN_INITIALIZED 0x00000400UL +#define CKF_SECONDARY_AUTHENTICATION 0x00000800UL +#define CKF_USER_PIN_COUNT_LOW 0x00010000UL +#define CKF_USER_PIN_FINAL_TRY 0x00020000UL +#define CKF_USER_PIN_LOCKED 0x00040000UL +#define CKF_USER_PIN_TO_BE_CHANGED 0x00080000UL +#define CKF_SO_PIN_COUNT_LOW 0x00100000UL +#define CKF_SO_PIN_FINAL_TRY 0x00200000UL +#define CKF_SO_PIN_LOCKED 0x00400000UL +#define CKF_SO_PIN_TO_BE_CHANGED 0x00800000UL +#define CKF_ERROR_STATE 0x01000000UL + +/* CKG (GCM) */ +#define CKG_NO_GENERATE 0x00000000UL +#define CKG_GENERATE 0x00000001UL +#define CKG_GENERATE_COUNTER 0x00000002UL +#define CKG_GENERATE_RANDOM 0x00000003UL +#define CKG_GENERATE_COUNTER_XOR 0x00000004UL + +/* CKG (MFG) */ +#define CKG_MGF1_SHA1 0x00000001UL +#define CKG_MGF1_SHA256 0x00000002UL +#define CKG_MGF1_SHA384 0x00000003UL +#define CKG_MGF1_SHA512 0x00000004UL +#define CKG_MGF1_SHA224 0x00000005UL +#define CKG_MGF1_SHA3_224 0x00000006UL +#define CKG_MGF1_SHA3_256 0x00000007UL +#define CKG_MGF1_SHA3_384 0x00000008UL +#define CKG_MGF1_SHA3_512 0x00000009UL + +/* CKH */ +#define CKH_MONOTONIC_COUNTER 0x00000001UL +#define CKH_CLOCK 0x00000002UL +#define CKH_USER_INTERFACE 0x00000003UL +#define CKH_VENDOR_DEFINED 0x80000000UL + +/* CKK */ +#define CKK_RSA 0x00000000UL +#define CKK_DSA 0x00000001UL +#define CKK_DH 0x00000002UL +#define CKK_EC 0x00000003UL +#define CKK_X9_42_DH 0x00000004UL +#define CKK_KEA 0x00000005UL +#define CKK_GENERIC_SECRET 0x00000010UL +#define CKK_RC2 0x00000011UL +#define CKK_RC4 0x00000012UL +#define CKK_DES 0x00000013UL +#define CKK_DES2 0x00000014UL +#define CKK_DES3 0x00000015UL +#define CKK_CAST 0x00000016UL +#define CKK_CAST3 0x00000017UL +#define CKK_CAST128 0x00000018UL +#define CKK_RC5 0x00000019UL +#define CKK_IDEA 0x0000001AUL +#define CKK_SKIPJACK 0x0000001BUL +#define CKK_BATON 0x0000001CUL +#define CKK_JUNIPER 0x0000001DUL +#define CKK_CDMF 0x0000001EUL +#define CKK_AES 0x0000001FUL +#define CKK_BLOWFISH 0x00000020UL +#define CKK_TWOFISH 0x00000021UL +#define CKK_SECURID 0x00000022UL +#define CKK_HOTP 0x00000023UL +#define CKK_ACTI 0x00000024UL +#define CKK_CAMELLIA 0x00000025UL +#define CKK_ARIA 0x00000026UL +#define CKK_MD5_HMAC 0x00000027UL +#define CKK_SHA_1_HMAC 0x00000028UL +#define CKK_RIPEMD128_HMAC 0x00000029UL +#define CKK_RIPEMD160_HMAC 0x0000002AUL +#define CKK_SHA256_HMAC 0x0000002BUL +#define CKK_SHA384_HMAC 0x0000002CUL +#define CKK_SHA512_HMAC 0x0000002DUL +#define CKK_SHA224_HMAC 0x0000002EUL +#define CKK_SEED 0x0000002FUL +#define CKK_GOSTR3410 0x00000030UL +#define CKK_GOSTR3411 0x00000031UL +#define CKK_GOST28147 0x00000032UL +#define CKK_CHACHA20 0x00000033UL +#define CKK_POLY1305 0x00000034UL +#define CKK_AES_XTS 0x00000035UL +#define CKK_SHA3_224_HMAC 0x00000036UL +#define CKK_SHA3_256_HMAC 0x00000037UL +#define CKK_SHA3_384_HMAC 0x00000038UL +#define CKK_SHA3_512_HMAC 0x00000039UL +#define CKK_BLAKE2B_160_HMAC 0x0000003AUL +#define CKK_BLAKE2B_256_HMAC 0x0000003BUL +#define CKK_BLAKE2B_384_HMAC 0x0000003CUL +#define CKK_BLAKE2B_512_HMAC 0x0000003DUL +#define CKK_SALSA20 0x0000003EUL +#define CKK_X2RATCHET 0x0000003FUL +#define CKK_EC_EDWARDS 0x00000040UL +#define CKK_EC_MONTGOMERY 0x00000041UL +#define CKK_HKDF 0x00000042UL +#define CKK_SHA512_224_HMAC 0x00000043UL +#define CKK_SHA512_256_HMAC 0x00000044UL +#define CKK_SHA512_T_HMAC 0x00000045UL +#define CKK_HSS 0x00000046UL +#define CKK_VENDOR_DEFINED 0x80000000UL +/* Deprecated */ +#ifdef PKCS11_DEPRECATED +#define CKK_ECDSA 0x00000003UL +#define CKK_CAST5 0x00000018UL +#endif + +/* CKM */ +#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000UL +#define CKM_RSA_PKCS 0x00000001UL +#define CKM_RSA_9796 0x00000002UL +#define CKM_RSA_X_509 0x00000003UL +#define CKM_MD2_RSA_PKCS 0x00000004UL +#define CKM_MD5_RSA_PKCS 0x00000005UL +#define CKM_SHA1_RSA_PKCS 0x00000006UL +#define CKM_RIPEMD128_RSA_PKCS 0x00000007UL +#define CKM_RIPEMD160_RSA_PKCS 0x00000008UL +#define CKM_RSA_PKCS_OAEP 0x00000009UL +#define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000AUL +#define CKM_RSA_X9_31 0x0000000BUL +#define CKM_SHA1_RSA_X9_31 0x0000000CUL +#define CKM_RSA_PKCS_PSS 0x0000000DUL +#define CKM_SHA1_RSA_PKCS_PSS 0x0000000EUL +#define CKM_DSA_KEY_PAIR_GEN 0x00000010UL +#define CKM_DSA 0x00000011UL +#define CKM_DSA_SHA1 0x00000012UL +#define CKM_DSA_SHA224 0x00000013UL +#define CKM_DSA_SHA256 0x00000014UL +#define CKM_DSA_SHA384 0x00000015UL +#define CKM_DSA_SHA512 0x00000016UL +#define CKM_DSA_SHA3_224 0x00000018UL +#define CKM_DSA_SHA3_256 0x00000019UL +#define CKM_DSA_SHA3_384 0x0000001AUL +#define CKM_DSA_SHA3_512 0x0000001BUL +#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020UL +#define CKM_DH_PKCS_DERIVE 0x00000021UL +#define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030UL +#define CKM_X9_42_DH_DERIVE 0x00000031UL +#define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032UL +#define CKM_X9_42_MQV_DERIVE 0x00000033UL +#define CKM_SHA256_RSA_PKCS 0x00000040UL +#define CKM_SHA384_RSA_PKCS 0x00000041UL +#define CKM_SHA512_RSA_PKCS 0x00000042UL +#define CKM_SHA256_RSA_PKCS_PSS 0x00000043UL +#define CKM_SHA384_RSA_PKCS_PSS 0x00000044UL +#define CKM_SHA512_RSA_PKCS_PSS 0x00000045UL +#define CKM_SHA224_RSA_PKCS 0x00000046UL +#define CKM_SHA224_RSA_PKCS_PSS 0x00000047UL +#define CKM_SHA512_224 0x00000048UL +#define CKM_SHA512_224_HMAC 0x00000049UL +#define CKM_SHA512_224_HMAC_GENERAL 0x0000004AUL +#define CKM_SHA512_224_KEY_DERIVATION 0x0000004BUL +#define CKM_SHA512_256 0x0000004CUL +#define CKM_SHA512_256_HMAC 0x0000004DUL +#define CKM_SHA512_256_HMAC_GENERAL 0x0000004EUL +#define CKM_SHA512_256_KEY_DERIVATION 0x0000004FUL +#define CKM_SHA512_T 0x00000050UL +#define CKM_SHA512_T_HMAC 0x00000051UL +#define CKM_SHA512_T_HMAC_GENERAL 0x00000052UL +#define CKM_SHA512_T_KEY_DERIVATION 0x00000053UL +#define CKM_SHA3_256_RSA_PKCS 0x00000060UL +#define CKM_SHA3_384_RSA_PKCS 0x00000061UL +#define CKM_SHA3_512_RSA_PKCS 0x00000062UL +#define CKM_SHA3_256_RSA_PKCS_PSS 0x00000063UL +#define CKM_SHA3_384_RSA_PKCS_PSS 0x00000064UL +#define CKM_SHA3_512_RSA_PKCS_PSS 0x00000065UL +#define CKM_SHA3_224_RSA_PKCS 0x00000066UL +#define CKM_SHA3_224_RSA_PKCS_PSS 0x00000067UL +#define CKM_RC2_KEY_GEN 0x00000100UL +#define CKM_RC2_ECB 0x00000101UL +#define CKM_RC2_CBC 0x00000102UL +#define CKM_RC2_MAC 0x00000103UL +#define CKM_RC2_MAC_GENERAL 0x00000104UL +#define CKM_RC2_CBC_PAD 0x00000105UL +#define CKM_RC4_KEY_GEN 0x00000110UL +#define CKM_RC4 0x00000111UL +#define CKM_DES_KEY_GEN 0x00000120UL +#define CKM_DES_ECB 0x00000121UL +#define CKM_DES_CBC 0x00000122UL +#define CKM_DES_MAC 0x00000123UL +#define CKM_DES_MAC_GENERAL 0x00000124UL +#define CKM_DES_CBC_PAD 0x00000125UL +#define CKM_DES2_KEY_GEN 0x00000130UL +#define CKM_DES3_KEY_GEN 0x00000131UL +#define CKM_DES3_ECB 0x00000132UL +#define CKM_DES3_CBC 0x00000133UL +#define CKM_DES3_MAC 0x00000134UL +#define CKM_DES3_MAC_GENERAL 0x00000135UL +#define CKM_DES3_CBC_PAD 0x00000136UL +#define CKM_DES3_CMAC_GENERAL 0x00000137UL +#define CKM_DES3_CMAC 0x00000138UL +#define CKM_CDMF_KEY_GEN 0x00000140UL +#define CKM_CDMF_ECB 0x00000141UL +#define CKM_CDMF_CBC 0x00000142UL +#define CKM_CDMF_MAC 0x00000143UL +#define CKM_CDMF_MAC_GENERAL 0x00000144UL +#define CKM_CDMF_CBC_PAD 0x00000145UL +#define CKM_DES_OFB64 0x00000150UL +#define CKM_DES_OFB8 0x00000151UL +#define CKM_DES_CFB64 0x00000152UL +#define CKM_DES_CFB8 0x00000153UL +#define CKM_MD2 0x00000200UL +#define CKM_MD2_HMAC 0x00000201UL +#define CKM_MD2_HMAC_GENERAL 0x00000202UL +#define CKM_MD5 0x00000210UL +#define CKM_MD5_HMAC 0x00000211UL +#define CKM_MD5_HMAC_GENERAL 0x00000212UL +#define CKM_SHA_1 0x00000220UL +#define CKM_SHA_1_HMAC 0x00000221UL +#define CKM_SHA_1_HMAC_GENERAL 0x00000222UL +#define CKM_RIPEMD128 0x00000230UL +#define CKM_RIPEMD128_HMAC 0x00000231UL +#define CKM_RIPEMD128_HMAC_GENERAL 0x00000232UL +#define CKM_RIPEMD160 0x00000240UL +#define CKM_RIPEMD160_HMAC 0x00000241UL +#define CKM_RIPEMD160_HMAC_GENERAL 0x00000242UL +#define CKM_SHA256 0x00000250UL +#define CKM_SHA256_HMAC 0x00000251UL +#define CKM_SHA256_HMAC_GENERAL 0x00000252UL +#define CKM_SHA224 0x00000255UL +#define CKM_SHA224_HMAC 0x00000256UL +#define CKM_SHA224_HMAC_GENERAL 0x00000257UL +#define CKM_SHA384 0x00000260UL +#define CKM_SHA384_HMAC 0x00000261UL +#define CKM_SHA384_HMAC_GENERAL 0x00000262UL +#define CKM_SHA512 0x00000270UL +#define CKM_SHA512_HMAC 0x00000271UL +#define CKM_SHA512_HMAC_GENERAL 0x00000272UL +#define CKM_SECURID_KEY_GEN 0x00000280UL +#define CKM_SECURID 0x00000282UL +#define CKM_HOTP_KEY_GEN 0x00000290UL +#define CKM_HOTP 0x00000291UL +#define CKM_ACTI 0x000002A0UL +#define CKM_ACTI_KEY_GEN 0x000002A1UL +#define CKM_SHA3_256 0x000002B0UL +#define CKM_SHA3_256_HMAC 0x000002B1UL +#define CKM_SHA3_256_HMAC_GENERAL 0x000002B2UL +#define CKM_SHA3_256_KEY_GEN 0x000002B3UL +#define CKM_SHA3_224 0x000002B5UL +#define CKM_SHA3_224_HMAC 0x000002B6UL +#define CKM_SHA3_224_HMAC_GENERAL 0x000002B7UL +#define CKM_SHA3_224_KEY_GEN 0x000002B8UL +#define CKM_SHA3_384 0x000002C0UL +#define CKM_SHA3_384_HMAC 0x000002C1UL +#define CKM_SHA3_384_HMAC_GENERAL 0x000002C2UL +#define CKM_SHA3_384_KEY_GEN 0x000002C3UL +#define CKM_SHA3_512 0x000002D0UL +#define CKM_SHA3_512_HMAC 0x000002D1UL +#define CKM_SHA3_512_HMAC_GENERAL 0x000002D2UL +#define CKM_SHA3_512_KEY_GEN 0x000002D3UL +#define CKM_CAST_KEY_GEN 0x00000300UL +#define CKM_CAST_ECB 0x00000301UL +#define CKM_CAST_CBC 0x00000302UL +#define CKM_CAST_MAC 0x00000303UL +#define CKM_CAST_MAC_GENERAL 0x00000304UL +#define CKM_CAST_CBC_PAD 0x00000305UL +#define CKM_CAST3_KEY_GEN 0x00000310UL +#define CKM_CAST3_ECB 0x00000311UL +#define CKM_CAST3_CBC 0x00000312UL +#define CKM_CAST3_MAC 0x00000313UL +#define CKM_CAST3_MAC_GENERAL 0x00000314UL +#define CKM_CAST3_CBC_PAD 0x00000315UL +#define CKM_CAST128_KEY_GEN 0x00000320UL +#define CKM_CAST5_ECB 0x00000321UL +#define CKM_CAST128_ECB 0x00000321UL +#define CKM_CAST128_MAC 0x00000323UL +#define CKM_CAST128_CBC 0x00000322UL +#define CKM_CAST128_MAC_GENERAL 0x00000324UL +#define CKM_CAST128_CBC_PAD 0x00000325UL +#define CKM_RC5_KEY_GEN 0x00000330UL +#define CKM_RC5_ECB 0x00000331UL +#define CKM_RC5_CBC 0x00000332UL +#define CKM_RC5_MAC 0x00000333UL +#define CKM_RC5_MAC_GENERAL 0x00000334UL +#define CKM_RC5_CBC_PAD 0x00000335UL +#define CKM_IDEA_KEY_GEN 0x00000340UL +#define CKM_IDEA_ECB 0x00000341UL +#define CKM_IDEA_CBC 0x00000342UL +#define CKM_IDEA_MAC 0x00000343UL +#define CKM_IDEA_MAC_GENERAL 0x00000344UL +#define CKM_IDEA_CBC_PAD 0x00000345UL +#define CKM_GENERIC_SECRET_KEY_GEN 0x00000350UL +#define CKM_CONCATENATE_BASE_AND_KEY 0x00000360UL +#define CKM_CONCATENATE_BASE_AND_DATA 0x00000362UL +#define CKM_CONCATENATE_DATA_AND_BASE 0x00000363UL +#define CKM_XOR_BASE_AND_DATA 0x00000364UL +#define CKM_EXTRACT_KEY_FROM_KEY 0x00000365UL +#define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370UL +#define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371UL +#define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372UL +#define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373UL +#define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374UL +#define CKM_TLS_MASTER_KEY_DERIVE 0x00000375UL +#define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376UL +#define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377UL +#define CKM_TLS_PRF 0x00000378UL +#define CKM_SSL3_MD5_MAC 0x00000380UL +#define CKM_SSL3_SHA1_MAC 0x00000381UL +#define CKM_MD5_KEY_DERIVATION 0x00000390UL +#define CKM_MD2_KEY_DERIVATION 0x00000391UL +#define CKM_SHA1_KEY_DERIVATION 0x00000392UL +#define CKM_SHA256_KEY_DERIVATION 0x00000393UL +#define CKM_SHA384_KEY_DERIVATION 0x00000394UL +#define CKM_SHA512_KEY_DERIVATION 0x00000395UL +#define CKM_SHA224_KEY_DERIVATION 0x00000396UL +#define CKM_SHA3_256_KEY_DERIVATION 0x00000397UL +#define CKM_SHA3_256_KEY_DERIVE 0x00000397UL +#define CKM_SHA3_224_KEY_DERIVATION 0x00000398UL +#define CKM_SHA3_224_KEY_DERIVE 0x00000398UL +#define CKM_SHA3_384_KEY_DERIVATION 0x00000399UL +#define CKM_SHA3_384_KEY_DERIVE 0x00000399UL +#define CKM_SHA3_512_KEY_DERIVATION 0x0000039AUL +#define CKM_SHA3_512_KEY_DERIVE 0x0000039AUL +#define CKM_SHAKE_128_KEY_DERIVATION 0x0000039BUL +#define CKM_SHAKE_128_KEY_DERIVE 0x0000039BUL +#define CKM_SHAKE_256_KEY_DERIVATION 0x0000039CUL +#define CKM_SHAKE_256_KEY_DERIVE 0x0000039CUL +#define CKM_PBE_MD2_DES_CBC 0x000003A0UL +#define CKM_PBE_MD5_DES_CBC 0x000003A1UL +#define CKM_PBE_MD5_CAST_CBC 0x000003A2UL +#define CKM_PBE_MD5_CAST3_CBC 0x000003A3UL +#define CKM_PBE_MD5_CAST128_CBC 0x000003A4UL +#define CKM_PBE_SHA1_CAST128_CBC 0x000003A5UL +#define CKM_PBE_SHA1_RC4_128 0x000003A6UL +#define CKM_PBE_SHA1_RC4_40 0x000003A7UL +#define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8UL +#define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9UL +#define CKM_PBE_SHA1_RC2_128_CBC 0x000003AAUL +#define CKM_PBE_SHA1_RC2_40_CBC 0x000003ABUL +#define CKM_PKCS5_PBKD2 0x000003B0UL +#define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0UL +#define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0UL +#define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1UL +#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2UL +#define CKM_WTLS_PRF 0x000003D3UL +#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4UL +#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5UL +#define CKM_TLS10_MAC_SERVER 0x000003D6UL +#define CKM_TLS10_MAC_CLIENT 0x000003D7UL +#define CKM_TLS12_MAC 0x000003D8UL +#define CKM_TLS12_KDF 0x000003D9UL +#define CKM_TLS12_MASTER_KEY_DERIVE 0x000003E0UL +#define CKM_TLS12_KEY_AND_MAC_DERIVE 0x000003E1UL +#define CKM_TLS12_MASTER_KEY_DERIVE_DH 0x000003E2UL +#define CKM_TLS12_KEY_SAFE_DERIVE 0x000003E3UL +#define CKM_TLS_MAC 0x000003E4UL +#define CKM_TLS_KDF 0x000003E5UL +#define CKM_KEY_WRAP_LYNKS 0x00000400UL +#define CKM_KEY_WRAP_SET_OAEP 0x00000401UL +#define CKM_CMS_SIG 0x00000500UL +#define CKM_KIP_DERIVE 0x00000510UL +#define CKM_KIP_WRAP 0x00000511UL +#define CKM_KIP_MAC 0x00000512UL +#define CKM_CAMELLIA_KEY_GEN 0x00000550UL +#define CKM_CAMELLIA_ECB 0x00000551UL +#define CKM_CAMELLIA_CBC 0x00000552UL +#define CKM_CAMELLIA_MAC 0x00000553UL +#define CKM_CAMELLIA_MAC_GENERAL 0x00000554UL +#define CKM_CAMELLIA_CBC_PAD 0x00000555UL +#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556UL +#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557UL +#define CKM_CAMELLIA_CTR 0x00000558UL +#define CKM_ARIA_KEY_GEN 0x00000560UL +#define CKM_ARIA_ECB 0x00000561UL +#define CKM_ARIA_CBC 0x00000562UL +#define CKM_ARIA_MAC 0x00000563UL +#define CKM_ARIA_MAC_GENERAL 0x00000564UL +#define CKM_ARIA_CBC_PAD 0x00000565UL +#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566UL +#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567UL +#define CKM_SEED_KEY_GEN 0x00000650UL +#define CKM_SEED_ECB 0x00000651UL +#define CKM_SEED_CBC 0x00000652UL +#define CKM_SEED_MAC 0x00000653UL +#define CKM_SEED_MAC_GENERAL 0x00000654UL +#define CKM_SEED_CBC_PAD 0x00000655UL +#define CKM_SEED_ECB_ENCRYPT_DATA 0x00000656UL +#define CKM_SEED_CBC_ENCRYPT_DATA 0x00000657UL +#define CKM_SKIPJACK_KEY_GEN 0x00001000UL +#define CKM_SKIPJACK_ECB64 0x00001001UL +#define CKM_SKIPJACK_CBC64 0x00001002UL +#define CKM_SKIPJACK_OFB64 0x00001003UL +#define CKM_SKIPJACK_CFB64 0x00001004UL +#define CKM_SKIPJACK_CFB32 0x00001005UL +#define CKM_SKIPJACK_CFB16 0x00001006UL +#define CKM_SKIPJACK_CFB8 0x00001007UL +#define CKM_SKIPJACK_WRAP 0x00001008UL +#define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009UL +#define CKM_SKIPJACK_RELAYX 0x0000100AUL +#define CKM_KEA_KEY_PAIR_GEN 0x00001010UL +#define CKM_KEA_KEY_DERIVE 0x00001011UL +#define CKM_KEA_DERIVE 0x00001012UL +#define CKM_FORTEZZA_TIMESTAMP 0x00001020UL +#define CKM_BATON_KEY_GEN 0x00001030UL +#define CKM_BATON_ECB128 0x00001031UL +#define CKM_BATON_ECB96 0x00001032UL +#define CKM_BATON_CBC128 0x00001033UL +#define CKM_BATON_COUNTER 0x00001034UL +#define CKM_BATON_SHUFFLE 0x00001035UL +#define CKM_BATON_WRAP 0x00001036UL +#define CKM_EC_KEY_PAIR_GEN 0x00001040UL +#define CKM_ECDSA 0x00001041UL +#define CKM_ECDSA_SHA1 0x00001042UL +#define CKM_ECDSA_SHA224 0x00001043UL +#define CKM_ECDSA_SHA256 0x00001044UL +#define CKM_ECDSA_SHA384 0x00001045UL +#define CKM_ECDSA_SHA512 0x00001046UL +#define CKM_EC_KEY_PAIR_GEN_W_EXTRA_BITS 0x0000140BUL +#define CKM_ECDH1_DERIVE 0x00001050UL +#define CKM_ECDH1_COFACTOR_DERIVE 0x00001051UL +#define CKM_ECMQV_DERIVE 0x00001052UL +#define CKM_ECDH_AES_KEY_WRAP 0x00001053UL +#define CKM_RSA_AES_KEY_WRAP 0x00001054UL +#define CKM_JUNIPER_KEY_GEN 0x00001060UL +#define CKM_JUNIPER_ECB128 0x00001061UL +#define CKM_JUNIPER_CBC128 0x00001062UL +#define CKM_JUNIPER_COUNTER 0x00001063UL +#define CKM_JUNIPER_SHUFFLE 0x00001064UL +#define CKM_JUNIPER_WRAP 0x00001065UL +#define CKM_FASTHASH 0x00001070UL +#define CKM_AES_XTS 0x00001071UL +#define CKM_AES_XTS_KEY_GEN 0x00001072UL +#define CKM_AES_KEY_GEN 0x00001080UL +#define CKM_AES_ECB 0x00001081UL +#define CKM_AES_CBC 0x00001082UL +#define CKM_AES_MAC 0x00001083UL +#define CKM_AES_MAC_GENERAL 0x00001084UL +#define CKM_AES_CBC_PAD 0x00001085UL +#define CKM_AES_CTR 0x00001086UL +#define CKM_AES_GCM 0x00001087UL +#define CKM_AES_CCM 0x00001088UL +#define CKM_AES_CTS 0x00001089UL +#define CKM_AES_CMAC 0x0000108AUL +#define CKM_AES_CMAC_GENERAL 0x0000108BUL +#define CKM_AES_XCBC_MAC 0x0000108CUL +#define CKM_AES_XCBC_MAC_96 0x0000108DUL +#define CKM_AES_GMAC 0x0000108EUL +#define CKM_BLOWFISH_KEY_GEN 0x00001090UL +#define CKM_BLOWFISH_CBC 0x00001091UL +#define CKM_TWOFISH_KEY_GEN 0x00001092UL +#define CKM_TWOFISH_CBC 0x00001093UL +#define CKM_BLOWFISH_CBC_PAD 0x00001094UL +#define CKM_TWOFISH_CBC_PAD 0x00001095UL +#define CKM_DES_ECB_ENCRYPT_DATA 0x00001100UL +#define CKM_DES_CBC_ENCRYPT_DATA 0x00001101UL +#define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102UL +#define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103UL +#define CKM_AES_ECB_ENCRYPT_DATA 0x00001104UL +#define CKM_AES_CBC_ENCRYPT_DATA 0x00001105UL +#define CKM_GOSTR3410_KEY_PAIR_GEN 0x00001200UL +#define CKM_GOSTR3410 0x00001201UL +#define CKM_GOSTR3410_WITH_GOSTR3411 0x00001202UL +#define CKM_GOSTR3410_KEY_WRAP 0x00001203UL +#define CKM_GOSTR3410_DERIVE 0x00001204UL +#define CKM_GOSTR3411 0x00001210UL +#define CKM_GOSTR3411_HMAC 0x00001211UL +#define CKM_GOST28147_KEY_GEN 0x00001220UL +#define CKM_GOST28147_ECB 0x00001221UL +#define CKM_GOST28147 0x00001222UL +#define CKM_GOST28147_MAC 0x00001223UL +#define CKM_GOST28147_KEY_WRAP 0x00001224UL +#define CKM_CHACHA20_KEY_GEN 0x00001225UL +#define CKM_CHACHA20 0x00001226UL +#define CKM_POLY1305_KEY_GEN 0x00001227UL +#define CKM_POLY1305 0x00001228UL +#define CKM_DSA_PARAMETER_GEN 0x00002000UL +#define CKM_DH_PKCS_PARAMETER_GEN 0x00002001UL +#define CKM_X9_42_DH_PARAMETER_GEN 0x00002002UL +#define CKM_DSA_PROBABILISTIC_PARAMETER_GEN 0x00002003UL +#define CKM_DSA_PROBABLISTIC_PARAMETER_GEN 0x00002003UL +#define CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN 0x00002004UL +#define CKM_DSA_FIPS_G_GEN 0x00002005UL +#define CKM_AES_OFB 0x00002104UL +#define CKM_AES_CFB64 0x00002105UL +#define CKM_AES_CFB8 0x00002106UL +#define CKM_AES_CFB128 0x00002107UL +#define CKM_AES_CFB1 0x00002108UL +#define CKM_AES_KEY_WRAP 0x00002109UL +#define CKM_AES_KEY_WRAP_PAD 0x0000210AUL +#define CKM_AES_KEY_WRAP_KWP 0x0000210BUL +#define CKM_AES_KEY_WRAP_PKCS7 0x0000210CUL +#define CKM_RSA_PKCS_TPM_1_1 0x00004001UL +#define CKM_RSA_PKCS_OAEP_TPM_1_1 0x00004002UL +#define CKM_SHA_1_KEY_GEN 0x00004003UL +#define CKM_SHA224_KEY_GEN 0x00004004UL +#define CKM_SHA256_KEY_GEN 0x00004005UL +#define CKM_SHA384_KEY_GEN 0x00004006UL +#define CKM_SHA512_KEY_GEN 0x00004007UL +#define CKM_SHA512_224_KEY_GEN 0x00004008UL +#define CKM_SHA512_256_KEY_GEN 0x00004009UL +#define CKM_SHA512_T_KEY_GEN 0x0000400AUL +#define CKM_NULL 0x0000400BUL +#define CKM_BLAKE2B_160 0x0000400CUL +#define CKM_BLAKE2B_160_HMAC 0x0000400DUL +#define CKM_BLAKE2B_160_HMAC_GENERAL 0x0000400EUL +#define CKM_BLAKE2B_160_KEY_DERIVE 0x0000400FUL +#define CKM_BLAKE2B_160_KEY_GEN 0x00004010UL +#define CKM_BLAKE2B_256 0x00004011UL +#define CKM_BLAKE2B_256_HMAC 0x00004012UL +#define CKM_BLAKE2B_256_HMAC_GENERAL 0x00004013UL +#define CKM_BLAKE2B_256_KEY_DERIVE 0x00004014UL +#define CKM_BLAKE2B_256_KEY_GEN 0x00004015UL +#define CKM_BLAKE2B_384 0x00004016UL +#define CKM_BLAKE2B_384_HMAC 0x00004017UL +#define CKM_BLAKE2B_384_HMAC_GENERAL 0x00004018UL +#define CKM_BLAKE2B_384_KEY_DERIVE 0x00004019UL +#define CKM_BLAKE2B_384_KEY_GEN 0x0000401AUL +#define CKM_BLAKE2B_512 0x0000401BUL +#define CKM_BLAKE2B_512_HMAC 0x0000401CUL +#define CKM_BLAKE2B_512_HMAC_GENERAL 0x0000401DUL +#define CKM_BLAKE2B_512_KEY_DERIVE 0x0000401EUL +#define CKM_BLAKE2B_512_KEY_GEN 0x0000401FUL +#define CKM_SALSA20 0x00004020UL +#define CKM_CHACHA20_POLY1305 0x00004021UL +#define CKM_SALSA20_POLY1305 0x00004022UL +#define CKM_X3DH_INITIALIZE 0x00004023UL +#define CKM_X3DH_RESPOND 0x00004024UL +#define CKM_X2RATCHET_INITIALIZE 0x00004025UL +#define CKM_X2RATCHET_RESPOND 0x00004026UL +#define CKM_X2RATCHET_ENCRYPT 0x00004027UL +#define CKM_X2RATCHET_DECRYPT 0x00004028UL +#define CKM_XEDDSA 0x00004029UL +#define CKM_HKDF_DERIVE 0x0000402AUL +#define CKM_HKDF_DATA 0x0000402BUL +#define CKM_HKDF_KEY_GEN 0x0000402CUL +#define CKM_SALSA20_KEY_GEN 0x0000402DUL +#define CKM_ECDSA_SHA3_224 0x00001047UL +#define CKM_ECDSA_SHA3_256 0x00001048UL +#define CKM_ECDSA_SHA3_384 0x00001049UL +#define CKM_ECDSA_SHA3_512 0x0000104AUL +#define CKM_EC_EDWARDS_KEY_PAIR_GEN 0x00001055UL +#define CKM_EC_MONTGOMERY_KEY_PAIR_GEN 0x00001056UL +#define CKM_EDDSA 0x00001057UL +#define CKM_SP800_108_COUNTER_KDF 0x000003ACUL +#define CKM_SP800_108_FEEDBACK_KDF 0x000003ADUL +#define CKM_SP800_108_DOUBLE_PIPELINE_KDF 0x000003AEUL +#define CKM_IKE2_PRF_PLUS_DERIVE 0x0000402EUL +#define CKM_IKE_PRF_DERIVE 0x0000402FUL +#define CKM_IKE1_PRF_DERIVE 0x00004030UL +#define CKM_IKE1_EXTENDED_DERIVE 0x00004031UL +#define CKM_HSS_KEY_PAIR_GEN 0x00004032UL +#define CKM_HSS 0x00004033UL +#define CKM_VENDOR_DEFINED 0x80000000UL +/* Deprecated */ +#ifdef PKCS11_DEPRECATED +#define CKM_CAST5_KEY_GEN 0x00000320UL +#define CKM_CAST5_CBC 0x00000322UL +#define CKM_CAST5_MAC 0x00000323UL +#define CKM_CAST5_MAC_GENERAL 0x00000324UL +#define CKM_CAST5_CBC_PAD 0x00000325UL +#define CKM_PBE_MD5_CAST5_CBC 0x000003A4UL +#define CKM_PBE_SHA1_CAST5_CBC 0x000003A5UL +#define CKM_ECDSA_KEY_PAIR_GEN 0x00001040UL +#endif + +/* CKN */ +#define CKN_SURRENDER 0UL +#define CKN_OTP_CHANGED 1UL + +/* CKO */ +#define CKO_DATA 0x00000000UL +#define CKO_CERTIFICATE 0x00000001UL +#define CKO_PUBLIC_KEY 0x00000002UL +#define CKO_PRIVATE_KEY 0x00000003UL +#define CKO_SECRET_KEY 0x00000004UL +#define CKO_HW_FEATURE 0x00000005UL +#define CKO_DOMAIN_PARAMETERS 0x00000006UL +#define CKO_MECHANISM 0x00000007UL +#define CKO_OTP_KEY 0x00000008UL +#define CKO_PROFILE 0x00000009UL +#define CKO_VENDOR_DEFINED 0x80000000UL + +/* CKP (profile) */ +#define CKP_INVALID_ID 0x00000000UL +#define CKP_BASELINE_PROVIDER 0x00000001UL +#define CKP_EXTENDED_PROVIDER 0x00000002UL +#define CKP_AUTHENTICATION_TOKEN 0x00000003UL +#define CKP_PUBLIC_CERTIFICATES_TOKEN 0x00000004UL +#define CKP_COMPLETE_PROVIDER 0x00000005UL +#define CKP_HKDF_TLS_TOKEN 0x00000006UL +#define CKP_VENDOR_DEFINED 0x80000000UL + +/* CKP (PBKD2) */ +#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001UL +#define CKP_PKCS5_PBKD2_HMAC_GOSTR3411 0x00000002UL +#define CKP_PKCS5_PBKD2_HMAC_SHA224 0x00000003UL +#define CKP_PKCS5_PBKD2_HMAC_SHA256 0x00000004UL +#define CKP_PKCS5_PBKD2_HMAC_SHA384 0x00000005UL +#define CKP_PKCS5_PBKD2_HMAC_SHA512 0x00000006UL +#define CKP_PKCS5_PBKD2_HMAC_SHA512_224 0x00000007UL +#define CKP_PKCS5_PBKD2_HMAC_SHA512_256 0x00000008UL + +/* CKR */ +#define CKR_OK 0x00000000UL +#define CKR_CANCEL 0x00000001UL +#define CKR_HOST_MEMORY 0x00000002UL +#define CKR_SLOT_ID_INVALID 0x00000003UL +#define CKR_GENERAL_ERROR 0x00000005UL +#define CKR_FUNCTION_FAILED 0x00000006UL +#define CKR_ARGUMENTS_BAD 0x00000007UL +#define CKR_NO_EVENT 0x00000008UL +#define CKR_NEED_TO_CREATE_THREADS 0x00000009UL +#define CKR_CANT_LOCK 0x0000000AUL +#define CKR_ATTRIBUTE_READ_ONLY 0x00000010UL +#define CKR_ATTRIBUTE_SENSITIVE 0x00000011UL +#define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012UL +#define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013UL +#define CKR_ACTION_PROHIBITED 0x0000001BUL +#define CKR_DATA_INVALID 0x00000020UL +#define CKR_DATA_LEN_RANGE 0x00000021UL +#define CKR_DEVICE_ERROR 0x00000030UL +#define CKR_DEVICE_MEMORY 0x00000031UL +#define CKR_DEVICE_REMOVED 0x00000032UL +#define CKR_ENCRYPTED_DATA_INVALID 0x00000040UL +#define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041UL +#define CKR_AEAD_DECRYPT_FAILED 0x00000042UL +#define CKR_FUNCTION_CANCELED 0x00000050UL +#define CKR_FUNCTION_NOT_PARALLEL 0x00000051UL +#define CKR_FUNCTION_NOT_SUPPORTED 0x00000054UL +#define CKR_KEY_HANDLE_INVALID 0x00000060UL +#define CKR_KEY_SIZE_RANGE 0x00000062UL +#define CKR_KEY_TYPE_INCONSISTENT 0x00000063UL +#define CKR_KEY_NOT_NEEDED 0x00000064UL +#define CKR_KEY_CHANGED 0x00000065UL +#define CKR_KEY_NEEDED 0x00000066UL +#define CKR_KEY_INDIGESTIBLE 0x00000067UL +#define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068UL +#define CKR_KEY_NOT_WRAPPABLE 0x00000069UL +#define CKR_KEY_UNEXTRACTABLE 0x0000006AUL +#define CKR_MECHANISM_INVALID 0x00000070UL +#define CKR_MECHANISM_PARAM_INVALID 0x00000071UL +#define CKR_OBJECT_HANDLE_INVALID 0x00000082UL +#define CKR_OPERATION_ACTIVE 0x00000090UL +#define CKR_OPERATION_NOT_INITIALIZED 0x00000091UL +#define CKR_PIN_INCORRECT 0x000000A0UL +#define CKR_PIN_INVALID 0x000000A1UL +#define CKR_PIN_LEN_RANGE 0x000000A2UL +#define CKR_PIN_EXPIRED 0x000000A3UL +#define CKR_PIN_LOCKED 0x000000A4UL +#define CKR_SESSION_CLOSED 0x000000B0UL +#define CKR_SESSION_COUNT 0x000000B1UL +#define CKR_SESSION_HANDLE_INVALID 0x000000B3UL +#define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4UL +#define CKR_SESSION_READ_ONLY 0x000000B5UL +#define CKR_SESSION_EXISTS 0x000000B6UL +#define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7UL +#define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8UL +#define CKR_SIGNATURE_INVALID 0x000000C0UL +#define CKR_SIGNATURE_LEN_RANGE 0x000000C1UL +#define CKR_TEMPLATE_INCOMPLETE 0x000000D0UL +#define CKR_TEMPLATE_INCONSISTENT 0x000000D1UL +#define CKR_TOKEN_NOT_PRESENT 0x000000E0UL +#define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1UL +#define CKR_TOKEN_WRITE_PROTECTED 0x000000E2UL +#define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0UL +#define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1UL +#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2UL +#define CKR_USER_ALREADY_LOGGED_IN 0x00000100UL +#define CKR_USER_NOT_LOGGED_IN 0x00000101UL +#define CKR_USER_PIN_NOT_INITIALIZED 0x00000102UL +#define CKR_USER_TYPE_INVALID 0x00000103UL +#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104UL +#define CKR_USER_TOO_MANY_TYPES 0x00000105UL +#define CKR_WRAPPED_KEY_INVALID 0x00000110UL +#define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112UL +#define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113UL +#define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114UL +#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115UL +#define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120UL +#define CKR_RANDOM_NO_RNG 0x00000121UL +#define CKR_DOMAIN_PARAMS_INVALID 0x00000130UL +#define CKR_CURVE_NOT_SUPPORTED 0x00000140UL +#define CKR_BUFFER_TOO_SMALL 0x00000150UL +#define CKR_SAVED_STATE_INVALID 0x00000160UL +#define CKR_INFORMATION_SENSITIVE 0x00000170UL +#define CKR_STATE_UNSAVEABLE 0x00000180UL +#define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190UL +#define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191UL +#define CKR_MUTEX_BAD 0x000001A0UL +#define CKR_MUTEX_NOT_LOCKED 0x000001A1UL +#define CKR_NEW_PIN_MODE 0x000001B0UL +#define CKR_NEXT_OTP 0x000001B1UL +#define CKR_EXCEEDED_MAX_ITERATIONS 0x000001B5UL +#define CKR_FIPS_SELF_TEST_FAILED 0x000001B6UL +#define CKR_LIBRARY_LOAD_FAILED 0x000001B7UL +#define CKR_PIN_TOO_WEAK 0x000001B8UL +#define CKR_PUBLIC_KEY_INVALID 0x000001B9UL +#define CKR_FUNCTION_REJECTED 0x00000200UL +#define CKR_TOKEN_RESOURCE_EXCEEDED 0x00000201UL +#define CKR_OPERATION_CANCEL_FAILED 0x00000202UL +#define CKR_KEY_EXHAUSTED 0x00000203UL +#define CKR_VENDOR_DEFINED 0x80000000UL + + +/* CKS */ +#define CKS_RO_PUBLIC_SESSION 0UL +#define CKS_RO_USER_FUNCTIONS 1UL +#define CKS_RW_PUBLIC_SESSION 2UL +#define CKS_RW_USER_FUNCTIONS 3UL +#define CKS_RW_SO_FUNCTIONS 4UL + +/* CKU */ +#define CKU_SO 0UL +#define CKU_USER 1UL +#define CKU_CONTEXT_SPECIFIC 2UL + +/* CKZ (data) */ +#define CKZ_DATA_SPECIFIED 0x00000001UL + +/* CKZ (salt) */ +#define CKZ_SALT_SPECIFIED 0x00000001UL + +/* Sundry structures type definition in alphabetical order */ +#define STRUCTDEF(__name__) \ +struct __name__; \ +typedef struct __name__ __name__; \ +typedef struct __name__ * __name__ ## _PTR; \ +typedef struct __name__ ** __name__ ## _PTR_PTR; + +STRUCTDEF(CK_ATTRIBUTE) +STRUCTDEF(CK_C_INITIALIZE_ARGS) +STRUCTDEF(CK_DATE) +STRUCTDEF(CK_DERIVED_KEY) +STRUCTDEF(CK_FUNCTION_LIST) +STRUCTDEF(CK_FUNCTION_LIST_3_0) +STRUCTDEF(CK_INFO) +STRUCTDEF(CK_INTERFACE) +STRUCTDEF(CK_MECHANISM) +STRUCTDEF(CK_MECHANISM_INFO) +STRUCTDEF(CK_SESSION_INFO) +STRUCTDEF(CK_SLOT_INFO) +STRUCTDEF(CK_TOKEN_INFO) +STRUCTDEF(CK_VERSION) + +/* Function type definitions */ +typedef CK_RV (* CK_NOTIFY)(CK_SESSION_HANDLE, CK_NOTIFICATION, void *); +typedef CK_RV (* CK_CREATEMUTEX)(void **); +typedef CK_RV (* CK_DESTROYMUTEX)(void *); +typedef CK_RV (* CK_LOCKMUTEX)(void *); +typedef CK_RV (* CK_UNLOCKMUTEX)(void *); + +/* General Structure definitions */ +struct CK_ATTRIBUTE { + CK_ATTRIBUTE_TYPE type; + void * pValue; + CK_ULONG ulValueLen; +}; + +struct CK_C_INITIALIZE_ARGS { + CK_CREATEMUTEX CreateMutex; + CK_DESTROYMUTEX DestroyMutex; + CK_LOCKMUTEX LockMutex; + CK_UNLOCKMUTEX UnlockMutex; + CK_FLAGS flags; + void * pReserved; +}; + +struct CK_DATE{ + CK_CHAR year[4]; + CK_CHAR month[2]; + CK_CHAR day[2]; +}; + +struct CK_DERIVED_KEY +{ + CK_ATTRIBUTE * pTemplate; + CK_ULONG ulAttributeCount; + CK_OBJECT_HANDLE * phKey; +}; + +struct CK_VERSION { + CK_BYTE major; + CK_BYTE minor; +}; + +struct CK_INFO { + struct CK_VERSION cryptokiVersion; + CK_UTF8CHAR manufacturerID[32]; + CK_FLAGS flags; + CK_UTF8CHAR libraryDescription[32]; + struct CK_VERSION libraryVersion; +}; + +struct CK_INTERFACE { + CK_CHAR * pInterfaceName; + void * pFunctionList; + CK_FLAGS flags; +}; + +struct CK_MECHANISM { + CK_MECHANISM_TYPE mechanism; + void * pParameter; + CK_ULONG ulParameterLen; +}; + +struct CK_MECHANISM_INFO { + CK_ULONG ulMinKeySize; + CK_ULONG ulMaxKeySize; + CK_FLAGS flags; +}; + +struct CK_SESSION_INFO { + CK_SLOT_ID slotID; + CK_STATE state; + CK_FLAGS flags; + CK_ULONG ulDeviceError; +}; + +struct CK_SLOT_INFO { + CK_UTF8CHAR slotDescription[64]; + CK_UTF8CHAR manufacturerID[32]; + CK_FLAGS flags; + CK_VERSION hardwareVersion; + CK_VERSION firmwareVersion; +}; + +struct CK_TOKEN_INFO { + CK_UTF8CHAR label[32]; + CK_UTF8CHAR manufacturerID[32]; + CK_UTF8CHAR model[16]; + CK_CHAR serialNumber[16]; + CK_FLAGS flags; + CK_ULONG ulMaxSessionCount; + CK_ULONG ulSessionCount; + CK_ULONG ulMaxRwSessionCount; + CK_ULONG ulRwSessionCount; + CK_ULONG ulMaxPinLen; + CK_ULONG ulMinPinLen; + CK_ULONG ulTotalPublicMemory; + CK_ULONG ulFreePublicMemory; + CK_ULONG ulTotalPrivateMemory; + CK_ULONG ulFreePrivateMemory; + CK_VERSION hardwareVersion; + CK_VERSION firmwareVersion; + CK_CHAR utcTime[16]; +}; + +/* Param Structure definitions in alphabetical order */ +STRUCTDEF(CK_AES_CBC_ENCRYPT_DATA_PARAMS) +STRUCTDEF(CK_AES_CCM_PARAMS) +STRUCTDEF(CK_AES_CTR_PARAMS) +STRUCTDEF(CK_AES_GCM_PARAMS) +STRUCTDEF(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) +STRUCTDEF(CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS) +STRUCTDEF(CK_CAMELLIA_CTR_PARAMS) +STRUCTDEF(CK_CCM_MESSAGE_PARAMS) +STRUCTDEF(CK_CCM_PARAMS) +STRUCTDEF(CK_CHACHA20_PARAMS) +STRUCTDEF(CK_CMS_SIG_PARAMS) +STRUCTDEF(CK_DES_CBC_ENCRYPT_DATA_PARAMS) +STRUCTDEF(CK_DSA_PARAMETER_GEN_PARAM) +STRUCTDEF(CK_ECDH_AES_KEY_WRAP_PARAMS) +STRUCTDEF(CK_ECDH1_DERIVE_PARAMS) +STRUCTDEF(CK_ECDH2_DERIVE_PARAMS) +STRUCTDEF(CK_ECMQV_DERIVE_PARAMS) +STRUCTDEF(CK_EDDSA_PARAMS) +STRUCTDEF(CK_GCM_MESSAGE_PARAMS) +STRUCTDEF(CK_GCM_PARAMS) +STRUCTDEF(CK_GOSTR3410_DERIVE_PARAMS) +STRUCTDEF(CK_GOSTR3410_KEY_WRAP_PARAMS) +STRUCTDEF(CK_HKDF_PARAMS) +STRUCTDEF(CK_IKE_PRF_DERIVE_PARAMS) +STRUCTDEF(CK_IKE1_EXTENDED_DERIVE_PARAMS) +STRUCTDEF(CK_IKE1_PRF_DERIVE_PARAMS) +STRUCTDEF(CK_IKE2_PRF_PLUS_DERIVE_PARAMS) +STRUCTDEF(CK_KEA_DERIVE_PARAMS) +STRUCTDEF(CK_KEY_DERIVATION_STRING_DATA) +STRUCTDEF(CK_KEY_WRAP_SET_OAEP_PARAMS) +STRUCTDEF(CK_KIP_PARAMS) +STRUCTDEF(CK_OTP_PARAM) +STRUCTDEF(CK_OTP_PARAMS) +STRUCTDEF(CK_OTP_SIGNATURE_INFO) +STRUCTDEF(CK_PBE_PARAMS) +STRUCTDEF(CK_PKCS5_PBKD2_PARAMS) +STRUCTDEF(CK_PKCS5_PBKD2_PARAMS2) +STRUCTDEF(CK_PRF_DATA_PARAM) +STRUCTDEF(CK_RC2_CBC_PARAMS) +STRUCTDEF(CK_RC2_MAC_GENERAL_PARAMS) +STRUCTDEF(CK_RC5_CBC_PARAMS) +STRUCTDEF(CK_RC5_MAC_GENERAL_PARAMS) +STRUCTDEF(CK_RC5_PARAMS) +STRUCTDEF(CK_RSA_AES_KEY_WRAP_PARAMS) +STRUCTDEF(CK_RSA_PKCS_OAEP_PARAMS) +STRUCTDEF(CK_RSA_PKCS_PSS_PARAMS) +STRUCTDEF(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS) +STRUCTDEF(CK_SALSA20_CHACHA20_POLY1305_PARAMS) +STRUCTDEF(CK_SALSA20_PARAMS) +STRUCTDEF(CK_SEED_CBC_ENCRYPT_DATA_PARAMS) +STRUCTDEF(CK_SKIPJACK_PRIVATE_WRAP_PARAMS) +STRUCTDEF(CK_SKIPJACK_RELAYX_PARAMS) +STRUCTDEF(CK_SP800_108_COUNTER_FORMAT) +STRUCTDEF(CK_SP800_108_DKM_LENGTH_FORMAT) +STRUCTDEF(CK_SP800_108_FEEDBACK_KDF_PARAMS) +STRUCTDEF(CK_SP800_108_KDF_PARAMS) +STRUCTDEF(CK_X2RATCHET_INITIALIZE_PARAMS) +STRUCTDEF(CK_X2RATCHET_RESPOND_PARAMS) +STRUCTDEF(CK_X3DH_INITIATE_PARAMS) +STRUCTDEF(CK_X3DH_RESPOND_PARAMS) +STRUCTDEF(CK_X9_42_DH1_DERIVE_PARAMS) +STRUCTDEF(CK_X9_42_DH2_DERIVE_PARAMS) +STRUCTDEF(CK_X9_42_MQV_DERIVE_PARAMS) +STRUCTDEF(CK_XEDDSA_PARAMS) +STRUCTDEF(specifiedParams) + +struct CK_AES_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE * pData; + CK_ULONG length; +}; + +struct CK_AES_CCM_PARAMS { + CK_ULONG ulDataLen; + CK_BYTE * pNonce; + CK_ULONG ulNonceLen; + CK_BYTE * pAAD; + CK_ULONG ulAADLen; + CK_ULONG ulMACLen; +}; + +struct CK_AES_CTR_PARAMS { + CK_ULONG ulCounterBits; + CK_BYTE cb[16]; +}; + +struct CK_AES_GCM_PARAMS { + CK_BYTE * pIv; + CK_ULONG ulIvLen; + CK_ULONG ulIvBits; + CK_BYTE * pAAD; + CK_ULONG ulAADLen; + CK_ULONG ulTagBits; +}; + +struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE * pData; + CK_ULONG length; +}; + +struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE * pData; + CK_ULONG length; +}; + +struct CK_CAMELLIA_CTR_PARAMS { + CK_ULONG ulCounterBits; + CK_BYTE cb[16]; +}; + +struct CK_CCM_MESSAGE_PARAMS { + CK_ULONG ulDataLen; + CK_BYTE * pNonce; + CK_ULONG ulNonceLen; + CK_ULONG ulNonceFixedBits; + CK_GENERATOR_FUNCTION nonceGenerator; + CK_BYTE * pMAC; + CK_ULONG ulMACLen; +}; + +struct CK_CCM_PARAMS { + CK_ULONG ulDataLen; + CK_BYTE * pNonce; + CK_ULONG ulNonceLen; + CK_BYTE * pAAD; + CK_ULONG ulAADLen; + CK_ULONG ulMACLen; +}; + +struct CK_CHACHA20_PARAMS { + CK_BYTE * pBlockCounter; + CK_ULONG blockCounterBits; + CK_BYTE * pNonce; + CK_ULONG ulNonceBits; +}; + +struct CK_CMS_SIG_PARAMS { + CK_OBJECT_HANDLE certificateHandle; + CK_MECHANISM * pSigningMechanism; + CK_MECHANISM * pDigestMechanism; + CK_UTF8CHAR * pContentType; + CK_BYTE * pRequestedAttributes; + CK_ULONG ulRequestedAttributesLen; + CK_BYTE * pRequiredAttributes; + CK_ULONG ulRequiredAttributesLen; +}; + +struct CK_DES_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[8]; + CK_BYTE * pData; + CK_ULONG length; +}; + +struct CK_DSA_PARAMETER_GEN_PARAM { + CK_MECHANISM_TYPE hash; + CK_BYTE * pSeed; + CK_ULONG ulSeedLen; + CK_ULONG ulIndex; +}; + +struct CK_ECDH_AES_KEY_WRAP_PARAMS { + CK_ULONG ulAESKeyBits; + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE * pSharedData; +}; + +struct CK_ECDH1_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE * pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; +}; + +struct CK_ECDH2_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE * pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE * pPublicData2; +}; + +struct CK_ECMQV_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE * pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE * pPublicData2; + CK_OBJECT_HANDLE publicKey; +}; + +struct CK_EDDSA_PARAMS { + CK_BBOOL phFlag; + CK_ULONG ulContextDataLen; + CK_BYTE * pContextData; +}; + +struct CK_GCM_MESSAGE_PARAMS { + CK_BYTE * pIv; + CK_ULONG ulIvLen; + CK_ULONG ulIvFixedBits; + CK_GENERATOR_FUNCTION ivGenerator; + CK_BYTE * pTag; + CK_ULONG ulTagBits; +}; + +struct CK_GCM_PARAMS { + CK_BYTE * pIv; + CK_ULONG ulIvLen; + CK_ULONG ulIvBits; + CK_BYTE * pAAD; + CK_ULONG ulAADLen; + CK_ULONG ulTagBits; +}; + +struct CK_GOSTR3410_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_BYTE * pPublicData; + CK_ULONG ulPublicDataLen; + CK_BYTE * pUKM; + CK_ULONG ulUKMLen; +}; + +struct CK_GOSTR3410_KEY_WRAP_PARAMS { + CK_BYTE * pWrapOID; + CK_ULONG ulWrapOIDLen; + CK_BYTE * pUKM; + CK_ULONG ulUKMLen; + CK_OBJECT_HANDLE hKey; +}; + +struct CK_HKDF_PARAMS { + CK_BBOOL bExtract; + CK_BBOOL bExpand; + CK_MECHANISM_TYPE prfHashMechanism; + CK_ULONG ulSaltType; + CK_BYTE * pSalt; + CK_ULONG ulSaltLen; + CK_OBJECT_HANDLE hSaltKey; + CK_BYTE * pInfo; + CK_ULONG ulInfoLen; +}; + +struct CK_IKE_PRF_DERIVE_PARAMS { + CK_MECHANISM_TYPE prfMechanism; + CK_BBOOL bDataAsKey; + CK_BBOOL bRekey; + CK_BYTE * pNi; + CK_ULONG ulNiLen; + CK_BYTE * pNr; + CK_ULONG ulNrLen; + CK_OBJECT_HANDLE hNewKey; +}; + +struct CK_IKE1_EXTENDED_DERIVE_PARAMS { + CK_MECHANISM_TYPE prfMechanism; + CK_BBOOL bHasKeygxy; + CK_OBJECT_HANDLE hKeygxy; + CK_BYTE * pExtraData; + CK_ULONG ulExtraDataLen; +}; + +struct CK_IKE1_PRF_DERIVE_PARAMS { + CK_MECHANISM_TYPE prfMechanism; + CK_BBOOL bHasPrevKey; + CK_OBJECT_HANDLE hKeygxy; + CK_OBJECT_HANDLE hPrevKey; + CK_BYTE * pCKYi; + CK_ULONG ulCKYiLen; + CK_BYTE * pCKYr; + CK_ULONG ulCKYrLen; + CK_BYTE keyNumber; +}; + +struct CK_IKE2_PRF_PLUS_DERIVE_PARAMS { + CK_MECHANISM_TYPE prfMechanism; + CK_BBOOL bHasSeedKey; + CK_OBJECT_HANDLE hSeedKey; + CK_BYTE * pSeedData; + CK_ULONG ulSeedDataLen; +}; + +struct CK_KEA_DERIVE_PARAMS { + CK_BBOOL isSender; + CK_ULONG ulRandomLen; + CK_BYTE * RandomA; + CK_BYTE * RandomB; + CK_ULONG ulPublicDataLen; + CK_BYTE * PublicData; +}; + +struct CK_KEY_DERIVATION_STRING_DATA { + CK_BYTE * pData; + CK_ULONG ulLen; +}; + +struct CK_KEY_WRAP_SET_OAEP_PARAMS { + CK_BYTE bBC; + CK_BYTE * pX; + CK_ULONG ulXLen; +}; + +struct CK_KIP_PARAMS { + CK_MECHANISM * pMechanism; + CK_OBJECT_HANDLE hKey; + CK_BYTE * pSeed; + CK_ULONG ulSeedLen; +}; + +struct CK_OTP_PARAM { + CK_OTP_PARAM_TYPE type; + void * pValue; + CK_ULONG ulValueLen; +}; + +struct CK_OTP_PARAMS { + CK_OTP_PARAM * pParams; + CK_ULONG ulCount; +}; + +struct CK_OTP_SIGNATURE_INFO { + CK_OTP_PARAM * pParams; + CK_ULONG ulCount; +}; + +struct CK_PBE_PARAMS { + CK_BYTE * pInitVector; + CK_UTF8CHAR * pPassword; + CK_ULONG ulPasswordLen; + CK_BYTE * pSalt; + CK_ULONG ulSaltLen; + CK_ULONG ulIteration; +}; + +struct CK_PKCS5_PBKD2_PARAMS { + CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; + void * pSaltSourceData; + CK_ULONG ulSaltSourceDataLen; + CK_ULONG iterations; + CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; + void * pPrfData; + CK_ULONG ulPrfDataLen; + CK_UTF8CHAR * pPassword; + CK_ULONG * ulPasswordLen; +}; + +struct CK_PKCS5_PBKD2_PARAMS2 { + CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; + void * pSaltSourceData; + CK_ULONG ulSaltSourceDataLen; + CK_ULONG iterations; + CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; + void * pPrfData; + CK_ULONG ulPrfDataLen; + CK_UTF8CHAR * pPassword; + CK_ULONG ulPasswordLen; +}; + +struct CK_PRF_DATA_PARAM { + CK_PRF_DATA_TYPE type; + void * pValue; + CK_ULONG ulValueLen; +}; + +struct CK_RC2_CBC_PARAMS { + CK_ULONG ulEffectiveBits; + CK_BYTE iv[8]; +}; + +struct CK_RC2_MAC_GENERAL_PARAMS { + CK_ULONG ulEffectiveBits; + CK_ULONG ulMacLength; +}; + +struct CK_RC5_CBC_PARAMS { + CK_ULONG ulWordsize; + CK_ULONG ulRounds; + CK_BYTE * pIv; + CK_ULONG ulIvLen; +}; + +struct CK_RC5_MAC_GENERAL_PARAMS { + CK_ULONG ulWordsize; + CK_ULONG ulRounds; + CK_ULONG ulMacLength; +}; + +struct CK_RC5_PARAMS { + CK_ULONG ulWordsize; + CK_ULONG ulRounds; +}; + +struct CK_RSA_AES_KEY_WRAP_PARAMS { + CK_ULONG ulAESKeyBits; + CK_RSA_PKCS_OAEP_PARAMS * pOAEPParams; +}; + +struct CK_RSA_PKCS_OAEP_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_RSA_PKCS_OAEP_SOURCE_TYPE source; + void * pSourceData; + CK_ULONG ulSourceDataLen; +}; + +struct CK_RSA_PKCS_PSS_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_ULONG sLen; +}; + +struct CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS { + CK_BYTE * pNonce; + CK_ULONG ulNonceLen; + CK_BYTE * pTag; +}; + +struct CK_SALSA20_CHACHA20_POLY1305_PARAMS { + CK_BYTE * pNonce; + CK_ULONG ulNonceLen; + CK_BYTE * pAAD; + CK_ULONG ulAADLen; +}; + +struct CK_SALSA20_PARAMS { + CK_BYTE * pBlockCounter; + CK_BYTE * pNonce; + CK_ULONG ulNonceBits; +}; + +struct CK_SEED_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE * pData; + CK_ULONG length; +}; + +struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS { + CK_ULONG ulPasswordLen; + CK_BYTE * pPassword; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; + CK_ULONG ulPAndGLen; + CK_ULONG ulQLen; + CK_ULONG ulRandomLen; + CK_BYTE * pRandomA; + CK_BYTE * pPrimeP; + CK_BYTE * pBaseG; + CK_BYTE * pSubprimeQ; +}; + +struct CK_SKIPJACK_RELAYX_PARAMS { + CK_ULONG ulOldWrappedXLen; + CK_BYTE * pOldWrappedX; + CK_ULONG ulOldPasswordLen; + CK_BYTE * pOldPassword; + CK_ULONG ulOldPublicDataLen; + CK_BYTE * pOldPublicData; + CK_ULONG ulOldRandomLen; + CK_BYTE * pOldRandomA; + CK_ULONG ulNewPasswordLen; + CK_BYTE * pNewPassword; + CK_ULONG ulNewPublicDataLen; + CK_BYTE * pNewPublicData; + CK_ULONG ulNewRandomLen; + CK_BYTE * pNewRandomA; +}; + +struct CK_SP800_108_COUNTER_FORMAT { + CK_BBOOL bLittleEndian; + CK_ULONG ulWidthInBits; +}; + +struct CK_SP800_108_DKM_LENGTH_FORMAT { + CK_SP800_108_DKM_LENGTH_METHOD dkmLengthMethod; + CK_BBOOL bLittleEndian; + CK_ULONG ulWidthInBits; +}; + +typedef CK_MECHANISM_TYPE CK_SP800_108_PRF_TYPE; + +struct CK_SP800_108_FEEDBACK_KDF_PARAMS +{ + CK_SP800_108_PRF_TYPE prfType; + CK_ULONG ulNumberOfDataParams; + CK_PRF_DATA_PARAM * pDataParams; + CK_ULONG ulIVLen; + CK_BYTE * pIV; + CK_ULONG ulAdditionalDerivedKeys; + CK_DERIVED_KEY * pAdditionalDerivedKeys; +}; + +struct CK_SP800_108_KDF_PARAMS +{ + CK_SP800_108_PRF_TYPE prfType; + CK_ULONG ulNumberOfDataParams; + CK_PRF_DATA_PARAM * pDataParams; + CK_ULONG ulAdditionalDerivedKeys; + CK_DERIVED_KEY * pAdditionalDerivedKeys; +}; + +struct CK_X2RATCHET_INITIALIZE_PARAMS { + CK_BYTE * sk; + CK_OBJECT_HANDLE peer_public_prekey; + CK_OBJECT_HANDLE peer_public_identity; + CK_OBJECT_HANDLE own_public_identity; + CK_BBOOL bEncryptedHeader; + CK_ULONG eCurve; + CK_MECHANISM_TYPE aeadMechanism; + CK_X2RATCHET_KDF_TYPE kdfMechanism; +}; + +struct CK_X2RATCHET_RESPOND_PARAMS { + CK_BYTE * sk; + CK_OBJECT_HANDLE own_prekey; + CK_OBJECT_HANDLE initiator_identity; + CK_OBJECT_HANDLE own_public_identity; + CK_BBOOL bEncryptedHeader; + CK_ULONG eCurve; + CK_MECHANISM_TYPE aeadMechanism; + CK_X2RATCHET_KDF_TYPE kdfMechanism; +}; + +struct CK_X3DH_INITIATE_PARAMS { + CK_X3DH_KDF_TYPE kdf; + CK_OBJECT_HANDLE pPeer_identity; + CK_OBJECT_HANDLE pPeer_prekey; + CK_BYTE * pPrekey_signature; + CK_BYTE * pOnetime_key; + CK_OBJECT_HANDLE pOwn_identity; + CK_OBJECT_HANDLE pOwn_ephemeral; +}; + +struct CK_X3DH_RESPOND_PARAMS { + CK_X3DH_KDF_TYPE kdf; + CK_BYTE * pIdentity_id; + CK_BYTE * pPrekey_id; + CK_BYTE * pOnetime_id; + CK_OBJECT_HANDLE pInitiator_identity; + CK_BYTE * pInitiator_ephemeral; +}; + +struct CK_X9_42_DH1_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE * pOtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; +}; + +struct CK_X9_42_DH2_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE * pOtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE * pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE * pPublicData2; +}; + +struct CK_X9_42_MQV_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE * OtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE * PublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE * PublicData2; + CK_OBJECT_HANDLE publicKey; +}; + +struct CK_XEDDSA_PARAMS { + CK_XEDDSA_HASH_TYPE hash; +}; + +struct specifiedParams { + CK_HSS_LEVELS levels; + CK_LMS_TYPE lm_type[8]; + CK_LMOTS_TYPE lm_ots_type[8]; +}; + +/* TLS related structure definitions */ +STRUCTDEF(CK_SSL3_KEY_MAT_OUT) +STRUCTDEF(CK_SSL3_KEY_MAT_PARAMS) +STRUCTDEF(CK_SSL3_MASTER_KEY_DERIVE_PARAMS) +STRUCTDEF(CK_SSL3_RANDOM_DATA) +STRUCTDEF(CK_TLS_KDF_PARAMS) +STRUCTDEF(CK_TLS_MAC_PARAMS) +STRUCTDEF(CK_TLS_PRF_PARAMS) +STRUCTDEF(CK_TLS12_KEY_MAT_PARAMS) +STRUCTDEF(CK_TLS12_MASTER_KEY_DERIVE_PARAMS) +STRUCTDEF(CK_WTLS_KEY_MAT_OUT) +STRUCTDEF(CK_WTLS_KEY_MAT_PARAMS) +STRUCTDEF(CK_WTLS_MASTER_KEY_DERIVE_PARAMS) +STRUCTDEF(CK_WTLS_PRF_PARAMS) +STRUCTDEF(CK_WTLS_RANDOM_DATA) + +struct CK_SSL3_KEY_MAT_OUT { + CK_OBJECT_HANDLE hClientMacSecret; + CK_OBJECT_HANDLE hServerMacSecret; + CK_OBJECT_HANDLE hClientKey; + CK_OBJECT_HANDLE hServerKey; + CK_BYTE * pIVClient; + CK_BYTE * pIVServer; +}; + +struct CK_SSL3_RANDOM_DATA { + CK_BYTE * pClientRandom; + CK_ULONG ulClientRandomLen; + CK_BYTE * pServerRandom; + CK_ULONG ulServerRandomLen; +}; + +struct CK_SSL3_KEY_MAT_PARAMS { + CK_ULONG ulMacSizeInBits; + CK_ULONG ulKeySizeInBits; + CK_ULONG ulIVSizeInBits; + CK_BBOOL bIsExport; + CK_SSL3_RANDOM_DATA RandomInfo; + CK_SSL3_KEY_MAT_OUT * pReturnedKeyMaterial; +}; + +struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS { + CK_SSL3_RANDOM_DATA RandomInfo; + CK_VERSION * pVersion; +}; + +struct CK_TLS_KDF_PARAMS { + CK_MECHANISM_TYPE prfMechanism; + CK_BYTE * pLabel; + CK_ULONG ulLabelLength; + CK_SSL3_RANDOM_DATA RandomInfo; + CK_BYTE * pContextData; + CK_ULONG ulContextDataLength; +}; + +struct CK_TLS_MAC_PARAMS { + CK_MECHANISM_TYPE prfHashMechanism; + CK_ULONG ulMacLength; + CK_ULONG ulServerOrClient; +}; + +struct CK_TLS_PRF_PARAMS { + CK_BYTE * pSeed; + CK_ULONG ulSeedLen; + CK_BYTE * pLabel; + CK_ULONG ulLabelLen; + CK_BYTE * pOutput; + CK_ULONG * pulOutputLen; +}; + +struct CK_TLS12_KEY_MAT_PARAMS { + CK_ULONG ulMacSizeInBits; + CK_ULONG ulKeySizeInBits; + CK_ULONG ulIVSizeInBits; + CK_BBOOL bIsExport; + CK_SSL3_RANDOM_DATA RandomInfo; + CK_SSL3_KEY_MAT_OUT * pReturnedKeyMaterial; + CK_MECHANISM_TYPE prfHashMechanism; +}; + +struct CK_TLS12_MASTER_KEY_DERIVE_PARAMS { + CK_SSL3_RANDOM_DATA RandomInfo; + CK_VERSION * pVersion; + CK_MECHANISM_TYPE prfHashMechanism; +}; + +struct CK_WTLS_KEY_MAT_OUT { + CK_OBJECT_HANDLE hMacSecret; + CK_OBJECT_HANDLE hKey; + CK_BYTE * pIV; +}; + +struct CK_WTLS_RANDOM_DATA { + CK_BYTE * pClientRandom; + CK_ULONG ulClientRandomLen; + CK_BYTE * pServerRandom; + CK_ULONG ulServerRandomLen; +}; + +struct CK_WTLS_KEY_MAT_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_ULONG ulMacSizeInBits; + CK_ULONG ulKeySizeInBits; + CK_ULONG ulIVSizeInBits; + CK_ULONG ulSequenceNumber; + CK_BBOOL bIsExport; + CK_WTLS_RANDOM_DATA RandomInfo; + CK_WTLS_KEY_MAT_OUT * pReturnedKeyMaterial; +}; + +struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_WTLS_RANDOM_DATA RandomInfo; + CK_BYTE * pVersion; +}; + +struct CK_WTLS_PRF_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_BYTE * pSeed; + CK_ULONG ulSeedLen; + CK_BYTE * pLabel; + CK_ULONG ulLabelLen; + CK_BYTE * pOutput; + CK_ULONG * pulOutputLen; +}; + +/* PKCS11 Functions */ +extern CK_RV C_Initialize(void *); +extern CK_RV C_Finalize(void *); +extern CK_RV C_GetInfo(CK_INFO *); +extern CK_RV C_GetFunctionList(CK_FUNCTION_LIST **); +extern CK_RV C_GetSlotList(CK_BBOOL, CK_SLOT_ID *, CK_ULONG *); +extern CK_RV C_GetSlotInfo(CK_SLOT_ID, CK_SLOT_INFO *); +extern CK_RV C_GetTokenInfo(CK_SLOT_ID, CK_TOKEN_INFO *); +extern CK_RV C_GetMechanismList(CK_SLOT_ID, CK_MECHANISM_TYPE *, CK_ULONG *); +extern CK_RV C_GetMechanismInfo(CK_SLOT_ID, CK_MECHANISM_TYPE, + CK_MECHANISM_INFO *); +extern CK_RV C_InitToken(CK_SLOT_ID, CK_UTF8CHAR *, CK_ULONG, CK_UTF8CHAR *); +extern CK_RV C_InitPIN(CK_SESSION_HANDLE, CK_UTF8CHAR *, CK_ULONG); +extern CK_RV C_SetPIN(CK_SESSION_HANDLE, CK_UTF8CHAR *, CK_ULONG, CK_UTF8CHAR *, + CK_ULONG); +extern CK_RV C_OpenSession(CK_SLOT_ID, CK_FLAGS, void *, CK_NOTIFY, + CK_SESSION_HANDLE *); +extern CK_RV C_CloseSession(CK_SESSION_HANDLE); +extern CK_RV C_CloseAllSessions(CK_SLOT_ID); +extern CK_RV C_GetSessionInfo(CK_SESSION_HANDLE, CK_SESSION_INFO *); +extern CK_RV C_GetOperationState(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_SetOperationState(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_OBJECT_HANDLE, CK_OBJECT_HANDLE); +extern CK_RV C_Login(CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR *, CK_ULONG); +extern CK_RV C_Logout(CK_SESSION_HANDLE); +extern CK_RV C_CreateObject(CK_SESSION_HANDLE, CK_ATTRIBUTE *, CK_ULONG, + CK_OBJECT_HANDLE *); +extern CK_RV C_CopyObject(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE *, + CK_ULONG, CK_OBJECT_HANDLE *); +extern CK_RV C_DestroyObject(CK_SESSION_HANDLE, CK_OBJECT_HANDLE); +extern CK_RV C_GetObjectSize(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG *); +extern CK_RV C_GetAttributeValue(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG); +extern CK_RV C_SetAttributeValue(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG); +extern CK_RV C_FindObjectsInit(CK_SESSION_HANDLE, CK_ATTRIBUTE *, CK_ULONG); +extern CK_RV C_FindObjects(CK_SESSION_HANDLE, CK_OBJECT_HANDLE *, CK_ULONG, + CK_ULONG *); +extern CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE); +extern CK_RV C_EncryptInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_Encrypt(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_EncryptUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_EncryptFinal(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_DecryptInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_Decrypt(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_DecryptUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_DecryptFinal(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_DigestInit(CK_SESSION_HANDLE, CK_MECHANISM *); +extern CK_RV C_Digest(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_DigestUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_DigestKey(CK_SESSION_HANDLE, CK_OBJECT_HANDLE); +extern CK_RV C_DigestFinal(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_SignInit(CK_SESSION_HANDLE, CK_MECHANISM *, CK_OBJECT_HANDLE); +extern CK_RV C_Sign(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_SignUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_SignFinal(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_SignRecoverInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_SignRecover(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_VerifyInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_Verify(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG); +extern CK_RV C_VerifyUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_VerifyFinal(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_VerifyRecover(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +extern CK_RV C_GenerateKey(CK_SESSION_HANDLE, CK_MECHANISM *, CK_ATTRIBUTE *, + CK_ULONG, CK_OBJECT_HANDLE *); +extern CK_RV C_GenerateKeyPair(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_ATTRIBUTE *, CK_ULONG, CK_ATTRIBUTE *, + CK_ULONG, CK_OBJECT_HANDLE *, + CK_OBJECT_HANDLE *); +extern CK_RV C_WrapKey(CK_SESSION_HANDLE, CK_MECHANISM *, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE, CK_BYTE *, CK_ULONG *); +extern CK_RV C_UnwrapKey(CK_SESSION_HANDLE, CK_MECHANISM *, CK_OBJECT_HANDLE, + CK_BYTE *, CK_ULONG *, CK_ATTRIBUTE *, CK_ULONG, + CK_OBJECT_HANDLE *); +extern CK_RV C_DeriveKey(CK_SESSION_HANDLE, CK_MECHANISM *, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG, CK_OBJECT_HANDLE *); +extern CK_RV C_SeedRandom(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_GenerateRandom(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +extern CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE); +extern CK_RV C_CancelFunction(CK_SESSION_HANDLE); +extern CK_RV C_WaitForSlotEvent(CK_FLAGS, CK_SLOT_ID *, void *); +extern CK_RV C_GetInterfaceList(CK_INTERFACE *, CK_ULONG *); +extern CK_RV C_GetInterface(CK_UTF8CHAR *, CK_VERSION *, CK_INTERFACE **, + CK_FLAGS); +extern CK_RV C_LoginUser(CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR *, + CK_ULONG, CK_UTF8CHAR *, CK_ULONG); +extern CK_RV C_SessionCancel(CK_SESSION_HANDLE, CK_FLAGS); +extern CK_RV C_MessageEncryptInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_EncryptMessage(CK_SESSION_HANDLE, void *, CK_ULONG, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_EncryptMessageBegin(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG); +extern CK_RV C_EncryptMessageNext(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG *, + CK_FLAGS); +extern CK_RV C_MessageEncryptFinal(CK_SESSION_HANDLE); +extern CK_RV C_MessageDecryptInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_DecryptMessage(CK_SESSION_HANDLE, void *, CK_ULONG, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +extern CK_RV C_DecryptMessageBegin(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG); +extern CK_RV C_DecryptMessageNext(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG *, + CK_FLAGS); +extern CK_RV C_MessageDecryptFinal(CK_SESSION_HANDLE); +extern CK_RV C_MessageSignInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_SignMessage(CK_SESSION_HANDLE, void *, CK_ULONG, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG *); +extern CK_RV C_SignMessageBegin(CK_SESSION_HANDLE, void *, CK_ULONG); +extern CK_RV C_SignMessageNext(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG *); +extern CK_RV C_MessageSignFinal(CK_SESSION_HANDLE); +extern CK_RV C_MessageVerifyInit(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +extern CK_RV C_VerifyMessage(CK_SESSION_HANDLE, void *, CK_ULONG, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG); +extern CK_RV C_VerifyMessageBegin(CK_SESSION_HANDLE, void *, CK_ULONG); +extern CK_RV C_VerifyMessageNext(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG); +extern CK_RV C_MessageVerifyFinal(CK_SESSION_HANDLE); + +typedef CK_RV (* CK_C_Initialize)(void *); +typedef CK_RV (* CK_C_Finalize)(void *); +typedef CK_RV (* CK_C_GetInfo)(CK_INFO *); +typedef CK_RV (* CK_C_GetFunctionList)(CK_FUNCTION_LIST **); +typedef CK_RV (* CK_C_GetSlotList)(CK_BBOOL, CK_SLOT_ID *, CK_ULONG *); +typedef CK_RV (* CK_C_GetSlotInfo)(CK_SLOT_ID, CK_SLOT_INFO *); +typedef CK_RV (* CK_C_GetTokenInfo)(CK_SLOT_ID, CK_TOKEN_INFO *); +typedef CK_RV (* CK_C_GetMechanismList)(CK_SLOT_ID, CK_MECHANISM_TYPE *, + CK_ULONG *); +typedef CK_RV (* CK_C_GetMechanismInfo)(CK_SLOT_ID, CK_MECHANISM_TYPE, + CK_MECHANISM_INFO *); +typedef CK_RV (* CK_C_InitToken)(CK_SLOT_ID, CK_UTF8CHAR *, CK_ULONG, + CK_UTF8CHAR *); +typedef CK_RV (* CK_C_InitPIN)(CK_SESSION_HANDLE, CK_UTF8CHAR *, CK_ULONG); +typedef CK_RV (* CK_C_SetPIN)(CK_SESSION_HANDLE, CK_UTF8CHAR *, CK_ULONG, + CK_UTF8CHAR *, CK_ULONG); +typedef CK_RV (* CK_C_OpenSession)(CK_SLOT_ID, CK_FLAGS, void *, CK_NOTIFY, + CK_SESSION_HANDLE *); +typedef CK_RV (* CK_C_CloseSession)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_CloseAllSessions)(CK_SLOT_ID); +typedef CK_RV (* CK_C_GetSessionInfo)(CK_SESSION_HANDLE, CK_SESSION_INFO *); +typedef CK_RV (* CK_C_GetOperationState)(CK_SESSION_HANDLE, CK_BYTE *, + CK_ULONG *); +typedef CK_RV (* CK_C_SetOperationState)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_OBJECT_HANDLE, CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_Login)(CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR *, + CK_ULONG); +typedef CK_RV (* CK_C_Logout)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_CreateObject)(CK_SESSION_HANDLE, CK_ATTRIBUTE *, CK_ULONG, + CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_CopyObject)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG, CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_DestroyObject)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_GetObjectSize)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ULONG *); +typedef CK_RV (* CK_C_GetAttributeValue)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG); +typedef CK_RV (* CK_C_SetAttributeValue)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_ATTRIBUTE *, CK_ULONG); +typedef CK_RV (* CK_C_FindObjectsInit)(CK_SESSION_HANDLE, CK_ATTRIBUTE *, + CK_ULONG); +typedef CK_RV (* CK_C_FindObjects)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE *, + CK_ULONG, CK_ULONG *); +typedef CK_RV (* CK_C_FindObjectsFinal)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_EncryptInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_Encrypt)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_EncryptUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_EncryptFinal)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_Decrypt)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptFinal)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DigestInit)(CK_SESSION_HANDLE, CK_MECHANISM *); +typedef CK_RV (* CK_C_Digest)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +typedef CK_RV (* CK_C_DigestUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_DigestKey)(CK_SESSION_HANDLE, CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_DigestFinal)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_SignInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_Sign)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +typedef CK_RV (* CK_C_SignUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_SignFinal)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_SignRecoverInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_SignRecover)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_VerifyInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_Verify)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG); +typedef CK_RV (* CK_C_VerifyUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_VerifyFinal)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_VerifyRecoverInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_VerifyRecover)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DigestEncryptUpdate)(CK_SESSION_HANDLE, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptDigestUpdate)(CK_SESSION_HANDLE, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_SignEncryptUpdate)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptVerifyUpdate)(CK_SESSION_HANDLE, CK_BYTE *, + CK_ULONG, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_GenerateKey)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_ATTRIBUTE *, CK_ULONG, + CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_GenerateKeyPair)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_ATTRIBUTE *, CK_ULONG, CK_ATTRIBUTE *, + CK_ULONG, CK_OBJECT_HANDLE *, + CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_WrapKey)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE *, + CK_ULONG *); +typedef CK_RV (* CK_C_UnwrapKey)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE, CK_BYTE *, CK_ULONG, + CK_ATTRIBUTE *, CK_ULONG, CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_DeriveKey)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE, CK_ATTRIBUTE *, CK_ULONG, + CK_OBJECT_HANDLE *); +typedef CK_RV (* CK_C_SeedRandom)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_GenerateRandom)(CK_SESSION_HANDLE, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_GetFunctionStatus)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_CancelFunction)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_WaitForSlotEvent)(CK_FLAGS, CK_SLOT_ID *, void *); +typedef CK_RV (* CK_C_GetInterfaceList)(CK_INTERFACE *, CK_ULONG *); +typedef CK_RV (* CK_C_GetInterface)(CK_UTF8CHAR *, CK_VERSION *, + CK_INTERFACE **, CK_FLAGS); +typedef CK_RV (* CK_C_LoginUser)(CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR *, + CK_ULONG, CK_UTF8CHAR *, CK_ULONG); +typedef CK_RV (* CK_C_SessionCancel)(CK_SESSION_HANDLE, CK_FLAGS); +typedef CK_RV (* CK_C_MessageEncryptInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_EncryptMessage)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_EncryptMessageBegin)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_EncryptMessageNext)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *, CK_FLAGS); +typedef CK_RV (* CK_C_MessageEncryptFinal)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_MessageDecryptInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_DecryptMessage)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG, + CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_DecryptMessageBegin)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_DecryptMessageNext)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *, CK_FLAGS); +typedef CK_RV (* CK_C_MessageDecryptFinal)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_MessageSignInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_SignMessage)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG *); +typedef CK_RV (* CK_C_SignMessageBegin)(CK_SESSION_HANDLE, void *, CK_ULONG); +typedef CK_RV (* CK_C_SignMessageNext)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG *); +typedef CK_RV (* CK_C_MessageSignFinal)(CK_SESSION_HANDLE); +typedef CK_RV (* CK_C_MessageVerifyInit)(CK_SESSION_HANDLE, CK_MECHANISM *, + CK_OBJECT_HANDLE); +typedef CK_RV (* CK_C_VerifyMessage)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, CK_ULONG); +typedef CK_RV (* CK_C_VerifyMessageBegin)(CK_SESSION_HANDLE, void *, CK_ULONG); +typedef CK_RV (* CK_C_VerifyMessageNext)(CK_SESSION_HANDLE, void *, CK_ULONG, + CK_BYTE *, CK_ULONG, CK_BYTE *, + CK_ULONG); +typedef CK_RV (* CK_C_MessageVerifyFinal)(CK_SESSION_HANDLE); + +struct CK_FUNCTION_LIST_3_0 { + CK_VERSION version; + CK_C_Initialize C_Initialize; + CK_C_Finalize C_Finalize; + CK_C_GetInfo C_GetInfo; + CK_C_GetFunctionList C_GetFunctionList; + CK_C_GetSlotList C_GetSlotList; + CK_C_GetSlotInfo C_GetSlotInfo; + CK_C_GetTokenInfo C_GetTokenInfo; + CK_C_GetMechanismList C_GetMechanismList; + CK_C_GetMechanismInfo C_GetMechanismInfo; + CK_C_InitToken C_InitToken; + CK_C_InitPIN C_InitPIN; + CK_C_SetPIN C_SetPIN; + CK_C_OpenSession C_OpenSession; + CK_C_CloseSession C_CloseSession; + CK_C_CloseAllSessions C_CloseAllSessions; + CK_C_GetSessionInfo C_GetSessionInfo; + CK_C_GetOperationState C_GetOperationState; + CK_C_SetOperationState C_SetOperationState; + CK_C_Login C_Login; + CK_C_Logout C_Logout; + CK_C_CreateObject C_CreateObject; + CK_C_CopyObject C_CopyObject; + CK_C_DestroyObject C_DestroyObject; + CK_C_GetObjectSize C_GetObjectSize; + CK_C_GetAttributeValue C_GetAttributeValue; + CK_C_SetAttributeValue C_SetAttributeValue; + CK_C_FindObjectsInit C_FindObjectsInit; + CK_C_FindObjects C_FindObjects; + CK_C_FindObjectsFinal C_FindObjectsFinal; + CK_C_EncryptInit C_EncryptInit; + CK_C_Encrypt C_Encrypt; + CK_C_EncryptUpdate C_EncryptUpdate; + CK_C_EncryptFinal C_EncryptFinal; + CK_C_DecryptInit C_DecryptInit; + CK_C_Decrypt C_Decrypt; + CK_C_DecryptUpdate C_DecryptUpdate; + CK_C_DecryptFinal C_DecryptFinal; + CK_C_DigestInit C_DigestInit; + CK_C_Digest C_Digest; + CK_C_DigestUpdate C_DigestUpdate; + CK_C_DigestKey C_DigestKey; + CK_C_DigestFinal C_DigestFinal; + CK_C_SignInit C_SignInit; + CK_C_Sign C_Sign; + CK_C_SignUpdate C_SignUpdate; + CK_C_SignFinal C_SignFinal; + CK_C_SignRecoverInit C_SignRecoverInit; + CK_C_SignRecover C_SignRecover; + CK_C_VerifyInit C_VerifyInit; + CK_C_Verify C_Verify; + CK_C_VerifyUpdate C_VerifyUpdate; + CK_C_VerifyFinal C_VerifyFinal; + CK_C_VerifyRecoverInit C_VerifyRecoverInit; + CK_C_VerifyRecover C_VerifyRecover; + CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; + CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; + CK_C_SignEncryptUpdate C_SignEncryptUpdate; + CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; + CK_C_GenerateKey C_GenerateKey; + CK_C_GenerateKeyPair C_GenerateKeyPair; + CK_C_WrapKey C_WrapKey; + CK_C_UnwrapKey C_UnwrapKey; + CK_C_DeriveKey C_DeriveKey; + CK_C_SeedRandom C_SeedRandom; + CK_C_GenerateRandom C_GenerateRandom; + CK_C_GetFunctionStatus C_GetFunctionStatus; + CK_C_CancelFunction C_CancelFunction; + CK_C_WaitForSlotEvent C_WaitForSlotEvent; + CK_C_GetInterfaceList C_GetInterfaceList; + CK_C_GetInterface C_GetInterface; + CK_C_LoginUser C_LoginUser; + CK_C_SessionCancel C_SessionCancel; + CK_C_MessageEncryptInit C_MessageEncryptInit; + CK_C_EncryptMessage C_EncryptMessage; + CK_C_EncryptMessageBegin C_EncryptMessageBegin; + CK_C_EncryptMessageNext C_EncryptMessageNext; + CK_C_MessageEncryptFinal C_MessageEncryptFinal; + CK_C_MessageDecryptInit C_MessageDecryptInit; + CK_C_DecryptMessage C_DecryptMessage; + CK_C_DecryptMessageBegin C_DecryptMessageBegin; + CK_C_DecryptMessageNext C_DecryptMessageNext; + CK_C_MessageDecryptFinal C_MessageDecryptFinal; + CK_C_MessageSignInit C_MessageSignInit; + CK_C_SignMessage C_SignMessage; + CK_C_SignMessageBegin C_SignMessageBegin; + CK_C_SignMessageNext C_SignMessageNext; + CK_C_MessageSignFinal C_MessageSignFinal; + CK_C_MessageVerifyInit C_MessageVerifyInit; + CK_C_VerifyMessage C_VerifyMessage; + CK_C_VerifyMessageBegin C_VerifyMessageBegin; + CK_C_VerifyMessageNext C_VerifyMessageNext; + CK_C_MessageVerifyFinal C_MessageVerifyFinal; +}; + +struct CK_FUNCTION_LIST { + CK_VERSION version; + CK_C_Initialize C_Initialize; + CK_C_Finalize C_Finalize; + CK_C_GetInfo C_GetInfo; + CK_C_GetFunctionList C_GetFunctionList; + CK_C_GetSlotList C_GetSlotList; + CK_C_GetSlotInfo C_GetSlotInfo; + CK_C_GetTokenInfo C_GetTokenInfo; + CK_C_GetMechanismList C_GetMechanismList; + CK_C_GetMechanismInfo C_GetMechanismInfo; + CK_C_InitToken C_InitToken; + CK_C_InitPIN C_InitPIN; + CK_C_SetPIN C_SetPIN; + CK_C_OpenSession C_OpenSession; + CK_C_CloseSession C_CloseSession; + CK_C_CloseAllSessions C_CloseAllSessions; + CK_C_GetSessionInfo C_GetSessionInfo; + CK_C_GetOperationState C_GetOperationState; + CK_C_SetOperationState C_SetOperationState; + CK_C_Login C_Login; + CK_C_Logout C_Logout; + CK_C_CreateObject C_CreateObject; + CK_C_CopyObject C_CopyObject; + CK_C_DestroyObject C_DestroyObject; + CK_C_GetObjectSize C_GetObjectSize; + CK_C_GetAttributeValue C_GetAttributeValue; + CK_C_SetAttributeValue C_SetAttributeValue; + CK_C_FindObjectsInit C_FindObjectsInit; + CK_C_FindObjects C_FindObjects; + CK_C_FindObjectsFinal C_FindObjectsFinal; + CK_C_EncryptInit C_EncryptInit; + CK_C_Encrypt C_Encrypt; + CK_C_EncryptUpdate C_EncryptUpdate; + CK_C_EncryptFinal C_EncryptFinal; + CK_C_DecryptInit C_DecryptInit; + CK_C_Decrypt C_Decrypt; + CK_C_DecryptUpdate C_DecryptUpdate; + CK_C_DecryptFinal C_DecryptFinal; + CK_C_DigestInit C_DigestInit; + CK_C_Digest C_Digest; + CK_C_DigestUpdate C_DigestUpdate; + CK_C_DigestKey C_DigestKey; + CK_C_DigestFinal C_DigestFinal; + CK_C_SignInit C_SignInit; + CK_C_Sign C_Sign; + CK_C_SignUpdate C_SignUpdate; + CK_C_SignFinal C_SignFinal; + CK_C_SignRecoverInit C_SignRecoverInit; + CK_C_SignRecover C_SignRecover; + CK_C_VerifyInit C_VerifyInit; + CK_C_Verify C_Verify; + CK_C_VerifyUpdate C_VerifyUpdate; + CK_C_VerifyFinal C_VerifyFinal; + CK_C_VerifyRecoverInit C_VerifyRecoverInit; + CK_C_VerifyRecover C_VerifyRecover; + CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; + CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; + CK_C_SignEncryptUpdate C_SignEncryptUpdate; + CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; + CK_C_GenerateKey C_GenerateKey; + CK_C_GenerateKeyPair C_GenerateKeyPair; + CK_C_WrapKey C_WrapKey; + CK_C_UnwrapKey C_UnwrapKey; + CK_C_DeriveKey C_DeriveKey; + CK_C_SeedRandom C_SeedRandom; + CK_C_GenerateRandom C_GenerateRandom; + CK_C_GetFunctionStatus C_GetFunctionStatus; + CK_C_CancelFunction C_CancelFunction; + CK_C_WaitForSlotEvent C_WaitForSlotEvent; +}; + + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9bec9edd799ccf877125dbcc698e8f6297a7fe83 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/CMakeLists.txt @@ -0,0 +1,26 @@ +set(MODULE_NAME "TestNCrypt") +set(MODULE_PREFIX "TEST_NCRYPT") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestNCryptSmartcard.c TestNCryptProviders.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_TESTS}) + get_filename_component(TestName ${test} NAME_WE) + add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName}) +endforeach() + +target_link_libraries(${MODULE_NAME} winpr ${OPENSSL_LIBRARIES}) +if(WIN32) + target_link_libraries(${MODULE_NAME} ncrypt) +endif() + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptProviders.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptProviders.c new file mode 100644 index 0000000000000000000000000000000000000000..e27cf90d0111525f1bb8df79a801d7f82aed873a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptProviders.c @@ -0,0 +1,51 @@ +/** + * WinPR: Windows Portable Runtime + * Test for NCrypt library + * + * Copyright 2021 David Fort + * + * 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 +#include +#include +#include +#include + +#define TAG "testNCrypt" + +int TestNCryptProviders(int argc, char* argv[]) +{ + SECURITY_STATUS status = 0; + DWORD nproviders = 0; + NCryptProviderName* providers = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + status = NCryptEnumStorageProviders(&nproviders, &providers, NCRYPT_SILENT_FLAG); + if (status != ERROR_SUCCESS) + return -1; + + for (DWORD i = 0; i < nproviders; i++) + { + const NCryptProviderName* provider = &providers[i]; + char providerNameStr[256] = { 0 }; + + (void)ConvertWCharToUtf8(provider->pszName, providerNameStr, ARRAYSIZE(providerNameStr)); + printf("%d: %s\n", i, providerNameStr); + } + + NCryptFreeBuffer(providers); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptSmartcard.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptSmartcard.c new file mode 100644 index 0000000000000000000000000000000000000000..aeeb4c2ca742759d04a1709b5e09a2302c46b549 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/ncrypt/test/TestNCryptSmartcard.c @@ -0,0 +1,164 @@ +/** + * WinPR: Windows Portable Runtime + * Test for NCrypt library + * + * Copyright 2021 David Fort + * + * 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 +#include +#include +#include +#include + +#include +#include + +#define TAG "testNCrypt" + +static void crypto_print_name(const BYTE* b, DWORD sz) +{ + if (sz > INT32_MAX) + return; + BIO* bio = BIO_new_mem_buf(b, (int)sz); + if (!bio) + return; + + X509* x509 = d2i_X509_bio(bio, NULL); + if (!x509) + goto bio_release; + + X509_NAME* name = X509_get_subject_name(x509); + if (!name) + goto x509_release; + + char* ret = calloc(1024, sizeof(char)); + if (!ret) + goto bio_release; + + char* ret2 = X509_NAME_oneline(name, ret, 1024); + + printf("\t%s\n", ret2); + free(ret); + +x509_release: + X509_free(x509); +bio_release: + BIO_free(bio); +} + +int TestNCryptSmartcard(int argc, char* argv[]) +{ + int rc = -1; + DWORD providerCount = 0; + NCryptProviderName* names = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + SECURITY_STATUS status = NCryptEnumStorageProviders(&providerCount, &names, NCRYPT_SILENT_FLAG); + if (status != ERROR_SUCCESS) + return -1; + + for (size_t j = 0; j < providerCount; j++) + { + const NCryptProviderName* name = &names[j]; + NCRYPT_PROV_HANDLE provider = 0; + char providerNameStr[256] = { 0 }; + PVOID enumState = NULL; + size_t i = 0; + NCryptKeyName* keyName = NULL; + + if (ConvertWCharToUtf8(name->pszName, providerNameStr, ARRAYSIZE(providerNameStr)) < 0) + continue; + printf("provider %" PRIuz ": %s\n", j, providerNameStr); + + status = NCryptOpenStorageProvider(&provider, name->pszName, 0); + if (status != ERROR_SUCCESS) + continue; + + while ((status = NCryptEnumKeys(provider, NULL, &keyName, &enumState, + NCRYPT_SILENT_FLAG)) == ERROR_SUCCESS) + { + NCRYPT_KEY_HANDLE phKey = 0; + DWORD dwFlags = 0; + DWORD cbOutput = 0; + char keyNameStr[256] = { 0 }; + WCHAR reader[1024] = { 0 }; + PBYTE certBytes = NULL; + + if (ConvertWCharToUtf8(keyName->pszName, keyNameStr, ARRAYSIZE(keyNameStr)) < 0) + continue; + + printf("\tkey %" PRIuz ": %s\n", i, keyNameStr); + status = NCryptOpenKey(provider, &phKey, keyName->pszName, keyName->dwLegacyKeySpec, + dwFlags); + if (status != ERROR_SUCCESS) + { + WLog_ERR(TAG, "unable to open key %s", keyNameStr); + continue; + } + + status = NCryptGetProperty(phKey, NCRYPT_READER_PROPERTY, (PBYTE)reader, sizeof(reader), + &cbOutput, dwFlags); + if (status == ERROR_SUCCESS) + { + char readerStr[1024] = { 0 }; + + (void)ConvertWCharNToUtf8(reader, cbOutput, readerStr, ARRAYSIZE(readerStr)); + printf("\treader: %s\n", readerStr); + } + + cbOutput = 0; + status = + NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, NULL, 0, &cbOutput, dwFlags); + if (status != ERROR_SUCCESS) + { + WLog_ERR(TAG, "unable to retrieve certificate len for key '%s'", keyNameStr); + goto endofloop; + } + + certBytes = calloc(1, cbOutput); + status = NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, certBytes, cbOutput, + &cbOutput, dwFlags); + if (status != ERROR_SUCCESS) + { + WLog_ERR(TAG, "unable to retrieve certificate for key %s", keyNameStr); + goto endofloop; + } + + crypto_print_name(certBytes, cbOutput); + free(certBytes); + + endofloop: + NCryptFreeBuffer(keyName); + NCryptFreeObject((NCRYPT_HANDLE)phKey); + i++; + } + + NCryptFreeBuffer(enumState); + NCryptFreeObject((NCRYPT_HANDLE)provider); + + if (status != NTE_NO_MORE_ITEMS) + { + (void)fprintf(stderr, "NCryptEnumKeys returned %s [0x%08" PRIx32 "]\n", + Win32ErrorCode2Tag(status), status); + } + } + + rc = 0; +fail: + NCryptFreeBuffer(names); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5152185a77dcf7c7a4918899c470cca8b56b7421 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/CMakeLists.txt @@ -0,0 +1,24 @@ +# WinPR: Windows Portable Runtime +# libwinpr-nt cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(nt.c ntstatus.c) + +winpr_library_add_private(${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS}) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..31ac6e78d187c53a84a0a13b957c2fc2cd8f2d2f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ModuleOptions.cmake @@ -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 "nt") +set(MINWIN_LONG_NAME "Windows Native System Services") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/nt.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/nt.c new file mode 100644 index 0000000000000000000000000000000000000000..1806901acdc46372c97cab4cdaa0a0d7b73445b7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/nt.c @@ -0,0 +1,69 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Native System Services + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2013 Thincast Technologies GmbH + * Copyright 2013 Norbert Federa + * + * 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 +#include + +#include +#include +#include +#include +#include + +#include "../log.h" +#define TAG WINPR_TAG("nt") + +#ifndef _WIN32 + +#include +#include + +#include "../handle/handle.h" + +static pthread_once_t sTebOnceControl = PTHREAD_ONCE_INIT; +static pthread_key_t sTebKey; + +static void sTebDestruct(void* teb) +{ + free(teb); +} + +static void sTebInitOnce(void) +{ + pthread_key_create(&sTebKey, sTebDestruct); +} + +PTEB NtCurrentTeb(void) +{ + PTEB teb = NULL; + + if (pthread_once(&sTebOnceControl, sTebInitOnce) == 0) + { + if ((teb = pthread_getspecific(sTebKey)) == NULL) + { + teb = calloc(1, sizeof(TEB)); + if (teb) + pthread_setspecific(sTebKey, teb); + } + } + return teb; +} +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ntstatus.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ntstatus.c new file mode 100644 index 0000000000000000000000000000000000000000..9abc42de6f985bc4f9091195e8f9aac3d111cbeb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/ntstatus.c @@ -0,0 +1,4660 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR ntstatus helper + * + * Copyright 2020 Armin Novak + * Copyright 2020 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 + +#include +#include + +struct ntstatus_map +{ + DWORD code; + const char* tag; +}; + +static const struct ntstatus_map win32errmap[] = { + { 0x00000000, "ERROR_SUCCESS" }, + { 0x00000001, "ERROR_INVALID_FUNCTION" }, + { 0x00000002, "ERROR_FILE_NOT_FOUND" }, + { 0x00000003, "ERROR_PATH_NOT_FOUND" }, + { 0x00000004, "ERROR_TOO_MANY_OPEN_FILES" }, + { 0x00000005, "ERROR_ACCESS_DENIED" }, + { 0x00000006, "ERROR_INVALID_HANDLE" }, + { 0x00000007, "ERROR_ARENA_TRASHED" }, + { 0x00000008, "ERROR_NOT_ENOUGH_MEMORY" }, + { 0x00000009, "ERROR_INVALID_BLOCK" }, + { 0x0000000A, "ERROR_BAD_ENVIRONMENT" }, + { 0x0000000B, "ERROR_BAD_FORMAT" }, + { 0x0000000C, "ERROR_INVALID_ACCESS" }, + { 0x0000000D, "ERROR_INVALID_DATA" }, + { 0x0000000E, "ERROR_OUTOFMEMORY" }, + { 0x0000000F, "ERROR_INVALID_DRIVE" }, + { 0x00000010, "ERROR_CURRENT_DIRECTORY" }, + { 0x00000011, "ERROR_NOT_SAME_DEVICE" }, + { 0x00000012, "ERROR_NO_MORE_FILES" }, + { 0x00000013, "ERROR_WRITE_PROTECT" }, + { 0x00000014, "ERROR_BAD_UNIT" }, + { 0x00000015, "ERROR_NOT_READY" }, + { 0x00000016, "ERROR_BAD_COMMAND" }, + { 0x00000017, "ERROR_CRC" }, + { 0x00000018, "ERROR_BAD_LENGTH" }, + { 0x00000019, "ERROR_SEEK" }, + { 0x0000001A, "ERROR_NOT_DOS_DISK" }, + { 0x0000001B, "ERROR_SECTOR_NOT_FOUND" }, + { 0x0000001C, "ERROR_OUT_OF_PAPER" }, + { 0x0000001D, "ERROR_WRITE_FAULT" }, + { 0x0000001E, "ERROR_READ_FAULT" }, + { 0x0000001F, "ERROR_GEN_FAILURE" }, + { 0x00000020, "ERROR_SHARING_VIOLATION" }, + { 0x00000021, "ERROR_LOCK_VIOLATION" }, + { 0x00000022, "ERROR_WRONG_DISK" }, + { 0x00000024, "ERROR_SHARING_BUFFER_EXCEEDED" }, + { 0x00000026, "ERROR_HANDLE_EOF" }, + { 0x00000027, "ERROR_HANDLE_DISK_FULL" }, + { 0x00000032, "ERROR_NOT_SUPPORTED" }, + { 0x00000033, "ERROR_REM_NOT_LIST" }, + { 0x00000034, "ERROR_DUP_NAME" }, + { 0x00000035, "ERROR_BAD_NETPATH" }, + { 0x00000036, "ERROR_NETWORK_BUSY" }, + { 0x00000037, "ERROR_DEV_NOT_EXIST" }, + { 0x00000038, "ERROR_TOO_MANY_CMDS" }, + { 0x00000039, "ERROR_ADAP_HDW_ERR" }, + { 0x0000003A, "ERROR_BAD_NET_RESP" }, + { 0x0000003B, "ERROR_UNEXP_NET_ERR" }, + { 0x0000003C, "ERROR_BAD_REM_ADAP" }, + { 0x0000003D, "ERROR_PRINTQ_FULL" }, + { 0x0000003E, "ERROR_NO_SPOOL_SPACE" }, + { 0x0000003F, "ERROR_PRINT_CANCELLED" }, + { 0x00000040, "ERROR_NETNAME_DELETED" }, + { 0x00000041, "ERROR_NETWORK_ACCESS_DENIED" }, + { 0x00000042, "ERROR_BAD_DEV_TYPE" }, + { 0x00000043, "ERROR_BAD_NET_NAME" }, + { 0x00000044, "ERROR_TOO_MANY_NAMES" }, + { 0x00000045, "ERROR_TOO_MANY_SESS" }, + { 0x00000046, "ERROR_SHARING_PAUSED" }, + { 0x00000047, "ERROR_REQ_NOT_ACCEP" }, + { 0x00000048, "ERROR_REDIR_PAUSED" }, + { 0x00000050, "ERROR_FILE_EXISTS" }, + { 0x00000052, "ERROR_CANNOT_MAKE" }, + { 0x00000053, "ERROR_FAIL_I24" }, + { 0x00000054, "ERROR_OUT_OF_STRUCTURES" }, + { 0x00000055, "ERROR_ALREADY_ASSIGNED" }, + { 0x00000056, "ERROR_INVALID_PASSWORD" }, + { 0x00000057, "ERROR_INVALID_PARAMETER" }, + { 0x00000058, "ERROR_NET_WRITE_FAULT" }, + { 0x00000059, "ERROR_NO_PROC_SLOTS" }, + { 0x00000064, "ERROR_TOO_MANY_SEMAPHORES" }, + { 0x00000065, "ERROR_EXCL_SEM_ALREADY_OWNED" }, + { 0x00000066, "ERROR_SEM_IS_SET" }, + { 0x00000067, "ERROR_TOO_MANY_SEM_REQUESTS" }, + { 0x00000068, "ERROR_INVALID_AT_INTERRUPT_TIME" }, + { 0x00000069, "ERROR_SEM_OWNER_DIED" }, + { 0x0000006A, "ERROR_SEM_USER_LIMIT" }, + { 0x0000006B, "ERROR_DISK_CHANGE" }, + { 0x0000006C, "ERROR_DRIVE_LOCKED" }, + { 0x0000006D, "ERROR_BROKEN_PIPE" }, + { 0x0000006E, "ERROR_OPEN_FAILED" }, + { 0x0000006F, "ERROR_BUFFER_OVERFLOW" }, + { 0x00000070, "ERROR_DISK_FULL" }, + { 0x00000071, "ERROR_NO_MORE_SEARCH_HANDLES" }, + { 0x00000072, "ERROR_INVALID_TARGET_HANDLE" }, + { 0x00000075, "ERROR_INVALID_CATEGORY" }, + { 0x00000076, "ERROR_INVALID_VERIFY_SWITCH" }, + { 0x00000077, "ERROR_BAD_DRIVER_LEVEL" }, + { 0x00000078, "ERROR_CALL_NOT_IMPLEMENTED" }, + { 0x00000079, "ERROR_SEM_TIMEOUT" }, + { 0x0000007A, "ERROR_INSUFFICIENT_BUFFER" }, + { 0x0000007B, "ERROR_INVALID_NAME" }, + { 0x0000007C, "ERROR_INVALID_LEVEL" }, + { 0x0000007D, "ERROR_NO_VOLUME_LABEL" }, + { 0x0000007E, "ERROR_MOD_NOT_FOUND" }, + { 0x0000007F, "ERROR_PROC_NOT_FOUND" }, + { 0x00000080, "ERROR_WAIT_NO_CHILDREN" }, + { 0x00000081, "ERROR_CHILD_NOT_COMPLETE" }, + { 0x00000082, "ERROR_DIRECT_ACCESS_HANDLE" }, + { 0x00000083, "ERROR_NEGATIVE_SEEK" }, + { 0x00000084, "ERROR_SEEK_ON_DEVICE" }, + { 0x00000085, "ERROR_IS_JOIN_TARGET" }, + { 0x00000086, "ERROR_IS_JOINED" }, + { 0x00000087, "ERROR_IS_SUBSTED" }, + { 0x00000088, "ERROR_NOT_JOINED" }, + { 0x00000089, "ERROR_NOT_SUBSTED" }, + { 0x0000008A, "ERROR_JOIN_TO_JOIN" }, + { 0x0000008B, "ERROR_SUBST_TO_SUBST" }, + { 0x0000008C, "ERROR_JOIN_TO_SUBST" }, + { 0x0000008D, "ERROR_SUBST_TO_JOIN" }, + { 0x0000008E, "ERROR_BUSY_DRIVE" }, + { 0x0000008F, "ERROR_SAME_DRIVE" }, + { 0x00000090, "ERROR_DIR_NOT_ROOT" }, + { 0x00000091, "ERROR_DIR_NOT_EMPTY" }, + { 0x00000092, "ERROR_IS_SUBST_PATH" }, + { 0x00000093, "ERROR_IS_JOIN_PATH" }, + { 0x00000094, "ERROR_PATH_BUSY" }, + { 0x00000095, "ERROR_IS_SUBST_TARGET" }, + { 0x00000096, "ERROR_SYSTEM_TRACE" }, + { 0x00000097, "ERROR_INVALID_EVENT_COUNT" }, + { 0x00000098, "ERROR_TOO_MANY_MUXWAITERS" }, + { 0x00000099, "ERROR_INVALID_LIST_FORMAT" }, + { 0x0000009A, "ERROR_LABEL_TOO_LONG" }, + { 0x0000009B, "ERROR_TOO_MANY_TCBS" }, + { 0x0000009C, "ERROR_SIGNAL_REFUSED" }, + { 0x0000009D, "ERROR_DISCARDED" }, + { 0x0000009E, "ERROR_NOT_LOCKED" }, + { 0x0000009F, "ERROR_BAD_THREADID_ADDR" }, + { 0x000000A0, "ERROR_BAD_ARGUMENTS" }, + { 0x000000A1, "ERROR_BAD_PATHNAME" }, + { 0x000000A2, "ERROR_SIGNAL_PENDING" }, + { 0x000000A4, "ERROR_MAX_THRDS_REACHED" }, + { 0x000000A7, "ERROR_LOCK_FAILED" }, + { 0x000000AA, "ERROR_BUSY" }, + { 0x000000AD, "ERROR_CANCEL_VIOLATION" }, + { 0x000000AE, "ERROR_ATOMIC_LOCKS_NOT_SUPPORTED" }, + { 0x000000B4, "ERROR_INVALID_SEGMENT_NUMBER" }, + { 0x000000B6, "ERROR_INVALID_ORDINAL" }, + { 0x000000B7, "ERROR_ALREADY_EXISTS" }, + { 0x000000BA, "ERROR_INVALID_FLAG_NUMBER" }, + { 0x000000BB, "ERROR_SEM_NOT_FOUND" }, + { 0x000000BC, "ERROR_INVALID_STARTING_CODESEG" }, + { 0x000000BD, "ERROR_INVALID_STACKSEG" }, + { 0x000000BE, "ERROR_INVALID_MODULETYPE" }, + { 0x000000BF, "ERROR_INVALID_EXE_SIGNATURE" }, + { 0x000000C0, "ERROR_EXE_MARKED_INVALID" }, + { 0x000000C1, "ERROR_BAD_EXE_FORMAT" }, + { 0x000000C2, "ERROR_ITERATED_DATA_EXCEEDS_64k" }, + { 0x000000C3, "ERROR_INVALID_MINALLOCSIZE" }, + { 0x000000C4, "ERROR_DYNLINK_FROM_INVALID_RING" }, + { 0x000000C5, "ERROR_IOPL_NOT_ENABLED" }, + { 0x000000C6, "ERROR_INVALID_SEGDPL" }, + { 0x000000C7, "ERROR_AUTODATASEG_EXCEEDS_64k" }, + { 0x000000C8, "ERROR_RING2SEG_MUST_BE_MOVABLE" }, + { 0x000000C9, "ERROR_RELOC_CHAIN_XEEDS_SEGLIM" }, + { 0x000000CA, "ERROR_INFLOOP_IN_RELOC_CHAIN" }, + { 0x000000CB, "ERROR_ENVVAR_NOT_FOUND" }, + { 0x000000CD, "ERROR_NO_SIGNAL_SENT" }, + { 0x000000CE, "ERROR_FILENAME_EXCED_RANGE" }, + { 0x000000CF, "ERROR_RING2_STACK_IN_USE" }, + { 0x000000D0, "ERROR_META_EXPANSION_TOO_LONG" }, + { 0x000000D1, "ERROR_INVALID_SIGNAL_NUMBER" }, + { 0x000000D2, "ERROR_THREAD_1_INACTIVE" }, + { 0x000000D4, "ERROR_LOCKED" }, + { 0x000000D6, "ERROR_TOO_MANY_MODULES" }, + { 0x000000D7, "ERROR_NESTING_NOT_ALLOWED" }, + { 0x000000D8, "ERROR_EXE_MACHINE_TYPE_MISMATCH" }, + { 0x000000D9, "ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY" }, + { 0x000000DA, "ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY" }, + { 0x000000DC, "ERROR_FILE_CHECKED_OUT" }, + { 0x000000DD, "ERROR_CHECKOUT_REQUIRED" }, + { 0x000000DE, "ERROR_BAD_FILE_TYPE" }, + { 0x000000DF, "ERROR_FILE_TOO_LARGE" }, + { 0x000000E0, "ERROR_FORMS_AUTH_REQUIRED" }, + { 0x000000E1, "ERROR_VIRUS_INFECTED" }, + { 0x000000E2, "ERROR_VIRUS_DELETED" }, + { 0x000000E5, "ERROR_PIPE_LOCAL" }, + { 0x000000E6, "ERROR_BAD_PIPE" }, + { 0x000000E7, "ERROR_PIPE_BUSY" }, + { 0x000000E8, "ERROR_NO_DATA" }, + { 0x000000E9, "ERROR_PIPE_NOT_CONNECTED" }, + { 0x000000EA, "ERROR_MORE_DATA" }, + { 0x000000F0, "ERROR_VC_DISCONNECTED" }, + { 0x000000FE, "ERROR_INVALID_EA_NAME" }, + { 0x000000FF, "ERROR_EA_LIST_INCONSISTENT" }, + { 0x00000102, "WAIT_TIMEOUT" }, + { 0x00000103, "ERROR_NO_MORE_ITEMS" }, + { 0x0000010A, "ERROR_CANNOT_COPY" }, + { 0x0000010B, "ERROR_DIRECTORY" }, + { 0x00000113, "ERROR_EAS_DIDNT_FIT" }, + { 0x00000114, "ERROR_EA_FILE_CORRUPT" }, + { 0x00000115, "ERROR_EA_TABLE_FULL" }, + { 0x00000116, "ERROR_INVALID_EA_HANDLE" }, + { 0x0000011A, "ERROR_EAS_NOT_SUPPORTED" }, + { 0x00000120, "ERROR_NOT_OWNER" }, + { 0x0000012A, "ERROR_TOO_MANY_POSTS" }, + { 0x0000012B, "ERROR_PARTIAL_COPY" }, + { 0x0000012C, "ERROR_OPLOCK_NOT_GRANTED" }, + { 0x0000012D, "ERROR_INVALID_OPLOCK_PROTOCOL" }, + { 0x0000012E, "ERROR_DISK_TOO_FRAGMENTED" }, + { 0x0000012F, "ERROR_DELETE_PENDING" }, + { 0x0000013D, "ERROR_MR_MID_NOT_FOUND" }, + { 0x0000013E, "ERROR_SCOPE_NOT_FOUND" }, + { 0x0000015E, "ERROR_FAIL_NOACTION_REBOOT" }, + { 0x0000015F, "ERROR_FAIL_SHUTDOWN" }, + { 0x00000160, "ERROR_FAIL_RESTART" }, + { 0x00000161, "ERROR_MAX_SESSIONS_REACHED" }, + { 0x00000190, "ERROR_THREAD_MODE_ALREADY_BACKGROUND" }, + { 0x00000191, "ERROR_THREAD_MODE_NOT_BACKGROUND" }, + { 0x00000192, "ERROR_PROCESS_MODE_ALREADY_BACKGROUND" }, + { 0x00000193, "ERROR_PROCESS_MODE_NOT_BACKGROUND" }, + { 0x000001E7, "ERROR_INVALID_ADDRESS" }, + { 0x000001F4, "ERROR_USER_PROFILE_LOAD" }, + { 0x00000216, "ERROR_ARITHMETIC_OVERFLOW" }, + { 0x00000217, "ERROR_PIPE_CONNECTED" }, + { 0x00000218, "ERROR_PIPE_LISTENING" }, + { 0x00000219, "ERROR_VERIFIER_STOP" }, + { 0x0000021A, "ERROR_ABIOS_ERROR" }, + { 0x0000021B, "ERROR_WX86_WARNING" }, + { 0x0000021C, "ERROR_WX86_ERROR" }, + { 0x0000021D, "ERROR_TIMER_NOT_CANCELED" }, + { 0x0000021E, "ERROR_UNWIND" }, + { 0x0000021F, "ERROR_BAD_STACK" }, + { 0x00000220, "ERROR_INVALID_UNWIND_TARGET" }, + { 0x00000221, "ERROR_INVALID_PORT_ATTRIBUTES" }, + { 0x00000222, "ERROR_PORT_MESSAGE_TOO_LONG" }, + { 0x00000223, "ERROR_INVALID_QUOTA_LOWER" }, + { 0x00000224, "ERROR_DEVICE_ALREADY_ATTACHED" }, + { 0x00000225, "ERROR_INSTRUCTION_MISALIGNMENT" }, + { 0x00000226, "ERROR_PROFILING_NOT_STARTED" }, + { 0x00000227, "ERROR_PROFILING_NOT_STOPPED" }, + { 0x00000228, "ERROR_COULD_NOT_INTERPRET" }, + { 0x00000229, "ERROR_PROFILING_AT_LIMIT" }, + { 0x0000022A, "ERROR_CANT_WAIT" }, + { 0x0000022B, "ERROR_CANT_TERMINATE_SELF" }, + { 0x0000022C, "ERROR_UNEXPECTED_MM_CREATE_ERR" }, + { 0x0000022D, "ERROR_UNEXPECTED_MM_MAP_ERROR" }, + { 0x0000022E, "ERROR_UNEXPECTED_MM_EXTEND_ERR" }, + { 0x0000022F, "ERROR_BAD_FUNCTION_TABLE" }, + { 0x00000230, "ERROR_NO_GUID_TRANSLATION" }, + { 0x00000231, "ERROR_INVALID_LDT_SIZE" }, + { 0x00000233, "ERROR_INVALID_LDT_OFFSET" }, + { 0x00000234, "ERROR_INVALID_LDT_DESCRIPTOR" }, + { 0x00000235, "ERROR_TOO_MANY_THREADS" }, + { 0x00000236, "ERROR_THREAD_NOT_IN_PROCESS" }, + { 0x00000237, "ERROR_PAGEFILE_QUOTA_EXCEEDED" }, + { 0x00000238, "ERROR_LOGON_SERVER_CONFLICT" }, + { 0x00000239, "ERROR_SYNCHRONIZATION_REQUIRED" }, + { 0x0000023A, "ERROR_NET_OPEN_FAILED" }, + { 0x0000023B, "ERROR_IO_PRIVILEGE_FAILED" }, + { 0x0000023C, "ERROR_CONTROL_C_EXIT" }, + { 0x0000023D, "ERROR_MISSING_SYSTEMFILE" }, + { 0x0000023E, "ERROR_UNHANDLED_EXCEPTION" }, + { 0x0000023F, "ERROR_APP_INIT_FAILURE" + "properly (,{0x%lx). Click OK to terminate the application." }, + { 0x00000240, "ERROR_PAGEFILE_CREATE_FAILED" }, + { 0x00000241, "ERROR_INVALID_IMAGE_HASH" }, + { 0x00000242, "ERROR_NO_PAGEFILE" }, + { 0x00000243, "ERROR_ILLEGAL_FLOAT_CONTEXT" }, + { 0x00000244, "ERROR_NO_EVENT_PAIR" }, + { 0x00000245, "ERROR_DOMAIN_CTRLR_CONFIG_ERROR" }, + { 0x00000246, "ERROR_ILLEGAL_CHARACTER" }, + { 0x00000247, "ERROR_UNDEFINED_CHARACTER" }, + { 0x00000248, "ERROR_FLOPPY_VOLUME" }, + { 0x00000249, "ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT" }, + { 0x0000024A, "ERROR_BACKUP_CONTROLLER" }, + { 0x0000024B, "ERROR_MUTANT_LIMIT_EXCEEDED" }, + { 0x0000024C, "ERROR_FS_DRIVER_REQUIRED" }, + { 0x0000024D, "ERROR_CANNOT_LOAD_REGISTRY_FILE" }, + { 0x0000024E, "ERROR_DEBUG_ATTACH_FAILED" + + }, + { 0x0000024F, "ERROR_SYSTEM_PROCESS_TERMINATED" + "terminated unexpectedly with a status of ,{0x%08x (,{0x%08x ,{0x%08x). The " }, + { 0x00000250, "ERROR_DATA_NOT_ACCEPTED" }, + { 0x00000251, "ERROR_VDM_HARD_ERROR" }, + { 0x00000252, "ERROR_DRIVER_CANCEL_TIMEOUT" }, + { 0x00000253, "ERROR_REPLY_MESSAGE_MISMATCH" + + }, + { 0x00000254, "ERROR_LOST_WRITEBEHIND_DATA" + + }, + { 0x00000255, "ERROR_CLIENT_SERVER_PARAMETERS_INVALID" }, + { 0x00000256, "ERROR_NOT_TINY_STREAM" }, + { 0x00000257, "ERROR_STACK_OVERFLOW_READ" }, + { 0x00000258, "ERROR_CONVERT_TO_LARGE" }, + { 0x00000259, "ERROR_FOUND_OUT_OF_SCOPE" }, + { 0x0000025A, "ERROR_ALLOCATE_BUCKET" }, + { 0x0000025B, "ERROR_MARSHALL_OVERFLOW" }, + { 0x0000025C, "ERROR_INVALID_VARIANT" }, + { 0x0000025D, "ERROR_BAD_COMPRESSION_BUFFER" }, + { 0x0000025E, "ERROR_AUDIT_FAILED" }, + { 0x0000025F, "ERROR_TIMER_RESOLUTION_NOT_SET" }, + { 0x00000260, "ERROR_INSUFFICIENT_LOGON_INFO" }, + { 0x00000261, "ERROR_BAD_DLL_ENTRYPOINT" + + }, + { 0x00000262, "ERROR_BAD_SERVICE_ENTRYPOINT" + + }, + { 0x00000263, "ERROR_IP_ADDRESS_CONFLICT1" }, + { 0x00000264, "ERROR_IP_ADDRESS_CONFLICT2" }, + { 0x00000265, "ERROR_REGISTRY_QUOTA_LIMIT" }, + { 0x00000266, "ERROR_NO_CALLBACK_ACTIVE" }, + { 0x00000267, "ERROR_PWD_TOO_SHORT" }, + { 0x00000268, "ERROR_PWD_TOO_RECENT" }, + { 0x00000269, "ERROR_PWD_HISTORY_CONFLICT" }, + { 0x0000026A, "ERROR_UNSUPPORTED_COMPRESSION" }, + { 0x0000026B, "ERROR_INVALID_HW_PROFILE" }, + { 0x0000026C, "ERROR_INVALID_PLUGPLAY_DEVICE_PATH" }, + { 0x0000026D, "ERROR_QUOTA_LIST_INCONSISTENT" }, + { 0x0000026E, "ERROR_EVALUATION_EXPIRATION" + + "in 1 hour. To restore access to this installation of Windows, upgrade this " }, + { 0x0000026F, "ERROR_ILLEGAL_DLL_RELOCATION" + + }, + { 0x00000270, "ERROR_DLL_INIT_FAILED_LOGOFF" }, + { 0x00000271, "ERROR_VALIDATE_CONTINUE" }, + { 0x00000272, "ERROR_NO_MORE_MATCHES" }, + { 0x00000273, "ERROR_RANGE_LIST_CONFLICT" }, + { 0x00000274, "ERROR_SERVER_SID_MISMATCH" }, + { 0x00000275, "ERROR_CANT_ENABLE_DENY_ONLY" }, + { 0x00000276, "ERROR_FLOAT_MULTIPLE_FAULTS" }, + { 0x00000277, "ERROR_FLOAT_MULTIPLE_TRAPS" }, + { 0x00000278, "ERROR_NOINTERFACE" }, + { 0x00000279, "ERROR_DRIVER_FAILED_SLEEP" }, + { 0x0000027A, "ERROR_CORRUPT_SYSTEM_FILE" }, + { 0x0000027B, "ERROR_COMMITMENT_MINIMUM" + + }, + { 0x0000027C, "ERROR_PNP_RESTART_ENUMERATION" }, + { 0x0000027D, "ERROR_SYSTEM_IMAGE_BAD_SIGNATURE" }, + { 0x0000027E, "ERROR_PNP_REBOOT_REQUIRED" }, + { 0x0000027F, "ERROR_INSUFFICIENT_POWER" }, + { 0x00000281, "ERROR_SYSTEM_SHUTDOWN" }, + { 0x00000282, "ERROR_PORT_NOT_SET" }, + { 0x00000283, "ERROR_DS_VERSION_CHECK_FAILURE" }, + { 0x00000284, "ERROR_RANGE_NOT_FOUND" }, + { 0x00000286, "ERROR_NOT_SAFE_MODE_DRIVER" }, + { 0x00000287, "ERROR_FAILED_DRIVER_ENTRY" }, + { 0x00000288, "ERROR_DEVICE_ENUMERATION_ERROR" }, + { 0x00000289, "ERROR_MOUNT_POINT_NOT_RESOLVED" }, + { 0x0000028A, "ERROR_INVALID_DEVICE_OBJECT_PARAMETER" }, + { 0x0000028B, "ERROR_MCA_OCCURED" }, + { 0x0000028C, "ERROR_DRIVER_DATABASE_ERROR" }, + { 0x0000028D, "ERROR_SYSTEM_HIVE_TOO_LARGE" }, + { 0x0000028E, "ERROR_DRIVER_FAILED_PRIOR_UNLOAD" }, + { 0x0000028F, "ERROR_VOLSNAP_PREPARE_HIBERNATE" }, + { 0x00000290, "ERROR_HIBERNATION_FAILURE" }, + { 0x00000299, "ERROR_FILE_SYSTEM_LIMITATION" }, + { 0x0000029C, "ERROR_ASSERTION_FAILURE" }, + { 0x0000029D, "ERROR_ACPI_ERROR" }, + { 0x0000029E, "ERROR_WOW_ASSERTION" }, + { 0x0000029F, "ERROR_PNP_BAD_MPS_TABLE" }, + { 0x000002A0, "ERROR_PNP_TRANSLATION_FAILED" }, + { 0x000002A1, "ERROR_PNP_IRQ_TRANSLATION_FAILED" }, + { 0x000002A2, "ERROR_PNP_INVALID_ID" }, + { 0x000002A3, "ERROR_WAKE_SYSTEM_DEBUGGER" }, + { 0x000002A4, "ERROR_HANDLES_CLOSED" }, + { 0x000002A5, "ERROR_EXTRANEOUS_INFORMATION" }, + { 0x000002A6, "ERROR_RXACT_COMMIT_NECESSARY" }, + { 0x000002A7, "ERROR_MEDIA_CHECK" }, + { 0x000002A8, "ERROR_GUID_SUBSTITUTION_MADE" + + }, + { 0x000002A9, "ERROR_STOPPED_ON_SYMLINK" }, + { 0x000002AA, "ERROR_LONGJUMP" }, + { 0x000002AB, "ERROR_PLUGPLAY_QUERY_VETOED" }, + { 0x000002AC, "ERROR_UNWIND_CONSOLIDATE" }, + { 0x000002AD, "ERROR_REGISTRY_HIVE_RECOVERED" }, + { 0x000002AE, "ERROR_DLL_MIGHT_BE_INSECURE" }, + { 0x000002AF, "ERROR_DLL_MIGHT_BE_INCOMPATIBLE" + + }, + { 0x000002B0, "ERROR_DBG_EXCEPTION_NOT_HANDLED" }, + { 0x000002B1, "ERROR_DBG_REPLY_LATER" }, + { 0x000002B2, "ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE" }, + { 0x000002B3, "ERROR_DBG_TERMINATE_THREAD" }, + { 0x000002B4, "ERROR_DBG_TERMINATE_PROCESS" }, + { 0x000002B5, "ERROR_DBG_CONTROL_C" }, + { 0x000002B6, "ERROR_DBG_PRINTEXCEPTION_C" }, + { 0x000002B7, "ERROR_DBG_RIPEXCEPTION" }, + { 0x000002B8, "ERROR_DBG_CONTROL_BREAK" }, + { 0x000002B9, "ERROR_DBG_COMMAND_EXCEPTION" }, + { 0x000002BA, "ERROR_OBJECT_NAME_EXISTS" }, + { 0x000002BB, "ERROR_THREAD_WAS_SUSPENDED" }, + { 0x000002BC, "ERROR_IMAGE_NOT_AT_BASE" }, + { 0x000002BD, "ERROR_RXACT_STATE_CREATED" }, + { 0x000002BE, + "ERROR_SEGMENT_NOTIFICATION" + "or moving an MS-DOS or Win16 program segment image. An exception is raised so a debugger " }, + { 0x000002BF, "ERROR_BAD_CURRENT_DIRECTORY" + + }, + { 0x000002C0, "ERROR_FT_READ_RECOVERY_FROM_BACKUP" + + }, + { 0x000002C1, "ERROR_FT_WRITE_RECOVERY" + + }, + { 0x000002C2, "ERROR_IMAGE_MACHINE_TYPE_MISMATCH" + + }, + { 0x000002C3, "ERROR_RECEIVE_PARTIAL" }, + { 0x000002C4, "ERROR_RECEIVE_EXPEDITED" }, + { 0x000002C5, "ERROR_RECEIVE_PARTIAL_EXPEDITED" + + }, + { 0x000002C6, "ERROR_EVENT_DONE" }, + { 0x000002C7, "ERROR_EVENT_PENDING" }, + { 0x000002C8, "ERROR_CHECKING_FILE_SYSTEM" }, + { 0x000002C9, "ERROR_FATAL_APP_EXIT" }, + { 0x000002CA, "ERROR_PREDEFINED_HANDLE" }, + { 0x000002CB, "ERROR_WAS_UNLOCKED" }, + { 0x000002CD, "ERROR_WAS_LOCKED" }, + { 0x000002CF, "ERROR_ALREADY_WIN32" }, + { 0x000002D0, "ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE" }, + { 0x000002D1, "ERROR_NO_YIELD_PERFORMED" }, + { 0x000002D2, "ERROR_TIMER_RESUME_IGNORED" }, + { 0x000002D3, "ERROR_ARBITRATION_UNHANDLED" }, + { 0x000002D4, "ERROR_CARDBUS_NOT_SUPPORTED" }, + { 0x000002D5, "ERROR_MP_PROCESSOR_MISMATCH" }, + { 0x000002D6, "ERROR_HIBERNATED" }, + { 0x000002D7, "ERROR_RESUME_HIBERNATION" }, + { 0x000002D8, "ERROR_FIRMWARE_UPDATED" }, + { 0x000002D9, "ERROR_DRIVERS_LEAKING_LOCKED_PAGES" }, + { 0x000002DA, "ERROR_WAKE_SYSTEM" }, + { 0x000002DF, "ERROR_ABANDONED_WAIT_0" }, + { 0x000002E4, "ERROR_ELEVATION_REQUIRED" }, + { 0x000002E5, "ERROR_REPARSE" }, + { 0x000002E6, "ERROR_OPLOCK_BREAK_IN_PROGRESS" }, + { 0x000002E7, "ERROR_VOLUME_MOUNTED" }, + { 0x000002E8, "ERROR_RXACT_COMMITTED" }, + { 0x000002E9, "ERROR_NOTIFY_CLEANUP" }, + { 0x000002EA, "ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED" + + }, + { 0x000002EB, "ERROR_PAGE_FAULT_TRANSITION" }, + { 0x000002EC, "ERROR_PAGE_FAULT_DEMAND_ZERO" }, + { 0x000002ED, "ERROR_PAGE_FAULT_COPY_ON_WRITE" }, + { 0x000002EE, "ERROR_PAGE_FAULT_GUARD_PAGE" }, + { 0x000002EF, "ERROR_PAGE_FAULT_PAGING_FILE" }, + { 0x000002F0, "ERROR_CACHE_PAGE_LOCKED" }, + { 0x000002F1, "ERROR_CRASH_DUMP" }, + { 0x000002F2, "ERROR_BUFFER_ALL_ZEROS" }, + { 0x000002F3, "ERROR_REPARSE_OBJECT" }, + { 0x000002F4, "ERROR_RESOURCE_REQUIREMENTS_CHANGED" }, + { 0x000002F5, "ERROR_TRANSLATION_COMPLETE" }, + { 0x000002F6, "ERROR_NOTHING_TO_TERMINATE" }, + { 0x000002F7, "ERROR_PROCESS_NOT_IN_JOB" }, + { 0x000002F8, "ERROR_PROCESS_IN_JOB" }, + { 0x000002F9, "ERROR_VOLSNAP_HIBERNATE_READY" }, + { 0x000002FA, "ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY" }, + { 0x000002FB, "ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED" }, + { 0x000002FC, "ERROR_INTERRUPT_STILL_CONNECTED" }, + { 0x000002FD, "ERROR_WAIT_FOR_OPLOCK" }, + { 0x000002FE, "ERROR_DBG_EXCEPTION_HANDLED" }, + { 0x000002FF, "ERROR_DBG_CONTINUE" }, + { 0x00000300, "ERROR_CALLBACK_POP_STACK" }, + { 0x00000301, "ERROR_COMPRESSION_DISABLED" }, + { 0x00000302, "ERROR_CANTFETCHBACKWARDS" }, + { 0x00000303, "ERROR_CANTSCROLLBACKWARDS" }, + { 0x00000304, "ERROR_ROWSNOTRELEASED" }, + { 0x00000305, "ERROR_BAD_ACCESSOR_FLAGS" }, + { 0x00000306, "ERROR_ERRORS_ENCOUNTERED" }, + { 0x00000307, "ERROR_NOT_CAPABLE" }, + { 0x00000308, "ERROR_REQUEST_OUT_OF_SEQUENCE" }, + { 0x00000309, "ERROR_VERSION_PARSE_ERROR" }, + { 0x0000030A, "ERROR_BADSTARTPOSITION" }, + { 0x0000030B, "ERROR_MEMORY_HARDWARE" }, + { 0x0000030C, "ERROR_DISK_REPAIR_DISABLED" }, + { 0x0000030D, "ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE" }, + { 0x0000030E, "ERROR_SYSTEM_POWERSTATE_TRANSITION" }, + { 0x0000030F, "ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION" }, + { 0x00000310, "ERROR_MCA_EXCEPTION" }, + { 0x00000311, "ERROR_ACCESS_AUDIT_BY_POLICY" }, + { 0x00000312, "ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY" }, + { 0x00000313, "ERROR_ABANDON_HIBERFILE" }, + { 0x00000314, "ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED" + + }, + { 0x00000315, "ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR" + + }, + { 0x00000316, "ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR" + + }, + { 0x000003E2, "ERROR_EA_ACCESS_DENIED" }, + { 0x000003E3, "ERROR_OPERATION_ABORTED" }, + { 0x000003E4, "ERROR_IO_INCOMPLETE" }, + { 0x000003E5, "ERROR_IO_PENDING" }, + { 0x000003E6, "ERROR_NOACCESS" }, + { 0x000003E7, "ERROR_SWAPERROR" }, + { 0x000003E9, "ERROR_STACK_OVERFLOW" }, + { 0x000003EA, "ERROR_INVALID_MESSAGE" }, + { 0x000003EB, "ERROR_CAN_NOT_COMPLETE" }, + { 0x000003EC, "ERROR_INVALID_FLAGS" }, + { 0x000003ED, "ERROR_UNRECOGNIZED_VOLUME" }, + { 0x000003EE, "ERROR_FILE_INVALID" }, + { 0x000003EF, "ERROR_FULLSCREEN_MODE" }, + { 0x000003F0, "ERROR_NO_TOKEN" }, + { 0x000003F1, "ERROR_BADDB" }, + { 0x000003F2, "ERROR_BADKEY" }, + { 0x000003F3, "ERROR_CANTOPEN" }, + { 0x000003F4, "ERROR_CANTREAD" }, + { 0x000003F5, "ERROR_CANTWRITE" }, + { 0x000003F6, "ERROR_REGISTRY_RECOVERED" }, + { 0x000003F7, "ERROR_REGISTRY_CORRUPT" }, + { 0x000003F8, "ERROR_REGISTRY_IO_FAILED" }, + { 0x000003F9, "ERROR_NOT_REGISTRY_FILE" }, + { 0x000003FA, "ERROR_KEY_DELETED" }, + { 0x000003FB, "ERROR_NO_LOG_SPACE" }, + { 0x000003FC, "ERROR_KEY_HAS_CHILDREN" }, + { 0x000003FD, "ERROR_CHILD_MUST_BE_VOLATILE" }, + { 0x000003FE, "ERROR_NOTIFY_ENUM_DIR" }, + { 0x0000041B, "ERROR_DEPENDENT_SERVICES_RUNNING" }, + { 0x0000041C, "ERROR_INVALID_SERVICE_CONTROL" }, + { 0x0000041D, "ERROR_SERVICE_REQUEST_TIMEOUT" }, + { 0x0000041E, "ERROR_SERVICE_NO_THREAD" }, + { 0x0000041F, "ERROR_SERVICE_DATABASE_LOCKED" }, + { 0x00000420, "ERROR_SERVICE_ALREADY_RUNNING" }, + { 0x00000421, "ERROR_INVALID_SERVICE_ACCOUNT" }, + { 0x00000422, "ERROR_SERVICE_DISABLED" }, + { 0x00000423, "ERROR_CIRCULAR_DEPENDENCY" }, + { 0x00000424, "ERROR_SERVICE_DOES_NOT_EXIST" }, + { 0x00000425, "ERROR_SERVICE_CANNOT_ACCEPT_CTRL" }, + { 0x00000426, "ERROR_SERVICE_NOT_ACTIVE" }, + { 0x00000427, "ERROR_FAILED_SERVICE_CONTROLLER_CONNECT" }, + { 0x00000428, "ERROR_EXCEPTION_IN_SERVICE" }, + { 0x00000429, "ERROR_DATABASE_DOES_NOT_EXIST" }, + { 0x0000042A, "ERROR_SERVICE_SPECIFIC_ERROR" }, + { 0x0000042B, "ERROR_PROCESS_ABORTED" }, + { 0x0000042C, "ERROR_SERVICE_DEPENDENCY_FAIL" }, + { 0x0000042D, "ERROR_SERVICE_LOGON_FAILED" }, + { 0x0000042E, "ERROR_SERVICE_START_HANG" }, + { 0x0000042F, "ERROR_INVALID_SERVICE_LOCK" }, + { 0x00000430, "ERROR_SERVICE_MARKED_FOR_DELETE" }, + { 0x00000431, "ERROR_SERVICE_EXISTS" }, + { 0x00000432, "ERROR_ALREADY_RUNNING_LKG" }, + { 0x00000433, "ERROR_SERVICE_DEPENDENCY_DELETED" }, + { 0x00000434, "ERROR_BOOT_ALREADY_ACCEPTED" }, + { 0x00000435, "ERROR_SERVICE_NEVER_STARTED" }, + { 0x00000436, "ERROR_DUPLICATE_SERVICE_NAME" }, + { 0x00000437, "ERROR_DIFFERENT_SERVICE_ACCOUNT" }, + { 0x00000438, "ERROR_CANNOT_DETECT_DRIVER_FAILURE" }, + { 0x00000439, "ERROR_CANNOT_DETECT_PROCESS_ABORT" }, + { 0x0000043A, "ERROR_NO_RECOVERY_PROGRAM" }, + { 0x0000043B, "ERROR_SERVICE_NOT_IN_EXE" }, + { 0x0000043C, "ERROR_NOT_SAFEBOOT_SERVICE" }, + { 0x0000044C, "ERROR_END_OF_MEDIA" }, + { 0x0000044D, "ERROR_FILEMARK_DETECTED" }, + { 0x0000044E, "ERROR_BEGINNING_OF_MEDIA" }, + { 0x0000044F, "ERROR_SETMARK_DETECTED" }, + { 0x00000450, "ERROR_NO_DATA_DETECTED" }, + { 0x00000451, "ERROR_PARTITION_FAILURE" }, + { 0x00000452, "ERROR_INVALID_BLOCK_LENGTH" }, + { 0x00000453, "ERROR_DEVICE_NOT_PARTITIONED" }, + { 0x00000454, "ERROR_UNABLE_TO_LOCK_MEDIA" }, + { 0x00000455, "ERROR_UNABLE_TO_UNLOAD_MEDIA" }, + { 0x00000456, "ERROR_MEDIA_CHANGED" }, + { 0x00000457, "ERROR_BUS_RESET" }, + { 0x00000458, "ERROR_NO_MEDIA_IN_DRIVE" }, + { 0x00000459, "ERROR_NO_UNICODE_TRANSLATION" }, + { 0x0000045A, "ERROR_DLL_INIT_FAILED" }, + { 0x0000045B, "ERROR_SHUTDOWN_IN_PROGRESS" }, + { 0x0000045C, "ERROR_NO_SHUTDOWN_IN_PROGRESS" }, + { 0x0000045D, "ERROR_IO_DEVICE" }, + { 0x0000045E, "ERROR_SERIAL_NO_DEVICE" }, + { 0x0000045F, "ERROR_IRQ_BUSY" }, + { 0x00000460, "ERROR_MORE_WRITES" + "port. (The IOCTL_SERIAL_XOFF_COUNTER reached zero.)" }, + { 0x00000461, "ERROR_COUNTER_TIMEOUT" + "expired. (The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.)" }, + { 0x00000462, "ERROR_FLOPPY_ID_MARK_NOT_FOUND" }, + { 0x00000463, "ERROR_FLOPPY_WRONG_CYLINDER" }, + { 0x00000464, "ERROR_FLOPPY_UNKNOWN_ERROR" }, + { 0x00000465, "ERROR_FLOPPY_BAD_REGISTERS" }, + { 0x00000466, "ERROR_DISK_RECALIBRATE_FAILED" }, + { 0x00000467, "ERROR_DISK_OPERATION_FAILED" }, + { 0x00000468, "ERROR_DISK_RESET_FAILED" }, + { 0x00000469, "ERROR_EOM_OVERFLOW" }, + { 0x0000046A, "ERROR_NOT_ENOUGH_SERVER_MEMORY" }, + { 0x0000046B, "ERROR_POSSIBLE_DEADLOCK" }, + { 0x0000046C, "ERROR_MAPPED_ALIGNMENT" }, + { 0x00000474, "ERROR_SET_POWER_STATE_VETOED" }, + { 0x00000475, "ERROR_SET_POWER_STATE_FAILED" }, + { 0x00000476, "ERROR_TOO_MANY_LINKS" }, + { 0x0000047E, "ERROR_OLD_WIN_VERSION" }, + { 0x0000047F, "ERROR_APP_WRONG_OS" }, + { 0x00000480, "ERROR_SINGLE_INSTANCE_APP" }, + { 0x00000481, "ERROR_RMODE_APP" }, + { 0x00000482, "ERROR_INVALID_DLL" }, + { 0x00000483, "ERROR_NO_ASSOCIATION" }, + { 0x00000484, "ERROR_DDE_FAIL" }, + { 0x00000485, "ERROR_DLL_NOT_FOUND" }, + { 0x00000486, "ERROR_NO_MORE_USER_HANDLES" }, + { 0x00000487, "ERROR_MESSAGE_SYNC_ONLY" }, + { 0x00000488, "ERROR_SOURCE_ELEMENT_EMPTY" }, + { 0x00000489, "ERROR_DESTINATION_ELEMENT_FULL" }, + { 0x0000048A, "ERROR_ILLEGAL_ELEMENT_ADDRESS" }, + { 0x0000048B, "ERROR_MAGAZINE_NOT_PRESENT" }, + { 0x0000048C, "ERROR_DEVICE_REINITIALIZATION_NEEDED" }, + { 0x0000048D, "ERROR_DEVICE_REQUIRES_CLEANING" }, + { 0x0000048E, "ERROR_DEVICE_DOOR_OPEN" }, + { 0x0000048F, "ERROR_DEVICE_NOT_CONNECTED" }, + { 0x00000490, "ERROR_NOT_FOUND" }, + { 0x00000491, "ERROR_NO_MATCH" }, + { 0x00000492, "ERROR_SET_NOT_FOUND" }, + { 0x00000493, "ERROR_POINT_NOT_FOUND" }, + { 0x00000494, "ERROR_NO_TRACKING_SERVICE" }, + { 0x00000495, "ERROR_NO_VOLUME_ID" }, + { 0x00000497, "ERROR_UNABLE_TO_REMOVE_REPLACED" }, + { 0x00000498, "ERROR_UNABLE_TO_MOVE_REPLACEMENT" }, + { 0x00000499, "ERROR_UNABLE_TO_MOVE_REPLACEMENT_2" }, + { 0x0000049A, "ERROR_JOURNAL_DELETE_IN_PROGRESS" }, + { 0x0000049B, "ERROR_JOURNAL_NOT_ACTIVE" }, + { 0x0000049C, "ERROR_POTENTIAL_FILE_FOUND" }, + { 0x0000049D, "ERROR_JOURNAL_ENTRY_DELETED" }, + { 0x000004A6, "ERROR_SHUTDOWN_IS_SCHEDULED" }, + { 0x000004A7, "ERROR_SHUTDOWN_USERS_LOGGED_ON" }, + { 0x000004B0, "ERROR_BAD_DEVICE" }, + { 0x000004B1, "ERROR_CONNECTION_UNAVAIL" }, + { 0x000004B2, "ERROR_DEVICE_ALREADY_REMEMBERED" }, + { 0x000004B3, "ERROR_NO_NET_OR_BAD_PATH" }, + { 0x000004B4, "ERROR_BAD_PROVIDER" }, + { 0x000004B5, "ERROR_CANNOT_OPEN_PROFILE" }, + { 0x000004B6, "ERROR_BAD_PROFILE" }, + { 0x000004B7, "ERROR_NOT_CONTAINER" }, + { 0x000004B8, "ERROR_EXTENDED_ERROR" }, + { 0x000004B9, "ERROR_INVALID_GROUPNAME" }, + { 0x000004BA, "ERROR_INVALID_COMPUTERNAME" }, + { 0x000004BB, "ERROR_INVALID_EVENTNAME" }, + { 0x000004BC, "ERROR_INVALID_DOMAINNAME" }, + { 0x000004BD, "ERROR_INVALID_SERVICENAME" }, + { 0x000004BE, "ERROR_INVALID_NETNAME" }, + { 0x000004BF, "ERROR_INVALID_SHARENAME" }, + { 0x000004C0, "ERROR_INVALID_PASSWORDNAME" }, + { 0x000004C1, "ERROR_INVALID_MESSAGENAME" }, + { 0x000004C2, "ERROR_INVALID_MESSAGEDEST" }, + { 0x000004C3, "ERROR_SESSION_CREDENTIAL_CONFLICT" }, + { 0x000004C4, "ERROR_REMOTE_SESSION_LIMIT_EXCEEDED" }, + { 0x000004C5, "ERROR_DUP_DOMAINNAME" }, + { 0x000004C6, "ERROR_NO_NETWORK" }, + { 0x000004C7, "ERROR_CANCELLED" }, + { 0x000004C8, "ERROR_USER_MAPPED_FILE" }, + { 0x000004C9, "ERROR_CONNECTION_REFUSED" }, + { 0x000004CA, "ERROR_GRACEFUL_DISCONNECT" }, + { 0x000004CB, "ERROR_ADDRESS_ALREADY_ASSOCIATED" }, + { 0x000004CC, "ERROR_ADDRESS_NOT_ASSOCIATED" }, + { 0x000004CD, "ERROR_CONNECTION_INVALID" }, + { 0x000004CE, "ERROR_CONNECTION_ACTIVE" }, + { 0x000004CF, "ERROR_NETWORK_UNREACHABLE" }, + { 0x000004D0, "ERROR_HOST_UNREACHABLE" }, + { 0x000004D1, "ERROR_PROTOCOL_UNREACHABLE" }, + { 0x000004D2, "ERROR_PORT_UNREACHABLE" }, + { 0x000004D3, "ERROR_REQUEST_ABORTED" }, + { 0x000004D4, "ERROR_CONNECTION_ABORTED" }, + { 0x000004D5, "ERROR_RETRY" }, + { 0x000004D6, "ERROR_CONNECTION_COUNT_LIMIT" }, + { 0x000004D7, "ERROR_LOGIN_TIME_RESTRICTION" }, + { 0x000004D8, "ERROR_LOGIN_WKSTA_RESTRICTION" }, + { 0x000004D9, "ERROR_INCORRECT_ADDRESS" }, + { 0x000004DA, "ERROR_ALREADY_REGISTERED" }, + { 0x000004DB, "ERROR_SERVICE_NOT_FOUND" }, + { 0x000004DC, "ERROR_NOT_AUTHENTICATED" }, + { 0x000004DD, "ERROR_NOT_LOGGED_ON" }, + { 0x000004DE, "ERROR_CONTINUE" }, + { 0x000004DF, "ERROR_ALREADY_INITIALIZED" }, + { 0x000004E0, "ERROR_NO_MORE_DEVICES" }, + { 0x000004E1, "ERROR_NO_SUCH_SITE" }, + { 0x000004E2, "ERROR_DOMAIN_CONTROLLER_EXISTS" }, + { 0x000004E3, "ERROR_ONLY_IF_CONNECTED" }, + { 0x000004E4, "ERROR_OVERRIDE_NOCHANGES" }, + { 0x000004E5, "ERROR_BAD_USER_PROFILE" }, + { 0x000004E6, "ERROR_NOT_SUPPORTED_ON_SBS" }, + { 0x000004E7, "ERROR_SERVER_SHUTDOWN_IN_PROGRESS" }, + { 0x000004E8, "ERROR_HOST_DOWN" }, + { 0x000004E9, "ERROR_NON_ACCOUNT_SID" }, + { 0x000004EA, "ERROR_NON_DOMAIN_SID" }, + { 0x000004EB, "ERROR_APPHELP_BLOCK" }, + { 0x000004EC, "ERROR_ACCESS_DISABLED_BY_POLICY" }, + { 0x000004ED, "ERROR_REG_NAT_CONSUMPTION" }, + { 0x000004EE, "ERROR_CSCSHARE_OFFLINE" }, + { 0x000004EF, "ERROR_PKINIT_FAILURE" }, + { 0x000004F0, "ERROR_SMARTCARD_SUBSYSTEM_FAILURE" }, + { 0x000004F1, "ERROR_DOWNGRADE_DETECTED" }, + { 0x000004F7, "ERROR_MACHINE_LOCKED" }, + { 0x000004F9, "ERROR_CALLBACK_SUPPLIED_INVALID_DATA" }, + { 0x000004FA, "ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED" }, + { 0x000004FB, "ERROR_DRIVER_BLOCKED" }, + { 0x000004FC, "ERROR_INVALID_IMPORT_OF_NON_DLL" }, + { 0x000004FD, "ERROR_ACCESS_DISABLED_WEBBLADE" }, + { 0x000004FE, "ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER" }, + { 0x000004FF, "ERROR_RECOVERY_FAILURE" }, + { 0x00000500, "ERROR_ALREADY_FIBER" }, + { 0x00000501, "ERROR_ALREADY_THREAD" }, + { 0x00000502, "ERROR_STACK_BUFFER_OVERRUN" }, + { 0x00000503, "ERROR_PARAMETER_QUOTA_EXCEEDED" }, + { 0x00000504, "ERROR_DEBUGGER_INACTIVE" }, + { 0x00000505, "ERROR_DELAY_LOAD_FAILED" }, + { 0x00000506, "ERROR_VDM_DISALLOWED" + "16-bit applications. Check your permissions with your system administrator." }, + { 0x00000507, "ERROR_UNIDENTIFIED_ERROR" }, + { 0x00000508, "ERROR_INVALID_CRUNTIME_PARAMETER" }, + { 0x00000509, "ERROR_BEYOND_VDL" }, + { 0x0000050A, "ERROR_INCOMPATIBLE_SERVICE_SID_TYPE" }, + { 0x0000050B, "ERROR_DRIVER_PROCESS_TERMINATED" }, + { 0x0000050C, "ERROR_IMPLEMENTATION_LIMIT" }, + { 0x0000050D, "ERROR_PROCESS_IS_PROTECTED" }, + { 0x0000050E, "ERROR_SERVICE_NOTIFY_CLIENT_LAGGING" }, + { 0x0000050F, "ERROR_DISK_QUOTA_EXCEEDED" }, + { 0x00000510, "ERROR_CONTENT_BLOCKED" }, + { 0x00000511, "ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE" }, + { 0x00000513, "ERROR_INVALID_LABEL" }, + { 0x00000514, "ERROR_NOT_ALL_ASSIGNED" }, + { 0x00000515, "ERROR_SOME_NOT_MAPPED" }, + { 0x00000516, "ERROR_NO_QUOTAS_FOR_ACCOUNT" }, + { 0x00000517, "ERROR_LOCAL_USER_SESSION_KEY" }, + { 0x00000518, "ERROR_NULL_LM_PASSWORD" }, + { 0x00000519, "ERROR_UNKNOWN_REVISION" }, + { 0x0000051A, "ERROR_REVISION_MISMATCH" }, + { 0x0000051B, "ERROR_INVALID_OWNER" }, + { 0x0000051C, "ERROR_INVALID_PRIMARY_GROUP" }, + { 0x0000051D, "ERROR_NO_IMPERSONATION_TOKEN" }, + { 0x0000051E, "ERROR_CANT_DISABLE_MANDATORY" }, + { 0x0000051F, "ERROR_NO_LOGON_SERVERS" }, + { 0x00000520, "ERROR_NO_SUCH_LOGON_SESSION" }, + { 0x00000521, "ERROR_NO_SUCH_PRIVILEGE" }, + { 0x00000522, "ERROR_PRIVILEGE_NOT_HELD" }, + { 0x00000523, "ERROR_INVALID_ACCOUNT_NAME" }, + { 0x00000524, "ERROR_USER_EXISTS" }, + { 0x00000525, "ERROR_NO_SUCH_USER" }, + { 0x00000526, "ERROR_GROUP_EXISTS" }, + { 0x00000527, "ERROR_NO_SUCH_GROUP" }, + { 0x00000528, "ERROR_MEMBER_IN_GROUP" }, + { 0x00000529, "ERROR_MEMBER_NOT_IN_GROUP" }, + { 0x0000052A, "ERROR_LAST_ADMIN" }, + { 0x0000052B, "ERROR_WRONG_PASSWORD" }, + { 0x0000052C, "ERROR_ILL_FORMED_PASSWORD" }, + { 0x0000052D, "ERROR_PASSWORD_RESTRICTION" }, + { 0x0000052E, "ERROR_LOGON_FAILURE" }, + { 0x0000052F, "ERROR_ACCOUNT_RESTRICTION" }, + { 0x00000530, "ERROR_INVALID_LOGON_HOURS" }, + { 0x00000531, "ERROR_INVALID_WORKSTATION" }, + { 0x00000532, "ERROR_PASSWORD_EXPIRED" }, + { 0x00000533, "ERROR_ACCOUNT_DISABLED" }, + { 0x00000534, "ERROR_NONE_MAPPED" }, + { 0x00000535, "ERROR_TOO_MANY_LUIDS_REQUESTED" }, + { 0x00000536, "ERROR_LUIDS_EXHAUSTED" }, + { 0x00000537, "ERROR_INVALID_SUB_AUTHORITY" }, + { 0x00000538, "ERROR_INVALID_ACL" }, + { 0x00000539, "ERROR_INVALID_SID" }, + { 0x0000053A, "ERROR_INVALID_SECURITY_DESCR" }, + { 0x0000053C, "ERROR_BAD_INHERITANCE_ACL" }, + { 0x0000053D, "ERROR_SERVER_DISABLED" }, + { 0x0000053E, "ERROR_SERVER_NOT_DISABLED" }, + { 0x0000053F, "ERROR_INVALID_ID_AUTHORITY" }, + { 0x00000540, "ERROR_ALLOTTED_SPACE_EXCEEDED" }, + { 0x00000541, "ERROR_INVALID_GROUP_ATTRIBUTES" }, + { 0x00000542, "ERROR_BAD_IMPERSONATION_LEVEL" }, + { 0x00000543, "ERROR_CANT_OPEN_ANONYMOUS" }, + { 0x00000544, "ERROR_BAD_VALIDATION_CLASS" }, + { 0x00000545, "ERROR_BAD_TOKEN_TYPE" }, + { 0x00000546, "ERROR_NO_SECURITY_ON_OBJECT" }, + { 0x00000547, "ERROR_CANT_ACCESS_DOMAIN_INFO" }, + { 0x00000548, "ERROR_INVALID_SERVER_STATE" }, + { 0x00000549, "ERROR_INVALID_DOMAIN_STATE" }, + { 0x0000054A, "ERROR_INVALID_DOMAIN_ROLE" }, + { 0x0000054B, "ERROR_NO_SUCH_DOMAIN" }, + { 0x0000054C, "ERROR_DOMAIN_EXISTS" }, + { 0x0000054D, "ERROR_DOMAIN_LIMIT_EXCEEDED" }, + { 0x0000054E, "ERROR_INTERNAL_DB_CORRUPTION" }, + { 0x0000054F, "ERROR_INTERNAL_ERROR" }, + { 0x00000550, "ERROR_GENERIC_NOT_MAPPED" }, + { 0x00000551, "ERROR_BAD_DESCRIPTOR_FORMAT" }, + { 0x00000552, "ERROR_NOT_LOGON_PROCESS" }, + { 0x00000553, "ERROR_LOGON_SESSION_EXISTS" }, + { 0x00000554, "ERROR_NO_SUCH_PACKAGE" }, + { 0x00000555, "ERROR_BAD_LOGON_SESSION_STATE" }, + { 0x00000556, "ERROR_LOGON_SESSION_COLLISION" }, + { 0x00000557, "ERROR_INVALID_LOGON_TYPE" }, + { 0x00000558, "ERROR_CANNOT_IMPERSONATE" }, + { 0x00000559, "ERROR_RXACT_INVALID_STATE" }, + { 0x0000055A, "ERROR_RXACT_COMMIT_FAILURE" }, + { 0x0000055B, "ERROR_SPECIAL_ACCOUNT" }, + { 0x0000055C, "ERROR_SPECIAL_GROUP" }, + { 0x0000055D, "ERROR_SPECIAL_USER" }, + { 0x0000055E, "ERROR_MEMBERS_PRIMARY_GROUP" }, + { 0x0000055F, "ERROR_TOKEN_ALREADY_IN_USE" }, + { 0x00000560, "ERROR_NO_SUCH_ALIAS" }, + { 0x00000561, "ERROR_MEMBER_NOT_IN_ALIAS" }, + { 0x00000562, "ERROR_MEMBER_IN_ALIAS" }, + { 0x00000563, "ERROR_ALIAS_EXISTS" }, + { 0x00000564, "ERROR_LOGON_NOT_GRANTED" }, + { 0x00000565, "ERROR_TOO_MANY_SECRETS" }, + { 0x00000566, "ERROR_SECRET_TOO_LONG" }, + { 0x00000567, "ERROR_INTERNAL_DB_ERROR" }, + { 0x00000568, "ERROR_TOO_MANY_CONTEXT_IDS" }, + { 0x00000569, "ERROR_LOGON_TYPE_NOT_GRANTED" }, + { 0x0000056A, "ERROR_NT_CROSS_ENCRYPTION_REQUIRED" }, + { 0x0000056B, "ERROR_NO_SUCH_MEMBER" }, + { 0x0000056C, "ERROR_INVALID_MEMBER" }, + { 0x0000056D, "ERROR_TOO_MANY_SIDS" }, + { 0x0000056E, "ERROR_LM_CROSS_ENCRYPTION_REQUIRED" }, + { 0x0000056F, "ERROR_NO_INHERITANCE" }, + { 0x00000570, "ERROR_FILE_CORRUPT" }, + { 0x00000571, "ERROR_DISK_CORRUPT" }, + { 0x00000572, "ERROR_NO_USER_SESSION_KEY" }, + { 0x00000573, "ERROR_LICENSE_QUOTA_EXCEEDED" }, + { 0x00000574, "ERROR_WRONG_TARGET_NAME" }, + { 0x00000575, "ERROR_MUTUAL_AUTH_FAILED" }, + { 0x00000576, "ERROR_TIME_SKEW" }, + { 0x00000577, "ERROR_CURRENT_DOMAIN_NOT_ALLOWED" }, + { 0x00000578, "ERROR_INVALID_WINDOW_HANDLE" }, + { 0x00000579, "ERROR_INVALID_MENU_HANDLE" }, + { 0x0000057A, "ERROR_INVALID_CURSOR_HANDLE" }, + { 0x0000057B, "ERROR_INVALID_ACCEL_HANDLE" }, + { 0x0000057C, "ERROR_INVALID_HOOK_HANDLE" }, + { 0x0000057D, "ERROR_INVALID_DWP_HANDLE" }, + { 0x0000057E, "ERROR_TLW_WITH_WSCHILD" }, + { 0x0000057F, "ERROR_CANNOT_FIND_WND_CLASS" }, + { 0x00000580, "ERROR_WINDOW_OF_OTHER_THREAD" }, + { 0x00000581, "ERROR_HOTKEY_ALREADY_REGISTERED" }, + { 0x00000582, "ERROR_CLASS_ALREADY_EXISTS" }, + { 0x00000583, "ERROR_CLASS_DOES_NOT_EXIST" }, + { 0x00000584, "ERROR_CLASS_HAS_WINDOWS" }, + { 0x00000585, "ERROR_INVALID_INDEX" }, + { 0x00000586, "ERROR_INVALID_ICON_HANDLE" }, + { 0x00000587, "ERROR_PRIVATE_DIALOG_INDEX" }, + { 0x00000588, "ERROR_LISTBOX_ID_NOT_FOUND" }, + { 0x00000589, "ERROR_NO_WILDCARD_CHARACTERS" }, + { 0x0000058A, "ERROR_CLIPBOARD_NOT_OPEN" }, + { 0x0000058B, "ERROR_HOTKEY_NOT_REGISTERED" }, + { 0x0000058C, "ERROR_WINDOW_NOT_DIALOG" }, + { 0x0000058D, "ERROR_CONTROL_ID_NOT_FOUND" }, + { 0x0000058E, "ERROR_INVALID_COMBOBOX_MESSAGE" }, + { 0x0000058F, "ERROR_WINDOW_NOT_COMBOBOX" }, + { 0x00000590, "ERROR_INVALID_EDIT_HEIGHT" }, + { 0x00000591, "ERROR_DC_NOT_FOUND" }, + { 0x00000592, "ERROR_INVALID_HOOK_FILTER" }, + { 0x00000593, "ERROR_INVALID_FILTER_PROC" }, + { 0x00000594, "ERROR_HOOK_NEEDS_HMOD" }, + { 0x00000595, "ERROR_GLOBAL_ONLY_HOOK" }, + { 0x00000596, "ERROR_JOURNAL_HOOK_SET" }, + { 0x00000597, "ERROR_HOOK_NOT_INSTALLED" }, + { 0x00000598, "ERROR_INVALID_LB_MESSAGE" }, + { 0x00000599, "ERROR_SETCOUNT_ON_BAD_LB_SETCOUNT" }, + { 0x0000059A, "ERROR_LB_WITHOUT_TABSTOPS" }, + { 0x0000059B, "ERROR_DESTROY_OBJECT_OF_OTHER_THREAD" }, + { 0x0000059C, "ERROR_CHILD_WINDOW_MENU" }, + { 0x0000059D, "ERROR_NO_SYSTEM_MENU" }, + { 0x0000059E, "ERROR_INVALID_MSGBOX_STYLE" }, + { 0x0000059F, "ERROR_INVALID_SPI_VALUE" }, + { 0x000005A0, "ERROR_SCREEN_ALREADY_LOCKED" }, + { 0x000005A1, "ERROR_HWNDS_HAVE_DIFF_PARENT" }, + { 0x000005A2, "ERROR_NOT_CHILD_WINDOW" }, + { 0x000005A3, "ERROR_INVALID_GW_COMMAND" }, + { 0x000005A4, "ERROR_INVALID_THREAD_ID" }, + { 0x000005A5, "ERROR_NON_MDICHILD_WINDOW" }, + { 0x000005A6, "ERROR_POPUP_ALREADY_ACTIVE" }, + { 0x000005A7, "ERROR_NO_SCROLLBARS" }, + { 0x000005A8, "ERROR_INVALID_SCROLLBAR_RANGE" }, + { 0x000005A9, "ERROR_INVALID_SHOWWIN_COMMAND" }, + { 0x000005AA, "ERROR_NO_SYSTEM_RESOURCES" }, + { 0x000005AB, "ERROR_NONPAGED_SYSTEM_RESOURCES" }, + { 0x000005AC, "ERROR_PAGED_SYSTEM_RESOURCES" }, + { 0x000005AD, "ERROR_WORKING_SET_QUOTA" }, + { 0x000005AE, "ERROR_PAGEFILE_QUOTA" }, + { 0x000005AF, "ERROR_COMMITMENT_LIMIT" }, + { 0x000005B0, "ERROR_MENU_ITEM_NOT_FOUND" }, + { 0x000005B1, "ERROR_INVALID_KEYBOARD_HANDLE" }, + { 0x000005B2, "ERROR_HOOK_TYPE_NOT_ALLOWED" }, + { 0x000005B3, "ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION" }, + { 0x000005B4, "ERROR_TIMEOUT" }, + { 0x000005B5, "ERROR_INVALID_MONITOR_HANDLE" }, + { 0x000005B6, "ERROR_INCORRECT_SIZE" }, + { 0x000005B7, "ERROR_SYMLINK_CLASS_DISABLED" }, + { 0x000005B8, "ERROR_SYMLINK_NOT_SUPPORTED" }, + { 0x000005DC, "ERROR_EVENTLOG_FILE_CORRUPT" }, + { 0x000005DD, "ERROR_EVENTLOG_CANT_START" }, + { 0x000005DE, "ERROR_LOG_FILE_FULL" }, + { 0x000005DF, "ERROR_EVENTLOG_FILE_CHANGED" }, + { 0x0000060E, "ERROR_INVALID_TASK_NAME" }, + { 0x0000060F, "ERROR_INVALID_TASK_INDEX" }, + { 0x00000610, "ERROR_THREAD_ALREADY_IN_TASK" }, + { 0x00000641, "ERROR_INSTALL_SERVICE_FAILURE" }, + { 0x00000642, "ERROR_INSTALL_USEREXIT" }, + { 0x00000643, "ERROR_INSTALL_FAILURE" }, + { 0x00000644, "ERROR_INSTALL_SUSPEND" }, + { 0x00000645, "ERROR_UNKNOWN_PRODUCT" }, + { 0x00000646, "ERROR_UNKNOWN_FEATURE" }, + { 0x00000647, "ERROR_UNKNOWN_COMPONENT" }, + { 0x00000648, "ERROR_UNKNOWN_PROPERTY" }, + { 0x00000649, "ERROR_INVALID_HANDLE_STATE" }, + { 0x0000064A, "ERROR_BAD_CONFIGURATION" }, + { 0x0000064B, "ERROR_INDEX_ABSENT" }, + { 0x0000064C, "ERROR_INSTALL_SOURCE_ABSENT" }, + { 0x0000064D, "ERROR_INSTALL_PACKAGE_VERSION" }, + { 0x0000064E, "ERROR_PRODUCT_UNINSTALLED" }, + { 0x0000064F, "ERROR_BAD_QUERY_SYNTAX" }, + { 0x00000650, "ERROR_INVALID_FIELD" }, + { 0x00000651, "ERROR_DEVICE_REMOVED" }, + { 0x00000652, "ERROR_INSTALL_ALREADY_RUNNING" }, + { 0x00000653, "ERROR_INSTALL_PACKAGE_OPEN_FAILED" }, + { 0x00000654, "ERROR_INSTALL_PACKAGE_INVALID" }, + { 0x00000655, "ERROR_INSTALL_UI_FAILURE" }, + { 0x00000656, "ERROR_INSTALL_LOG_FAILURE" }, + { 0x00000657, "ERROR_INSTALL_LANGUAGE_UNSUPPORTED" }, + { 0x00000658, "ERROR_INSTALL_TRANSFORM_FAILURE" }, + { 0x00000659, "ERROR_INSTALL_PACKAGE_REJECTED" }, + { 0x0000065A, "ERROR_FUNCTION_NOT_CALLED" }, + { 0x0000065B, "ERROR_FUNCTION_FAILED" }, + { 0x0000065C, "ERROR_INVALID_TABLE" }, + { 0x0000065D, "ERROR_DATATYPE_MISMATCH" }, + { 0x0000065E, "ERROR_UNSUPPORTED_TYPE" }, + { 0x0000065F, "ERROR_CREATE_FAILED" }, + { 0x00000660, "ERROR_INSTALL_TEMP_UNWRITABLE" }, + { 0x00000661, "ERROR_INSTALL_PLATFORM_UNSUPPORTED" }, + { 0x00000662, "ERROR_INSTALL_NOTUSED" }, + { 0x00000663, "ERROR_PATCH_PACKAGE_OPEN_FAILED" }, + { 0x00000664, "ERROR_PATCH_PACKAGE_INVALID" }, + { 0x00000665, "ERROR_PATCH_PACKAGE_UNSUPPORTED" }, + { 0x00000666, "ERROR_PRODUCT_VERSION" }, + { 0x00000667, "ERROR_INVALID_COMMAND_LINE" }, + { 0x00000668, "ERROR_INSTALL_REMOTE_DISALLOWED" }, + { 0x00000669, "ERROR_SUCCESS_REBOOT_INITIATED" }, + { 0x0000066A, "ERROR_PATCH_TARGET_NOT_FOUND" }, + { 0x0000066B, "ERROR_PATCH_PACKAGE_REJECTED" }, + { 0x0000066C, "ERROR_INSTALL_TRANSFORM_REJECTED" }, + { 0x0000066D, "ERROR_INSTALL_REMOTE_PROHIBITED" }, + { 0x0000066E, "ERROR_PATCH_REMOVAL_UNSUPPORTED" }, + { 0x0000066F, "ERROR_UNKNOWN_PATCH" }, + { 0x00000670, "ERROR_PATCH_NO_SEQUENCE" }, + { 0x00000671, "ERROR_PATCH_REMOVAL_DISALLOWED" }, + { 0x00000672, "ERROR_INVALID_PATCH_XML" }, + { 0x00000673, "ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT" }, + { 0x00000674, "ERROR_INSTALL_SERVICE_SAFEBOOT" }, + { 0x000006A4, "RPC_S_INVALID_STRING_BINDING" }, + { 0x000006A5, "RPC_S_WRONG_KIND_OF_BINDING" }, + { 0x000006A6, "RPC_S_INVALID_BINDING" }, + { 0x000006A7, "RPC_S_PROTSEQ_NOT_SUPPORTED" }, + { 0x000006A8, "RPC_S_INVALID_RPC_PROTSEQ" }, + { 0x000006A9, "RPC_S_INVALID_STRING_UUID" }, + { 0x000006AA, "RPC_S_INVALID_ENDPOINT_FORMAT" }, + { 0x000006AB, "RPC_S_INVALID_NET_ADDR" }, + { 0x000006AC, "RPC_S_NO_ENDPOINT_FOUND" }, + { 0x000006AD, "RPC_S_INVALID_TIMEOUT" }, + { 0x000006AE, "RPC_S_OBJECT_NOT_FOUND" }, + { 0x000006AF, "RPC_S_ALREADY_REGISTERED" }, + { 0x000006B0, "RPC_S_TYPE_ALREADY_REGISTERED" }, + { 0x000006B1, "RPC_S_ALREADY_LISTENING" }, + { 0x000006B2, "RPC_S_NO_PROTSEQS_REGISTERED" }, + { 0x000006B3, "RPC_S_NOT_LISTENING" }, + { 0x000006B4, "RPC_S_UNKNOWN_MGR_TYPE" }, + { 0x000006B5, "RPC_S_UNKNOWN_IF" }, + { 0x000006B6, "RPC_S_NO_BINDINGS" }, + { 0x000006B7, "RPC_S_NO_PROTSEQS" }, + { 0x000006B8, "RPC_S_CANT_CREATE_ENDPOINT" }, + { 0x000006B9, "RPC_S_OUT_OF_RESOURCES" }, + { 0x000006BA, "RPC_S_SERVER_UNAVAILABLE" }, + { 0x000006BB, "RPC_S_SERVER_TOO_BUSY" }, + { 0x000006BC, "RPC_S_INVALID_NETWORK_OPTIONS" }, + { 0x000006BD, "RPC_S_NO_CALL_ACTIVE" }, + { 0x000006BE, "RPC_S_CALL_FAILED" }, + { 0x000006BF, "RPC_S_CALL_FAILED_DNE" }, + { 0x000006C0, "RPC_S_PROTOCOL_ERROR" }, + { 0x000006C1, "RPC_S_PROXY_ACCESS_DENIED" }, + { 0x000006C2, "RPC_S_UNSUPPORTED_TRANS_SYN" }, + { 0x000006C4, "RPC_S_UNSUPPORTED_TYPE" }, + { 0x000006C5, "RPC_S_INVALID_TAG" }, + { 0x000006C6, "RPC_S_INVALID_BOUND" }, + { 0x000006C7, "RPC_S_NO_ENTRY_NAME" }, + { 0x000006C8, "RPC_S_INVALID_NAME_SYNTAX" }, + { 0x000006C9, "RPC_S_UNSUPPORTED_NAME_SYNTAX" }, + { 0x000006CB, "RPC_S_UUID_NO_ADDRESS" }, + { 0x000006CC, "RPC_S_DUPLICATE_ENDPOINT" }, + { 0x000006CD, "RPC_S_UNKNOWN_AUTHN_TYPE" }, + { 0x000006CE, "RPC_S_MAX_CALLS_TOO_SMALL" }, + { 0x000006CF, "RPC_S_STRING_TOO_LONG" }, + { 0x000006D0, "RPC_S_PROTSEQ_NOT_FOUND" }, + { 0x000006D1, "RPC_S_PROCNUM_OUT_OF_RANGE" }, + { 0x000006D2, "RPC_S_BINDING_HAS_NO_AUTH" }, + { 0x000006D3, "RPC_S_UNKNOWN_AUTHN_SERVICE" }, + { 0x000006D4, "RPC_S_UNKNOWN_AUTHN_LEVEL" }, + { 0x000006D5, "RPC_S_INVALID_AUTH_IDENTITY" }, + { 0x000006D6, "RPC_S_UNKNOWN_AUTHZ_SERVICE" }, + { 0x000006D7, "EPT_S_INVALID_ENTRY" }, + { 0x000006D8, "EPT_S_CANT_PERFORM_OP" }, + { 0x000006D9, "EPT_S_NOT_REGISTERED" }, + { 0x000006DA, "RPC_S_NOTHING_TO_EXPORT" }, + { 0x000006DB, "RPC_S_INCOMPLETE_NAME" }, + { 0x000006DC, "RPC_S_INVALID_VERS_OPTION" }, + { 0x000006DD, "RPC_S_NO_MORE_MEMBERS" }, + { 0x000006DE, "RPC_S_NOT_ALL_OBJS_UNEXPORTED" }, + { 0x000006DF, "RPC_S_INTERFACE_NOT_FOUND" }, + { 0x000006E0, "RPC_S_ENTRY_ALREADY_EXISTS" }, + { 0x000006E1, "RPC_S_ENTRY_NOT_FOUND" }, + { 0x000006E2, "RPC_S_NAME_SERVICE_UNAVAILABLE" }, + { 0x000006E3, "RPC_S_INVALID_NAF_ID" }, + { 0x000006E4, "RPC_S_CANNOT_SUPPORT" }, + { 0x000006E5, "RPC_S_NO_CONTEXT_AVAILABLE" }, + { 0x000006E6, "RPC_S_INTERNAL_ERROR" }, + { 0x000006E7, "RPC_S_ZERO_DIVIDE" }, + { 0x000006E8, "RPC_S_ADDRESS_ERROR" }, + { 0x000006E9, "RPC_S_FP_DIV_ZERO" }, + { 0x000006EA, "RPC_S_FP_UNDERFLOW" }, + { 0x000006EB, "RPC_S_FP_OVERFLOW" }, + { 0x000006EC, "RPC_X_NO_MORE_ENTRIES" }, + { 0x000006ED, "RPC_X_SS_CHAR_TRANS_OPEN_FAIL" }, + { 0x000006EE, "RPC_X_SS_CHAR_TRANS_SHORT_FILE" }, + { 0x000006EF, "RPC_X_SS_IN_NULL_CONTEXT" }, + { 0x000006F1, "RPC_X_SS_CONTEXT_DAMAGED" }, + { 0x000006F2, "RPC_X_SS_HANDLES_MISMATCH" }, + { 0x000006F3, "RPC_X_SS_CANNOT_GET_CALL_HANDLE" }, + { 0x000006F4, "RPC_X_NULL_REF_POINTER" }, + { 0x000006F5, "RPC_X_ENUM_VALUE_OUT_OF_RANGE" }, + { 0x000006F6, "RPC_X_BYTE_COUNT_TOO_SMALL" }, + { 0x000006F7, "RPC_X_BAD_STUB_DATA" }, + { 0x000006F8, "ERROR_INVALID_USER_BUFFER" }, + { 0x000006F9, "ERROR_UNRECOGNIZED_MEDIA" }, + { 0x000006FA, "ERROR_NO_TRUST_LSA_SECRET" }, + { 0x000006FB, "ERROR_NO_TRUST_SAM_ACCOUNT" }, + { 0x000006FC, "ERROR_TRUSTED_DOMAIN_FAILURE" }, + { 0x000006FD, "ERROR_TRUSTED_RELATIONSHIP_FAILURE" }, + { 0x000006FE, "ERROR_TRUST_FAILURE" }, + { 0x000006FF, "RPC_S_CALL_IN_PROGRESS" }, + { 0x00000700, "ERROR_NETLOGON_NOT_STARTED" }, + { 0x00000701, "ERROR_ACCOUNT_EXPIRED" }, + { 0x00000702, "ERROR_REDIRECTOR_HAS_OPEN_HANDLES" }, + { 0x00000703, "ERROR_PRINTER_DRIVER_ALREADY_INSTALLED" }, + { 0x00000704, "ERROR_UNKNOWN_PORT" }, + { 0x00000705, "ERROR_UNKNOWN_PRINTER_DRIVER" }, + { 0x00000706, "ERROR_UNKNOWN_PRINTPROCESSOR" }, + { 0x00000707, "ERROR_INVALID_SEPARATOR_FILE" }, + { 0x00000708, "ERROR_INVALID_PRIORITY" }, + { 0x00000709, "ERROR_INVALID_PRINTER_NAME" }, + { 0x0000070A, "ERROR_PRINTER_ALREADY_EXISTS" }, + { 0x0000070B, "ERROR_INVALID_PRINTER_COMMAND" }, + { 0x0000070C, "ERROR_INVALID_DATATYPE" }, + { 0x0000070D, "ERROR_INVALID_ENVIRONMENT" }, + { 0x0000070E, "RPC_S_NO_MORE_BINDINGS" }, + { 0x0000070F, "ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT" }, + { 0x00000710, "ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT" }, + { 0x00000711, "ERROR_NOLOGON_SERVER_TRUST_ACCOUNT" }, + { 0x00000712, "ERROR_DOMAIN_TRUST_INCONSISTENT" }, + { 0x00000713, "ERROR_SERVER_HAS_OPEN_HANDLES" }, + { 0x00000714, "ERROR_RESOURCE_DATA_NOT_FOUND" }, + { 0x00000715, "ERROR_RESOURCE_TYPE_NOT_FOUND" }, + { 0x00000716, "ERROR_RESOURCE_NAME_NOT_FOUND" }, + { 0x00000717, "ERROR_RESOURCE_LANG_NOT_FOUND" }, + { 0x00000718, "ERROR_NOT_ENOUGH_QUOTA" }, + { 0x00000719, "RPC_S_NO_INTERFACES" }, + { 0x0000071A, "RPC_S_CALL_CANCELLED" }, + { 0x0000071B, "RPC_S_BINDING_INCOMPLETE" }, + { 0x0000071C, "RPC_S_COMM_FAILURE" }, + { 0x0000071D, "RPC_S_UNSUPPORTED_AUTHN_LEVEL" }, + { 0x0000071E, "RPC_S_NO_PRINC_NAME" }, + { 0x0000071F, "RPC_S_NOT_RPC_ERROR" }, + { 0x00000720, "RPC_S_UUID_LOCAL_ONLY" }, + { 0x00000721, "RPC_S_SEC_PKG_ERROR" }, + { 0x00000722, "RPC_S_NOT_CANCELLED" }, + { 0x00000723, "RPC_X_INVALID_ES_ACTION" }, + { 0x00000724, "RPC_X_WRONG_ES_VERSION" }, + { 0x00000725, "RPC_X_WRONG_STUB_VERSION" }, + { 0x00000726, "RPC_X_INVALID_PIPE_OBJECT" }, + { 0x00000727, "RPC_X_WRONG_PIPE_ORDER" }, + { 0x00000728, "RPC_X_WRONG_PIPE_VERSION" }, + { 0x0000076A, "RPC_S_GROUP_MEMBER_NOT_FOUND" }, + { 0x0000076B, "EPT_S_CANT_CREATE" }, + { 0x0000076C, "RPC_S_INVALID_OBJECT" }, + { 0x0000076D, "ERROR_INVALID_TIME" }, + { 0x0000076E, "ERROR_INVALID_FORM_NAME" }, + { 0x0000076F, "ERROR_INVALID_FORM_SIZE" }, + { 0x00000770, "ERROR_ALREADY_WAITING" }, + { 0x00000771, "ERROR_PRINTER_DELETED" }, + { 0x00000772, "ERROR_INVALID_PRINTER_STATE" }, + { 0x00000773, "ERROR_PASSWORD_MUST_CHANGE" }, + { 0x00000774, "ERROR_DOMAIN_CONTROLLER_NOT_FOUND" }, + { 0x00000775, "ERROR_ACCOUNT_LOCKED_OUT" }, + { 0x00000776, "OR_INVALID_OXID" }, + { 0x00000777, "OR_INVALID_OID" }, + { 0x00000778, "OR_INVALID_SET" }, + { 0x00000779, "RPC_S_SEND_INCOMPLETE" }, + { 0x0000077A, "RPC_S_INVALID_ASYNC_HANDLE" }, + { 0x0000077B, "RPC_S_INVALID_ASYNC_CALL" }, + { 0x0000077C, "RPC_X_PIPE_CLOSED" }, + { 0x0000077D, "RPC_X_PIPE_DISCIPLINE_ERROR" }, + { 0x0000077E, "RPC_X_PIPE_EMPTY" }, + { 0x0000077F, "ERROR_NO_SITENAME" }, + { 0x00000780, "ERROR_CANT_ACCESS_FILE" }, + { 0x00000781, "ERROR_CANT_RESOLVE_FILENAME" }, + { 0x00000782, "RPC_S_ENTRY_TYPE_MISMATCH" }, + { 0x00000783, "RPC_S_NOT_ALL_OBJS_EXPORTED" }, + { 0x00000784, "RPC_S_INTERFACE_NOT_EXPORTED" }, + { 0x00000785, "RPC_S_PROFILE_NOT_ADDED" }, + { 0x00000786, "RPC_S_PRF_ELT_NOT_ADDED" }, + { 0x00000787, "RPC_S_PRF_ELT_NOT_REMOVED" }, + { 0x00000788, "RPC_S_GRP_ELT_NOT_ADDED" }, + { 0x00000789, "RPC_S_GRP_ELT_NOT_REMOVED" }, + { 0x0000078A, "ERROR_KM_DRIVER_BLOCKED" }, + { 0x0000078B, "ERROR_CONTEXT_EXPIRED" }, + { 0x0000078C, "ERROR_PER_USER_TRUST_QUOTA_EXCEEDED" }, + { 0x0000078D, "ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED" }, + { 0x0000078E, "ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED" }, + { 0x0000078F, "ERROR_AUTHENTICATION_FIREWALL_FAILED" }, + { 0x00000790, "ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED" }, + { 0x000007D0, "ERROR_INVALID_PIXEL_FORMAT" }, + { 0x000007D1, "ERROR_BAD_DRIVER" }, + { 0x000007D2, "ERROR_INVALID_WINDOW_STYLE" }, + { 0x000007D3, "ERROR_METAFILE_NOT_SUPPORTED" }, + { 0x000007D4, "ERROR_TRANSFORM_NOT_SUPPORTED" }, + { 0x000007D5, "ERROR_CLIPPING_NOT_SUPPORTED" }, + { 0x000007DA, "ERROR_INVALID_CMM" }, + { 0x000007DB, "ERROR_INVALID_PROFILE" }, + { 0x000007DC, "ERROR_TAG_NOT_FOUND" }, + { 0x000007DD, "ERROR_TAG_NOT_PRESENT" }, + { 0x000007DE, "ERROR_DUPLICATE_TAG" }, + { 0x000007DF, "ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE" }, + { 0x000007E0, "ERROR_PROFILE_NOT_FOUND" }, + { 0x000007E1, "ERROR_INVALID_COLORSPACE" }, + { 0x000007E2, "ERROR_ICM_NOT_ENABLED" }, + { 0x000007E3, "ERROR_DELETING_ICM_XFORM" }, + { 0x000007E4, "ERROR_INVALID_TRANSFORM" }, + { 0x000007E5, "ERROR_COLORSPACE_MISMATCH" }, + { 0x000007E6, "ERROR_INVALID_COLORINDEX" }, + { 0x000007E7, "ERROR_PROFILE_DOES_NOT_MATCH_DEVICE" }, + { 0x00000836, "NERR_NetNotStarted" }, + { 0x00000837, "NERR_UnknownServer" }, + { 0x00000838, "NERR_ShareMem" }, + { 0x00000839, "NERR_NoNetworkResource" }, + { 0x0000083A, "NERR_RemoteOnly" }, + { 0x0000083B, "NERR_DevNotRedirected" }, + { 0x0000083C, "ERROR_CONNECTED_OTHER_PASSWORD" }, + { 0x0000083D, "ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT" }, + { 0x00000842, "NERR_ServerNotStarted" }, + { 0x00000843, "NERR_ItemNotFound" }, + { 0x00000844, "NERR_UnknownDevDir" }, + { 0x00000845, "NERR_RedirectedPath" }, + { 0x00000846, "NERR_DuplicateShare" }, + { 0x00000847, "NERR_NoRoom" }, + { 0x00000849, "NERR_TooManyItems" }, + { 0x0000084A, "NERR_InvalidMaxUsers" }, + { 0x0000084B, "NERR_BufTooSmall" }, + { 0x0000084F, "NERR_RemoteErr" }, + { 0x00000853, "NERR_LanmanIniError" }, + { 0x00000858, "NERR_NetworkError" }, + { 0x00000859, "NERR_WkstaInconsistentState" }, + { 0x0000085A, "NERR_WkstaNotStarted" }, + { 0x0000085B, "NERR_BrowserNotStarted" }, + { 0x0000085C, "NERR_InternalError" }, + { 0x0000085D, "NERR_BadTransactConfig" }, + { 0x0000085E, "NERR_InvalidAPI" }, + { 0x0000085F, "NERR_BadEventName" }, + { 0x00000860, "NERR_DupNameReboot" }, + { 0x00000862, "NERR_CfgCompNotFound" }, + { 0x00000863, "NERR_CfgParamNotFound" }, + { 0x00000865, "NERR_LineTooLong" }, + { 0x00000866, "NERR_QNotFound" }, + { 0x00000867, "NERR_JobNotFound" }, + { 0x00000868, "NERR_DestNotFound" }, + { 0x00000869, "NERR_DestExists" }, + { 0x0000086A, "NERR_QExists" }, + { 0x0000086B, "NERR_QNoRoom" }, + { 0x0000086C, "NERR_JobNoRoom" }, + { 0x0000086D, "NERR_DestNoRoom" }, + { 0x0000086E, "NERR_DestIdle" }, + { 0x0000086F, "NERR_DestInvalidOp" }, + { 0x00000870, "NERR_ProcNoRespond" }, + { 0x00000871, "NERR_SpoolerNotLoaded" }, + { 0x00000872, "NERR_DestInvalidState" }, + { 0x00000873, "NERR_QinvalidState" }, + { 0x00000874, "NERR_JobInvalidState" }, + { 0x00000875, "NERR_SpoolNoMemory" }, + { 0x00000876, "NERR_DriverNotFound" }, + { 0x00000877, "NERR_DataTypeInvalid" }, + { 0x00000878, "NERR_ProcNotFound" }, + { 0x00000884, "NERR_ServiceTableLocked" }, + { 0x00000885, "NERR_ServiceTableFull" }, + { 0x00000886, "NERR_ServiceInstalled" }, + { 0x00000887, "NERR_ServiceEntryLocked" }, + { 0x00000888, "NERR_ServiceNotInstalled" }, + { 0x00000889, "NERR_BadServiceName" }, + { 0x0000088A, "NERR_ServiceCtlTimeout" }, + { 0x0000088B, "NERR_ServiceCtlBusy" }, + { 0x0000088C, "NERR_BadServiceProgName" }, + { 0x0000088D, "NERR_ServiceNotCtrl" }, + { 0x0000088E, "NERR_ServiceKillProc" }, + { 0x0000088F, "NERR_ServiceCtlNotValid" }, + { 0x00000890, "NERR_NotInDispatchTbl" }, + { 0x00000891, "NERR_BadControlRecv" }, + { 0x00000892, "NERR_ServiceNotStarting" }, + { 0x00000898, "NERR_AlreadyLoggedOn" }, + { 0x00000899, "NERR_NotLoggedOn" }, + { 0x0000089A, "NERR_BadUsername" }, + { 0x0000089B, "NERR_BadPassword" }, + { 0x0000089C, "NERR_UnableToAddName_W" }, + { 0x0000089D, "NERR_UnableToAddName_F" }, + { 0x0000089E, "NERR_UnableToDelName_W" }, + { 0x0000089F, "NERR_UnableToDelName_F" }, + { 0x000008A1, "NERR_LogonsPaused" }, + { 0x000008A2, "NERR_LogonServerConflict" }, + { 0x000008A3, "NERR_LogonNoUserPath" }, + { 0x000008A4, "NERR_LogonScriptError" }, + { 0x000008A6, "NERR_StandaloneLogon" }, + { 0x000008A7, "NERR_LogonServerNotFound" }, + { 0x000008A8, "NERR_LogonDomainExists" }, + { 0x000008A9, "NERR_NonValidatedLogon" }, + { 0x000008AB, "NERR_ACFNotFound" }, + { 0x000008AC, "NERR_GroupNotFound" }, + { 0x000008AD, "NERR_UserNotFound" }, + { 0x000008AE, "NERR_ResourceNotFound" }, + { 0x000008AF, "NERR_GroupExists" }, + { 0x000008B0, "NERR_UserExists" }, + { 0x000008B1, "NERR_ResourceExists" }, + { 0x000008B2, "NERR_NotPrimary" }, + { 0x000008B3, "NERR_ACFNotLoaded" }, + { 0x000008B4, "NERR_ACFNoRoom" }, + { 0x000008B5, "NERR_ACFFileIOFail" }, + { 0x000008B6, "NERR_ACFTooManyLists" }, + { 0x000008B7, "NERR_UserLogon" }, + { 0x000008B8, "NERR_ACFNoParent" }, + { 0x000008B9, "NERR_CanNotGrowSegment" }, + { 0x000008BA, "NERR_SpeGroupOp" }, + { 0x000008BB, "NERR_NotInCache" }, + { 0x000008BC, "NERR_UserInGroup" }, + { 0x000008BD, "NERR_UserNotInGroup" }, + { 0x000008BE, "NERR_AccountUndefined" }, + { 0x000008BF, "NERR_AccountExpired" }, + { 0x000008C0, "NERR_InvalidWorkstation" }, + { 0x000008C1, "NERR_InvalidLogonHours" }, + { 0x000008C2, "NERR_PasswordExpired" }, + { 0x000008C3, "NERR_PasswordCantChange" }, + { 0x000008C4, "NERR_PasswordHistConflict" }, + { 0x000008C5, "NERR_PasswordTooShort" }, + { 0x000008C6, "NERR_PasswordTooRecent" }, + { 0x000008C7, "NERR_InvalidDatabase" }, + { 0x000008C8, "NERR_DatabaseUpToDate" }, + { 0x000008C9, "NERR_SyncRequired" }, + { 0x000008CA, "NERR_UseNotFound" }, + { 0x000008CB, "NERR_BadAsgType_type" }, + { 0x000008CC, "NERR_DeviceIsShared" }, + { 0x000008DE, "NERR_NoComputerName" }, + { 0x000008DF, "NERR_MsgAlreadyStarted" }, + { 0x000008E0, "NERR_MsgInitFailed" }, + { 0x000008E1, "NERR_NameNotFound" }, + { 0x000008E2, "NERR_AlreadyForwarded" }, + { 0x000008E3, "NERR_AddForwarded" }, + { 0x000008E4, "NERR_AlreadyExists" }, + { 0x000008E5, "NERR_TooManyNames" }, + { 0x000008E6, "NERR_DelComputerName" }, + { 0x000008E7, "NERR_LocalForward" }, + { 0x000008E8, "NERR_GrpMsgProcessor" }, + { 0x000008E9, "NERR_PausedRemote" }, + { 0x000008EA, "NERR_BadReceive" }, + { 0x000008EB, "NERR_NameInUse" }, + { 0x000008EC, "NERR_MsgNotStarted" }, + { 0x000008ED, "NERR_NotLocalName" }, + { 0x000008EE, "NERR_NoForwardName" }, + { 0x000008EF, "NERR_RemoteFull" }, + { 0x000008F0, "NERR_NameNotForwarded" }, + { 0x000008F1, "NERR_TruncatedBroadcast" }, + { 0x000008F6, "NERR_InvalidDevice" }, + { 0x000008F7, "NERR_WriteFault" }, + { 0x000008F9, "NERR_DuplicateName" }, + { 0x000008FA, "NERR_DeleteLater" }, + { 0x000008FB, "NERR_IncompleteDel" }, + { 0x000008FC, "NERR_MultipleNets" }, + { 0x00000906, "NERR_NetNameNotFound" }, + { 0x00000907, "NERR_DeviceNotShared" }, + { 0x00000908, "NERR_ClientNameNotFound" }, + { 0x0000090A, "NERR_FileIdNotFound" }, + { 0x0000090B, "NERR_ExecFailure" }, + { 0x0000090C, "NERR_TmpFile" }, + { 0x0000090D, "NERR_TooMuchData" }, + { 0x0000090E, "NERR_DeviceShareConflict" }, + { 0x0000090F, "NERR_BrowserTableIncomplete" }, + { 0x00000910, "NERR_NotLocalDomain" }, + { 0x00000911, "NERR_IsDfsShare" }, + { 0x0000091B, "NERR_DevInvalidOpCode" }, + { 0x0000091C, "NERR_DevNotFound" }, + { 0x0000091D, "NERR_DevNotOpen" }, + { 0x0000091E, "NERR_BadQueueDevString" }, + { 0x0000091F, "NERR_BadQueuePriority" }, + { 0x00000921, "NERR_NoCommDevs" }, + { 0x00000922, "NERR_QueueNotFound" }, + { 0x00000924, "NERR_BadDevString" }, + { 0x00000925, "NERR_BadDev" }, + { 0x00000926, "NERR_InUseBySpooler" }, + { 0x00000927, "NERR_CommDevInUse" }, + { 0x0000092F, "NERR_InvalidComputer" }, + { 0x00000932, "NERR_MaxLenExceeded" }, + { 0x00000934, "NERR_BadComponent" }, + { 0x00000935, "NERR_CantType" }, + { 0x0000093A, "NERR_TooManyEntries" }, + { 0x00000942, "NERR_ProfileFileTooBig" }, + { 0x00000943, "NERR_ProfileOffset" }, + { 0x00000944, "NERR_ProfileCleanup" }, + { 0x00000945, "NERR_ProfileUnknownCmd" }, + { 0x00000946, "NERR_ProfileLoadErr" }, + { 0x00000947, "NERR_ProfileSaveErr" }, + { 0x00000949, "NERR_LogOverflow" }, + { 0x0000094A, "NERR_LogFileChanged" }, + { 0x0000094B, "NERR_LogFileCorrupt" }, + { 0x0000094C, "NERR_SourceIsDir" }, + { 0x0000094D, "NERR_BadSource" }, + { 0x0000094E, "NERR_BadDest" }, + { 0x0000094F, "NERR_DifferentServers" }, + { 0x00000951, "NERR_RunSrvPaused" }, + { 0x00000955, "NERR_ErrCommRunSrv" }, + { 0x00000957, "NERR_ErrorExecingGhost" }, + { 0x00000958, "NERR_ShareNotFound" }, + { 0x00000960, "NERR_InvalidLana" }, + { 0x00000961, "NERR_OpenFiles" }, + { 0x00000962, "NERR_ActiveConns" }, + { 0x00000963, "NERR_BadPasswordCore" }, + { 0x00000964, "NERR_DevInUse" }, + { 0x00000965, "NERR_LocalDrive" }, + { 0x0000097E, "NERR_AlertExists" }, + { 0x0000097F, "NERR_TooManyAlerts" }, + { 0x00000980, "NERR_NoSuchAlert" }, + { 0x00000981, "NERR_BadRecipient" }, + { 0x00000982, "NERR_AcctLimitExceeded" }, + { 0x00000988, "NERR_InvalidLogSeek" }, + { 0x00000992, "NERR_BadUasConfig" }, + { 0x00000993, "NERR_InvalidUASOp" }, + { 0x00000994, "NERR_LastAdmin" }, + { 0x00000995, "NERR_DCNotFound" }, + { 0x00000996, "NERR_LogonTrackingError" }, + { 0x00000997, "NERR_NetlogonNotStarted" }, + { 0x00000998, "NERR_CanNotGrowUASFile" }, + { 0x00000999, "NERR_TimeDiffAtDC" }, + { 0x0000099A, "NERR_PasswordMismatch" }, + { 0x0000099C, "NERR_NoSuchServer" }, + { 0x0000099D, "NERR_NoSuchSession" }, + { 0x0000099E, "NERR_NoSuchConnection" }, + { 0x0000099F, "NERR_TooManyServers" }, + { 0x000009A0, "NERR_TooManySessions" }, + { 0x000009A1, "NERR_TooManyConnections" }, + { 0x000009A2, "NERR_TooManyFiles" }, + { 0x000009A3, "NERR_NoAlternateServers" }, + { 0x000009A6, "NERR_TryDownLevel" }, + { 0x000009B0, "NERR_UPSDriverNotStarted" }, + { 0x000009B1, "NERR_UPSInvalidConfig" }, + { 0x000009B2, "NERR_UPSInvalidCommPort" }, + { 0x000009B3, "NERR_UPSSignalAsserted" }, + { 0x000009B4, "NERR_UPSShutdownFailed" }, + { 0x000009C4, "NERR_BadDosRetCode" }, + { 0x000009C5, "NERR_ProgNeedsExtraMem" }, + { 0x000009C6, "NERR_BadDosFunction" }, + { 0x000009C7, "NERR_RemoteBootFailed" }, + { 0x000009C8, "NERR_BadFileCheckSum" }, + { 0x000009C9, "NERR_NoRplBootSystem" }, + { 0x000009CA, "NERR_RplLoadrNetBiosErr" }, + { 0x000009CB, "NERR_RplLoadrDiskErr" }, + { 0x000009CC, "NERR_ImageParamErr" }, + { 0x000009CD, "NERR_TooManyImageParams" }, + { 0x000009CE, "NERR_NonDosFloppyUsed" }, + { 0x000009CF, "NERR_RplBootRestart" }, + { 0x000009D0, "NERR_RplSrvrCallFailed" }, + { 0x000009D1, "NERR_CantConnectRplSrvr" }, + { 0x000009D2, "NERR_CantOpenImageFile" }, + { 0x000009D3, "NERR_CallingRplSrvr" }, + { 0x000009D4, "NERR_StartingRplBoot" }, + { 0x000009D5, "NERR_RplBootServiceTerm" }, + { 0x000009D6, "NERR_RplBootStartFailed" }, + { 0x000009D7, "NERR_RPL_CONNECTED" }, + { 0x000009F6, "NERR_BrowserConfiguredToNotRun" }, + { 0x00000A32, "NERR_RplNoAdaptersStarted" }, + { 0x00000A33, "NERR_RplBadRegistry" }, + { 0x00000A34, "NERR_RplBadDatabase" }, + { 0x00000A35, "NERR_RplRplfilesShare" }, + { 0x00000A36, "NERR_RplNotRplServer" }, + { 0x00000A37, "NERR_RplCannotEnum" }, + { 0x00000A38, "NERR_RplWkstaInfoCorrupted" }, + { 0x00000A39, "NERR_RplWkstaNotFound" }, + { 0x00000A3A, "NERR_RplWkstaNameUnavailable" }, + { 0x00000A3B, "NERR_RplProfileInfoCorrupted" }, + { 0x00000A3C, "NERR_RplProfileNotFound" }, + { 0x00000A3D, "NERR_RplProfileNameUnavailable" }, + { 0x00000A3E, "NERR_RplProfileNotEmpty" }, + { 0x00000A3F, "NERR_RplConfigInfoCorrupted" }, + { 0x00000A40, "NERR_RplConfigNotFound" }, + { 0x00000A41, "NERR_RplAdapterInfoCorrupted" }, + { 0x00000A42, "NERR_RplInternal" }, + { 0x00000A43, "NERR_RplVendorInfoCorrupted" }, + { 0x00000A44, "NERR_RplBootInfoCorrupted" }, + { 0x00000A45, "NERR_RplWkstaNeedsUserAcct" }, + { 0x00000A46, "NERR_RplNeedsRPLUSERAcct" }, + { 0x00000A47, "NERR_RplBootNotFound" }, + { 0x00000A48, "NERR_RplIncompatibleProfile" }, + { 0x00000A49, "NERR_RplAdapterNameUnavailable" }, + { 0x00000A4A, "NERR_RplConfigNotEmpty" }, + { 0x00000A4B, "NERR_RplBootInUse" }, + { 0x00000A4C, "NERR_RplBackupDatabase" }, + { 0x00000A4D, "NERR_RplAdapterNotFound" }, + { 0x00000A4E, "NERR_RplVendorNotFound" }, + { 0x00000A4F, "NERR_RplVendorNameUnavailable" }, + { 0x00000A50, "NERR_RplBootNameUnavailable" }, + { 0x00000A51, "NERR_RplConfigNameUnavailable" }, + { 0x00000A64, "NERR_DfsInternalCorruption" }, + { 0x00000A65, "NERR_DfsVolumeDataCorrupt" }, + { 0x00000A66, "NERR_DfsNoSuchVolume" }, + { 0x00000A67, "NERR_DfsVolumeAlreadyExists" }, + { 0x00000A68, "NERR_DfsAlreadyShared" }, + { 0x00000A69, "NERR_DfsNoSuchShare" }, + { 0x00000A6A, "NERR_DfsNotALeafVolume" }, + { 0x00000A6B, "NERR_DfsLeafVolume" }, + { 0x00000A6C, "NERR_DfsVolumeHasMultipleServers" }, + { 0x00000A6D, "NERR_DfsCantCreateJunctionPoint" }, + { 0x00000A6E, "NERR_DfsServerNotDfsAware" }, + { 0x00000A6F, "NERR_DfsBadRenamePath" }, + { 0x00000A70, "NERR_DfsVolumeIsOffline" }, + { 0x00000A71, "NERR_DfsNoSuchServer" }, + { 0x00000A72, "NERR_DfsCyclicalName" }, + { 0x00000A73, "NERR_DfsNotSupportedInServerDfs" }, + { 0x00000A74, "NERR_DfsDuplicateService" }, + { 0x00000A75, "NERR_DfsCantRemoveLastServerShare" }, + { 0x00000A76, "NERR_DfsVolumeIsInterDfs" }, + { 0x00000A77, "NERR_DfsInconsistent" }, + { 0x00000A78, "NERR_DfsServerUpgraded" }, + { 0x00000A79, "NERR_DfsDataIsIdentical" }, + { 0x00000A7A, "NERR_DfsCantRemoveDfsRoot" }, + { 0x00000A7B, "NERR_DfsChildOrParentInDfs" }, + { 0x00000A82, "NERR_DfsInternalError" }, + { 0x00000A83, "NERR_SetupAlreadyJoined" }, + { 0x00000A84, "NERR_SetupNotJoined" }, + { 0x00000A85, "NERR_SetupDomainController" }, + { 0x00000A86, "NERR_DefaultJoinRequired" }, + { 0x00000A87, "NERR_InvalidWorkgroupName" }, + { 0x00000A88, "NERR_NameUsesIncompatibleCodePage" }, + { 0x00000A89, "NERR_ComputerAccountNotFound" }, + { 0x00000A8A, "NERR_PersonalSku" }, + { 0x00000A8D, "NERR_PasswordMustChange" }, + { 0x00000A8E, "NERR_AccountLockedOut" }, + { 0x00000A8F, "NERR_PasswordTooLong" }, + { 0x00000A90, "NERR_PasswordNotComplexEnough" }, + { 0x00000A91, "NERR_PasswordFilterError" }, + { 0x00000BB8, "ERROR_UNKNOWN_PRINT_MONITOR" }, + { 0x00000BB9, "ERROR_PRINTER_DRIVER_IN_USE" }, + { 0x00000BBA, "ERROR_SPOOL_FILE_NOT_FOUND" }, + { 0x00000BBB, "ERROR_SPL_NO_STARTDOC" }, + { 0x00000BBC, "ERROR_SPL_NO_ADDJOB" }, + { 0x00000BBD, "ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED" }, + { 0x00000BBE, "ERROR_PRINT_MONITOR_ALREADY_INSTALLED" }, + { 0x00000BBF, "ERROR_INVALID_PRINT_MONITOR" }, + { 0x00000BC0, "ERROR_PRINT_MONITOR_IN_USE" }, + { 0x00000BC1, "ERROR_PRINTER_HAS_JOBS_QUEUED" }, + { 0x00000BC2, "ERROR_SUCCESS_REBOOT_REQUIRED" }, + { 0x00000BC3, "ERROR_SUCCESS_RESTART_REQUIRED" }, + { 0x00000BC4, "ERROR_PRINTER_NOT_FOUND" }, + { 0x00000BC5, "ERROR_PRINTER_DRIVER_WARNED" }, + { 0x00000BC6, "ERROR_PRINTER_DRIVER_BLOCKED" }, + { 0x00000BC7, "ERROR_PRINTER_DRIVER_PACKAGE_IN_USE" }, + { 0x00000BC8, "ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND" }, + { 0x00000BC9, "ERROR_FAIL_REBOOT_REQUIRED" }, + { 0x00000BCA, "ERROR_FAIL_REBOOT_INITIATED" }, + { 0x00000BCB, "ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED" }, + { 0x00000BCE, "ERROR_PRINTER_NOT_SHAREABLE" }, + { 0x00000F6E, "ERROR_IO_REISSUE_AS_CACHED" }, + { 0x00000FA0, "ERROR_WINS_INTERNAL" }, + { 0x00000FA1, "ERROR_CAN_NOT_DEL_LOCAL_WINS" }, + { 0x00000FA2, "ERROR_STATIC_INIT" }, + { 0x00000FA3, "ERROR_INC_BACKUP" }, + { 0x00000FA4, "ERROR_FULL_BACKUP" }, + { 0x00000FA5, "ERROR_REC_NON_EXISTENT" }, + { 0x00000FA6, "ERROR_RPL_NOT_ALLOWED" }, + { 0x00000FD2, "PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED" }, + { 0x00000FD3, "PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO" }, + { 0x00000FD4, "PEERDIST_ERROR_MISSING_DATA" }, + { 0x00000FD5, "PEERDIST_ERROR_NO_MORE" }, + { 0x00000FD6, "PEERDIST_ERROR_NOT_INITIALIZED" }, + { 0x00000FD7, "PEERDIST_ERROR_ALREADY_INITIALIZED" }, + { 0x00000FD8, "PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS" }, + { 0x00000FD9, "PEERDIST_ERROR_INVALIDATED" }, + { 0x00000FDA, "PEERDIST_ERROR_ALREADY_EXISTS" }, + { 0x00000FDB, "PEERDIST_ERROR_OPERATION_NOTFOUND" }, + { 0x00000FDC, "PEERDIST_ERROR_ALREADY_COMPLETED" }, + { 0x00000FDD, "PEERDIST_ERROR_OUT_OF_BOUNDS" }, + { 0x00000FDE, "PEERDIST_ERROR_VERSION_UNSUPPORTED" }, + { 0x00000FDF, "PEERDIST_ERROR_INVALID_CONFIGURATION" }, + { 0x00000FE0, "PEERDIST_ERROR_NOT_LICENSED" }, + { 0x00000FE1, "PEERDIST_ERROR_SERVICE_UNAVAILABLE" }, + { 0x00001004, "ERROR_DHCP_ADDRESS_CONFLICT" + + }, + { 0x00001068, "ERROR_WMI_GUID_NOT_FOUND" }, + { 0x00001069, "ERROR_WMI_INSTANCE_NOT_FOUND" }, + { 0x0000106A, "ERROR_WMI_ITEMID_NOT_FOUND" }, + { 0x0000106B, "ERROR_WMI_TRY_AGAIN" }, + { 0x0000106C, "ERROR_WMI_DP_NOT_FOUND" }, + { 0x0000106D, "ERROR_WMI_UNRESOLVED_INSTANCE_REF" }, + { 0x0000106E, "ERROR_WMI_ALREADY_ENABLED" }, + { 0x0000106F, "ERROR_WMI_GUID_DISCONNECTED" }, + { 0x00001070, "ERROR_WMI_SERVER_UNAVAILABLE" }, + { 0x00001071, "ERROR_WMI_DP_FAILED" }, + { 0x00001072, "ERROR_WMI_INVALID_MOF" }, + { 0x00001073, "ERROR_WMI_INVALID_REGINFO" }, + { 0x00001074, "ERROR_WMI_ALREADY_DISABLED" }, + { 0x00001075, "ERROR_WMI_READ_ONLY" }, + { 0x00001076, "ERROR_WMI_SET_FAILURE" }, + { 0x000010CC, "ERROR_INVALID_MEDIA" }, + { 0x000010CD, "ERROR_INVALID_LIBRARY" }, + { 0x000010CE, "ERROR_INVALID_MEDIA_POOL" }, + { 0x000010CF, "ERROR_DRIVE_MEDIA_MISMATCH" }, + { 0x000010D0, "ERROR_MEDIA_OFFLINE" }, + { 0x000010D1, "ERROR_LIBRARY_OFFLINE" }, + { 0x000010D2, "ERROR_EMPTY" }, + { 0x000010D3, "ERROR_NOT_EMPTY" }, + { 0x000010D4, "ERROR_MEDIA_UNAVAILABLE" }, + { 0x000010D5, "ERROR_RESOURCE_DISABLED" }, + { 0x000010D6, "ERROR_INVALID_CLEANER" }, + { 0x000010D7, "ERROR_UNABLE_TO_CLEAN" }, + { 0x000010D8, "ERROR_OBJECT_NOT_FOUND" }, + { 0x000010D9, "ERROR_DATABASE_FAILURE" }, + { 0x000010DA, "ERROR_DATABASE_FULL" }, + { 0x000010DB, "ERROR_MEDIA_INCOMPATIBLE" }, + { 0x000010DC, "ERROR_RESOURCE_NOT_PRESENT" }, + { 0x000010DD, "ERROR_INVALID_OPERATION" }, + { 0x000010DE, "ERROR_MEDIA_NOT_AVAILABLE" }, + { 0x000010DF, "ERROR_DEVICE_NOT_AVAILABLE" }, + { 0x000010E0, "ERROR_REQUEST_REFUSED" }, + { 0x000010E1, "ERROR_INVALID_DRIVE_OBJECT" }, + { 0x000010E2, "ERROR_LIBRARY_FULL" }, + { 0x000010E3, "ERROR_MEDIUM_NOT_ACCESSIBLE" }, + { 0x000010E4, "ERROR_UNABLE_TO_LOAD_MEDIUM" }, + { 0x000010E5, "ERROR_UNABLE_TO_INVENTORY_DRIVE" }, + { 0x000010E6, "ERROR_UNABLE_TO_INVENTORY_SLOT" }, + { 0x000010E7, "ERROR_UNABLE_TO_INVENTORY_TRANSPORT" }, + { 0x000010E8, "ERROR_TRANSPORT_FULL" }, + { 0x000010E9, "ERROR_CONTROLLING_IEPORT" }, + { 0x000010EA, "ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA" }, + { 0x000010EB, "ERROR_CLEANER_SLOT_SET" }, + { 0x000010EC, "ERROR_CLEANER_SLOT_NOT_SET" }, + { 0x000010ED, "ERROR_CLEANER_CARTRIDGE_SPENT" }, + { 0x000010EE, "ERROR_UNEXPECTED_OMID" }, + { 0x000010EF, "ERROR_CANT_DELETE_LAST_ITEM" }, + { 0x000010F0, "ERROR_MESSAGE_EXCEEDS_MAX_SIZE" }, + { 0x000010F1, "ERROR_VOLUME_CONTAINS_SYS_FILES" }, + { 0x000010F2, "ERROR_INDIGENOUS_TYPE" }, + { 0x000010F3, "ERROR_NO_SUPPORTING_DRIVES" }, + { 0x000010F4, "ERROR_CLEANER_CARTRIDGE_INSTALLED" }, + { 0x000010F5, "ERROR_IEPORT_FULL" }, + { 0x000010FE, "ERROR_FILE_OFFLINE" }, + { 0x000010FF, "ERROR_REMOTE_STORAGE_NOT_ACTIVE" }, + { 0x00001100, "ERROR_REMOTE_STORAGE_MEDIA_ERROR" }, + { 0x00001126, "ERROR_NOT_A_REPARSE_POINT" }, + { 0x00001127, "ERROR_REPARSE_ATTRIBUTE_CONFLICT" }, + { 0x00001128, "ERROR_INVALID_REPARSE_DATA" }, + { 0x00001129, "ERROR_REPARSE_TAG_INVALID" }, + { 0x0000112A, "ERROR_REPARSE_TAG_MISMATCH" }, + { 0x00001194, "ERROR_VOLUME_NOT_SIS_ENABLED" }, + { 0x00001389, "ERROR_DEPENDENT_RESOURCE_EXISTS" }, + { 0x0000138A, "ERROR_DEPENDENCY_NOT_FOUND" }, + { 0x0000138B, "ERROR_DEPENDENCY_ALREADY_EXISTS" }, + { 0x0000138C, "ERROR_RESOURCE_NOT_ONLINE" }, + { 0x0000138D, "ERROR_HOST_NODE_NOT_AVAILABLE" }, + { 0x0000138E, "ERROR_RESOURCE_NOT_AVAILABLE" }, + { 0x0000138F, "ERROR_RESOURCE_NOT_FOUND" }, + { 0x00001390, "ERROR_SHUTDOWN_CLUSTER" }, + { 0x00001391, "ERROR_CANT_EVICT_ACTIVE_NODE" }, + { 0x00001392, "ERROR_OBJECT_ALREADY_EXISTS" }, + { 0x00001393, "ERROR_OBJECT_IN_LIST" }, + { 0x00001394, "ERROR_GROUP_NOT_AVAILABLE" }, + { 0x00001395, "ERROR_GROUP_NOT_FOUND" }, + { 0x00001396, "ERROR_GROUP_NOT_ONLINE" }, + { 0x00001397, "ERROR_HOST_NODE_NOT_RESOURCE_OWNER" }, + { 0x00001398, "ERROR_HOST_NODE_NOT_GROUP_OWNER" }, + { 0x00001399, "ERROR_RESMON_CREATE_FAILED" }, + { 0x0000139A, "ERROR_RESMON_ONLINE_FAILED" }, + { 0x0000139B, "ERROR_RESOURCE_ONLINE" }, + { 0x0000139C, "ERROR_QUORUM_RESOURCE" }, + { 0x0000139D, "ERROR_NOT_QUORUM_CAPABLE" }, + { 0x0000139E, "ERROR_CLUSTER_SHUTTING_DOWN" }, + { 0x0000139F, "ERROR_INVALID_STATE" }, + { 0x000013A0, "ERROR_RESOURCE_PROPERTIES_STORED" }, + { 0x000013A1, "ERROR_NOT_QUORUM_CLASS" }, + { 0x000013A2, "ERROR_CORE_RESOURCE" }, + { 0x000013A3, "ERROR_QUORUM_RESOURCE_ONLINE_FAILED" }, + { 0x000013A4, "ERROR_QUORUMLOG_OPEN_FAILED" }, + { 0x000013A5, "ERROR_CLUSTERLOG_CORRUPT" }, + { 0x000013A6, "ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE" }, + { 0x000013A7, "ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE" }, + { 0x000013A8, "ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND" }, + { 0x000013A9, "ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE" }, + { 0x000013AA, "ERROR_QUORUM_OWNER_ALIVE" }, + { 0x000013AB, "ERROR_NETWORK_NOT_AVAILABLE" }, + { 0x000013AC, "ERROR_NODE_NOT_AVAILABLE" }, + { 0x000013AD, "ERROR_ALL_NODES_NOT_AVAILABLE" }, + { 0x000013AE, "ERROR_RESOURCE_FAILED" }, + { 0x000013AF, "ERROR_CLUSTER_INVALID_NODE" }, + { 0x000013B0, "ERROR_CLUSTER_NODE_EXISTS" }, + { 0x000013B1, "ERROR_CLUSTER_JOIN_IN_PROGRESS" }, + { 0x000013B2, "ERROR_CLUSTER_NODE_NOT_FOUND" }, + { 0x000013B3, "ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND" }, + { 0x000013B4, "ERROR_CLUSTER_NETWORK_EXISTS" }, + { 0x000013B5, "ERROR_CLUSTER_NETWORK_NOT_FOUND" }, + { 0x000013B6, "ERROR_CLUSTER_NETINTERFACE_EXISTS" }, + { 0x000013B7, "ERROR_CLUSTER_NETINTERFACE_NOT_FOUND" }, + { 0x000013B8, "ERROR_CLUSTER_INVALID_REQUEST" }, + { 0x000013B9, "ERROR_CLUSTER_INVALID_NETWORK_PROVIDER" }, + { 0x000013BA, "ERROR_CLUSTER_NODE_DOWN" }, + { 0x000013BB, "ERROR_CLUSTER_NODE_UNREACHABLE" }, + { 0x000013BC, "ERROR_CLUSTER_NODE_NOT_MEMBER" }, + { 0x000013BD, "ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS" }, + { 0x000013BE, "ERROR_CLUSTER_INVALID_NETWORK" }, + { 0x000013C0, "ERROR_CLUSTER_NODE_UP" }, + { 0x000013C1, "ERROR_CLUSTER_IPADDR_IN_USE" }, + { 0x000013C2, "ERROR_CLUSTER_NODE_NOT_PAUSED" }, + { 0x000013C3, "ERROR_CLUSTER_NO_SECURITY_CONTEXT" }, + { 0x000013C4, "ERROR_CLUSTER_NETWORK_NOT_INTERNAL" }, + { 0x000013C5, "ERROR_CLUSTER_NODE_ALREADY_UP" }, + { 0x000013C6, "ERROR_CLUSTER_NODE_ALREADY_DOWN" }, + { 0x000013C7, "ERROR_CLUSTER_NETWORK_ALREADY_ONLINE" }, + { 0x000013C8, "ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE" }, + { 0x000013C9, "ERROR_CLUSTER_NODE_ALREADY_MEMBER" }, + { 0x000013CA, "ERROR_CLUSTER_LAST_INTERNAL_NETWORK" }, + { 0x000013CB, "ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS" }, + { 0x000013CC, "ERROR_INVALID_OPERATION_ON_QUORUM" }, + { 0x000013CD, "ERROR_DEPENDENCY_NOT_ALLOWED" }, + { 0x000013CE, "ERROR_CLUSTER_NODE_PAUSED" }, + { 0x000013CF, "ERROR_NODE_CANT_HOST_RESOURCE" }, + { 0x000013D0, "ERROR_CLUSTER_NODE_NOT_READY" }, + { 0x000013D1, "ERROR_CLUSTER_NODE_SHUTTING_DOWN" }, + { 0x000013D2, "ERROR_CLUSTER_JOIN_ABORTED" }, + { 0x000013D3, "ERROR_CLUSTER_INCOMPATIBLE_VERSIONS" }, + { 0x000013D4, "ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED" }, + { 0x000013D5, "ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED" }, + { 0x000013D6, "ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND" }, + { 0x000013D7, "ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED" }, + { 0x000013D8, "ERROR_CLUSTER_RESNAME_NOT_FOUND" }, + { 0x000013D9, "ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED" }, + { 0x000013DA, "ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST" }, + { 0x000013DB, "ERROR_CLUSTER_DATABASE_SEQMISMATCH" }, + { 0x000013DC, "ERROR_RESMON_INVALID_STATE" }, + { 0x000013DD, "ERROR_CLUSTER_GUM_NOT_LOCKER" }, + { 0x000013DE, "ERROR_QUORUM_DISK_NOT_FOUND" }, + { 0x000013DF, "ERROR_DATABASE_BACKUP_CORRUPT" }, + { 0x000013E0, "ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT" }, + { 0x000013E1, "ERROR_RESOURCE_PROPERTY_UNCHANGEABLE" }, + { 0x00001702, "ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE" }, + { 0x00001703, "ERROR_CLUSTER_QUORUMLOG_NOT_FOUND" }, + { 0x00001704, "ERROR_CLUSTER_MEMBERSHIP_HALT" }, + { 0x00001705, "ERROR_CLUSTER_INSTANCE_ID_MISMATCH" }, + { 0x00001706, "ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP" }, + { 0x00001707, "ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH" }, + { 0x00001708, "ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP" + + }, + { 0x00001709, "ERROR_CLUSTER_PARAMETER_MISMATCH" }, + { 0x0000170A, "ERROR_NODE_CANNOT_BE_CLUSTERED" }, + { 0x0000170B, "ERROR_CLUSTER_WRONG_OS_VERSION" }, + { 0x0000170C, "ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME" }, + { 0x0000170D, "ERROR_CLUSCFG_ALREADY_COMMITTED" }, + { 0x0000170E, "ERROR_CLUSCFG_ROLLBACK_FAILED" }, + { 0x0000170F, "ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT" }, + { 0x00001710, "ERROR_CLUSTER_OLD_VERSION" }, + { 0x00001711, "ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME" }, + { 0x00001712, "ERROR_CLUSTER_NO_NET_ADAPTERS" }, + { 0x00001713, "ERROR_CLUSTER_POISONED" }, + { 0x00001714, "ERROR_CLUSTER_GROUP_MOVING" }, + { 0x00001715, "ERROR_CLUSTER_RESOURCE_TYPE_BUSY" }, + { 0x00001716, "ERROR_RESOURCE_CALL_TIMED_OUT" }, + { 0x00001717, "ERROR_INVALID_CLUSTER_IPV6_ADDRESS" }, + { 0x00001718, "ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION" }, + { 0x00001719, "ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS" }, + { 0x0000171A, "ERROR_CLUSTER_PARTIAL_SEND" }, + { 0x0000171B, "ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION" }, + { 0x0000171C, "ERROR_CLUSTER_INVALID_STRING_TERMINATION" }, + { 0x0000171D, "ERROR_CLUSTER_INVALID_STRING_FORMAT" }, + { 0x0000171E, "ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS" }, + { 0x0000171F, "ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS" }, + { 0x00001720, "ERROR_CLUSTER_NULL_DATA" }, + { 0x00001721, "ERROR_CLUSTER_PARTIAL_READ" }, + { 0x00001722, "ERROR_CLUSTER_PARTIAL_WRITE" }, + { 0x00001723, "ERROR_CLUSTER_CANT_DESERIALIZE_DATA" }, + { 0x00001724, "ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT" }, + { 0x00001725, "ERROR_CLUSTER_NO_QUORUM" }, + { 0x00001726, "ERROR_CLUSTER_INVALID_IPV6_NETWORK" }, + { 0x00001727, "ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK" }, + { 0x00001728, "ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP" }, + { 0x00001770, "ERROR_ENCRYPTION_FAILED" }, + { 0x00001771, "ERROR_DECRYPTION_FAILED" }, + { 0x00001772, "ERROR_FILE_ENCRYPTED" }, + { 0x00001773, "ERROR_NO_RECOVERY_POLICY" }, + { 0x00001774, "ERROR_NO_EFS" }, + { 0x00001775, "ERROR_WRONG_EFS" }, + { 0x00001776, "ERROR_NO_USER_KEYS" }, + { 0x00001777, "ERROR_FILE_NOT_ENCRYPTED" }, + { 0x00001778, "ERROR_NOT_EXPORT_FORMAT" }, + { 0x00001779, "ERROR_FILE_READ_ONLY" }, + { 0x0000177A, "ERROR_DIR_EFS_DISALLOWED" }, + { 0x0000177B, "ERROR_EFS_SERVER_NOT_TRUSTED" }, + { 0x0000177C, "ERROR_BAD_RECOVERY_POLICY" }, + { 0x0000177D, "ERROR_EFS_ALG_BLOB_TOO_BIG" }, + { 0x0000177E, "ERROR_VOLUME_NOT_SUPPORT_EFS" }, + { 0x0000177F, "ERROR_EFS_DISABLED" }, + { 0x00001780, "ERROR_EFS_VERSION_NOT_SUPPORT" }, + { 0x00001781, "ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE" }, + { 0x00001782, "ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER" }, + { 0x00001783, "ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE" }, + { 0x00001784, "ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE" }, + { 0x00001785, "ERROR_CS_ENCRYPTION_FILE_NOT_CSE" }, + { 0x000017E6, "ERROR_NO_BROWSER_SERVERS_FOUND" }, + { 0x00001838, "SCHED_E_SERVICE_NOT_LOCALSYSTEM" }, + { 0x000019C8, "ERROR_LOG_SECTOR_INVALID" }, + { 0x000019C9, "ERROR_LOG_SECTOR_PARITY_INVALID" }, + { 0x000019CA, "ERROR_LOG_SECTOR_REMAPPED" }, + { 0x000019CB, "ERROR_LOG_BLOCK_INCOMPLETE" }, + { 0x000019CC, "ERROR_LOG_INVALID_RANGE" }, + { 0x000019CD, "ERROR_LOG_BLOCKS_EXHAUSTED" }, + { 0x000019CE, "ERROR_LOG_READ_CONTEXT_INVALID" }, + { 0x000019CF, "ERROR_LOG_RESTART_INVALID" }, + { 0x000019D0, "ERROR_LOG_BLOCK_VERSION" }, + { 0x000019D1, "ERROR_LOG_BLOCK_INVALID" }, + { 0x000019D2, "ERROR_LOG_READ_MODE_INVALID" }, + { 0x000019D3, "ERROR_LOG_NO_RESTART" }, + { 0x000019D4, "ERROR_LOG_METADATA_CORRUPT" }, + { 0x000019D5, "ERROR_LOG_METADATA_INVALID" }, + { 0x000019D6, "ERROR_LOG_METADATA_INCONSISTENT" }, + { 0x000019D7, "ERROR_LOG_RESERVATION_INVALID" }, + { 0x000019D8, "ERROR_LOG_CANT_DELETE" }, + { 0x000019D9, "ERROR_LOG_CONTAINER_LIMIT_EXCEEDED" }, + { 0x000019DA, "ERROR_LOG_START_OF_LOG" }, + { 0x000019DB, "ERROR_LOG_POLICY_ALREADY_INSTALLED" }, + { 0x000019DC, "ERROR_LOG_POLICY_NOT_INSTALLED" }, + { 0x000019DD, "ERROR_LOG_POLICY_INVALID" }, + { 0x000019DE, "ERROR_LOG_POLICY_CONFLICT" }, + { 0x000019DF, "ERROR_LOG_PINNED_ARCHIVE_TAIL" }, + { 0x000019E0, "ERROR_LOG_RECORD_NONEXISTENT" }, + { 0x000019E1, "ERROR_LOG_RECORDS_RESERVED_INVALID" }, + { 0x000019E2, "ERROR_LOG_SPACE_RESERVED_INVALID" }, + { 0x000019E3, "ERROR_LOG_TAIL_INVALID" }, + { 0x000019E4, "ERROR_LOG_FULL" }, + { 0x000019E5, "ERROR_COULD_NOT_RESIZE_LOG" }, + { 0x000019E6, "ERROR_LOG_MULTIPLEXED" }, + { 0x000019E7, "ERROR_LOG_DEDICATED" }, + { 0x000019E8, "ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS" }, + { 0x000019E9, "ERROR_LOG_ARCHIVE_IN_PROGRESS" }, + { 0x000019EA, "ERROR_LOG_EPHEMERAL" }, + { 0x000019EB, "ERROR_LOG_NOT_ENOUGH_CONTAINERS" }, + { 0x000019EC, "ERROR_LOG_CLIENT_ALREADY_REGISTERED" }, + { 0x000019ED, "ERROR_LOG_CLIENT_NOT_REGISTERED" }, + { 0x000019EE, "ERROR_LOG_FULL_HANDLER_IN_PROGRESS" }, + { 0x000019EF, "ERROR_LOG_CONTAINER_READ_FAILED" }, + { 0x000019F0, "ERROR_LOG_CONTAINER_WRITE_FAILED" }, + { 0x000019F1, "ERROR_LOG_CONTAINER_OPEN_FAILED" }, + { 0x000019F2, "ERROR_LOG_CONTAINER_STATE_INVALID" }, + { 0x000019F3, "ERROR_LOG_STATE_INVALID" }, + { 0x000019F4, "ERROR_LOG_PINNED" }, + { 0x000019F5, "ERROR_LOG_METADATA_FLUSH_FAILED" }, + { 0x000019F6, "ERROR_LOG_INCONSISTENT_SECURITY" }, + { 0x000019F7, "ERROR_LOG_APPENDED_FLUSH_FAILED" }, + { 0x000019F8, "ERROR_LOG_PINNED_RESERVATION" }, + { 0x00001A2C, "ERROR_INVALID_TRANSACTION" }, + { 0x00001A2D, "ERROR_TRANSACTION_NOT_ACTIVE" }, + { 0x00001A2E, "ERROR_TRANSACTION_REQUEST_NOT_VALID" }, + { 0x00001A2F, "ERROR_TRANSACTION_NOT_REQUESTED" }, + { 0x00001A30, "ERROR_TRANSACTION_ALREADY_ABORTED" }, + { 0x00001A31, "ERROR_TRANSACTION_ALREADY_COMMITTED" }, + { 0x00001A32, "ERROR_TM_INITIALIZATION_FAILED" }, + { 0x00001A33, "ERROR_RESOURCEMANAGER_READ_ONLY" }, + { 0x00001A34, "ERROR_TRANSACTION_NOT_JOINED" }, + { 0x00001A35, "ERROR_TRANSACTION_SUPERIOR_EXISTS" }, + { 0x00001A36, "ERROR_CRM_PROTOCOL_ALREADY_EXISTS" }, + { 0x00001A37, "ERROR_TRANSACTION_PROPAGATION_FAILED" }, + { 0x00001A38, "ERROR_CRM_PROTOCOL_NOT_FOUND" }, + { 0x00001A39, "ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER" }, + { 0x00001A3A, "ERROR_CURRENT_TRANSACTION_NOT_VALID" }, + { 0x00001A3B, "ERROR_TRANSACTION_NOT_FOUND" }, + { 0x00001A3C, "ERROR_RESOURCEMANAGER_NOT_FOUND" }, + { 0x00001A3D, "ERROR_ENLISTMENT_NOT_FOUND" }, + { 0x00001A3E, "ERROR_TRANSACTIONMANAGER_NOT_FOUND" }, + { 0x00001A3F, "ERROR_TRANSACTIONMANAGER_NOT_ONLINE" }, + { 0x00001A40, "ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION" }, + { 0x00001A90, "ERROR_TRANSACTIONAL_CONFLICT" }, + { 0x00001A91, "ERROR_RM_NOT_ACTIVE" }, + { 0x00001A92, "ERROR_RM_METADATA_CORRUPT" }, + { 0x00001A93, "ERROR_DIRECTORY_NOT_RM" }, + { 0x00001A95, "ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE" }, + { 0x00001A96, "ERROR_LOG_RESIZE_INVALID_SIZE" }, + { 0x00001A97, "ERROR_OBJECT_NO_LONGER_EXISTS" }, + { 0x00001A98, "ERROR_STREAM_MINIVERSION_NOT_FOUND" }, + { 0x00001A99, "ERROR_STREAM_MINIVERSION_NOT_VALID" }, + { 0x00001A9A, "ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION" }, + { 0x00001A9B, "ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT" }, + { 0x00001A9C, "ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS" }, + { 0x00001A9E, "ERROR_REMOTE_FILE_VERSION_MISMATCH" }, + { 0x00001A9F, "ERROR_HANDLE_NO_LONGER_VALID" }, + { 0x00001AA0, "ERROR_NO_TXF_METADATA" }, + { 0x00001AA1, "ERROR_LOG_CORRUPTION_DETECTED" }, + { 0x00001AA2, "ERROR_CANT_RECOVER_WITH_HANDLE_OPEN" }, + { 0x00001AA3, "ERROR_RM_DISCONNECTED" }, + { 0x00001AA4, "ERROR_ENLISTMENT_NOT_SUPERIOR" }, + { 0x00001AA5, "ERROR_RECOVERY_NOT_NEEDED" }, + { 0x00001AA6, "ERROR_RM_ALREADY_STARTED" }, + { 0x00001AA7, "ERROR_FILE_IDENTITY_NOT_PERSISTENT" }, + { 0x00001AA8, "ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY" }, + { 0x00001AA9, "ERROR_CANT_CROSS_RM_BOUNDARY" }, + { 0x00001AAA, "ERROR_TXF_DIR_NOT_EMPTY" }, + { 0x00001AAB, "ERROR_INDOUBT_TRANSACTIONS_EXIST" }, + { 0x00001AAC, "ERROR_TM_VOLATILE" }, + { 0x00001AAD, "ERROR_ROLLBACK_TIMER_EXPIRED" }, + { 0x00001AAE, "ERROR_TXF_ATTRIBUTE_CORRUPT" }, + { 0x00001AAF, "ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION" }, + { 0x00001AB0, "ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED" }, + { 0x00001AB1, "ERROR_LOG_GROWTH_FAILED" }, + { 0x00001AB2, "ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE" }, + { 0x00001AB3, "ERROR_TXF_METADATA_ALREADY_PRESENT" }, + { 0x00001AB4, "ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET" }, + { 0x00001AB5, "ERROR_TRANSACTION_REQUIRED_PROMOTION" }, + { 0x00001AB6, "ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION" }, + { 0x00001AB7, "ERROR_TRANSACTIONS_NOT_FROZEN" }, + { 0x00001AB8, "ERROR_TRANSACTION_FREEZE_IN_PROGRESS" }, + { 0x00001AB9, "ERROR_NOT_SNAPSHOT_VOLUME" }, + { 0x00001ABA, "ERROR_NO_SAVEPOINT_WITH_OPEN_FILES" }, + { 0x00001ABB, "ERROR_DATA_LOST_REPAIR" }, + { 0x00001ABC, "ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION" }, + { 0x00001ABD, "ERROR_TM_IDENTITY_MISMATCH" }, + { 0x00001ABE, "ERROR_FLOATED_SECTION" }, + { 0x00001ABF, "ERROR_CANNOT_ACCEPT_TRANSACTED_WORK" }, + { 0x00001AC0, "ERROR_CANNOT_ABORT_TRANSACTIONS" }, + { 0x00001B59, "ERROR_CTX_WINSTATION_NAME_INVALID" }, + { 0x00001B5A, "ERROR_CTX_INVALID_PD" }, + { 0x00001B5B, "ERROR_CTX_PD_NOT_FOUND" }, + { 0x00001B5C, "ERROR_CTX_WD_NOT_FOUND" }, + { 0x00001B5D, "ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY" }, + { 0x00001B5E, "ERROR_CTX_SERVICE_NAME_COLLISION" }, + { 0x00001B5F, "ERROR_CTX_CLOSE_PENDING" }, + { 0x00001B60, "ERROR_CTX_NO_OUTBUF" }, + { 0x00001B61, "ERROR_CTX_MODEM_INF_NOT_FOUND" }, + { 0x00001B62, "ERROR_CTX_INVALID_MODEMNAME" }, + { 0x00001B63, "ERROR_CTX_MODEM_RESPONSE_ERROR" }, + { 0x00001B64, "ERROR_CTX_MODEM_RESPONSE_TIMEOUT" }, + { 0x00001B65, "ERROR_CTX_MODEM_RESPONSE_NO_CARRIER" }, + { 0x00001B66, "ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE" }, + { 0x00001B67, "ERROR_CTX_MODEM_RESPONSE_BUSY" }, + { 0x00001B68, "ERROR_CTX_MODEM_RESPONSE_VOICE" }, + { 0x00001B69, "ERROR_CTX_TD_ERROR" }, + { 0x00001B6E, "ERROR_CTX_WINSTATION_NOT_FOUND" }, + { 0x00001B6F, "ERROR_CTX_WINSTATION_ALREADY_EXISTS" }, + { 0x00001B70, "ERROR_CTX_WINSTATION_BUSY" }, + { 0x00001B71, "ERROR_CTX_BAD_VIDEO_MODE" }, + { 0x00001B7B, "ERROR_CTX_GRAPHICS_INVALID" }, + { 0x00001B7D, "ERROR_CTX_LOGON_DISABLED" }, + { 0x00001B7E, "ERROR_CTX_NOT_CONSOLE" }, + { 0x00001B80, "ERROR_CTX_CLIENT_QUERY_TIMEOUT" }, + { 0x00001B81, "ERROR_CTX_CONSOLE_DISCONNECT" }, + { 0x00001B82, "ERROR_CTX_CONSOLE_CONNECT" }, + { 0x00001B84, "ERROR_CTX_SHADOW_DENIED" }, + { 0x00001B85, "ERROR_CTX_WINSTATION_ACCESS_DENIED" }, + { 0x00001B89, "ERROR_CTX_INVALID_WD" }, + { 0x00001B8A, "ERROR_CTX_SHADOW_INVALID" }, + { 0x00001B8B, "ERROR_CTX_SHADOW_DISABLED" }, + { 0x00001B8C, "ERROR_CTX_CLIENT_LICENSE_IN_USE" }, + { 0x00001B8D, "ERROR_CTX_CLIENT_LICENSE_NOT_SET" }, + { 0x00001B8E, "ERROR_CTX_LICENSE_NOT_AVAILABLE" }, + { 0x00001B8F, "ERROR_CTX_LICENSE_CLIENT_INVALID" }, + { 0x00001B90, "ERROR_CTX_LICENSE_EXPIRED" }, + { 0x00001B91, "ERROR_CTX_SHADOW_NOT_RUNNING" }, + { 0x00001B92, "ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE" }, + { 0x00001B93, "ERROR_ACTIVATION_COUNT_EXCEEDED" }, + { 0x00001B94, "ERROR_CTX_WINSTATIONS_DISABLED" }, + { 0x00001B95, "ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED" }, + { 0x00001B96, "ERROR_CTX_SESSION_IN_USE" }, + { 0x00001B97, "ERROR_CTX_NO_FORCE_LOGOFF" }, + { 0x00001B98, "ERROR_CTX_ACCOUNT_RESTRICTION" }, + { 0x00001B99, "ERROR_RDP_PROTOCOL_ERROR" }, + { 0x00001B9A, "ERROR_CTX_CDM_CONNECT" }, + { 0x00001B9B, "ERROR_CTX_CDM_DISCONNECT" }, + { 0x00001B9C, "ERROR_CTX_SECURITY_LAYER_ERROR" }, + { 0x00001B9D, "ERROR_TS_INCOMPATIBLE_SESSIONS" }, + { 0x00001F41, "FRS_ERR_INVALID_API_SEQUENCE" }, + { 0x00001F42, "FRS_ERR_STARTING_SERVICE" }, + { 0x00001F43, "FRS_ERR_STOPPING_SERVICE" }, + { 0x00001F44, "FRS_ERR_INTERNAL_API" }, + { 0x00001F45, "FRS_ERR_INTERNAL" }, + { 0x00001F46, "FRS_ERR_SERVICE_COMM" }, + { 0x00001F47, "FRS_ERR_INSUFFICIENT_PRIV" }, + { 0x00001F48, "FRS_ERR_AUTHENTICATION" }, + { 0x00001F49, "FRS_ERR_PARENT_INSUFFICIENT_PRIV" }, + { 0x00001F4A, "FRS_ERR_PARENT_AUTHENTICATION" }, + { 0x00001F4B, "FRS_ERR_CHILD_TO_PARENT_COMM" }, + { 0x00001F4C, "FRS_ERR_PARENT_TO_CHILD_COMM" }, + { 0x00001F4D, "FRS_ERR_SYSVOL_POPULATE" }, + { 0x00001F4E, "FRS_ERR_SYSVOL_POPULATE_TIMEOUT" }, + { 0x00001F4F, "FRS_ERR_SYSVOL_IS_BUSY" }, + { 0x00001F50, "FRS_ERR_SYSVOL_DEMOTE" }, + { 0x00001F51, "FRS_ERR_INVALID_SERVICE_PARAMETER" }, + { 0x00002008, "ERROR_DS_NOT_INSTALLED" }, + { 0x00002009, "ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY" }, + { 0x0000200A, "ERROR_DS_NO_ATTRIBUTE_OR_VALUE" }, + { 0x0000200B, "ERROR_DS_INVALID_ATTRIBUTE_SYNTAX" }, + { 0x0000200C, "ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED" }, + { 0x0000200D, "ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS" }, + { 0x0000200E, "ERROR_DS_BUSY" }, + { 0x0000200F, "ERROR_DS_UNAVAILABLE" }, + { 0x00002010, "ERROR_DS_NO_RIDS_ALLOCATED" }, + { 0x00002011, "ERROR_DS_NO_MORE_RIDS" }, + { 0x00002012, "ERROR_DS_INCORRECT_ROLE_OWNER" }, + { 0x00002013, "ERROR_DS_RIDMGR_INIT_ERROR" }, + { 0x00002014, "ERROR_DS_OBJ_CLASS_VIOLATION" }, + { 0x00002015, "ERROR_DS_CANT_ON_NON_LEAF" }, + { 0x00002016, "ERROR_DS_CANT_ON_RDN" }, + { 0x00002017, "ERROR_DS_CANT_MOD_OBJ_CLASS" }, + { 0x00002018, "ERROR_DS_CROSS_DOM_MOVE_ERROR" }, + { 0x00002019, "ERROR_DS_GC_NOT_AVAILABLE" }, + { 0x0000201A, "ERROR_SHARED_POLICY" }, + { 0x0000201B, "ERROR_POLICY_OBJECT_NOT_FOUND" }, + { 0x0000201C, "ERROR_POLICY_ONLY_IN_DS" }, + { 0x0000201D, "ERROR_PROMOTION_ACTIVE" }, + { 0x0000201E, "ERROR_NO_PROMOTION_ACTIVE" }, + { 0x00002020, "ERROR_DS_OPERATIONS_ERROR" }, + { 0x00002021, "ERROR_DS_PROTOCOL_ERROR" }, + { 0x00002022, "ERROR_DS_TIMELIMIT_EXCEEDED" }, + { 0x00002023, "ERROR_DS_SIZELIMIT_EXCEEDED" }, + { 0x00002024, "ERROR_DS_ADMIN_LIMIT_EXCEEDED" }, + { 0x00002025, "ERROR_DS_COMPARE_FALSE" }, + { 0x00002026, "ERROR_DS_COMPARE_TRUE" }, + { 0x00002027, "ERROR_DS_AUTH_METHOD_NOT_SUPPORTED" }, + { 0x00002028, "ERROR_DS_STRONG_AUTH_REQUIRED" }, + { 0x00002029, "ERROR_DS_INAPPROPRIATE_AUTH" }, + { 0x0000202A, "ERROR_DS_AUTH_UNKNOWN" }, + { 0x0000202B, "ERROR_DS_REFERRAL" }, + { 0x0000202C, "ERROR_DS_UNAVAILABLE_CRIT_EXTENSION" }, + { 0x0000202D, "ERROR_DS_CONFIDENTIALITY_REQUIRED" }, + { 0x0000202E, "ERROR_DS_INAPPROPRIATE_MATCHING" }, + { 0x0000202F, "ERROR_DS_CONSTRAINT_VIOLATION" }, + { 0x00002030, "ERROR_DS_NO_SUCH_OBJECT" }, + { 0x00002031, "ERROR_DS_ALIAS_PROBLEM" }, + { 0x00002032, "ERROR_DS_INVALID_DN_SYNTAX" }, + { 0x00002033, "ERROR_DS_IS_LEAF" }, + { 0x00002034, "ERROR_DS_ALIAS_DEREF_PROBLEM" }, + { 0x00002035, "ERROR_DS_UNWILLING_TO_PERFORM" }, + { 0x00002036, "ERROR_DS_LOOP_DETECT" }, + { 0x00002037, "ERROR_DS_NAMING_VIOLATION" }, + { 0x00002038, "ERROR_DS_OBJECT_RESULTS_TOO_LARGE" }, + { 0x00002039, "ERROR_DS_AFFECTS_MULTIPLE_DSAS" }, + { 0x0000203A, "ERROR_DS_SERVER_DOWN" }, + { 0x0000203B, "ERROR_DS_LOCAL_ERROR" }, + { 0x0000203C, "ERROR_DS_ENCODING_ERROR" }, + { 0x0000203D, "ERROR_DS_DECODING_ERROR" }, + { 0x0000203E, "ERROR_DS_FILTER_UNKNOWN" }, + { 0x0000203F, "ERROR_DS_PARAM_ERROR" }, + { 0x00002040, "ERROR_DS_NOT_SUPPORTED" }, + { 0x00002041, "ERROR_DS_NO_RESULTS_RETURNED" }, + { 0x00002042, "ERROR_DS_CONTROL_NOT_FOUND" }, + { 0x00002043, "ERROR_DS_CLIENT_LOOP" }, + { 0x00002044, "ERROR_DS_REFERRAL_LIMIT_EXCEEDED" }, + { 0x00002045, "ERROR_DS_SORT_CONTROL_MISSING" }, + { 0x00002046, "ERROR_DS_OFFSET_RANGE_ERROR" }, + { 0x0000206D, "ERROR_DS_ROOT_MUST_BE_NC" }, + { 0x0000206E, "ERROR_DS_ADD_REPLICA_INHIBITED" }, + { 0x0000206F, "ERROR_DS_ATT_NOT_DEF_IN_SCHEMA" }, + { 0x00002070, "ERROR_DS_MAX_OBJ_SIZE_EXCEEDED" }, + { 0x00002071, "ERROR_DS_OBJ_STRING_NAME_EXISTS" }, + { 0x00002072, "ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA" }, + { 0x00002073, "ERROR_DS_RDN_DOESNT_MATCH_SCHEMA" }, + { 0x00002074, "ERROR_DS_NO_REQUESTED_ATTS_FOUND" }, + { 0x00002075, "ERROR_DS_USER_BUFFER_TO_SMALL" }, + { 0x00002076, "ERROR_DS_ATT_IS_NOT_ON_OBJ" }, + { 0x00002077, "ERROR_DS_ILLEGAL_MOD_OPERATION" }, + { 0x00002078, "ERROR_DS_OBJ_TOO_LARGE" }, + { 0x00002079, "ERROR_DS_BAD_INSTANCE_TYPE" }, + { 0x0000207A, "ERROR_DS_MASTERDSA_REQUIRED" }, + { 0x0000207B, "ERROR_DS_OBJECT_CLASS_REQUIRED" }, + { 0x0000207C, "ERROR_DS_MISSING_REQUIRED_ATT" }, + { 0x0000207D, "ERROR_DS_ATT_NOT_DEF_FOR_CLASS" }, + { 0x0000207E, "ERROR_DS_ATT_ALREADY_EXISTS" }, + { 0x00002080, "ERROR_DS_CANT_ADD_ATT_VALUES" }, + { 0x00002081, "ERROR_DS_SINGLE_VALUE_CONSTRAINT" }, + { 0x00002082, "ERROR_DS_RANGE_CONSTRAINT" }, + { 0x00002083, "ERROR_DS_ATT_VAL_ALREADY_EXISTS" }, + { 0x00002084, "ERROR_DS_CANT_REM_MISSING_ATT" }, + { 0x00002085, "ERROR_DS_CANT_REM_MISSING_ATT_VAL" }, + { 0x00002086, "ERROR_DS_ROOT_CANT_BE_SUBREF" }, + { 0x00002087, "ERROR_DS_NO_CHAINING" }, + { 0x00002088, "ERROR_DS_NO_CHAINED_EVAL" }, + { 0x00002089, "ERROR_DS_NO_PARENT_OBJECT" }, + { 0x0000208A, "ERROR_DS_PARENT_IS_AN_ALIAS" }, + { 0x0000208B, "ERROR_DS_CANT_MIX_MASTER_AND_REPS" }, + { 0x0000208C, "ERROR_DS_CHILDREN_EXIST" }, + { 0x0000208D, "ERROR_DS_OBJ_NOT_FOUND" }, + { 0x0000208E, "ERROR_DS_ALIASED_OBJ_MISSING" }, + { 0x0000208F, "ERROR_DS_BAD_NAME_SYNTAX" }, + { 0x00002090, "ERROR_DS_ALIAS_POINTS_TO_ALIAS" }, + { 0x00002091, "ERROR_DS_CANT_DEREF_ALIAS" }, + { 0x00002092, "ERROR_DS_OUT_OF_SCOPE" }, + { 0x00002093, "ERROR_DS_OBJECT_BEING_REMOVED" }, + { 0x00002094, "ERROR_DS_CANT_DELETE_DSA_OBJ" }, + { 0x00002095, "ERROR_DS_GENERIC_ERROR" }, + { 0x00002096, "ERROR_DS_DSA_MUST_BE_INT_MASTER" }, + { 0x00002097, "ERROR_DS_CLASS_NOT_DSA" }, + { 0x00002098, "ERROR_DS_INSUFF_ACCESS_RIGHTS" }, + { 0x00002099, "ERROR_DS_ILLEGAL_SUPERIOR" }, + { 0x0000209A, "ERROR_DS_ATTRIBUTE_OWNED_BY_SAM" }, + { 0x0000209B, "ERROR_DS_NAME_TOO_MANY_PARTS" }, + { 0x0000209C, "ERROR_DS_NAME_TOO_LONG" }, + { 0x0000209D, "ERROR_DS_NAME_VALUE_TOO_LONG" }, + { 0x0000209E, "ERROR_DS_NAME_UNPARSEABLE" }, + { 0x0000209F, "ERROR_DS_NAME_TYPE_UNKNOWN" }, + { 0x000020A0, "ERROR_DS_NOT_AN_OBJECT" }, + { 0x000020A1, "ERROR_DS_SEC_DESC_TOO_SHORT" }, + { 0x000020A2, "ERROR_DS_SEC_DESC_INVALID" }, + { 0x000020A3, "ERROR_DS_NO_DELETED_NAME" }, + { 0x000020A4, "ERROR_DS_SUBREF_MUST_HAVE_PARENT" }, + { 0x000020A5, "ERROR_DS_NCNAME_MUST_BE_NC" }, + { 0x000020A6, "ERROR_DS_CANT_ADD_SYSTEM_ONLY" }, + { 0x000020A7, "ERROR_DS_CLASS_MUST_BE_CONCRETE" }, + { 0x000020A8, "ERROR_DS_INVALID_DMD" }, + { 0x000020A9, "ERROR_DS_OBJ_GUID_EXISTS" }, + { 0x000020AA, "ERROR_DS_NOT_ON_BACKLINK" }, + { 0x000020AB, "ERROR_DS_NO_CROSSREF_FOR_NC" }, + { 0x000020AC, "ERROR_DS_SHUTTING_DOWN" }, + { 0x000020AD, "ERROR_DS_UNKNOWN_OPERATION" }, + { 0x000020AE, "ERROR_DS_INVALID_ROLE_OWNER" }, + { 0x000020AF, "ERROR_DS_COULDNT_CONTACT_FSMO" }, + { 0x000020B0, "ERROR_DS_CROSS_NC_DN_RENAME" }, + { 0x000020B1, "ERROR_DS_CANT_MOD_SYSTEM_ONLY" }, + { 0x000020B2, "ERROR_DS_REPLICATOR_ONLY" }, + { 0x000020B3, "ERROR_DS_OBJ_CLASS_NOT_DEFINED" }, + { 0x000020B4, "ERROR_DS_OBJ_CLASS_NOT_SUBCLASS" }, + { 0x000020B5, "ERROR_DS_NAME_REFERENCE_INVALID" }, + { 0x000020B6, "ERROR_DS_CROSS_REF_EXISTS" }, + { 0x000020B7, "ERROR_DS_CANT_DEL_MASTER_CROSSREF" }, + { 0x000020B8, "ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD" }, + { 0x000020B9, "ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX" }, + { 0x000020BA, "ERROR_DS_DUP_RDN" }, + { 0x000020BB, "ERROR_DS_DUP_OID" }, + { 0x000020BC, "ERROR_DS_DUP_MAPI_ID" }, + { 0x000020BD, "ERROR_DS_DUP_SCHEMA_ID_GUID" }, + { 0x000020BE, "ERROR_DS_DUP_LDAP_DISPLAY_NAME" }, + { 0x000020BF, "ERROR_DS_SEMANTIC_ATT_TEST" }, + { 0x000020C0, "ERROR_DS_SYNTAX_MISMATCH" }, + { 0x000020C1, "ERROR_DS_EXISTS_IN_MUST_HAVE" }, + { 0x000020C2, "ERROR_DS_EXISTS_IN_MAY_HAVE" }, + { 0x000020C3, "ERROR_DS_NONEXISTENT_MAY_HAVE" }, + { 0x000020C4, "ERROR_DS_NONEXISTENT_MUST_HAVE" }, + { 0x000020C5, "ERROR_DS_AUX_CLS_TEST_FAIL" }, + { 0x000020C6, "ERROR_DS_NONEXISTENT_POSS_SUP" }, + { 0x000020C7, "ERROR_DS_SUB_CLS_TEST_FAIL" }, + { 0x000020C8, "ERROR_DS_BAD_RDN_ATT_ID_SYNTAX" }, + { 0x000020C9, "ERROR_DS_EXISTS_IN_AUX_CLS" }, + { 0x000020CA, "ERROR_DS_EXISTS_IN_SUB_CLS" }, + { 0x000020CB, "ERROR_DS_EXISTS_IN_POSS_SUP" }, + { 0x000020CC, "ERROR_DS_RECALCSCHEMA_FAILED" }, + { 0x000020CD, "ERROR_DS_TREE_DELETE_NOT_FINISHED" }, + { 0x000020CE, "ERROR_DS_CANT_DELETE" }, + { 0x000020CF, "ERROR_DS_ATT_SCHEMA_REQ_ID" }, + { 0x000020D0, "ERROR_DS_BAD_ATT_SCHEMA_SYNTAX" }, + { 0x000020D1, "ERROR_DS_CANT_CACHE_ATT" }, + { 0x000020D2, "ERROR_DS_CANT_CACHE_CLASS" }, + { 0x000020D3, "ERROR_DS_CANT_REMOVE_ATT_CACHE" }, + { 0x000020D4, "ERROR_DS_CANT_REMOVE_CLASS_CACHE" }, + { 0x000020D5, "ERROR_DS_CANT_RETRIEVE_DN" }, + { 0x000020D6, "ERROR_DS_MISSING_SUPREF" }, + { 0x000020D7, "ERROR_DS_CANT_RETRIEVE_INSTANCE" }, + { 0x000020D8, "ERROR_DS_CODE_INCONSISTENCY" }, + { 0x000020D9, "ERROR_DS_DATABASE_ERROR" }, + { 0x000020DA, "ERROR_DS_GOVERNSID_MISSING" }, + { 0x000020DB, "ERROR_DS_MISSING_EXPECTED_ATT" }, + { 0x000020DC, "ERROR_DS_NCNAME_MISSING_CR_REF" }, + { 0x000020DD, "ERROR_DS_SECURITY_CHECKING_ERROR" }, + { 0x000020DE, "ERROR_DS_SCHEMA_NOT_LOADED" }, + { 0x000020DF, "ERROR_DS_SCHEMA_ALLOC_FAILED" }, + { 0x000020E0, "ERROR_DS_ATT_SCHEMA_REQ_SYNTAX" }, + { 0x000020E1, "ERROR_DS_GCVERIFY_ERROR" }, + { 0x000020E2, "ERROR_DS_DRA_SCHEMA_MISMATCH" }, + { 0x000020E3, "ERROR_DS_CANT_FIND_DSA_OBJ" }, + { 0x000020E4, "ERROR_DS_CANT_FIND_EXPECTED_NC" }, + { 0x000020E5, "ERROR_DS_CANT_FIND_NC_IN_CACHE" }, + { 0x000020E6, "ERROR_DS_CANT_RETRIEVE_CHILD" }, + { 0x000020E7, "ERROR_DS_SECURITY_ILLEGAL_MODIFY" }, + { 0x000020E8, "ERROR_DS_CANT_REPLACE_HIDDEN_REC" }, + { 0x000020E9, "ERROR_DS_BAD_HIERARCHY_FILE" }, + { 0x000020EA, "ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED" }, + { 0x000020EB, "ERROR_DS_CONFIG_PARAM_MISSING" }, + { 0x000020EC, "ERROR_DS_COUNTING_AB_INDICES_FAILED" }, + { 0x000020ED, "ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED" }, + { 0x000020EE, "ERROR_DS_INTERNAL_FAILURE" }, + { 0x000020EF, "ERROR_DS_UNKNOWN_ERROR" }, + { 0x000020F0, "ERROR_DS_ROOT_REQUIRES_CLASS_TO" }, + { 0x000020F1, "ERROR_DS_REFUSING_FSMO_ROLES" }, + { 0x000020F2, "ERROR_DS_MISSING_FSMO_SETTINGS" }, + { 0x000020F3, "ERROR_DS_UNABLE_TO_SURRENDER_ROLES" }, + { 0x000020F4, "ERROR_DS_DRA_GENERIC" }, + { 0x000020F5, "ERROR_DS_DRA_INVALID_PARAMETER" }, + { 0x000020F6, "ERROR_DS_DRA_BUSY" }, + { 0x000020F7, "ERROR_DS_DRA_BAD_DN" }, + { 0x000020F8, "ERROR_DS_DRA_BAD_NC" }, + { 0x000020F9, "ERROR_DS_DRA_DN_EXISTS" }, + { 0x000020FA, "ERROR_DS_DRA_INTERNAL_ERROR" }, + { 0x000020FB, "ERROR_DS_DRA_INCONSISTENT_DIT" }, + { 0x000020FC, "ERROR_DS_DRA_CONNECTION_FAILED" }, + { 0x000020FD, "ERROR_DS_DRA_BAD_INSTANCE_TYPE" }, + { 0x000020FE, "ERROR_DS_DRA_OUT_OF_MEM" }, + { 0x000020FF, "ERROR_DS_DRA_MAIL_PROBLEM" }, + { 0x00002100, "ERROR_DS_DRA_REF_ALREADY_EXISTS" }, + { 0x00002101, "ERROR_DS_DRA_REF_NOT_FOUND" }, + { 0x00002102, "ERROR_DS_DRA_OBJ_IS_REP_SOURCE" }, + { 0x00002103, "ERROR_DS_DRA_DB_ERROR" }, + { 0x00002104, "ERROR_DS_DRA_NO_REPLICA" }, + { 0x00002105, "ERROR_DS_DRA_ACCESS_DENIED" }, + { 0x00002106, "ERROR_DS_DRA_NOT_SUPPORTED" }, + { 0x00002107, "ERROR_DS_DRA_RPC_CANCELLED" }, + { 0x00002108, "ERROR_DS_DRA_SOURCE_DISABLED" }, + { 0x00002109, "ERROR_DS_DRA_SINK_DISABLED" }, + { 0x0000210A, "ERROR_DS_DRA_NAME_COLLISION" }, + { 0x0000210B, "ERROR_DS_DRA_SOURCE_REINSTALLED" }, + { 0x0000210C, "ERROR_DS_DRA_MISSING_PARENT" }, + { 0x0000210D, "ERROR_DS_DRA_PREEMPTED" }, + { 0x0000210E, "ERROR_DS_DRA_ABANDON_SYNC" }, + { 0x0000210F, "ERROR_DS_DRA_SHUTDOWN" }, + { 0x00002110, "ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET" }, + { 0x00002111, "ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA" }, + { 0x00002112, "ERROR_DS_DRA_EXTN_CONNECTION_FAILED" }, + { 0x00002113, "ERROR_DS_INSTALL_SCHEMA_MISMATCH" }, + { 0x00002114, "ERROR_DS_DUP_LINK_ID" }, + { 0x00002115, "ERROR_DS_NAME_ERROR_RESOLVING" }, + { 0x00002116, "ERROR_DS_NAME_ERROR_NOT_FOUND" }, + { 0x00002117, "ERROR_DS_NAME_ERROR_NOT_UNIQUE" }, + { 0x00002118, "ERROR_DS_NAME_ERROR_NO_MAPPING" }, + { 0x00002119, "ERROR_DS_NAME_ERROR_DOMAIN_ONLY" }, + { 0x0000211A, "ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING" }, + { 0x0000211B, "ERROR_DS_CONSTRUCTED_ATT_MOD" }, + { 0x0000211C, "ERROR_DS_WRONG_OM_OBJ_CLASS" }, + { 0x0000211D, "ERROR_DS_DRA_REPL_PENDING" }, + { 0x0000211E, "ERROR_DS_DS_REQUIRED" }, + { 0x0000211F, "ERROR_DS_INVALID_LDAP_DISPLAY_NAME" }, + { 0x00002120, "ERROR_DS_NON_BASE_SEARCH" }, + { 0x00002121, "ERROR_DS_CANT_RETRIEVE_ATTS" }, + { 0x00002122, "ERROR_DS_BACKLINK_WITHOUT_LINK" }, + { 0x00002123, "ERROR_DS_EPOCH_MISMATCH" }, + { 0x00002124, "ERROR_DS_SRC_NAME_MISMATCH" }, + { 0x00002125, "ERROR_DS_SRC_AND_DST_NC_IDENTICAL" }, + { 0x00002126, "ERROR_DS_DST_NC_MISMATCH" + + }, + { 0x00002127, "ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC" }, + { 0x00002128, "ERROR_DS_SRC_GUID_MISMATCH" }, + { 0x00002129, "ERROR_DS_CANT_MOVE_DELETED_OBJECT" }, + { 0x0000212A, "ERROR_DS_PDC_OPERATION_IN_PROGRESS" }, + { 0x0000212B, "ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD" + + }, + { 0x0000212C, "ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION" + + }, + { 0x0000212D, "ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS" }, + { 0x0000212E, "ERROR_DS_NC_MUST_HAVE_NC_PARENT" }, + { 0x0000212F, + "ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE" + "partners. (Applies only to Windows 2000 operating system domain naming masters.)" }, + { 0x00002130, "ERROR_DS_DST_DOMAIN_NOT_NATIVE" }, + { 0x00002131, "ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER" }, + { 0x00002132, "ERROR_DS_CANT_MOVE_ACCOUNT_GROUP" }, + { 0x00002133, "ERROR_DS_CANT_MOVE_RESOURCE_GROUP" }, + { 0x00002134, "ERROR_DS_INVALID_SEARCH_FLAG" }, + { 0x00002135, "ERROR_DS_NO_TREE_DELETE_ABOVE_NC" }, + { 0x00002136, "ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE" }, + { 0x00002137, "ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE" }, + { 0x00002138, "ERROR_DS_SAM_INIT_FAILURE" }, + { 0x00002139, "ERROR_DS_SENSITIVE_GROUP_VIOLATION" }, + { 0x0000213A, "ERROR_DS_CANT_MOD_PRIMARYGROUPID" }, + { 0x0000213B, "ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD" }, + { 0x0000213C, "ERROR_DS_NONSAFE_SCHEMA_CHANGE" + + }, + { 0x0000213D, "ERROR_DS_SCHEMA_UPDATE_DISALLOWED" }, + { 0x0000213E, "ERROR_DS_CANT_CREATE_UNDER_SCHEMA" }, + { 0x0000213F, "ERROR_DS_INSTALL_NO_SRC_SCH_VERSION" }, + { 0x00002140, "ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE" }, + { 0x00002141, "ERROR_DS_INVALID_GROUP_TYPE" }, + { 0x00002142, "ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN" }, + { 0x00002143, "ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN" }, + { 0x00002144, "ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER" }, + { 0x00002145, "ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER" }, + { 0x00002146, "ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER" }, + { 0x00002147, "ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER" }, + { 0x00002148, "ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER" }, + { 0x00002149, "ERROR_DS_HAVE_PRIMARY_MEMBERS" }, + { 0x0000214A, "ERROR_DS_STRING_SD_CONVERSION_FAILED" }, + { 0x0000214B, "ERROR_DS_NAMING_MASTER_GC" }, + { 0x0000214C, "ERROR_DS_DNS_LOOKUP_FAILURE" }, + { 0x0000214D, "ERROR_DS_COULDNT_UPDATE_SPNS" }, + { 0x0000214E, "ERROR_DS_CANT_RETRIEVE_SD" }, + { 0x0000214F, "ERROR_DS_KEY_NOT_UNIQUE" }, + { 0x00002150, "ERROR_DS_WRONG_LINKED_ATT_SYNTAX" }, + { 0x00002151, "ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD" }, + { 0x00002152, "ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY" }, + { 0x00002153, "ERROR_DS_CANT_START" }, + { 0x00002154, "ERROR_DS_INIT_FAILURE" }, + { 0x00002155, "ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION" }, + { 0x00002156, "ERROR_DS_SOURCE_DOMAIN_IN_FOREST" }, + { 0x00002157, "ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST" }, + { 0x00002158, "ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED" }, + { 0x00002159, "ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN" }, + { 0x0000215A, "ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER" }, + { 0x0000215B, "ERROR_DS_SRC_SID_EXISTS_IN_FOREST" }, + { 0x0000215C, "ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH" }, + { 0x0000215D, "ERROR_SAM_INIT_FAILURE" }, + { 0x0000215E, "ERROR_DS_DRA_SCHEMA_INFO_SHIP" }, + { 0x0000215F, "ERROR_DS_DRA_SCHEMA_CONFLICT" }, + { 0x00002160, "ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT" }, + { 0x00002161, "ERROR_DS_DRA_OBJ_NC_MISMATCH" }, + { 0x00002162, "ERROR_DS_NC_STILL_HAS_DSAS" }, + { 0x00002163, "ERROR_DS_GC_REQUIRED" }, + { 0x00002164, "ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY" }, + { 0x00002165, "ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS" }, + { 0x00002166, "ERROR_DS_CANT_ADD_TO_GC" }, + { 0x00002167, "ERROR_DS_NO_CHECKPOINT_WITH_PDC" }, + { 0x00002168, "ERROR_DS_SOURCE_AUDITING_NOT_ENABLED" }, + { 0x00002169, "ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC" }, + { 0x0000216A, "ERROR_DS_INVALID_NAME_FOR_SPN" }, + { 0x0000216B, "ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS" }, + { 0x0000216C, "ERROR_DS_UNICODEPWD_NOT_IN_QUOTES" }, + { 0x0000216D, "ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED" }, + { 0x0000216E, "ERROR_DS_MUST_BE_RUN_ON_DST_DC" }, + { 0x0000216F, "ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER" }, + { 0x00002170, "ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ" }, + { 0x00002171, "ERROR_DS_INIT_FAILURE_CONSOLE" }, + { 0x00002172, "ERROR_DS_SAM_INIT_FAILURE_CONSOLE" }, + { 0x00002173, "ERROR_DS_FOREST_VERSION_TOO_HIGH" }, + { 0x00002174, "ERROR_DS_DOMAIN_VERSION_TOO_HIGH" }, + { 0x00002175, "ERROR_DS_FOREST_VERSION_TOO_LOW" }, + { 0x00002176, "ERROR_DS_DOMAIN_VERSION_TOO_LOW" }, + { 0x00002177, "ERROR_DS_INCOMPATIBLE_VERSION" }, + { 0x00002178, "ERROR_DS_LOW_DSA_VERSION" + + }, + { 0x00002179, "ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN" }, + { 0x0000217A, "ERROR_DS_NOT_SUPPORTED_SORT_ORDER" }, + { 0x0000217B, "ERROR_DS_NAME_NOT_UNIQUE" }, + { 0x0000217C, "ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4" }, + { 0x0000217D, "ERROR_DS_OUT_OF_VERSION_STORE" }, + { 0x0000217E, "ERROR_DS_INCOMPATIBLE_CONTROLS_USED" }, + { 0x0000217F, "ERROR_DS_NO_REF_DOMAIN" }, + { 0x00002180, "ERROR_DS_RESERVED_LINK_ID" }, + { 0x00002181, "ERROR_DS_LINK_ID_NOT_AVAILABLE" }, + { 0x00002182, "ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER" }, + { 0x00002183, "ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE" }, + { 0x00002184, "ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC" }, + { 0x00002185, "ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG" }, + { 0x00002186, "ERROR_DS_MODIFYDN_WRONG_GRANDPARENT" }, + { 0x00002187, "ERROR_DS_NAME_ERROR_TRUST_REFERRAL" }, + { 0x00002188, "ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER" }, + { 0x00002189, "ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD" }, + { 0x0000218A, "ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2" + + }, + { 0x0000218B, "ERROR_DS_THREAD_LIMIT_EXCEEDED" }, + { 0x0000218C, "ERROR_DS_NOT_CLOSEST" }, + { 0x0000218D, "ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF" }, + { 0x0000218E, "ERROR_DS_SINGLE_USER_MODE_FAILED" }, + { 0x0000218F, "ERROR_DS_NTDSCRIPT_SYNTAX_ERROR" }, + { 0x00002190, "ERROR_DS_NTDSCRIPT_PROCESS_ERROR" }, + { 0x00002191, "ERROR_DS_DIFFERENT_REPL_EPOCHS" }, + { 0x00002192, "ERROR_DS_DRS_EXTENSIONS_CHANGED" }, + { 0x00002193, "ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR" }, + { 0x00002194, "ERROR_DS_NO_MSDS_INTID" }, + { 0x00002195, "ERROR_DS_DUP_MSDS_INTID" }, + { 0x00002196, "ERROR_DS_EXISTS_IN_RDNATTID" }, + { 0x00002197, "ERROR_DS_AUTHORIZATION_FAILED" }, + { 0x00002198, "ERROR_DS_INVALID_SCRIPT" }, + { 0x00002199, "ERROR_DS_REMOTE_CROSSREF_OP_FAILED" }, + { 0x0000219A, "ERROR_DS_CROSS_REF_BUSY" }, + { 0x0000219B, "ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN" }, + { 0x0000219C, "ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC" }, + { 0x0000219D, "ERROR_DS_DUPLICATE_ID_FOUND" }, + { 0x0000219E, "ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT" }, + { 0x0000219F, "ERROR_DS_GROUP_CONVERSION_ERROR" }, + { 0x000021A0, "ERROR_DS_CANT_MOVE_APP_BASIC_GROUP" }, + { 0x000021A1, "ERROR_DS_CANT_MOVE_APP_QUERY_GROUP" }, + { 0x000021A2, "ERROR_DS_ROLE_NOT_VERIFIED" }, + { 0x000021A3, "ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL" }, + { 0x000021A4, "ERROR_DS_DOMAIN_RENAME_IN_PROGRESS" }, + { 0x000021A5, "ERROR_DS_EXISTING_AD_CHILD_NC" }, + { 0x000021A6, "ERROR_DS_REPL_LIFETIME_EXCEEDED" }, + { 0x000021A7, "ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER" }, + { 0x000021A8, "ERROR_DS_LDAP_SEND_QUEUE_FULL" + + }, + { 0x000021A9, "ERROR_DS_DRA_OUT_SCHEDULE_WINDOW" }, + { 0x000021AA, "ERROR_DS_POLICY_NOT_KNOWN" }, + { 0x000021AB, "ERROR_NO_SITE_SETTINGS_OBJECT" }, + { 0x000021AC, "ERROR_NO_SECRETS" }, + { 0x000021AD, "ERROR_NO_WRITABLE_DC_FOUND" }, + { 0x000021AE, "ERROR_DS_NO_SERVER_OBJECT" }, + { 0x000021AF, "ERROR_DS_NO_NTDSA_OBJECT" }, + { 0x000021B0, "ERROR_DS_NON_ASQ_SEARCH" }, + { 0x000021B1, "ERROR_DS_AUDIT_FAILURE" }, + { 0x000021B2, "ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE" }, + { 0x000021B3, "ERROR_DS_INVALID_SEARCH_FLAG_TUPLE" }, + { 0x000021BF, "ERROR_DS_DRA_RECYCLED_TARGET" }, + { 0x000021C2, "ERROR_DS_HIGH_DSA_VERSION" }, + { 0x000021C7, "ERROR_DS_SPN_VALUE_NOT_UNIQUE_IN_FOREST" }, + { 0x000021C8, "ERROR_DS_UPN_VALUE_NOT_UNIQUE_IN_FOREST" }, + { 0x00002329, "DNS_ERROR_RCODE_FORMAT_ERROR" }, + { 0x0000232A, "DNS_ERROR_RCODE_SERVER_FAILURE" }, + { 0x0000232B, "DNS_ERROR_RCODE_NAME_ERROR" }, + { 0x0000232C, "DNS_ERROR_RCODE_NOT_IMPLEMENTED" }, + { 0x0000232D, "DNS_ERROR_RCODE_REFUSED" }, + { 0x0000232E, "DNS_ERROR_RCODE_YXDOMAIN" }, + { 0x0000232F, "DNS_ERROR_RCODE_YXRRSET" }, + { 0x00002330, "DNS_ERROR_RCODE_NXRRSET" }, + { 0x00002331, "DNS_ERROR_RCODE_NOTAUTH" }, + { 0x00002332, "DNS_ERROR_RCODE_NOTZONE" }, + { 0x00002338, "DNS_ERROR_RCODE_BADSIG" }, + { 0x00002339, "DNS_ERROR_RCODE_BADKEY" }, + { 0x0000233A, "DNS_ERROR_RCODE_BADTIME" }, + { 0x0000251D, "DNS_INFO_NO_RECORDS" }, + { 0x0000251E, "DNS_ERROR_BAD_PACKET" }, + { 0x0000251F, "DNS_ERROR_NO_PACKET" }, + { 0x00002520, "DNS_ERROR_RCODE" }, + { 0x00002521, "DNS_ERROR_UNSECURE_PACKET" }, + { 0x0000254F, "DNS_ERROR_INVALID_TYPE" }, + { 0x00002550, "DNS_ERROR_INVALID_IP_ADDRESS" }, + { 0x00002551, "DNS_ERROR_INVALID_PROPERTY" }, + { 0x00002552, "DNS_ERROR_TRY_AGAIN_LATER" }, + { 0x00002553, "DNS_ERROR_NOT_UNIQUE" }, + { 0x00002554, "DNS_ERROR_NON_RFC_NAME" }, + { 0x00002555, "DNS_STATUS_FQDN" }, + { 0x00002556, "DNS_STATUS_DOTTED_NAME" }, + { 0x00002557, "DNS_STATUS_SINGLE_PART_NAME" }, + { 0x00002558, "DNS_ERROR_INVALID_NAME_CHAR" }, + { 0x00002559, "DNS_ERROR_NUMERIC_NAME" }, + { 0x0000255A, "DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER" }, + { 0x0000255B, "DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION" }, + { 0x0000255C, "DNS_ERROR_CANNOT_FIND_ROOT_HINTS" }, + { 0x0000255D, "DNS_ERROR_INCONSISTENT_ROOT_HINTS" }, + { 0x0000255E, "DNS_ERROR_DWORD_VALUE_TOO_SMALL" }, + { 0x0000255F, "DNS_ERROR_DWORD_VALUE_TOO_LARGE" }, + { 0x00002560, "DNS_ERROR_BACKGROUND_LOADING" }, + { 0x00002561, "DNS_ERROR_NOT_ALLOWED_ON_RODC" }, + { 0x00002581, "DNS_ERROR_ZONE_DOES_NOT_EXIST" }, + { 0x00002582, "DNS_ERROR_NO_ZONE_INFO" }, + { 0x00002583, "DNS_ERROR_INVALID_ZONE_OPERATION" }, + { 0x00002584, "DNS_ERROR_ZONE_CONFIGURATION_ERROR" }, + { 0x00002585, "DNS_ERROR_ZONE_HAS_NO_SOA_RECORD" }, + { 0x00002586, "DNS_ERROR_ZONE_HAS_NO_NS_RECORDS" }, + { 0x00002587, "DNS_ERROR_ZONE_LOCKED" }, + { 0x00002588, "DNS_ERROR_ZONE_CREATION_FAILED" }, + { 0x00002589, "DNS_ERROR_ZONE_ALREADY_EXISTS" }, + { 0x0000258A, "DNS_ERROR_AUTOZONE_ALREADY_EXISTS" }, + { 0x0000258B, "DNS_ERROR_INVALID_ZONE_TYPE" }, + { 0x0000258C, "DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP" }, + { 0x0000258D, "DNS_ERROR_ZONE_NOT_SECONDARY" }, + { 0x0000258E, "DNS_ERROR_NEED_SECONDARY_ADDRESSES" }, + { 0x0000258F, "DNS_ERROR_WINS_INIT_FAILED" }, + { 0x00002590, "DNS_ERROR_NEED_WINS_SERVERS" }, + { 0x00002591, "DNS_ERROR_NBSTAT_INIT_FAILED" }, + { 0x00002592, "DNS_ERROR_SOA_DELETE_INVALID" }, + { 0x00002593, "DNS_ERROR_FORWARDER_ALREADY_EXISTS" }, + { 0x00002594, "DNS_ERROR_ZONE_REQUIRES_MASTER_IP" }, + { 0x00002595, "DNS_ERROR_ZONE_IS_SHUTDOWN" }, + { 0x000025B3, "DNS_ERROR_PRIMARY_REQUIRES_DATAFILE" }, + { 0x000025B4, "DNS_ERROR_INVALID_DATAFILE_NAME" }, + { 0x000025B5, "DNS_ERROR_DATAFILE_OPEN_FAILURE" }, + { 0x000025B6, "DNS_ERROR_FILE_WRITEBACK_FAILED" }, + { 0x000025B7, "DNS_ERROR_DATAFILE_PARSING" }, + { 0x000025E5, "DNS_ERROR_RECORD_DOES_NOT_EXIST" }, + { 0x000025E6, "DNS_ERROR_RECORD_FORMAT" }, + { 0x000025E7, "DNS_ERROR_NODE_CREATION_FAILED" }, + { 0x000025E8, "DNS_ERROR_UNKNOWN_RECORD_TYPE" }, + { 0x000025E9, "DNS_ERROR_RECORD_TIMED_OUT" }, + { 0x000025EA, "DNS_ERROR_NAME_NOT_IN_ZONE" }, + { 0x000025EB, "DNS_ERROR_CNAME_LOOP" }, + { 0x000025EC, "DNS_ERROR_NODE_IS_CNAME" }, + { 0x000025ED, "DNS_ERROR_CNAME_COLLISION" }, + { 0x000025EE, "DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT" }, + { 0x000025EF, "DNS_ERROR_RECORD_ALREADY_EXISTS" }, + { 0x000025F0, "DNS_ERROR_SECONDARY_DATA" }, + { 0x000025F1, "DNS_ERROR_NO_CREATE_CACHE_DATA" }, + { 0x000025F2, "DNS_ERROR_NAME_DOES_NOT_EXIST" }, + { 0x000025F3, "DNS_WARNING_PTR_CREATE_FAILED" }, + { 0x000025F4, "DNS_WARNING_DOMAIN_UNDELETED" }, + { 0x000025F5, "DNS_ERROR_DS_UNAVAILABLE" }, + { 0x000025F6, "DNS_ERROR_DS_ZONE_ALREADY_EXISTS" }, + { 0x000025F7, "DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE" }, + { 0x00002617, "DNS_INFO_AXFR_COMPLETE" }, + { 0x00002618, "DNS_ERROR_AXFR" }, + { 0x00002619, "DNS_INFO_ADDED_LOCAL_WINS" }, + { 0x00002649, "DNS_STATUS_CONTINUE_NEEDED" }, + { 0x0000267B, "DNS_ERROR_NO_TCPIP" }, + { 0x0000267C, "DNS_ERROR_NO_DNS_SERVERS" }, + { 0x000026AD, "DNS_ERROR_DP_DOES_NOT_EXIST" }, + { 0x000026AE, "DNS_ERROR_DP_ALREADY_EXISTS" }, + { 0x000026AF, "DNS_ERROR_DP_NOT_ENLISTED" }, + { 0x000026B0, "DNS_ERROR_DP_ALREADY_ENLISTED" }, + { 0x000026B1, "DNS_ERROR_DP_NOT_AVAILABLE" }, + { 0x000026B2, "DNS_ERROR_DP_FSMO_ERROR" }, + { 0x00002714, "WSAEINTR" }, + { 0x00002719, "WSAEBADF" }, + { 0x0000271D, "WSAEACCES" }, + { 0x0000271E, "WSAEFAULT" }, + { 0x00002726, "WSAEINVAL" }, + { 0x00002728, "WSAEMFILE" }, + { 0x00002733, "WSAEWOULDBLOCK" }, + { 0x00002734, "WSAEINPROGRESS" }, + { 0x00002735, "WSAEALREADY" }, + { 0x00002736, "WSAENOTSOCK" }, + { 0x00002737, "WSAEDESTADDRREQ" }, + { 0x00002738, "WSAEMSGSIZE" }, + { 0x00002739, "WSAEPROTOTYPE" }, + { 0x0000273A, "WSAENOPROTOOPT" }, + { 0x0000273B, "WSAEPROTONOSUPPORT" }, + { 0x0000273C, "WSAESOCKTNOSUPPORT" }, + { 0x0000273D, "WSAEOPNOTSUPP" }, + { 0x0000273E, "WSAEPFNOSUPPORT" }, + { 0x0000273F, "WSAEAFNOSUPPORT" }, + { 0x00002740, "WSAEADDRINUSE" }, + { 0x00002741, "WSAEADDRNOTAVAIL" }, + { 0x00002742, "WSAENETDOWN" }, + { 0x00002743, "WSAENETUNREACH" }, + { 0x00002744, "WSAENETRESET" }, + { 0x00002745, "WSAECONNABORTED" }, + { 0x00002746, "WSAECONNRESET" }, + { 0x00002747, "WSAENOBUFS" }, + { 0x00002748, "WSAEISCONN" }, + { 0x00002749, "WSAENOTCONN" }, + { 0x0000274A, "WSAESHUTDOWN" }, + { 0x0000274B, "WSAETOOMANYREFS" }, + { 0x0000274C, "WSAETIMEDOUT" }, + { 0x0000274D, "WSAECONNREFUSED" }, + { 0x0000274E, "WSAELOOP" }, + { 0x0000274F, "WSAENAMETOOLONG" }, + { 0x00002750, "WSAEHOSTDOWN" }, + { 0x00002751, "WSAEHOSTUNREACH" }, + { 0x00002752, "WSAENOTEMPTY" }, + { 0x00002753, "WSAEPROCLIM" }, + { 0x00002754, "WSAEUSERS" }, + { 0x00002755, "WSAEDQUOT" }, + { 0x00002756, "WSAESTALE" }, + { 0x00002757, "WSAEREMOTE" }, + { 0x0000276B, "WSASYSNOTREADY" }, + { 0x0000276C, "WSAVERNOTSUPPORTED" }, + { 0x0000276D, "WSANOTINITIALISED" }, + { 0x00002775, "WSAEDISCON" }, + { 0x00002776, "WSAENOMORE" }, + { 0x00002777, "WSAECANCELLED" }, + { 0x00002778, "WSAEINVALIDPROCTABLE" }, + { 0x00002779, "WSAEINVALIDPROVIDER" }, + { 0x0000277A, "WSAEPROVIDERFAILEDINIT" }, + { 0x0000277B, "WSASYSCALLFAILURE" }, + { 0x0000277C, "WSASERVICE_NOT_FOUND" }, + { 0x0000277D, "WSATYPE_NOT_FOUND" }, + { 0x0000277E, "WSA_E_NO_MORE" }, + { 0x0000277F, "WSA_E_CANCELLED" }, + { 0x00002780, "WSAEREFUSED" }, + { 0x00002AF9, "WSAHOST_NOT_FOUND" }, + { 0x00002AFA, "WSATRY_AGAIN" }, + { 0x00002AFB, "WSANO_RECOVERY" }, + { 0x00002AFC, "WSANO_DATA" }, + { 0x00002AFD, "WSA_QOS_RECEIVERS" }, + { 0x00002AFE, "WSA_QOS_SENDERS" }, + { 0x00002AFF, "WSA_QOS_NO_SENDERS" }, + { 0x00002B00, "WSA_QOS_NO_RECEIVERS" }, + { 0x00002B01, "WSA_QOS_REQUEST_CONFIRMED" }, + { 0x00002B02, "WSA_QOS_ADMISSION_FAILURE" }, + { 0x00002B03, "WSA_QOS_POLICY_FAILURE" }, + { 0x00002B04, "WSA_QOS_BAD_STYLE" }, + { 0x00002B05, "WSA_QOS_BAD_OBJECT" }, + { 0x00002B06, "WSA_QOS_TRAFFIC_CTRL_ERROR" }, + { 0x00002B07, "WSA_QOS_GENERIC_ERROR" }, + { 0x00002B08, "WSA_QOS_ESERVICETYPE" }, + { 0x00002B09, "WSA_QOS_EFLOWSPEC" }, + { 0x00002B0A, "WSA_QOS_EPROVSPECBUF" }, + { 0x00002B0B, "WSA_QOS_EFILTERSTYLE" }, + { 0x00002B0C, "WSA_QOS_EFILTERTYPE" }, + { 0x00002B0D, "WSA_QOS_EFILTERCOUNT" }, + { 0x00002B0E, "WSA_QOS_EOBJLENGTH" }, + { 0x00002B0F, "WSA_QOS_EFLOWCOUNT" }, + { 0x00002B10, "WSA_QOS_EUNKOWNPSOBJ" }, + { 0x00002B11, "WSA_QOS_EPOLICYOBJ" }, + { 0x00002B12, "WSA_QOS_EFLOWDESC" }, + { 0x00002B13, "WSA_QOS_EPSFLOWSPEC" }, + { 0x00002B14, "WSA_QOS_EPSFILTERSPEC" }, + { 0x00002B15, "WSA_QOS_ESDMODEOBJ" }, + { 0x00002B16, "WSA_QOS_ESHAPERATEOBJ" }, + { 0x00002B17, "WSA_QOS_RESERVED_PETYPE" }, + { 0x000032C8, "ERROR_IPSEC_QM_POLICY_EXISTS" }, + { 0x000032C9, "ERROR_IPSEC_QM_POLICY_NOT_FOUND" }, + { 0x000032CA, "ERROR_IPSEC_QM_POLICY_IN_USE" }, + { 0x000032CB, "ERROR_IPSEC_MM_POLICY_EXISTS" }, + { 0x000032CC, "ERROR_IPSEC_MM_POLICY_NOT_FOUND" }, + { 0x000032CD, "ERROR_IPSEC_MM_POLICY_IN_USE" }, + { 0x000032CE, "ERROR_IPSEC_MM_FILTER_EXISTS" }, + { 0x000032CF, "ERROR_IPSEC_MM_FILTER_NOT_FOUND" }, + { 0x000032D0, "ERROR_IPSEC_TRANSPORT_FILTER_EXISTS" }, + { 0x000032D1, "ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND" }, + { 0x000032D2, "ERROR_IPSEC_MM_AUTH_EXISTS" }, + { 0x000032D3, "ERROR_IPSEC_MM_AUTH_NOT_FOUND" }, + { 0x000032D4, "ERROR_IPSEC_MM_AUTH_IN_USE" }, + { 0x000032D5, "ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND" }, + { 0x000032D6, "ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND" }, + { 0x000032D7, "ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND" }, + { 0x000032D8, "ERROR_IPSEC_TUNNEL_FILTER_EXISTS" }, + { 0x000032D9, "ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND" }, + { 0x000032DA, "ERROR_IPSEC_MM_FILTER_PENDING_DELETION" }, + { 0x000032DB, "ERROR_IPSEC_TRANSPORT_FILTER_ENDING_DELETION" }, + { 0x000032DC, "ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION" }, + { 0x000032DD, "ERROR_IPSEC_MM_POLICY_PENDING_ELETION" }, + { 0x000032DE, "ERROR_IPSEC_MM_AUTH_PENDING_DELETION" }, + { 0x000032DF, "ERROR_IPSEC_QM_POLICY_PENDING_DELETION" }, + { 0x000032E0, "WARNING_IPSEC_MM_POLICY_PRUNED" }, + { 0x000032E1, "WARNING_IPSEC_QM_POLICY_PRUNED" }, + { 0x000035E8, "ERROR_IPSEC_IKE_NEG_STATUS_BEGIN" }, + { 0x000035E9, "ERROR_IPSEC_IKE_AUTH_FAIL" }, + { 0x000035EA, "ERROR_IPSEC_IKE_ATTRIB_FAIL" }, + { 0x000035EB, "ERROR_IPSEC_IKE_NEGOTIATION_PENDING" }, + { 0x000035EC, "ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR" }, + { 0x000035ED, "ERROR_IPSEC_IKE_TIMED_OUT" }, + { 0x000035EE, "ERROR_IPSEC_IKE_NO_CERT" }, + { 0x000035EF, "ERROR_IPSEC_IKE_SA_DELETED" }, + { 0x000035F0, "ERROR_IPSEC_IKE_SA_REAPED" }, + { 0x000035F1, "ERROR_IPSEC_IKE_MM_ACQUIRE_DROP" }, + { 0x000035F2, "ERROR_IPSEC_IKE_QM_ACQUIRE_DROP" }, + { 0x000035F3, "ERROR_IPSEC_IKE_QUEUE_DROP_MM" }, + { 0x000035F4, "ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM" }, + { 0x000035F5, "ERROR_IPSEC_IKE_DROP_NO_RESPONSE" }, + { 0x000035F6, "ERROR_IPSEC_IKE_MM_DELAY_DROP" }, + { 0x000035F7, "ERROR_IPSEC_IKE_QM_DELAY_DROP" }, + { 0x000035F8, "ERROR_IPSEC_IKE_ERROR" }, + { 0x000035F9, "ERROR_IPSEC_IKE_CRL_FAILED" }, + { 0x000035FA, "ERROR_IPSEC_IKE_INVALID_KEY_USAGE" }, + { 0x000035FB, "ERROR_IPSEC_IKE_INVALID_CERT_TYPE" }, + { 0x000035FC, "ERROR_IPSEC_IKE_NO_PRIVATE_KEY" }, + { 0x000035FE, "ERROR_IPSEC_IKE_DH_FAIL" }, + { 0x00003600, "ERROR_IPSEC_IKE_INVALID_HEADER" }, + { 0x00003601, "ERROR_IPSEC_IKE_NO_POLICY" }, + { 0x00003602, "ERROR_IPSEC_IKE_INVALID_SIGNATURE" }, + { 0x00003603, "ERROR_IPSEC_IKE_KERBEROS_ERROR" }, + { 0x00003604, "ERROR_IPSEC_IKE_NO_PUBLIC_KEY" }, + { 0x00003605, "ERROR_IPSEC_IKE_PROCESS_ERR" }, + { 0x00003606, "ERROR_IPSEC_IKE_PROCESS_ERR_SA" }, + { 0x00003607, "ERROR_IPSEC_IKE_PROCESS_ERR_PROP" }, + { 0x00003608, "ERROR_IPSEC_IKE_PROCESS_ERR_TRANS" }, + { 0x00003609, "ERROR_IPSEC_IKE_PROCESS_ERR_KE" }, + { 0x0000360A, "ERROR_IPSEC_IKE_PROCESS_ERR_ID" }, + { 0x0000360B, "ERROR_IPSEC_IKE_PROCESS_ERR_CERT" }, + { 0x0000360C, "ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ" }, + { 0x0000360D, "ERROR_IPSEC_IKE_PROCESS_ERR_HASH" }, + { 0x0000360E, "ERROR_IPSEC_IKE_PROCESS_ERR_SIG" }, + { 0x0000360F, "ERROR_IPSEC_IKE_PROCESS_ERR_NONCE" }, + { 0x00003610, "ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY" }, + { 0x00003611, "ERROR_IPSEC_IKE_PROCESS_ERR_DELETE" }, + { 0x00003612, "ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR" }, + { 0x00003613, "ERROR_IPSEC_IKE_INVALID_PAYLOAD" }, + { 0x00003614, "ERROR_IPSEC_IKE_LOAD_SOFT_SA" }, + { 0x00003615, "ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN" }, + { 0x00003616, "ERROR_IPSEC_IKE_INVALID_COOKIE" }, + { 0x00003617, "ERROR_IPSEC_IKE_NO_PEER_CERT" }, + { 0x00003618, "ERROR_IPSEC_IKE_PEER_CRL_FAILED" }, + { 0x00003619, "ERROR_IPSEC_IKE_POLICY_CHANGE" }, + { 0x0000361A, "ERROR_IPSEC_IKE_NO_MM_POLICY" }, + { 0x0000361B, "ERROR_IPSEC_IKE_NOTCBPRIV" }, + { 0x0000361C, "ERROR_IPSEC_IKE_SECLOADFAIL" }, + { 0x0000361D, "ERROR_IPSEC_IKE_FAILSSPINIT" }, + { 0x0000361E, "ERROR_IPSEC_IKE_FAILQUERYSSP" }, + { 0x0000361F, "ERROR_IPSEC_IKE_SRVACQFAIL" }, + { 0x00003620, "ERROR_IPSEC_IKE_SRVQUERYCRED" }, + { 0x00003621, "ERROR_IPSEC_IKE_GETSPIFAIL" + + }, + { 0x00003622, "ERROR_IPSEC_IKE_INVALID_FILTER" }, + { 0x00003623, "ERROR_IPSEC_IKE_OUT_OF_MEMORY" }, + { 0x00003624, "ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED" }, + { 0x00003625, "ERROR_IPSEC_IKE_INVALID_POLICY" }, + { 0x00003626, "ERROR_IPSEC_IKE_UNKNOWN_DOI" }, + { 0x00003627, "ERROR_IPSEC_IKE_INVALID_SITUATION" }, + { 0x00003628, "ERROR_IPSEC_IKE_DH_FAILURE" }, + { 0x00003629, "ERROR_IPSEC_IKE_INVALID_GROUP" }, + { 0x0000362A, "ERROR_IPSEC_IKE_ENCRYPT" }, + { 0x0000362B, "ERROR_IPSEC_IKE_DECRYPT" }, + { 0x0000362C, "ERROR_IPSEC_IKE_POLICY_MATCH" }, + { 0x0000362D, "ERROR_IPSEC_IKE_UNSUPPORTED_ID" }, + { 0x0000362E, "ERROR_IPSEC_IKE_INVALID_HASH" }, + { 0x0000362F, "ERROR_IPSEC_IKE_INVALID_HASH_ALG" }, + { 0x00003630, "ERROR_IPSEC_IKE_INVALID_HASH_SIZE" }, + { 0x00003631, "ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG" }, + { 0x00003632, "ERROR_IPSEC_IKE_INVALID_AUTH_ALG" }, + { 0x00003633, "ERROR_IPSEC_IKE_INVALID_SIG" }, + { 0x00003634, "ERROR_IPSEC_IKE_LOAD_FAILED" }, + { 0x00003635, "ERROR_IPSEC_IKE_RPC_DELETE" }, + { 0x00003636, "ERROR_IPSEC_IKE_BENIGN_REINIT" }, + { 0x00003637, "ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY" }, + { 0x00003639, "ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN" }, + { 0x0000363A, "ERROR_IPSEC_IKE_MM_LIMIT" }, + { 0x0000363B, "ERROR_IPSEC_IKE_NEGOTIATION_DISABLED" }, + { 0x0000363C, "ERROR_IPSEC_IKE_QM_LIMIT" }, + { 0x0000363D, "ERROR_IPSEC_IKE_MM_EXPIRED" }, + { 0x0000363E, "ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID" }, + { 0x0000363F, "ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH" }, + { 0x00003640, "ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID" }, + { 0x00003641, "ERROR_IPSEC_IKE_INVALID_UMATTS" }, + { 0x00003642, "ERROR_IPSEC_IKE_DOS_COOKIE_SENT" }, + { 0x00003643, "ERROR_IPSEC_IKE_SHUTTING_DOWN" }, + { 0x00003644, "ERROR_IPSEC_IKE_CGA_AUTH_FAILED" }, + { 0x00003645, "ERROR_IPSEC_IKE_PROCESS_ERR_NATOA" }, + { 0x00003646, "ERROR_IPSEC_IKE_INVALID_MM_FOR_QM" }, + { 0x00003647, "ERROR_IPSEC_IKE_QM_EXPIRED" }, + { 0x00003648, "ERROR_IPSEC_IKE_TOO_MANY_FILTERS" }, + { 0x00003649, "ERROR_IPSEC_IKE_NEG_STATUS_END" }, + { 0x000036B0, "ERROR_SXS_SECTION_NOT_FOUND" }, + { 0x000036B1, "ERROR_SXS_CANT_GEN_ACTCTX" }, + { 0x000036B2, "ERROR_SXS_INVALID_ACTCTXDATA_FORMAT" }, + { 0x000036B3, "ERROR_SXS_ASSEMBLY_NOT_FOUND" }, + { 0x000036B4, "ERROR_SXS_MANIFEST_FORMAT_ERROR" }, + { 0x000036B5, "ERROR_SXS_MANIFEST_PARSE_ERROR" }, + { 0x000036B6, "ERROR_SXS_ACTIVATION_CONTEXT_DISABLED" }, + { 0x000036B7, "ERROR_SXS_KEY_NOT_FOUND" }, + { 0x000036B8, "ERROR_SXS_VERSION_CONFLICT" }, + { 0x000036B9, "ERROR_SXS_WRONG_SECTION_TYPE" }, + { 0x000036BA, "ERROR_SXS_THREAD_QUERIES_DISABLED" }, + { 0x000036BB, "ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET" }, + { 0x000036BC, "ERROR_SXS_UNKNOWN_ENCODING_GROUP" }, + { 0x000036BD, "ERROR_SXS_UNKNOWN_ENCODING" }, + { 0x000036BE, "ERROR_SXS_INVALID_XML_NAMESPACE_URI" }, + { 0x000036BF, "ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_OT_INSTALLED" }, + { 0x000036C0, "ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED" }, + { 0x000036C1, "ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE" }, + { 0x000036C2, "ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE" }, + { 0x000036C3, "ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE" }, + { 0x000036C4, "ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT" }, + { 0x000036C5, "ERROR_SXS_DUPLICATE_DLL_NAME" }, + { 0x000036C6, "ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME" }, + { 0x000036C7, "ERROR_SXS_DUPLICATE_CLSID" }, + { 0x000036C8, "ERROR_SXS_DUPLICATE_IID" }, + { 0x000036C9, "ERROR_SXS_DUPLICATE_TLBID" }, + { 0x000036CA, "ERROR_SXS_DUPLICATE_PROGID" }, + { 0x000036CB, "ERROR_SXS_DUPLICATE_ASSEMBLY_NAME" }, + { 0x000036CC, "ERROR_SXS_FILE_HASH_MISMATCH" }, + { 0x000036CD, "ERROR_SXS_POLICY_PARSE_ERROR" }, + { 0x000036CE, "ERROR_SXS_XML_E_MISSINGQUOTE" }, + { 0x000036CF, "ERROR_SXS_XML_E_COMMENTSYNTAX" }, + { 0x000036D0, "ERROR_SXS_XML_E_BADSTARTNAMECHAR" }, + { 0x000036D1, "ERROR_SXS_XML_E_BADNAMECHAR" }, + { 0x000036D2, "ERROR_SXS_XML_E_BADCHARINSTRING" }, + { 0x000036D3, "ERROR_SXS_XML_E_XMLDECLSYNTAX" }, + { 0x000036D4, "ERROR_SXS_XML_E_BADCHARDATA" }, + { 0x000036D5, "ERROR_SXS_XML_E_MISSINGWHITESPACE" }, + { 0x000036D6, "ERROR_SXS_XML_E_EXPECTINGTAGEND" }, + { 0x000036D7, "ERROR_SXS_XML_E_MISSINGSEMICOLON" }, + { 0x000036D8, "ERROR_SXS_XML_E_UNBALANCEDPAREN" }, + { 0x000036D9, "ERROR_SXS_XML_E_INTERNALERROR" }, + { 0x000036DA, "ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE" }, + { 0x000036DB, "ERROR_SXS_XML_E_INCOMPLETE_ENCODING" }, + { 0x000036DC, "ERROR_SXS_XML_E_MISSING_PAREN" }, + { 0x000036DD, "ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE" }, + { 0x000036DE, "ERROR_SXS_XML_E_MULTIPLE_COLONS" }, + { 0x000036DF, "ERROR_SXS_XML_E_INVALID_DECIMAL" }, + { 0x000036E0, "ERROR_SXS_XML_E_INVALID_HEXIDECIMAL" }, + { 0x000036E1, "ERROR_SXS_XML_E_INVALID_UNICODE" }, + { 0x000036E2, "ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK" }, + { 0x000036E3, "ERROR_SXS_XML_E_UNEXPECTEDENDTAG" }, + { 0x000036E4, "ERROR_SXS_XML_E_UNCLOSEDTAG" }, + { 0x000036E5, "ERROR_SXS_XML_E_DUPLICATEATTRIBUTE" }, + { 0x000036E6, "ERROR_SXS_XML_E_MULTIPLEROOTS" }, + { 0x000036E7, "ERROR_SXS_XML_E_INVALIDATROOTLEVEL" }, + { 0x000036E8, "ERROR_SXS_XML_E_BADXMLDECL" }, + { 0x000036E9, "ERROR_SXS_XML_E_MISSINGROOT" }, + { 0x000036EA, "ERROR_SXS_XML_E_UNEXPECTEDEOF" }, + { 0x000036EB, "ERROR_SXS_XML_E_BADPEREFINSUBSET" }, + { 0x000036EC, "ERROR_SXS_XML_E_UNCLOSEDSTARTTAG" }, + { 0x000036ED, "ERROR_SXS_XML_E_UNCLOSEDENDTAG" }, + { 0x000036EE, "ERROR_SXS_XML_E_UNCLOSEDSTRING" }, + { 0x000036EF, "ERROR_SXS_XML_E_UNCLOSEDCOMMENT" }, + { 0x000036F0, "ERROR_SXS_XML_E_UNCLOSEDDECL" }, + { 0x000036F1, "ERROR_SXS_XML_E_UNCLOSEDCDATA" }, + { 0x000036F2, "ERROR_SXS_XML_E_RESERVEDNAMESPACE" }, + { 0x000036F3, "ERROR_SXS_XML_E_INVALIDENCODING" }, + { 0x000036F4, "ERROR_SXS_XML_E_INVALIDSWITCH" }, + { 0x000036F5, "ERROR_SXS_XML_E_BADXMLCASE" }, + { 0x000036F6, "ERROR_SXS_XML_E_INVALID_STANDALONE" }, + { 0x000036F7, "ERROR_SXS_XML_E_UNEXPECTED_STANDALONE" }, + { 0x000036F8, "ERROR_SXS_XML_E_INVALID_VERSION" }, + { 0x000036F9, "ERROR_SXS_XML_E_MISSINGEQUALS" }, + { 0x000036FA, "ERROR_SXS_PROTECTION_RECOVERY_FAILED" }, + { 0x000036FB, "ERROR_SXS_PROTECTION_PUBLIC_KEY_OO_SHORT" }, + { 0x000036FC, "ERROR_SXS_PROTECTION_CATALOG_NOT_VALID" }, + { 0x000036FD, "ERROR_SXS_UNTRANSLATABLE_HRESULT" }, + { 0x000036FE, "ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING" }, + { 0x000036FF, "ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE" }, + { 0x00003700, "ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME" }, + { 0x00003701, "ERROR_SXS_ASSEMBLY_MISSING" }, + { 0x00003702, "ERROR_SXS_CORRUPT_ACTIVATION_STACK" }, + { 0x00003703, "ERROR_SXS_CORRUPTION" }, + { 0x00003704, "ERROR_SXS_EARLY_DEACTIVATION" }, + { 0x00003705, "ERROR_SXS_INVALID_DEACTIVATION" }, + { 0x00003706, "ERROR_SXS_MULTIPLE_DEACTIVATION" }, + { 0x00003707, "ERROR_SXS_PROCESS_TERMINATION_REQUESTED" }, + { 0x00003708, "ERROR_SXS_RELEASE_ACTIVATION_ONTEXT" }, + { 0x00003709, "ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY" }, + { 0x0000370A, "ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE" }, + { 0x0000370B, "ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME" }, + { 0x0000370C, "ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE" }, + { 0x0000370D, "ERROR_SXS_IDENTITY_PARSE_ERROR" }, + { 0x0000370E, "ERROR_MALFORMED_SUBSTITUTION_STRING" }, + { 0x0000370F, "ERROR_SXS_INCORRECT_PUBLIC_KEY_OKEN" }, + { 0x00003710, "ERROR_UNMAPPED_SUBSTITUTION_STRING" }, + { 0x00003711, "ERROR_SXS_ASSEMBLY_NOT_LOCKED" }, + { 0x00003712, "ERROR_SXS_COMPONENT_STORE_CORRUPT" }, + { 0x00003713, "ERROR_ADVANCED_INSTALLER_FAILED" }, + { 0x00003714, "ERROR_XML_ENCODING_MISMATCH" }, + { 0x00003715, "ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT" }, + { 0x00003716, "ERROR_SXS_IDENTITIES_DIFFERENT" }, + { 0x00003717, "ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT" }, + { 0x00003718, "ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY" }, + { 0x00003719, "ERROR_SXS_MANIFEST_TOO_BIG" }, + { 0x0000371A, "ERROR_SXS_SETTING_NOT_REGISTERED" }, + { 0x0000371B, "ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE" }, + { 0x00003A98, "ERROR_EVT_INVALID_CHANNEL_PATH" }, + { 0x00003A99, "ERROR_EVT_INVALID_QUERY" }, + { 0x00003A9A, "ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND" }, + { 0x00003A9B, "ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND" }, + { 0x00003A9C, "ERROR_EVT_INVALID_PUBLISHER_NAME" }, + { 0x00003A9D, "ERROR_EVT_INVALID_EVENT_DATA" }, + { 0x00003A9F, "ERROR_EVT_CHANNEL_NOT_FOUND" }, + { 0x00003AA0, "ERROR_EVT_MALFORMED_XML_TEXT" }, + { 0x00003AA1, "ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL" }, + { 0x00003AA2, "ERROR_EVT_CONFIGURATION_ERROR" }, + { 0x00003AA3, "ERROR_EVT_QUERY_RESULT_STALE" }, + { 0x00003AA4, "ERROR_EVT_QUERY_RESULT_INVALID_POSITION" }, + { 0x00003AA5, "ERROR_EVT_NON_VALIDATING_MSXML" }, + { 0x00003AA6, "ERROR_EVT_FILTER_ALREADYSCOPED" }, + { 0x00003AA7, "ERROR_EVT_FILTER_NOTELTSET" }, + { 0x00003AA8, "ERROR_EVT_FILTER_INVARG" }, + { 0x00003AA9, "ERROR_EVT_FILTER_INVTEST" }, + { 0x00003AAA, "ERROR_EVT_FILTER_INVTYPE" }, + { 0x00003AAB, "ERROR_EVT_FILTER_PARSEERR" }, + { 0x00003AAC, "ERROR_EVT_FILTER_UNSUPPORTEDOP" }, + { 0x00003AAD, "ERROR_EVT_FILTER_UNEXPECTEDTOKEN" }, + { 0x00003AAE, "ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL" }, + { 0x00003AAF, "ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE" + + }, + { 0x00003AB0, "ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE" + + }, + { 0x00003AB1, "ERROR_EVT_CHANNEL_CANNOT_ACTIVATE" }, + { 0x00003AB2, "ERROR_EVT_FILTER_TOO_COMPLEX" }, + { 0x00003AB3, "ERROR_EVT_MESSAGE_NOT_FOUND" }, + { 0x00003AB4, "ERROR_EVT_MESSAGE_ID_NOT_FOUND" }, + { 0x00003AB5, "ERROR_EVT_UNRESOLVED_VALUE_INSERT" }, + { 0x00003AB6, "ERROR_EVT_UNRESOLVED_PARAMETER_INSERT" }, + { 0x00003AB7, "ERROR_EVT_MAX_INSERTS_REACHED" }, + { 0x00003AB8, "ERROR_EVT_EVENT_DEFINITION_NOT_OUND" }, + { 0x00003AB9, "ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND" }, + { 0x00003ABA, "ERROR_EVT_VERSION_TOO_OLD" }, + { 0x00003ABB, "ERROR_EVT_VERSION_TOO_NEW" }, + { 0x00003ABC, "ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY" }, + { 0x00003ABD, "ERROR_EVT_PUBLISHER_DISABLED" }, + { 0x00003AE8, "ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE" }, + { 0x00003AE9, "ERROR_EC_LOG_DISABLED" }, + { 0x00003AFC, "ERROR_MUI_FILE_NOT_FOUND" }, + { 0x00003AFD, "ERROR_MUI_INVALID_FILE" }, + { 0x00003AFE, "ERROR_MUI_INVALID_RC_CONFIG" }, + { 0x00003AFF, "ERROR_MUI_INVALID_LOCALE_NAME" }, + { 0x00003B00, "ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME" }, + { 0x00003B01, "ERROR_MUI_FILE_NOT_LOADED" }, + { 0x00003B02, "ERROR_RESOURCE_ENUM_USER_STOP" }, + { 0x00003B03, "ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED" }, + { 0x00003B04, "ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME" }, + { 0x00003B60, "ERROR_MCA_INVALID_CAPABILITIES_STRING" }, + { 0x00003B61, "ERROR_MCA_INVALID_VCP_VERSION" }, + { 0x00003B62, "ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION" }, + { 0x00003B63, "ERROR_MCA_MCCS_VERSION_MISMATCH" }, + { 0x00003B64, "ERROR_MCA_UNSUPPORTED_MCCS_VERSION" }, + { 0x00003B65, "ERROR_MCA_INTERNAL_ERROR" }, + { 0x00003B66, "ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED" }, + { 0x00003B67, "ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE" }, + { 0x00003B92, "ERROR_AMBIGUOUS_SYSTEM_DEVICE" }, + { 0x00003BC3, "ERROR_SYSTEM_DEVICE_NOT_FOUND" } +}; + +static const struct ntstatus_map ntstatusmap[] = { + + { 0x00000000, "STATUS_SUCCESS" }, + { 0x00000000, "STATUS_WAIT_0" }, + { 0x00000001, "STATUS_WAIT_1" }, + { 0x00000002, "STATUS_WAIT_2" }, + { 0x00000003, "STATUS_WAIT_3" }, + { 0x0000003F, "STATUS_WAIT_63" }, + { 0x00000080, "STATUS_ABANDONED" }, + { 0x00000080, "STATUS_ABANDONED_WAIT_0" }, + { 0x000000BF, "STATUS_ABANDONED_WAIT_63" }, + { 0x000000C0, "STATUS_USER_APC" }, + { 0x00000101, "STATUS_ALERTED" }, + { 0x00000102, "STATUS_TIMEOUT" }, + { 0x00000103, "STATUS_PENDING" }, + { 0x00000104, "STATUS_REPARSE" }, + { 0x00000105, "STATUS_MORE_ENTRIES" }, + { 0x00000106, "STATUS_NOT_ALL_ASSIGNED" }, + { 0x00000107, "STATUS_SOME_NOT_MAPPED" }, + { 0x00000108, "STATUS_OPLOCK_BREAK_IN_PROGRESS" }, + { 0x00000109, "STATUS_VOLUME_MOUNTED" }, + { 0x0000010A, "STATUS_RXACT_COMMITTED" }, + { 0x0000010B, "STATUS_NOTIFY_CLEANUP" }, + { 0x0000010C, "STATUS_NOTIFY_ENUM_DIR" }, + { 0x0000010D, "STATUS_NO_QUOTAS_FOR_ACCOUNT" }, + { 0x0000010E, "STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED" }, + { 0x00000110, "STATUS_PAGE_FAULT_TRANSITION" }, + { 0x00000111, "STATUS_PAGE_FAULT_DEMAND_ZERO" }, + { 0x00000112, "STATUS_PAGE_FAULT_COPY_ON_WRITE" }, + { 0x00000113, "STATUS_PAGE_FAULT_GUARD_PAGE" }, + { 0x00000114, "STATUS_PAGE_FAULT_PAGING_FILE" }, + { 0x00000115, "STATUS_CACHE_PAGE_LOCKED" }, + { 0x00000116, "STATUS_CRASH_DUMP" }, + { 0x00000117, "STATUS_BUFFER_ALL_ZEROS" }, + { 0x00000118, "STATUS_REPARSE_OBJECT" }, + { 0x00000119, "STATUS_RESOURCE_REQUIREMENTS_CHANGED" }, + { 0x00000120, "STATUS_TRANSLATION_COMPLETE" }, + { 0x00000121, "STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY" }, + { 0x00000122, "STATUS_NOTHING_TO_TERMINATE" }, + { 0x00000123, "STATUS_PROCESS_NOT_IN_JOB" }, + { 0x00000124, "STATUS_PROCESS_IN_JOB" }, + { 0x00000125, "STATUS_VOLSNAP_HIBERNATE_READY" }, + { 0x00000126, "STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY" }, + { 0x00000127, "STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED" }, + { 0x00000128, "STATUS_INTERRUPT_STILL_CONNECTED" }, + { 0x00000129, "STATUS_PROCESS_CLONED" }, + { 0x0000012A, "STATUS_FILE_LOCKED_WITH_ONLY_READERS" }, + { 0x0000012B, "STATUS_FILE_LOCKED_WITH_WRITERS" }, + { 0x00000202, "STATUS_RESOURCEMANAGER_READ_ONLY" }, + { 0x00000367, "STATUS_WAIT_FOR_OPLOCK" }, + { 0x00010001, "DBG_EXCEPTION_HANDLED" }, + { 0x00010002, "DBG_CONTINUE" }, + { 0x001C0001, "STATUS_FLT_IO_COMPLETE" }, + { 0x40000000, "STATUS_OBJECT_NAME_EXISTS" }, + { 0x40000001, "STATUS_THREAD_WAS_SUSPENDED" }, + { 0x40000002, "STATUS_WORKING_SET_LIMIT_RANGE" }, + { 0x40000003, "STATUS_IMAGE_NOT_AT_BASE" }, + { 0x40000004, "STATUS_RXACT_STATE_CREATED" }, + { 0x40000005, "STATUS_SEGMENT_NOTIFICATION" }, + { 0x40000006, "STATUS_LOCAL_USER_SESSION_KEY" }, + { 0x40000007, "STATUS_BAD_CURRENT_DIRECTORY" }, + { 0x40000008, "STATUS_SERIAL_MORE_WRITES" }, + { 0x40000009, "STATUS_REGISTRY_RECOVERED" }, + { 0x4000000A, "STATUS_FT_READ_RECOVERY_FROM_BACKUP" }, + { 0x4000000B, "STATUS_FT_WRITE_RECOVERY" }, + { 0x4000000C, "STATUS_SERIAL_COUNTER_TIMEOUT" }, + { 0x4000000D, "STATUS_NULL_LM_PASSWORD" }, + { 0x4000000E, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH" }, + { 0x4000000F, "STATUS_RECEIVE_PARTIAL" }, + { 0x40000010, "STATUS_RECEIVE_EXPEDITED" }, + { 0x40000011, "STATUS_RECEIVE_PARTIAL_EXPEDITED" }, + { 0x40000012, "STATUS_EVENT_DONE" }, + { 0x40000013, "STATUS_EVENT_PENDING" }, + { 0x40000014, "STATUS_CHECKING_FILE_SYSTEM" }, + { 0x40000015, "STATUS_FATAL_APP_EXIT" }, + { 0x40000016, "STATUS_PREDEFINED_HANDLE" }, + { 0x40000017, "STATUS_WAS_UNLOCKED" }, + { 0x40000018, "STATUS_SERVICE_NOTIFICATION" }, + { 0x40000019, "STATUS_WAS_LOCKED" }, + { 0x4000001A, "STATUS_LOG_HARD_ERROR" }, + { 0x4000001B, "STATUS_ALREADY_WIN32" }, + { 0x4000001C, "STATUS_WX86_UNSIMULATE" }, + { 0x4000001D, "STATUS_WX86_CONTINUE" }, + { 0x4000001E, "STATUS_WX86_SINGLE_STEP" }, + { 0x4000001F, "STATUS_WX86_BREAKPOINT" }, + { 0x40000020, "STATUS_WX86_EXCEPTION_CONTINUE" }, + { 0x40000021, "STATUS_WX86_EXCEPTION_LASTCHANCE" }, + { 0x40000022, "STATUS_WX86_EXCEPTION_CHAIN" }, + { 0x40000023, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE" }, + { 0x40000024, "STATUS_NO_YIELD_PERFORMED" }, + { 0x40000025, "STATUS_TIMER_RESUME_IGNORED" }, + { 0x40000026, "STATUS_ARBITRATION_UNHANDLED" }, + { 0x40000027, "STATUS_CARDBUS_NOT_SUPPORTED" }, + { 0x40000028, "STATUS_WX86_CREATEWX86TIB" }, + { 0x40000029, "STATUS_MP_PROCESSOR_MISMATCH" }, + { 0x4000002A, "STATUS_HIBERNATED" }, + { 0x4000002B, "STATUS_RESUME_HIBERNATION" }, + { 0x4000002C, "STATUS_FIRMWARE_UPDATED" }, + { 0x4000002D, "STATUS_DRIVERS_LEAKING_LOCKED_PAGES" }, + { 0x4000002E, "STATUS_MESSAGE_RETRIEVED" }, + { 0x4000002F, "STATUS_SYSTEM_POWERSTATE_TRANSITION" }, + { 0x40000030, "STATUS_ALPC_CHECK_COMPLETION_LIST" }, + { 0x40000031, "STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION" }, + { 0x40000032, "STATUS_ACCESS_AUDIT_BY_POLICY" }, + { 0x40000033, "STATUS_ABANDON_HIBERFILE" }, + { 0x40000034, "STATUS_BIZRULES_NOT_ENABLED" }, + { 0x40000294, "STATUS_WAKE_SYSTEM" }, + { 0x40000370, "STATUS_DS_SHUTTING_DOWN" }, + { 0x40010001, "DBG_REPLY_LATER" }, + { 0x40010002, "DBG_UNABLE_TO_PROVIDE_HANDLE" }, + { 0x40010003, "DBG_TERMINATE_THREAD" }, + { 0x40010004, "DBG_TERMINATE_PROCESS" }, + { 0x40010005, "DBG_CONTROL_C" }, + { 0x40010006, "DBG_PRINTEXCEPTION_C" }, + { 0x40010007, "DBG_RIPEXCEPTION" }, + { 0x40010008, "DBG_CONTROL_BREAK" }, + { 0x40010009, "DBG_COMMAND_EXCEPTION" }, + { 0x40020056, "RPC_NT_UUID_LOCAL_ONLY" }, + { 0x400200AF, "RPC_NT_SEND_INCOMPLETE" }, + { 0x400A0004, "STATUS_CTX_CDM_CONNECT" }, + { 0x400A0005, "STATUS_CTX_CDM_DISCONNECT" }, + { 0x4015000D, "STATUS_SXS_RELEASE_ACTIVATION_CONTEXT" }, + { 0x40190034, "STATUS_RECOVERY_NOT_NEEDED" }, + { 0x40190035, "STATUS_RM_ALREADY_STARTED" }, + { 0x401A000C, "STATUS_LOG_NO_RESTART" }, + { 0x401B00EC, "STATUS_VIDEO_DRIVER_DEBUG_REPORT_REQUEST" }, + { 0x401E000A, "STATUS_GRAPHICS_PARTIAL_DATA_POPULATED" }, + { 0x401E0117, "STATUS_GRAPHICS_DRIVER_MISMATCH" }, + { 0x401E0307, "STATUS_GRAPHICS_MODE_NOT_PINNED" }, + { 0x401E031E, "STATUS_GRAPHICS_NO_PREFERRED_MODE" }, + { 0x401E034B, "STATUS_GRAPHICS_DATASET_IS_EMPTY" }, + { 0x401E034C, "STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET" }, + { 0x401E0351, "STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED" }, + { 0x401E042F, "STATUS_GRAPHICS_UNKNOWN_CHILD_STATUS" }, + { 0x401E0437, "STATUS_GRAPHICS_LEADLINK_START_DEFERRED" }, + { 0x401E0439, "STATUS_GRAPHICS_POLLING_TOO_FREQUENTLY" }, + { 0x401E043A, "STATUS_GRAPHICS_START_DEFERRED" }, + { 0x40230001, "STATUS_NDIS_INDICATION_REQUIRED" }, + { 0x80000001, "STATUS_GUARD_PAGE_VIOLATION" }, + { 0x80000002, "STATUS_DATATYPE_MISALIGNMENT" }, + { 0x80000003, "STATUS_BREAKPOINT" }, + { 0x80000004, "STATUS_SINGLE_STEP" }, + { 0x80000005, "STATUS_BUFFER_OVERFLOW" }, + { 0x80000006, "STATUS_NO_MORE_FILES" }, + { 0x80000007, "STATUS_WAKE_SYSTEM_DEBUGGER" }, + { 0x8000000A, "STATUS_HANDLES_CLOSED" }, + { 0x8000000B, "STATUS_NO_INHERITANCE" }, + { 0x8000000C, "STATUS_GUID_SUBSTITUTION_MADE" }, + { 0x8000000D, "STATUS_PARTIAL_COPY" }, + { 0x8000000E, "STATUS_DEVICE_PAPER_EMPTY" }, + { 0x8000000F, "STATUS_DEVICE_POWERED_OFF" }, + { 0x80000010, "STATUS_DEVICE_OFF_LINE" }, + { 0x80000011, "STATUS_DEVICE_BUSY" }, + { 0x80000012, "STATUS_NO_MORE_EAS" }, + { 0x80000013, "STATUS_INVALID_EA_NAME" }, + { 0x80000014, "STATUS_EA_LIST_INCONSISTENT" }, + { 0x80000015, "STATUS_INVALID_EA_FLAG" }, + { 0x80000016, "STATUS_VERIFY_REQUIRED" }, + { 0x80000017, "STATUS_EXTRANEOUS_INFORMATION" }, + { 0x80000018, "STATUS_RXACT_COMMIT_NECESSARY" }, + { 0x8000001A, "STATUS_NO_MORE_ENTRIES" }, + { 0x8000001B, "STATUS_FILEMARK_DETECTED" }, + { 0x8000001C, "STATUS_MEDIA_CHANGED" }, + { 0x8000001D, "STATUS_BUS_RESET" }, + { 0x8000001E, "STATUS_END_OF_MEDIA" }, + { 0x8000001F, "STATUS_BEGINNING_OF_MEDIA" }, + { 0x80000020, "STATUS_MEDIA_CHECK" }, + { 0x80000021, "STATUS_SETMARK_DETECTED" }, + { 0x80000022, "STATUS_NO_DATA_DETECTED" }, + { 0x80000023, "STATUS_REDIRECTOR_HAS_OPEN_HANDLES" }, + { 0x80000024, "STATUS_SERVER_HAS_OPEN_HANDLES" }, + { 0x80000025, "STATUS_ALREADY_DISCONNECTED" }, + { 0x80000026, "STATUS_LONGJUMP" }, + { 0x80000027, "STATUS_CLEANER_CARTRIDGE_INSTALLED" }, + { 0x80000028, "STATUS_PLUGPLAY_QUERY_VETOED" }, + { 0x80000029, "STATUS_UNWIND_CONSOLIDATE" }, + { 0x8000002A, "STATUS_REGISTRY_HIVE_RECOVERED" }, + { 0x8000002B, "STATUS_DLL_MIGHT_BE_INSECURE" }, + { 0x8000002C, "STATUS_DLL_MIGHT_BE_INCOMPATIBLE" }, + { 0x8000002D, "STATUS_STOPPED_ON_SYMLINK" }, + { 0x80000288, "STATUS_DEVICE_REQUIRES_CLEANING" }, + { 0x80000289, "STATUS_DEVICE_DOOR_OPEN" }, + { 0x80000803, "STATUS_DATA_LOST_REPAIR" }, + { 0x80010001, "DBG_EXCEPTION_NOT_HANDLED" }, + { 0x80130001, "STATUS_CLUSTER_NODE_ALREADY_UP" }, + { 0x80130002, "STATUS_CLUSTER_NODE_ALREADY_DOWN" }, + { 0x80130003, "STATUS_CLUSTER_NETWORK_ALREADY_ONLINE" }, + { 0x80130004, "STATUS_CLUSTER_NETWORK_ALREADY_OFFLINE" }, + { 0x80130005, "STATUS_CLUSTER_NODE_ALREADY_MEMBER" }, + { 0x80190009, "STATUS_COULD_NOT_RESIZE_LOG" }, + { 0x80190029, "STATUS_NO_TXF_METADATA" }, + { 0x80190031, "STATUS_CANT_RECOVER_WITH_HANDLE_OPEN" }, + { 0x80190041, "STATUS_TXF_METADATA_ALREADY_PRESENT" }, + { 0x80190042, "STATUS_TRANSACTION_SCOPE_CALLBACKS_NOT_SET" }, + { 0x801B00EB, "STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED" }, + { 0x801C0001, "STATUS_FLT_BUFFER_TOO_SMALL" }, + { 0x80210001, "STATUS_FVE_PARTIAL_METADATA" }, + { 0x80210002, "STATUS_FVE_TRANSIENT_STATE" }, + { 0xC0000001, "STATUS_UNSUCCESSFUL" }, + { 0xC0000002, "STATUS_NOT_IMPLEMENTED" }, + { 0xC0000003, "STATUS_INVALID_INFO_CLASS" }, + { 0xC0000004, "STATUS_INFO_LENGTH_MISMATCH" }, + { 0xC0000005, "STATUS_ACCESS_VIOLATION" }, + { 0xC0000006, "STATUS_IN_PAGE_ERROR" }, + { 0xC0000007, "STATUS_PAGEFILE_QUOTA" }, + { 0xC0000008, "STATUS_INVALID_HANDLE" }, + { 0xC0000009, "STATUS_BAD_INITIAL_STACK" }, + { 0xC000000A, "STATUS_BAD_INITIAL_PC" }, + { 0xC000000B, "STATUS_INVALID_CID" }, + { 0xC000000C, "STATUS_TIMER_NOT_CANCELED" }, + { 0xC000000D, "STATUS_INVALID_PARAMETER" }, + { 0xC000000E, "STATUS_NO_SUCH_DEVICE" }, + { 0xC000000F, "STATUS_NO_SUCH_FILE" }, + { 0xC0000010, "STATUS_INVALID_DEVICE_REQUEST" }, + { 0xC0000011, "STATUS_END_OF_FILE" }, + { 0xC0000012, "STATUS_WRONG_VOLUME" }, + { 0xC0000013, "STATUS_NO_MEDIA_IN_DEVICE" }, + { 0xC0000014, "STATUS_UNRECOGNIZED_MEDIA" }, + { 0xC0000015, "STATUS_NONEXISTENT_SECTOR" }, + { 0xC0000016, "STATUS_MORE_PROCESSING_REQUIRED" }, + { 0xC0000017, "STATUS_NO_MEMORY" }, + { 0xC0000018, "STATUS_CONFLICTING_ADDRESSES" }, + { 0xC0000019, "STATUS_NOT_MAPPED_VIEW" }, + { 0xC000001A, "STATUS_UNABLE_TO_FREE_VM" }, + { 0xC000001B, "STATUS_UNABLE_TO_DELETE_SECTION" }, + { 0xC000001C, "STATUS_INVALID_SYSTEM_SERVICE" }, + { 0xC000001D, "STATUS_ILLEGAL_INSTRUCTION" }, + { 0xC000001E, "STATUS_INVALID_LOCK_SEQUENCE" }, + { 0xC000001F, "STATUS_INVALID_VIEW_SIZE" }, + { 0xC0000020, "STATUS_INVALID_FILE_FOR_SECTION" }, + { 0xC0000021, "STATUS_ALREADY_COMMITTED" }, + { 0xC0000022, "STATUS_ACCESS_DENIED" }, + { 0xC0000023, "STATUS_BUFFER_TOO_SMALL" }, + { 0xC0000024, "STATUS_OBJECT_TYPE_MISMATCH" }, + { 0xC0000025, "STATUS_NONCONTINUABLE_EXCEPTION" }, + { 0xC0000026, "STATUS_INVALID_DISPOSITION" }, + { 0xC0000027, "STATUS_UNWIND" }, + { 0xC0000028, "STATUS_BAD_STACK" }, + { 0xC0000029, "STATUS_INVALID_UNWIND_TARGET" }, + { 0xC000002A, "STATUS_NOT_LOCKED" }, + { 0xC000002B, "STATUS_PARITY_ERROR" }, + { 0xC000002C, "STATUS_UNABLE_TO_DECOMMIT_VM" }, + { 0xC000002D, "STATUS_NOT_COMMITTED" }, + { 0xC000002E, "STATUS_INVALID_PORT_ATTRIBUTES" }, + { 0xC000002F, "STATUS_PORT_MESSAGE_TOO_LONG" }, + { 0xC0000030, "STATUS_INVALID_PARAMETER_MIX" }, + { 0xC0000031, "STATUS_INVALID_QUOTA_LOWER" }, + { 0xC0000032, "STATUS_DISK_CORRUPT_ERROR" }, + { 0xC0000033, "STATUS_OBJECT_NAME_INVALID" }, + { 0xC0000034, "STATUS_OBJECT_NAME_NOT_FOUND" }, + { 0xC0000035, "STATUS_OBJECT_NAME_COLLISION" }, + { 0xC0000037, "STATUS_PORT_DISCONNECTED" }, + { 0xC0000038, "STATUS_DEVICE_ALREADY_ATTACHED" }, + { 0xC0000039, "STATUS_OBJECT_PATH_INVALID" }, + { 0xC000003A, "STATUS_OBJECT_PATH_NOT_FOUND" }, + { 0xC000003B, "STATUS_OBJECT_PATH_SYNTAX_BAD" }, + { 0xC000003C, "STATUS_DATA_OVERRUN" }, + { 0xC000003D, "STATUS_DATA_LATE_ERROR" }, + { 0xC000003E, "STATUS_DATA_ERROR" }, + { 0xC000003F, "STATUS_CRC_ERROR" }, + { 0xC0000040, "STATUS_SECTION_TOO_BIG" }, + { 0xC0000041, "STATUS_PORT_CONNECTION_REFUSED" }, + { 0xC0000042, "STATUS_INVALID_PORT_HANDLE" }, + { 0xC0000043, "STATUS_SHARING_VIOLATION" }, + { 0xC0000044, "STATUS_QUOTA_EXCEEDED" }, + { 0xC0000045, "STATUS_INVALID_PAGE_PROTECTION" }, + { 0xC0000046, "STATUS_MUTANT_NOT_OWNED" }, + { 0xC0000047, "STATUS_SEMAPHORE_LIMIT_EXCEEDED" }, + { 0xC0000048, "STATUS_PORT_ALREADY_SET" }, + { 0xC0000049, "STATUS_SECTION_NOT_IMAGE" }, + { 0xC000004A, "STATUS_SUSPEND_COUNT_EXCEEDED" }, + { 0xC000004B, "STATUS_THREAD_IS_TERMINATING" }, + { 0xC000004C, "STATUS_BAD_WORKING_SET_LIMIT" }, + { 0xC000004D, "STATUS_INCOMPATIBLE_FILE_MAP" }, + { 0xC000004E, "STATUS_SECTION_PROTECTION" }, + { 0xC000004F, "STATUS_EAS_NOT_SUPPORTED" }, + { 0xC0000050, "STATUS_EA_TOO_LARGE" }, + { 0xC0000051, "STATUS_NONEXISTENT_EA_ENTRY" }, + { 0xC0000052, "STATUS_NO_EAS_ON_FILE" }, + { 0xC0000053, "STATUS_EA_CORRUPT_ERROR" }, + { 0xC0000054, "STATUS_FILE_LOCK_CONFLICT" }, + { 0xC0000055, "STATUS_LOCK_NOT_GRANTED" }, + { 0xC0000056, "STATUS_DELETE_PENDING" }, + { 0xC0000057, "STATUS_CTL_FILE_NOT_SUPPORTED" }, + { 0xC0000058, "STATUS_UNKNOWN_REVISION" }, + { 0xC0000059, "STATUS_REVISION_MISMATCH" }, + { 0xC000005A, "STATUS_INVALID_OWNER" }, + { 0xC000005B, "STATUS_INVALID_PRIMARY_GROUP" }, + { 0xC000005C, "STATUS_NO_IMPERSONATION_TOKEN" }, + { 0xC000005D, "STATUS_CANT_DISABLE_MANDATORY" }, + { 0xC000005E, "STATUS_NO_LOGON_SERVERS" }, + { 0xC000005F, "STATUS_NO_SUCH_LOGON_SESSION" }, + { 0xC0000060, "STATUS_NO_SUCH_PRIVILEGE" }, + { 0xC0000061, "STATUS_PRIVILEGE_NOT_HELD" }, + { 0xC0000062, "STATUS_INVALID_ACCOUNT_NAME" }, + { 0xC0000063, "STATUS_USER_EXISTS" }, + { 0xC0000064, "STATUS_NO_SUCH_USER" }, + { 0xC0000065, "STATUS_GROUP_EXISTS" }, + { 0xC0000066, "STATUS_NO_SUCH_GROUP" }, + { 0xC0000067, "STATUS_MEMBER_IN_GROUP" }, + { 0xC0000068, "STATUS_MEMBER_NOT_IN_GROUP" }, + { 0xC0000069, "STATUS_LAST_ADMIN" }, + { 0xC000006A, "STATUS_WRONG_PASSWORD" }, + { 0xC000006B, "STATUS_ILL_FORMED_PASSWORD" }, + { 0xC000006C, "STATUS_PASSWORD_RESTRICTION" }, + { 0xC000006D, "STATUS_LOGON_FAILURE" }, + { 0xC000006E, "STATUS_ACCOUNT_RESTRICTION" }, + { 0xC000006F, "STATUS_INVALID_LOGON_HOURS" }, + { 0xC0000070, "STATUS_INVALID_WORKSTATION" }, + { 0xC0000071, "STATUS_PASSWORD_EXPIRED" }, + { 0xC0000072, "STATUS_ACCOUNT_DISABLED" }, + { 0xC0000073, "STATUS_NONE_MAPPED" }, + { 0xC0000074, "STATUS_TOO_MANY_LUIDS_REQUESTED" }, + { 0xC0000075, "STATUS_LUIDS_EXHAUSTED" }, + { 0xC0000076, "STATUS_INVALID_SUB_AUTHORITY" }, + { 0xC0000077, "STATUS_INVALID_ACL" }, + { 0xC0000078, "STATUS_INVALID_SID" }, + { 0xC0000079, "STATUS_INVALID_SECURITY_DESCR" }, + { 0xC000007A, "STATUS_PROCEDURE_NOT_FOUND" }, + { 0xC000007B, "STATUS_INVALID_IMAGE_FORMAT" }, + { 0xC000007C, "STATUS_NO_TOKEN" }, + { 0xC000007D, "STATUS_BAD_INHERITANCE_ACL" }, + { 0xC000007E, "STATUS_RANGE_NOT_LOCKED" }, + { 0xC000007F, "STATUS_DISK_FULL" }, + { 0xC0000080, "STATUS_SERVER_DISABLED" }, + { 0xC0000081, "STATUS_SERVER_NOT_DISABLED" }, + { 0xC0000082, "STATUS_TOO_MANY_GUIDS_REQUESTED" }, + { 0xC0000083, "STATUS_GUIDS_EXHAUSTED" }, + { 0xC0000084, "STATUS_INVALID_ID_AUTHORITY" }, + { 0xC0000085, "STATUS_AGENTS_EXHAUSTED" }, + { 0xC0000086, "STATUS_INVALID_VOLUME_LABEL" }, + { 0xC0000087, "STATUS_SECTION_NOT_EXTENDED" }, + { 0xC0000088, "STATUS_NOT_MAPPED_DATA" }, + { 0xC0000089, "STATUS_RESOURCE_DATA_NOT_FOUND" }, + { 0xC000008A, "STATUS_RESOURCE_TYPE_NOT_FOUND" }, + { 0xC000008B, "STATUS_RESOURCE_NAME_NOT_FOUND" }, + { 0xC000008C, "STATUS_ARRAY_BOUNDS_EXCEEDED" }, + { 0xC000008D, "STATUS_FLOAT_DENORMAL_OPERAND" }, + { 0xC000008E, "STATUS_FLOAT_DIVIDE_BY_ZERO" }, + { 0xC000008F, "STATUS_FLOAT_INEXACT_RESULT" }, + { 0xC0000090, "STATUS_FLOAT_INVALID_OPERATION" }, + { 0xC0000091, "STATUS_FLOAT_OVERFLOW" }, + { 0xC0000092, "STATUS_FLOAT_STACK_CHECK" }, + { 0xC0000093, "STATUS_FLOAT_UNDERFLOW" }, + { 0xC0000094, "STATUS_INTEGER_DIVIDE_BY_ZERO" }, + { 0xC0000095, "STATUS_INTEGER_OVERFLOW" }, + { 0xC0000096, "STATUS_PRIVILEGED_INSTRUCTION" }, + { 0xC0000097, "STATUS_TOO_MANY_PAGING_FILES" }, + { 0xC0000098, "STATUS_FILE_INVALID" }, + { 0xC0000099, "STATUS_ALLOTTED_SPACE_EXCEEDED" }, + { 0xC000009A, "STATUS_INSUFFICIENT_RESOURCES" }, + { 0xC000009B, "STATUS_DFS_EXIT_PATH_FOUND" }, + { 0xC000009C, "STATUS_DEVICE_DATA_ERROR" }, + { 0xC000009D, "STATUS_DEVICE_NOT_CONNECTED" }, + { 0xC000009F, "STATUS_FREE_VM_NOT_AT_BASE" }, + { 0xC00000A0, "STATUS_MEMORY_NOT_ALLOCATED" }, + { 0xC00000A1, "STATUS_WORKING_SET_QUOTA" }, + { 0xC00000A2, "STATUS_MEDIA_WRITE_PROTECTED" }, + { 0xC00000A3, "STATUS_DEVICE_NOT_READY" }, + { 0xC00000A4, "STATUS_INVALID_GROUP_ATTRIBUTES" }, + { 0xC00000A5, "STATUS_BAD_IMPERSONATION_LEVEL" }, + { 0xC00000A6, "STATUS_CANT_OPEN_ANONYMOUS" }, + { 0xC00000A7, "STATUS_BAD_VALIDATION_CLASS" }, + { 0xC00000A8, "STATUS_BAD_TOKEN_TYPE" }, + { 0xC00000A9, "STATUS_BAD_MASTER_BOOT_RECORD" }, + { 0xC00000AA, "STATUS_INSTRUCTION_MISALIGNMENT" }, + { 0xC00000AB, "STATUS_INSTANCE_NOT_AVAILABLE" }, + { 0xC00000AC, "STATUS_PIPE_NOT_AVAILABLE" }, + { 0xC00000AD, "STATUS_INVALID_PIPE_STATE" }, + { 0xC00000AE, "STATUS_PIPE_BUSY" }, + { 0xC00000AF, "STATUS_ILLEGAL_FUNCTION" }, + { 0xC00000B0, "STATUS_PIPE_DISCONNECTED" }, + { 0xC00000B1, "STATUS_PIPE_CLOSING" }, + { 0xC00000B2, "STATUS_PIPE_CONNECTED" }, + { 0xC00000B3, "STATUS_PIPE_LISTENING" }, + { 0xC00000B4, "STATUS_INVALID_READ_MODE" }, + { 0xC00000B5, "STATUS_IO_TIMEOUT" }, + { 0xC00000B6, "STATUS_FILE_FORCED_CLOSED" }, + { 0xC00000B7, "STATUS_PROFILING_NOT_STARTED" }, + { 0xC00000B8, "STATUS_PROFILING_NOT_STOPPED" }, + { 0xC00000B9, "STATUS_COULD_NOT_INTERPRET" }, + { 0xC00000BA, "STATUS_FILE_IS_A_DIRECTORY" }, + { 0xC00000BB, "STATUS_NOT_SUPPORTED" }, + { 0xC00000BC, "STATUS_REMOTE_NOT_LISTENING" }, + { 0xC00000BD, "STATUS_DUPLICATE_NAME" }, + { 0xC00000BE, "STATUS_BAD_NETWORK_PATH" }, + { 0xC00000BF, "STATUS_NETWORK_BUSY" }, + { 0xC00000C0, "STATUS_DEVICE_DOES_NOT_EXIST" }, + { 0xC00000C1, "STATUS_TOO_MANY_COMMANDS" }, + { 0xC00000C2, "STATUS_ADAPTER_HARDWARE_ERROR" }, + { 0xC00000C3, "STATUS_INVALID_NETWORK_RESPONSE" }, + { 0xC00000C4, "STATUS_UNEXPECTED_NETWORK_ERROR" }, + { 0xC00000C5, "STATUS_BAD_REMOTE_ADAPTER" }, + { 0xC00000C6, "STATUS_PRINT_QUEUE_FULL" }, + { 0xC00000C7, "STATUS_NO_SPOOL_SPACE" }, + { 0xC00000C8, "STATUS_PRINT_CANCELLED" }, + { 0xC00000C9, "STATUS_NETWORK_NAME_DELETED" }, + { 0xC00000CA, "STATUS_NETWORK_ACCESS_DENIED" }, + { 0xC00000CB, "STATUS_BAD_DEVICE_TYPE" }, + { 0xC00000CC, "STATUS_BAD_NETWORK_NAME" }, + { 0xC00000CD, "STATUS_TOO_MANY_NAMES" }, + { 0xC00000CE, "STATUS_TOO_MANY_SESSIONS" }, + { 0xC00000CF, "STATUS_SHARING_PAUSED" }, + { 0xC00000D0, "STATUS_REQUEST_NOT_ACCEPTED" }, + { 0xC00000D1, "STATUS_REDIRECTOR_PAUSED" }, + { 0xC00000D2, "STATUS_NET_WRITE_FAULT" }, + { 0xC00000D3, "STATUS_PROFILING_AT_LIMIT" }, + { 0xC00000D4, "STATUS_NOT_SAME_DEVICE" }, + { 0xC00000D5, "STATUS_FILE_RENAMED" }, + { 0xC00000D6, "STATUS_VIRTUAL_CIRCUIT_CLOSED" }, + { 0xC00000D7, "STATUS_NO_SECURITY_ON_OBJECT" }, + { 0xC00000D8, "STATUS_CANT_WAIT" }, + { 0xC00000D9, "STATUS_PIPE_EMPTY" }, + { 0xC00000DA, "STATUS_CANT_ACCESS_DOMAIN_INFO" }, + { 0xC00000DB, "STATUS_CANT_TERMINATE_SELF" }, + { 0xC00000DC, "STATUS_INVALID_SERVER_STATE" }, + { 0xC00000DD, "STATUS_INVALID_DOMAIN_STATE" }, + { 0xC00000DE, "STATUS_INVALID_DOMAIN_ROLE" }, + { 0xC00000DF, "STATUS_NO_SUCH_DOMAIN" }, + { 0xC00000E0, "STATUS_DOMAIN_EXISTS" }, + { 0xC00000E1, "STATUS_DOMAIN_LIMIT_EXCEEDED" }, + { 0xC00000E2, "STATUS_OPLOCK_NOT_GRANTED" }, + { 0xC00000E3, "STATUS_INVALID_OPLOCK_PROTOCOL" }, + { 0xC00000E4, "STATUS_INTERNAL_DB_CORRUPTION" }, + { 0xC00000E5, "STATUS_INTERNAL_ERROR" }, + { 0xC00000E6, "STATUS_GENERIC_NOT_MAPPED" }, + { 0xC00000E7, "STATUS_BAD_DESCRIPTOR_FORMAT" }, + { 0xC00000E8, "STATUS_INVALID_USER_BUFFER" }, + { 0xC00000E9, "STATUS_UNEXPECTED_IO_ERROR" }, + { 0xC00000EA, "STATUS_UNEXPECTED_MM_CREATE_ERR" }, + { 0xC00000EB, "STATUS_UNEXPECTED_MM_MAP_ERROR" }, + { 0xC00000EC, "STATUS_UNEXPECTED_MM_EXTEND_ERR" }, + { 0xC00000ED, "STATUS_NOT_LOGON_PROCESS" }, + { 0xC00000EE, "STATUS_LOGON_SESSION_EXISTS" }, + { 0xC00000EF, "STATUS_INVALID_PARAMETER_1" }, + { 0xC00000F0, "STATUS_INVALID_PARAMETER_2" }, + { 0xC00000F1, "STATUS_INVALID_PARAMETER_3" }, + { 0xC00000F2, "STATUS_INVALID_PARAMETER_4" }, + { 0xC00000F3, "STATUS_INVALID_PARAMETER_5" }, + { 0xC00000F4, "STATUS_INVALID_PARAMETER_6" }, + { 0xC00000F5, "STATUS_INVALID_PARAMETER_7" }, + { 0xC00000F6, "STATUS_INVALID_PARAMETER_8" }, + { 0xC00000F7, "STATUS_INVALID_PARAMETER_9" }, + { 0xC00000F8, "STATUS_INVALID_PARAMETER_10" }, + { 0xC00000F9, "STATUS_INVALID_PARAMETER_11" }, + { 0xC00000FA, "STATUS_INVALID_PARAMETER_12" }, + { 0xC00000FB, "STATUS_REDIRECTOR_NOT_STARTED" }, + { 0xC00000FC, "STATUS_REDIRECTOR_STARTED" }, + { 0xC00000FD, "STATUS_STACK_OVERFLOW" }, + { 0xC00000FE, "STATUS_NO_SUCH_PACKAGE" }, + { 0xC00000FF, "STATUS_BAD_FUNCTION_TABLE" }, + { 0xC0000100, "STATUS_VARIABLE_NOT_FOUND" }, + { 0xC0000101, "STATUS_DIRECTORY_NOT_EMPTY" }, + { 0xC0000102, "STATUS_FILE_CORRUPT_ERROR" }, + { 0xC0000103, "STATUS_NOT_A_DIRECTORY" }, + { 0xC0000104, "STATUS_BAD_LOGON_SESSION_STATE" }, + { 0xC0000105, "STATUS_LOGON_SESSION_COLLISION" }, + { 0xC0000106, "STATUS_NAME_TOO_LONG" }, + { 0xC0000107, "STATUS_FILES_OPEN" }, + { 0xC0000108, "STATUS_CONNECTION_IN_USE" }, + { 0xC0000109, "STATUS_MESSAGE_NOT_FOUND" }, + { 0xC000010A, "STATUS_PROCESS_IS_TERMINATING" }, + { 0xC000010B, "STATUS_INVALID_LOGON_TYPE" }, + { 0xC000010C, "STATUS_NO_GUID_TRANSLATION" }, + { 0xC000010D, "STATUS_CANNOT_IMPERSONATE" }, + { 0xC000010E, "STATUS_IMAGE_ALREADY_LOADED" }, + { 0xC0000117, "STATUS_NO_LDT" }, + { 0xC0000118, "STATUS_INVALID_LDT_SIZE" }, + { 0xC0000119, "STATUS_INVALID_LDT_OFFSET" }, + { 0xC000011A, "STATUS_INVALID_LDT_DESCRIPTOR" }, + { 0xC000011B, "STATUS_INVALID_IMAGE_NE_FORMAT" }, + { 0xC000011C, "STATUS_RXACT_INVALID_STATE" }, + { 0xC000011D, "STATUS_RXACT_COMMIT_FAILURE" }, + { 0xC000011E, "STATUS_MAPPED_FILE_SIZE_ZERO" }, + { 0xC000011F, "STATUS_TOO_MANY_OPENED_FILES" }, + { 0xC0000120, "STATUS_CANCELLED" }, + { 0xC0000121, "STATUS_CANNOT_DELETE" }, + { 0xC0000122, "STATUS_INVALID_COMPUTER_NAME" }, + { 0xC0000123, "STATUS_FILE_DELETED" }, + { 0xC0000124, "STATUS_SPECIAL_ACCOUNT" }, + { 0xC0000125, "STATUS_SPECIAL_GROUP" }, + { 0xC0000126, "STATUS_SPECIAL_USER" }, + { 0xC0000127, "STATUS_MEMBERS_PRIMARY_GROUP" }, + { 0xC0000128, "STATUS_FILE_CLOSED" }, + { 0xC0000129, "STATUS_TOO_MANY_THREADS" }, + { 0xC000012A, "STATUS_THREAD_NOT_IN_PROCESS" }, + { 0xC000012B, "STATUS_TOKEN_ALREADY_IN_USE" }, + { 0xC000012C, "STATUS_PAGEFILE_QUOTA_EXCEEDED" }, + { 0xC000012D, "STATUS_COMMITMENT_LIMIT" }, + { 0xC000012E, "STATUS_INVALID_IMAGE_LE_FORMAT" }, + { 0xC000012F, "STATUS_INVALID_IMAGE_NOT_MZ" }, + { 0xC0000130, "STATUS_INVALID_IMAGE_PROTECT" }, + { 0xC0000131, "STATUS_INVALID_IMAGE_WIN_16" }, + { 0xC0000132, "STATUS_LOGON_SERVER_CONFLICT" }, + { 0xC0000133, "STATUS_TIME_DIFFERENCE_AT_DC" }, + { 0xC0000134, "STATUS_SYNCHRONIZATION_REQUIRED" }, + { 0xC0000135, "STATUS_DLL_NOT_FOUND" }, + { 0xC0000136, "STATUS_OPEN_FAILED" }, + { 0xC0000137, "STATUS_IO_PRIVILEGE_FAILED" }, + { 0xC0000138, "STATUS_ORDINAL_NOT_FOUND" }, + { 0xC0000139, "STATUS_ENTRYPOINT_NOT_FOUND" }, + { 0xC000013A, "STATUS_CONTROL_C_EXIT" }, + { 0xC000013B, "STATUS_LOCAL_DISCONNECT" }, + { 0xC000013C, "STATUS_REMOTE_DISCONNECT" }, + { 0xC000013D, "STATUS_REMOTE_RESOURCES" }, + { 0xC000013E, "STATUS_LINK_FAILED" }, + { 0xC000013F, "STATUS_LINK_TIMEOUT" }, + { 0xC0000140, "STATUS_INVALID_CONNECTION" }, + { 0xC0000141, "STATUS_INVALID_ADDRESS" }, + { 0xC0000142, "STATUS_DLL_INIT_FAILED" }, + { 0xC0000143, "STATUS_MISSING_SYSTEMFILE" }, + { 0xC0000144, "STATUS_UNHANDLED_EXCEPTION" }, + { 0xC0000145, "STATUS_APP_INIT_FAILURE" }, + { 0xC0000146, "STATUS_PAGEFILE_CREATE_FAILED" }, + { 0xC0000147, "STATUS_NO_PAGEFILE" }, + { 0xC0000148, "STATUS_INVALID_LEVEL" }, + { 0xC0000149, "STATUS_WRONG_PASSWORD_CORE" }, + { 0xC000014A, "STATUS_ILLEGAL_FLOAT_CONTEXT" }, + { 0xC000014B, "STATUS_PIPE_BROKEN" }, + { 0xC000014C, "STATUS_REGISTRY_CORRUPT" }, + { 0xC000014D, "STATUS_REGISTRY_IO_FAILED" }, + { 0xC000014E, "STATUS_NO_EVENT_PAIR" }, + { 0xC000014F, "STATUS_UNRECOGNIZED_VOLUME" }, + { 0xC0000150, "STATUS_SERIAL_NO_DEVICE_INITED" }, + { 0xC0000151, "STATUS_NO_SUCH_ALIAS" }, + { 0xC0000152, "STATUS_MEMBER_NOT_IN_ALIAS" }, + { 0xC0000153, "STATUS_MEMBER_IN_ALIAS" }, + { 0xC0000154, "STATUS_ALIAS_EXISTS" }, + { 0xC0000155, "STATUS_LOGON_NOT_GRANTED" }, + { 0xC0000156, "STATUS_TOO_MANY_SECRETS" }, + { 0xC0000157, "STATUS_SECRET_TOO_LONG" }, + { 0xC0000158, "STATUS_INTERNAL_DB_ERROR" }, + { 0xC0000159, "STATUS_FULLSCREEN_MODE" }, + { 0xC000015A, "STATUS_TOO_MANY_CONTEXT_IDS" }, + { 0xC000015B, "STATUS_LOGON_TYPE_NOT_GRANTED" }, + { 0xC000015C, "STATUS_NOT_REGISTRY_FILE" }, + { 0xC000015D, "STATUS_NT_CROSS_ENCRYPTION_REQUIRED" }, + { 0xC000015E, "STATUS_DOMAIN_CTRLR_CONFIG_ERROR" }, + { 0xC000015F, "STATUS_FT_MISSING_MEMBER" }, + { 0xC0000160, "STATUS_ILL_FORMED_SERVICE_ENTRY" }, + { 0xC0000161, "STATUS_ILLEGAL_CHARACTER" }, + { 0xC0000162, "STATUS_UNMAPPABLE_CHARACTER" }, + { 0xC0000163, "STATUS_UNDEFINED_CHARACTER" }, + { 0xC0000164, "STATUS_FLOPPY_VOLUME" }, + { 0xC0000165, "STATUS_FLOPPY_ID_MARK_NOT_FOUND" }, + { 0xC0000166, "STATUS_FLOPPY_WRONG_CYLINDER" }, + { 0xC0000167, "STATUS_FLOPPY_UNKNOWN_ERROR" }, + { 0xC0000168, "STATUS_FLOPPY_BAD_REGISTERS" }, + { 0xC0000169, "STATUS_DISK_RECALIBRATE_FAILED" }, + { 0xC000016A, "STATUS_DISK_OPERATION_FAILED" }, + { 0xC000016B, "STATUS_DISK_RESET_FAILED" }, + { 0xC000016C, "STATUS_SHARED_IRQ_BUSY" }, + { 0xC000016D, "STATUS_FT_ORPHANING" }, + { 0xC000016E, "STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT" }, + { 0xC0000172, "STATUS_PARTITION_FAILURE" }, + { 0xC0000173, "STATUS_INVALID_BLOCK_LENGTH" }, + { 0xC0000174, "STATUS_DEVICE_NOT_PARTITIONED" }, + { 0xC0000175, "STATUS_UNABLE_TO_LOCK_MEDIA" }, + { 0xC0000176, "STATUS_UNABLE_TO_UNLOAD_MEDIA" }, + { 0xC0000177, "STATUS_EOM_OVERFLOW" }, + { 0xC0000178, "STATUS_NO_MEDIA" }, + { 0xC000017A, "STATUS_NO_SUCH_MEMBER" }, + { 0xC000017B, "STATUS_INVALID_MEMBER" }, + { 0xC000017C, "STATUS_KEY_DELETED" }, + { 0xC000017D, "STATUS_NO_LOG_SPACE" }, + { 0xC000017E, "STATUS_TOO_MANY_SIDS" }, + { 0xC000017F, "STATUS_LM_CROSS_ENCRYPTION_REQUIRED" }, + { 0xC0000180, "STATUS_KEY_HAS_CHILDREN" }, + { 0xC0000181, "STATUS_CHILD_MUST_BE_VOLATILE" }, + { 0xC0000182, "STATUS_DEVICE_CONFIGURATION_ERROR" }, + { 0xC0000183, "STATUS_DRIVER_INTERNAL_ERROR" }, + { 0xC0000184, "STATUS_INVALID_DEVICE_STATE" }, + { 0xC0000185, "STATUS_IO_DEVICE_ERROR" }, + { 0xC0000186, "STATUS_DEVICE_PROTOCOL_ERROR" }, + { 0xC0000187, "STATUS_BACKUP_CONTROLLER" }, + { 0xC0000188, "STATUS_LOG_FILE_FULL" }, + { 0xC0000189, "STATUS_TOO_LATE" }, + { 0xC000018A, "STATUS_NO_TRUST_LSA_SECRET" }, + { 0xC000018B, "STATUS_NO_TRUST_SAM_ACCOUNT" }, + { 0xC000018C, "STATUS_TRUSTED_DOMAIN_FAILURE" }, + { 0xC000018D, "STATUS_TRUSTED_RELATIONSHIP_FAILURE" }, + { 0xC000018E, "STATUS_EVENTLOG_FILE_CORRUPT" }, + { 0xC000018F, "STATUS_EVENTLOG_CANT_START" }, + { 0xC0000190, "STATUS_TRUST_FAILURE" }, + { 0xC0000191, "STATUS_MUTANT_LIMIT_EXCEEDED" }, + { 0xC0000192, "STATUS_NETLOGON_NOT_STARTED" }, + { 0xC0000193, "STATUS_ACCOUNT_EXPIRED" }, + { 0xC0000194, "STATUS_POSSIBLE_DEADLOCK" }, + { 0xC0000195, "STATUS_NETWORK_CREDENTIAL_CONFLICT" }, + { 0xC0000196, "STATUS_REMOTE_SESSION_LIMIT" }, + { 0xC0000197, "STATUS_EVENTLOG_FILE_CHANGED" }, + { 0xC0000198, "STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT" }, + { 0xC0000199, "STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT" }, + { 0xC000019A, "STATUS_NOLOGON_SERVER_TRUST_ACCOUNT" }, + { 0xC000019B, "STATUS_DOMAIN_TRUST_INCONSISTENT" }, + { 0xC000019C, "STATUS_FS_DRIVER_REQUIRED" }, + { 0xC000019D, "STATUS_IMAGE_ALREADY_LOADED_AS_DLL" }, + { 0xC000019E, "STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING" }, + { 0xC000019F, "STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME" }, + { 0xC00001A0, "STATUS_SECURITY_STREAM_IS_INCONSISTENT" }, + { 0xC00001A1, "STATUS_INVALID_LOCK_RANGE" }, + { 0xC00001A2, "STATUS_INVALID_ACE_CONDITION" }, + { 0xC00001A3, "STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT" }, + { 0xC00001A4, "STATUS_NOTIFICATION_GUID_ALREADY_DEFINED" }, + { 0xC0000201, "STATUS_NETWORK_OPEN_RESTRICTION" }, + { 0xC0000202, "STATUS_NO_USER_SESSION_KEY" }, + { 0xC0000203, "STATUS_USER_SESSION_DELETED" }, + { 0xC0000204, "STATUS_RESOURCE_LANG_NOT_FOUND" }, + { 0xC0000205, "STATUS_INSUFF_SERVER_RESOURCES" }, + { 0xC0000206, "STATUS_INVALID_BUFFER_SIZE" }, + { 0xC0000207, "STATUS_INVALID_ADDRESS_COMPONENT" }, + { 0xC0000208, "STATUS_INVALID_ADDRESS_WILDCARD" }, + { 0xC0000209, "STATUS_TOO_MANY_ADDRESSES" }, + { 0xC000020A, "STATUS_ADDRESS_ALREADY_EXISTS" }, + { 0xC000020B, "STATUS_ADDRESS_CLOSED" }, + { 0xC000020C, "STATUS_CONNECTION_DISCONNECTED" }, + { 0xC000020D, "STATUS_CONNECTION_RESET" }, + { 0xC000020E, "STATUS_TOO_MANY_NODES" }, + { 0xC000020F, "STATUS_TRANSACTION_ABORTED" }, + { 0xC0000210, "STATUS_TRANSACTION_TIMED_OUT" }, + { 0xC0000211, "STATUS_TRANSACTION_NO_RELEASE" }, + { 0xC0000212, "STATUS_TRANSACTION_NO_MATCH" }, + { 0xC0000213, "STATUS_TRANSACTION_RESPONDED" }, + { 0xC0000214, "STATUS_TRANSACTION_INVALID_ID" }, + { 0xC0000215, "STATUS_TRANSACTION_INVALID_TYPE" }, + { 0xC0000216, "STATUS_NOT_SERVER_SESSION" }, + { 0xC0000217, "STATUS_NOT_CLIENT_SESSION" }, + { 0xC0000218, "STATUS_CANNOT_LOAD_REGISTRY_FILE" }, + { 0xC0000219, "STATUS_DEBUG_ATTACH_FAILED" }, + { 0xC000021A, "STATUS_SYSTEM_PROCESS_TERMINATED" }, + { 0xC000021B, "STATUS_DATA_NOT_ACCEPTED" }, + { 0xC000021C, "STATUS_NO_BROWSER_SERVERS_FOUND" }, + { 0xC000021D, "STATUS_VDM_HARD_ERROR" }, + { 0xC000021E, "STATUS_DRIVER_CANCEL_TIMEOUT" }, + { 0xC000021F, "STATUS_REPLY_MESSAGE_MISMATCH" }, + { 0xC0000220, "STATUS_MAPPED_ALIGNMENT" }, + { 0xC0000221, "STATUS_IMAGE_CHECKSUM_MISMATCH" }, + { 0xC0000222, "STATUS_LOST_WRITEBEHIND_DATA" }, + { 0xC0000223, "STATUS_CLIENT_SERVER_PARAMETERS_INVALID" }, + { 0xC0000224, "STATUS_PASSWORD_MUST_CHANGE" }, + { 0xC0000225, "STATUS_NOT_FOUND" }, + { 0xC0000226, "STATUS_NOT_TINY_STREAM" }, + { 0xC0000227, "STATUS_RECOVERY_FAILURE" }, + { 0xC0000228, "STATUS_STACK_OVERFLOW_READ" }, + { 0xC0000229, "STATUS_FAIL_CHECK" }, + { 0xC000022A, "STATUS_DUPLICATE_OBJECTID" }, + { 0xC000022B, "STATUS_OBJECTID_EXISTS" }, + { 0xC000022C, "STATUS_CONVERT_TO_LARGE" }, + { 0xC000022D, "STATUS_RETRY" }, + { 0xC000022E, "STATUS_FOUND_OUT_OF_SCOPE" }, + { 0xC000022F, "STATUS_ALLOCATE_BUCKET" }, + { 0xC0000230, "STATUS_PROPSET_NOT_FOUND" }, + { 0xC0000231, "STATUS_MARSHALL_OVERFLOW" }, + { 0xC0000232, "STATUS_INVALID_VARIANT" }, + { 0xC0000233, "STATUS_DOMAIN_CONTROLLER_NOT_FOUND" }, + { 0xC0000234, "STATUS_ACCOUNT_LOCKED_OUT" }, + { 0xC0000235, "STATUS_HANDLE_NOT_CLOSABLE" }, + { 0xC0000236, "STATUS_CONNECTION_REFUSED" }, + { 0xC0000237, "STATUS_GRACEFUL_DISCONNECT" }, + { 0xC0000238, "STATUS_ADDRESS_ALREADY_ASSOCIATED" }, + { 0xC0000239, "STATUS_ADDRESS_NOT_ASSOCIATED" }, + { 0xC000023A, "STATUS_CONNECTION_INVALID" }, + { 0xC000023B, "STATUS_CONNECTION_ACTIVE" }, + { 0xC000023C, "STATUS_NETWORK_UNREACHABLE" }, + { 0xC000023D, "STATUS_HOST_UNREACHABLE" }, + { 0xC000023E, "STATUS_PROTOCOL_UNREACHABLE" }, + { 0xC000023F, "STATUS_PORT_UNREACHABLE" }, + { 0xC0000240, "STATUS_REQUEST_ABORTED" }, + { 0xC0000241, "STATUS_CONNECTION_ABORTED" }, + { 0xC0000242, "STATUS_BAD_COMPRESSION_BUFFER" }, + { 0xC0000243, "STATUS_USER_MAPPED_FILE" }, + { 0xC0000244, "STATUS_AUDIT_FAILED" }, + { 0xC0000245, "STATUS_TIMER_RESOLUTION_NOT_SET" }, + { 0xC0000246, "STATUS_CONNECTION_COUNT_LIMIT" }, + { 0xC0000247, "STATUS_LOGIN_TIME_RESTRICTION" }, + { 0xC0000248, "STATUS_LOGIN_WKSTA_RESTRICTION" }, + { 0xC0000249, "STATUS_IMAGE_MP_UP_MISMATCH" }, + { 0xC0000250, "STATUS_INSUFFICIENT_LOGON_INFO" }, + { 0xC0000251, "STATUS_BAD_DLL_ENTRYPOINT" }, + { 0xC0000252, "STATUS_BAD_SERVICE_ENTRYPOINT" }, + { 0xC0000253, "STATUS_LPC_REPLY_LOST" }, + { 0xC0000254, "STATUS_IP_ADDRESS_CONFLICT1" }, + { 0xC0000255, "STATUS_IP_ADDRESS_CONFLICT2" }, + { 0xC0000256, "STATUS_REGISTRY_QUOTA_LIMIT" }, + { 0xC0000257, "STATUS_PATH_NOT_COVERED" }, + { 0xC0000258, "STATUS_NO_CALLBACK_ACTIVE" }, + { 0xC0000259, "STATUS_LICENSE_QUOTA_EXCEEDED" }, + { 0xC000025A, "STATUS_PWD_TOO_SHORT" }, + { 0xC000025B, "STATUS_PWD_TOO_RECENT" }, + { 0xC000025C, "STATUS_PWD_HISTORY_CONFLICT" }, + { 0xC000025E, "STATUS_PLUGPLAY_NO_DEVICE" }, + { 0xC000025F, "STATUS_UNSUPPORTED_COMPRESSION" }, + { 0xC0000260, "STATUS_INVALID_HW_PROFILE" }, + { 0xC0000261, "STATUS_INVALID_PLUGPLAY_DEVICE_PATH" }, + { 0xC0000262, "STATUS_DRIVER_ORDINAL_NOT_FOUND" }, + { 0xC0000263, "STATUS_DRIVER_ENTRYPOINT_NOT_FOUND" }, + { 0xC0000264, "STATUS_RESOURCE_NOT_OWNED" }, + { 0xC0000265, "STATUS_TOO_MANY_LINKS" }, + { 0xC0000266, "STATUS_QUOTA_LIST_INCONSISTENT" }, + { 0xC0000267, "STATUS_FILE_IS_OFFLINE" }, + { 0xC0000268, "STATUS_EVALUATION_EXPIRATION" }, + { 0xC0000269, "STATUS_ILLEGAL_DLL_RELOCATION" }, + { 0xC000026A, "STATUS_LICENSE_VIOLATION" }, + { 0xC000026B, "STATUS_DLL_INIT_FAILED_LOGOFF" }, + { 0xC000026C, "STATUS_DRIVER_UNABLE_TO_LOAD" }, + { 0xC000026D, "STATUS_DFS_UNAVAILABLE" }, + { 0xC000026E, "STATUS_VOLUME_DISMOUNTED" }, + { 0xC000026F, "STATUS_WX86_INTERNAL_ERROR" }, + { 0xC0000270, "STATUS_WX86_FLOAT_STACK_CHECK" }, + { 0xC0000271, "STATUS_VALIDATE_CONTINUE" }, + { 0xC0000272, "STATUS_NO_MATCH" }, + { 0xC0000273, "STATUS_NO_MORE_MATCHES" }, + { 0xC0000275, "STATUS_NOT_A_REPARSE_POINT" }, + { 0xC0000276, "STATUS_IO_REPARSE_TAG_INVALID" }, + { 0xC0000277, "STATUS_IO_REPARSE_TAG_MISMATCH" }, + { 0xC0000278, "STATUS_IO_REPARSE_DATA_INVALID" }, + { 0xC0000279, "STATUS_IO_REPARSE_TAG_NOT_HANDLED" }, + { 0xC0000280, "STATUS_REPARSE_POINT_NOT_RESOLVED" }, + { 0xC0000281, "STATUS_DIRECTORY_IS_A_REPARSE_POINT" }, + { 0xC0000282, "STATUS_RANGE_LIST_CONFLICT" }, + { 0xC0000283, "STATUS_SOURCE_ELEMENT_EMPTY" }, + { 0xC0000284, "STATUS_DESTINATION_ELEMENT_FULL" }, + { 0xC0000285, "STATUS_ILLEGAL_ELEMENT_ADDRESS" }, + { 0xC0000286, "STATUS_MAGAZINE_NOT_PRESENT" }, + { 0xC0000287, "STATUS_REINITIALIZATION_NEEDED" }, + { 0xC000028A, "STATUS_ENCRYPTION_FAILED" }, + { 0xC000028B, "STATUS_DECRYPTION_FAILED" }, + { 0xC000028C, "STATUS_RANGE_NOT_FOUND" }, + { 0xC000028D, "STATUS_NO_RECOVERY_POLICY" }, + { 0xC000028E, "STATUS_NO_EFS" }, + { 0xC000028F, "STATUS_WRONG_EFS" }, + { 0xC0000290, "STATUS_NO_USER_KEYS" }, + { 0xC0000291, "STATUS_FILE_NOT_ENCRYPTED" }, + { 0xC0000292, "STATUS_NOT_EXPORT_FORMAT" }, + { 0xC0000293, "STATUS_FILE_ENCRYPTED" }, + { 0xC0000295, "STATUS_WMI_GUID_NOT_FOUND" }, + { 0xC0000296, "STATUS_WMI_INSTANCE_NOT_FOUND" }, + { 0xC0000297, "STATUS_WMI_ITEMID_NOT_FOUND" }, + { 0xC0000298, "STATUS_WMI_TRY_AGAIN" }, + { 0xC0000299, "STATUS_SHARED_POLICY" }, + { 0xC000029A, "STATUS_POLICY_OBJECT_NOT_FOUND" }, + { 0xC000029B, "STATUS_POLICY_ONLY_IN_DS" }, + { 0xC000029C, "STATUS_VOLUME_NOT_UPGRADED" }, + { 0xC000029D, "STATUS_REMOTE_STORAGE_NOT_ACTIVE" }, + { 0xC000029E, "STATUS_REMOTE_STORAGE_MEDIA_ERROR" }, + { 0xC000029F, "STATUS_NO_TRACKING_SERVICE" }, + { 0xC00002A0, "STATUS_SERVER_SID_MISMATCH" }, + { 0xC00002A1, "STATUS_DS_NO_ATTRIBUTE_OR_VALUE" }, + { 0xC00002A2, "STATUS_DS_INVALID_ATTRIBUTE_SYNTAX" }, + { 0xC00002A3, "STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED" }, + { 0xC00002A4, "STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS" }, + { 0xC00002A5, "STATUS_DS_BUSY" }, + { 0xC00002A6, "STATUS_DS_UNAVAILABLE" }, + { 0xC00002A7, "STATUS_DS_NO_RIDS_ALLOCATED" }, + { 0xC00002A8, "STATUS_DS_NO_MORE_RIDS" }, + { 0xC00002A9, "STATUS_DS_INCORRECT_ROLE_OWNER" }, + { 0xC00002AA, "STATUS_DS_RIDMGR_INIT_ERROR" }, + { 0xC00002AB, "STATUS_DS_OBJ_CLASS_VIOLATION" }, + { 0xC00002AC, "STATUS_DS_CANT_ON_NON_LEAF" }, + { 0xC00002AD, "STATUS_DS_CANT_ON_RDN" }, + { 0xC00002AE, "STATUS_DS_CANT_MOD_OBJ_CLASS" }, + { 0xC00002AF, "STATUS_DS_CROSS_DOM_MOVE_FAILED" }, + { 0xC00002B0, "STATUS_DS_GC_NOT_AVAILABLE" }, + { 0xC00002B1, "STATUS_DIRECTORY_SERVICE_REQUIRED" }, + { 0xC00002B2, "STATUS_REPARSE_ATTRIBUTE_CONFLICT" }, + { 0xC00002B3, "STATUS_CANT_ENABLE_DENY_ONLY" }, + { 0xC00002B4, "STATUS_FLOAT_MULTIPLE_FAULTS" }, + { 0xC00002B5, "STATUS_FLOAT_MULTIPLE_TRAPS" }, + { 0xC00002B6, "STATUS_DEVICE_REMOVED" }, + { 0xC00002B7, "STATUS_JOURNAL_DELETE_IN_PROGRESS" }, + { 0xC00002B8, "STATUS_JOURNAL_NOT_ACTIVE" }, + { 0xC00002B9, "STATUS_NOINTERFACE" }, + { 0xC00002C1, "STATUS_DS_ADMIN_LIMIT_EXCEEDED" }, + { 0xC00002C2, "STATUS_DRIVER_FAILED_SLEEP" }, + { 0xC00002C3, "STATUS_MUTUAL_AUTHENTICATION_FAILED" }, + { 0xC00002C4, "STATUS_CORRUPT_SYSTEM_FILE" }, + { 0xC00002C5, "STATUS_DATATYPE_MISALIGNMENT_ERROR" }, + { 0xC00002C6, "STATUS_WMI_READ_ONLY" }, + { 0xC00002C7, "STATUS_WMI_SET_FAILURE" }, + { 0xC00002C8, "STATUS_COMMITMENT_MINIMUM" }, + { 0xC00002C9, "STATUS_REG_NAT_CONSUMPTION" }, + { 0xC00002CA, "STATUS_TRANSPORT_FULL" }, + { 0xC00002CB, "STATUS_DS_SAM_INIT_FAILURE" }, + { 0xC00002CC, "STATUS_ONLY_IF_CONNECTED" }, + { 0xC00002CD, "STATUS_DS_SENSITIVE_GROUP_VIOLATION" }, + { 0xC00002CE, "STATUS_PNP_RESTART_ENUMERATION" }, + { 0xC00002CF, "STATUS_JOURNAL_ENTRY_DELETED" }, + { 0xC00002D0, "STATUS_DS_CANT_MOD_PRIMARYGROUPID" }, + { 0xC00002D1, "STATUS_SYSTEM_IMAGE_BAD_SIGNATURE" }, + { 0xC00002D2, "STATUS_PNP_REBOOT_REQUIRED" }, + { 0xC00002D3, "STATUS_POWER_STATE_INVALID" }, + { 0xC00002D4, "STATUS_DS_INVALID_GROUP_TYPE" }, + { 0xC00002D5, "STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN" }, + { 0xC00002D6, "STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN" }, + { 0xC00002D7, "STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER" }, + { 0xC00002D8, "STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER" }, + { 0xC00002D9, "STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER" }, + { 0xC00002DA, "STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER" }, + { 0xC00002DB, "STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER" }, + { 0xC00002DC, "STATUS_DS_HAVE_PRIMARY_MEMBERS" }, + { 0xC00002DD, "STATUS_WMI_NOT_SUPPORTED" }, + { 0xC00002DE, "STATUS_INSUFFICIENT_POWER" }, + { 0xC00002DF, "STATUS_SAM_NEED_BOOTKEY_PASSWORD" }, + { 0xC00002E0, "STATUS_SAM_NEED_BOOTKEY_FLOPPY" }, + { 0xC00002E1, "STATUS_DS_CANT_START" }, + { 0xC00002E2, "STATUS_DS_INIT_FAILURE" }, + { 0xC00002E3, "STATUS_SAM_INIT_FAILURE" }, + { 0xC00002E4, "STATUS_DS_GC_REQUIRED" }, + { 0xC00002E5, "STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY" }, + { 0xC00002E6, "STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS" }, + { 0xC00002E7, "STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED" }, + { 0xC00002E9, "STATUS_CURRENT_DOMAIN_NOT_ALLOWED" }, + { 0xC00002EA, "STATUS_CANNOT_MAKE" }, + { 0xC00002EB, "STATUS_SYSTEM_SHUTDOWN" }, + { 0xC00002EC, "STATUS_DS_INIT_FAILURE_CONSOLE" }, + { 0xC00002ED, "STATUS_DS_SAM_INIT_FAILURE_CONSOLE" }, + { 0xC00002EE, "STATUS_UNFINISHED_CONTEXT_DELETED" }, + { 0xC00002EF, "STATUS_NO_TGT_REPLY" }, + { 0xC00002F0, "STATUS_OBJECTID_NOT_FOUND" }, + { 0xC00002F1, "STATUS_NO_IP_ADDRESSES" }, + { 0xC00002F2, "STATUS_WRONG_CREDENTIAL_HANDLE" }, + { 0xC00002F3, "STATUS_CRYPTO_SYSTEM_INVALID" }, + { 0xC00002F4, "STATUS_MAX_REFERRALS_EXCEEDED" }, + { 0xC00002F5, "STATUS_MUST_BE_KDC" }, + { 0xC00002F6, "STATUS_STRONG_CRYPTO_NOT_SUPPORTED" }, + { 0xC00002F7, "STATUS_TOO_MANY_PRINCIPALS" }, + { 0xC00002F8, "STATUS_NO_PA_DATA" }, + { 0xC00002F9, "STATUS_PKINIT_NAME_MISMATCH" }, + { 0xC00002FA, "STATUS_SMARTCARD_LOGON_REQUIRED" }, + { 0xC00002FB, "STATUS_KDC_INVALID_REQUEST" }, + { 0xC00002FC, "STATUS_KDC_UNABLE_TO_REFER" }, + { 0xC00002FD, "STATUS_KDC_UNKNOWN_ETYPE" }, + { 0xC00002FE, "STATUS_SHUTDOWN_IN_PROGRESS" }, + { 0xC00002FF, "STATUS_SERVER_SHUTDOWN_IN_PROGRESS" }, + { 0xC0000300, "STATUS_NOT_SUPPORTED_ON_SBS" }, + { 0xC0000301, "STATUS_WMI_GUID_DISCONNECTED" }, + { 0xC0000302, "STATUS_WMI_ALREADY_DISABLED" }, + { 0xC0000303, "STATUS_WMI_ALREADY_ENABLED" }, + { 0xC0000304, "STATUS_MFT_TOO_FRAGMENTED" }, + { 0xC0000305, "STATUS_COPY_PROTECTION_FAILURE" }, + { 0xC0000306, "STATUS_CSS_AUTHENTICATION_FAILURE" }, + { 0xC0000307, "STATUS_CSS_KEY_NOT_PRESENT" }, + { 0xC0000308, "STATUS_CSS_KEY_NOT_ESTABLISHED" }, + { 0xC0000309, "STATUS_CSS_SCRAMBLED_SECTOR" }, + { 0xC000030A, "STATUS_CSS_REGION_MISMATCH" }, + { 0xC000030B, "STATUS_CSS_RESETS_EXHAUSTED" }, + { 0xC0000320, "STATUS_PKINIT_FAILURE" }, + { 0xC0000321, "STATUS_SMARTCARD_SUBSYSTEM_FAILURE" }, + { 0xC0000322, "STATUS_NO_KERB_KEY" }, + { 0xC0000350, "STATUS_HOST_DOWN" }, + { 0xC0000351, "STATUS_UNSUPPORTED_PREAUTH" }, + { 0xC0000352, "STATUS_EFS_ALG_BLOB_TOO_BIG" }, + { 0xC0000353, "STATUS_PORT_NOT_SET" }, + { 0xC0000354, "STATUS_DEBUGGER_INACTIVE" }, + { 0xC0000355, "STATUS_DS_VERSION_CHECK_FAILURE" }, + { 0xC0000356, "STATUS_AUDITING_DISABLED" }, + { 0xC0000357, "STATUS_PRENT4_MACHINE_ACCOUNT" }, + { 0xC0000358, "STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER" }, + { 0xC0000359, "STATUS_INVALID_IMAGE_WIN_32" }, + { 0xC000035A, "STATUS_INVALID_IMAGE_WIN_64" }, + { 0xC000035B, "STATUS_BAD_BINDINGS" }, + { 0xC000035C, "STATUS_NETWORK_SESSION_EXPIRED" }, + { 0xC000035D, "STATUS_APPHELP_BLOCK" }, + { 0xC000035E, "STATUS_ALL_SIDS_FILTERED" }, + { 0xC000035F, "STATUS_NOT_SAFE_MODE_DRIVER" }, + { 0xC0000361, "STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT" }, + { 0xC0000362, "STATUS_ACCESS_DISABLED_BY_POLICY_PATH" }, + { 0xC0000363, "STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER" }, + { 0xC0000364, "STATUS_ACCESS_DISABLED_BY_POLICY_OTHER" }, + { 0xC0000365, "STATUS_FAILED_DRIVER_ENTRY" }, + { 0xC0000366, "STATUS_DEVICE_ENUMERATION_ERROR" }, + { 0xC0000368, "STATUS_MOUNT_POINT_NOT_RESOLVED" }, + { 0xC0000369, "STATUS_INVALID_DEVICE_OBJECT_PARAMETER" }, + { 0xC000036A, "STATUS_MCA_OCCURED" }, + { 0xC000036B, "STATUS_DRIVER_BLOCKED_CRITICAL" }, + { 0xC000036C, "STATUS_DRIVER_BLOCKED" }, + { 0xC000036D, "STATUS_DRIVER_DATABASE_ERROR" }, + { 0xC000036E, "STATUS_SYSTEM_HIVE_TOO_LARGE" }, + { 0xC000036F, "STATUS_INVALID_IMPORT_OF_NON_DLL" }, + { 0xC0000371, "STATUS_NO_SECRETS" }, + { 0xC0000372, "STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY" }, + { 0xC0000373, "STATUS_FAILED_STACK_SWITCH" }, + { 0xC0000374, "STATUS_HEAP_CORRUPTION" }, + { 0xC0000380, "STATUS_SMARTCARD_WRONG_PIN" }, + { 0xC0000381, "STATUS_SMARTCARD_CARD_BLOCKED" }, + { 0xC0000382, "STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED" }, + { 0xC0000383, "STATUS_SMARTCARD_NO_CARD" }, + { 0xC0000384, "STATUS_SMARTCARD_NO_KEY_CONTAINER" }, + { 0xC0000385, "STATUS_SMARTCARD_NO_CERTIFICATE" }, + { 0xC0000386, "STATUS_SMARTCARD_NO_KEYSET" }, + { 0xC0000387, "STATUS_SMARTCARD_IO_ERROR" }, + { 0xC0000388, "STATUS_DOWNGRADE_DETECTED" }, + { 0xC0000389, "STATUS_SMARTCARD_CERT_REVOKED" }, + { 0xC000038A, "STATUS_ISSUING_CA_UNTRUSTED" }, + { 0xC000038B, "STATUS_REVOCATION_OFFLINE_C" }, + { 0xC000038C, "STATUS_PKINIT_CLIENT_FAILURE" }, + { 0xC000038D, "STATUS_SMARTCARD_CERT_EXPIRED" }, + { 0xC000038E, "STATUS_DRIVER_FAILED_PRIOR_UNLOAD" }, + { 0xC000038F, "STATUS_SMARTCARD_SILENT_CONTEXT" }, + { 0xC0000401, "STATUS_PER_USER_TRUST_QUOTA_EXCEEDED" }, + { 0xC0000402, "STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED" }, + { 0xC0000403, "STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED" }, + { 0xC0000404, "STATUS_DS_NAME_NOT_UNIQUE" }, + { 0xC0000405, "STATUS_DS_DUPLICATE_ID_FOUND" }, + { 0xC0000406, "STATUS_DS_GROUP_CONVERSION_ERROR" }, + { 0xC0000407, "STATUS_VOLSNAP_PREPARE_HIBERNATE" }, + { 0xC0000408, "STATUS_USER2USER_REQUIRED" }, + { 0xC0000409, "STATUS_STACK_BUFFER_OVERRUN" }, + { 0xC000040A, "STATUS_NO_S4U_PROT_SUPPORT" }, + { 0xC000040B, "STATUS_CROSSREALM_DELEGATION_FAILURE" }, + { 0xC000040C, "STATUS_REVOCATION_OFFLINE_KDC" }, + { 0xC000040D, "STATUS_ISSUING_CA_UNTRUSTED_KDC" }, + { 0xC000040E, "STATUS_KDC_CERT_EXPIRED" }, + { 0xC000040F, "STATUS_KDC_CERT_REVOKED" }, + { 0xC0000410, "STATUS_PARAMETER_QUOTA_EXCEEDED" }, + { 0xC0000411, "STATUS_HIBERNATION_FAILURE" }, + { 0xC0000412, "STATUS_DELAY_LOAD_FAILED" }, + { 0xC0000413, "STATUS_AUTHENTICATION_FIREWALL_FAILED" }, + { 0xC0000414, "STATUS_VDM_DISALLOWED" }, + { 0xC0000415, "STATUS_HUNG_DISPLAY_DRIVER_THREAD" }, + { 0xC0000416, "STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE" }, + { 0xC0000417, "STATUS_INVALID_CRUNTIME_PARAMETER" }, + { 0xC0000418, "STATUS_NTLM_BLOCKED" }, + { 0xC0000419, "STATUS_DS_SRC_SID_EXISTS_IN_FOREST" }, + { 0xC000041A, "STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST" }, + { 0xC000041B, "STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST" }, + { 0xC000041C, "STATUS_INVALID_USER_PRINCIPAL_NAME" }, + { 0xC0000420, "STATUS_ASSERTION_FAILURE" }, + { 0xC0000421, "STATUS_VERIFIER_STOP" }, + { 0xC0000423, "STATUS_CALLBACK_POP_STACK" }, + { 0xC0000424, "STATUS_INCOMPATIBLE_DRIVER_BLOCKED" }, + { 0xC0000425, "STATUS_HIVE_UNLOADED" }, + { 0xC0000426, "STATUS_COMPRESSION_DISABLED" }, + { 0xC0000427, "STATUS_FILE_SYSTEM_LIMITATION" }, + { 0xC0000428, "STATUS_INVALID_IMAGE_HASH" }, + { 0xC0000429, "STATUS_NOT_CAPABLE" }, + { 0xC000042A, "STATUS_REQUEST_OUT_OF_SEQUENCE" }, + { 0xC000042B, "STATUS_IMPLEMENTATION_LIMIT" }, + { 0xC000042C, "STATUS_ELEVATION_REQUIRED" }, + { 0xC000042D, "STATUS_NO_SECURITY_CONTEXT" }, + { 0xC000042E, "STATUS_PKU2U_CERT_FAILURE" }, + { 0xC0000432, "STATUS_BEYOND_VDL" }, + { 0xC0000433, "STATUS_ENCOUNTERED_WRITE_IN_PROGRESS" }, + { 0xC0000434, "STATUS_PTE_CHANGED" }, + { 0xC0000435, "STATUS_PURGE_FAILED" }, + { 0xC0000440, "STATUS_CRED_REQUIRES_CONFIRMATION" }, + { 0xC0000441, "STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE" }, + { 0xC0000442, "STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER" }, + { 0xC0000443, "STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE" }, + { 0xC0000444, "STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE" }, + { 0xC0000445, "STATUS_CS_ENCRYPTION_FILE_NOT_CSE" }, + { 0xC0000446, "STATUS_INVALID_LABEL" }, + { 0xC0000450, "STATUS_DRIVER_PROCESS_TERMINATED" }, + { 0xC0000451, "STATUS_AMBIGUOUS_SYSTEM_DEVICE" }, + { 0xC0000452, "STATUS_SYSTEM_DEVICE_NOT_FOUND" }, + { 0xC0000453, "STATUS_RESTART_BOOT_APPLICATION" }, + { 0xC0000454, "STATUS_INSUFFICIENT_NVRAM_RESOURCES" }, + { 0xC0000460, "STATUS_NO_RANGES_PROCESSED" }, + { 0xC0000463, "STATUS_DEVICE_FEATURE_NOT_SUPPORTED" }, + { 0xC0000464, "STATUS_DEVICE_UNREACHABLE" }, + { 0xC0000465, "STATUS_INVALID_TOKEN" }, + { 0xC0000466, "STATUS_SERVER_UNAVAILABLE" }, + { 0xC0000467, "STATUS_FILE_NOT_AVAILABLE" }, + { 0xC0000480, "STATUS_SHARE_UNAVAILABLE" }, + { 0xC0000500, "STATUS_INVALID_TASK_NAME" }, + { 0xC0000501, "STATUS_INVALID_TASK_INDEX" }, + { 0xC0000502, "STATUS_THREAD_ALREADY_IN_TASK" }, + { 0xC0000503, "STATUS_CALLBACK_BYPASS" }, + { 0xC0000602, "STATUS_FAIL_FAST_EXCEPTION" }, + { 0xC0000603, "STATUS_IMAGE_CERT_REVOKED" }, + { 0xC0000700, "STATUS_PORT_CLOSED" }, + { 0xC0000701, "STATUS_MESSAGE_LOST" }, + { 0xC0000702, "STATUS_INVALID_MESSAGE" }, + { 0xC0000703, "STATUS_REQUEST_CANCELED" }, + { 0xC0000704, "STATUS_RECURSIVE_DISPATCH" }, + { 0xC0000705, "STATUS_LPC_RECEIVE_BUFFER_EXPECTED" }, + { 0xC0000706, "STATUS_LPC_INVALID_CONNECTION_USAGE" }, + { 0xC0000707, "STATUS_LPC_REQUESTS_NOT_ALLOWED" }, + { 0xC0000708, "STATUS_RESOURCE_IN_USE" }, + { 0xC0000709, "STATUS_HARDWARE_MEMORY_ERROR" }, + { 0xC000070A, "STATUS_THREADPOOL_HANDLE_EXCEPTION" }, + { 0xC000070B, "STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED" }, + { 0xC000070C, "STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED" }, + { 0xC000070D, "STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED" }, + { 0xC000070E, "STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED" }, + { 0xC000070F, "STATUS_THREADPOOL_RELEASED_DURING_OPERATION" }, + { 0xC0000710, "STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING" }, + { 0xC0000711, "STATUS_APC_RETURNED_WHILE_IMPERSONATING" }, + { 0xC0000712, "STATUS_PROCESS_IS_PROTECTED" }, + { 0xC0000713, "STATUS_MCA_EXCEPTION" }, + { 0xC0000714, "STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE" }, + { 0xC0000715, "STATUS_SYMLINK_CLASS_DISABLED" }, + { 0xC0000716, "STATUS_INVALID_IDN_NORMALIZATION" }, + { 0xC0000717, "STATUS_NO_UNICODE_TRANSLATION" }, + { 0xC0000718, "STATUS_ALREADY_REGISTERED" }, + { 0xC0000719, "STATUS_CONTEXT_MISMATCH" }, + { 0xC000071A, "STATUS_PORT_ALREADY_HAS_COMPLETION_LIST" }, + { 0xC000071B, "STATUS_CALLBACK_RETURNED_THREAD_PRIORITY" }, + { 0xC000071C, "STATUS_INVALID_THREAD" }, + { 0xC000071D, "STATUS_CALLBACK_RETURNED_TRANSACTION" }, + { 0xC000071E, "STATUS_CALLBACK_RETURNED_LDR_LOCK" }, + { 0xC000071F, "STATUS_CALLBACK_RETURNED_LANG" }, + { 0xC0000720, "STATUS_CALLBACK_RETURNED_PRI_BACK" }, + { 0xC0000721, "STATUS_CALLBACK_RETURNED_THREAD_AFFINITY" }, + { 0xC0000800, "STATUS_DISK_REPAIR_DISABLED" }, + { 0xC0000801, "STATUS_DS_DOMAIN_RENAME_IN_PROGRESS" }, + { 0xC0000802, "STATUS_DISK_QUOTA_EXCEEDED" }, + { 0xC0000804, "STATUS_CONTENT_BLOCKED" }, + { 0xC0000805, "STATUS_BAD_CLUSTERS" }, + { 0xC0000806, "STATUS_VOLUME_DIRTY" }, + { 0xC0000901, "STATUS_FILE_CHECKED_OUT" }, + { 0xC0000902, "STATUS_CHECKOUT_REQUIRED" }, + { 0xC0000903, "STATUS_BAD_FILE_TYPE" }, + { 0xC0000904, "STATUS_FILE_TOO_LARGE" }, + { 0xC0000905, "STATUS_FORMS_AUTH_REQUIRED" }, + { 0xC0000906, "STATUS_VIRUS_INFECTED" }, + { 0xC0000907, "STATUS_VIRUS_DELETED" }, + { 0xC0000908, "STATUS_BAD_MCFG_TABLE" }, + { 0xC0000909, "STATUS_CANNOT_BREAK_OPLOCK" }, + { 0xC0009898, "STATUS_WOW_ASSERTION" }, + { 0xC000A000, "STATUS_INVALID_SIGNATURE" }, + { 0xC000A001, "STATUS_HMAC_NOT_SUPPORTED" }, + { 0xC000A010, "STATUS_IPSEC_QUEUE_OVERFLOW" }, + { 0xC000A011, "STATUS_ND_QUEUE_OVERFLOW" }, + { 0xC000A012, "STATUS_HOPLIMIT_EXCEEDED" }, + { 0xC000A013, "STATUS_PROTOCOL_NOT_SUPPORTED" }, + { 0xC000A080, "STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED" }, + { 0xC000A081, "STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR" }, + { 0xC000A082, "STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR" }, + { 0xC000A083, "STATUS_XML_PARSE_ERROR" }, + { 0xC000A084, "STATUS_XMLDSIG_ERROR" }, + { 0xC000A085, "STATUS_WRONG_COMPARTMENT" }, + { 0xC000A086, "STATUS_AUTHIP_FAILURE" }, + { 0xC000A087, "STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS" }, + { 0xC000A088, "STATUS_DS_OID_NOT_FOUND" }, + { 0xC000A100, "STATUS_HASH_NOT_SUPPORTED" }, + { 0xC000A101, "STATUS_HASH_NOT_PRESENT" }, + { 0xC000A2A1, "STATUS_OFFLOAD_READ_FLT_NOT_SUPPORTED" }, + { 0xC000A2A2, "STATUS_OFFLOAD_WRITE_FLT_NOT_SUPPORTED" }, + { 0xC000A2A3, "STATUS_OFFLOAD_READ_FILE_NOT_SUPPORTED" }, + { 0xC0010001, "DBG_NO_STATE_CHANGE" }, + { 0xC0010002, "DBG_APP_NOT_IDLE" }, + { 0xC0020001, "RPC_NT_INVALID_STRING_BINDING" }, + { 0xC0020002, "RPC_NT_WRONG_KIND_OF_BINDING" }, + { 0xC0020003, "RPC_NT_INVALID_BINDING" }, + { 0xC0020004, "RPC_NT_PROTSEQ_NOT_SUPPORTED" }, + { 0xC0020005, "RPC_NT_INVALID_RPC_PROTSEQ" }, + { 0xC0020006, "RPC_NT_INVALID_STRING_UUID" }, + { 0xC0020007, "RPC_NT_INVALID_ENDPOINT_FORMAT" }, + { 0xC0020008, "RPC_NT_INVALID_NET_ADDR" }, + { 0xC0020009, "RPC_NT_NO_ENDPOINT_FOUND" }, + { 0xC002000A, "RPC_NT_INVALID_TIMEOUT" }, + { 0xC002000B, "RPC_NT_OBJECT_NOT_FOUND" }, + { 0xC002000C, "RPC_NT_ALREADY_REGISTERED" }, + { 0xC002000D, "RPC_NT_TYPE_ALREADY_REGISTERED" }, + { 0xC002000E, "RPC_NT_ALREADY_LISTENING" }, + { 0xC002000F, "RPC_NT_NO_PROTSEQS_REGISTERED" }, + { 0xC0020010, "RPC_NT_NOT_LISTENING" }, + { 0xC0020011, "RPC_NT_UNKNOWN_MGR_TYPE" }, + { 0xC0020012, "RPC_NT_UNKNOWN_IF" }, + { 0xC0020013, "RPC_NT_NO_BINDINGS" }, + { 0xC0020014, "RPC_NT_NO_PROTSEQS" }, + { 0xC0020015, "RPC_NT_CANT_CREATE_ENDPOINT" }, + { 0xC0020016, "RPC_NT_OUT_OF_RESOURCES" }, + { 0xC0020017, "RPC_NT_SERVER_UNAVAILABLE" }, + { 0xC0020018, "RPC_NT_SERVER_TOO_BUSY" }, + { 0xC0020019, "RPC_NT_INVALID_NETWORK_OPTIONS" }, + { 0xC002001A, "RPC_NT_NO_CALL_ACTIVE" }, + { 0xC002001B, "RPC_NT_CALL_FAILED" }, + { 0xC002001C, "RPC_NT_CALL_FAILED_DNE" }, + { 0xC002001D, "RPC_NT_PROTOCOL_ERROR" }, + { 0xC002001F, "RPC_NT_UNSUPPORTED_TRANS_SYN" }, + { 0xC0020021, "RPC_NT_UNSUPPORTED_TYPE" }, + { 0xC0020022, "RPC_NT_INVALID_TAG" }, + { 0xC0020023, "RPC_NT_INVALID_BOUND" }, + { 0xC0020024, "RPC_NT_NO_ENTRY_NAME" }, + { 0xC0020025, "RPC_NT_INVALID_NAME_SYNTAX" }, + { 0xC0020026, "RPC_NT_UNSUPPORTED_NAME_SYNTAX" }, + { 0xC0020028, "RPC_NT_UUID_NO_ADDRESS" }, + { 0xC0020029, "RPC_NT_DUPLICATE_ENDPOINT" }, + { 0xC002002A, "RPC_NT_UNKNOWN_AUTHN_TYPE" }, + { 0xC002002B, "RPC_NT_MAX_CALLS_TOO_SMALL" }, + { 0xC002002C, "RPC_NT_STRING_TOO_LONG" }, + { 0xC002002D, "RPC_NT_PROTSEQ_NOT_FOUND" }, + { 0xC002002E, "RPC_NT_PROCNUM_OUT_OF_RANGE" }, + { 0xC002002F, "RPC_NT_BINDING_HAS_NO_AUTH" }, + { 0xC0020030, "RPC_NT_UNKNOWN_AUTHN_SERVICE" }, + { 0xC0020031, "RPC_NT_UNKNOWN_AUTHN_LEVEL" }, + { 0xC0020032, "RPC_NT_INVALID_AUTH_IDENTITY" }, + { 0xC0020033, "RPC_NT_UNKNOWN_AUTHZ_SERVICE" }, + { 0xC0020034, "EPT_NT_INVALID_ENTRY" }, + { 0xC0020035, "EPT_NT_CANT_PERFORM_OP" }, + { 0xC0020036, "EPT_NT_NOT_REGISTERED" }, + { 0xC0020037, "RPC_NT_NOTHING_TO_EXPORT" }, + { 0xC0020038, "RPC_NT_INCOMPLETE_NAME" }, + { 0xC0020039, "RPC_NT_INVALID_VERS_OPTION" }, + { 0xC002003A, "RPC_NT_NO_MORE_MEMBERS" }, + { 0xC002003B, "RPC_NT_NOT_ALL_OBJS_UNEXPORTED" }, + { 0xC002003C, "RPC_NT_INTERFACE_NOT_FOUND" }, + { 0xC002003D, "RPC_NT_ENTRY_ALREADY_EXISTS" }, + { 0xC002003E, "RPC_NT_ENTRY_NOT_FOUND" }, + { 0xC002003F, "RPC_NT_NAME_SERVICE_UNAVAILABLE" }, + { 0xC0020040, "RPC_NT_INVALID_NAF_ID" }, + { 0xC0020041, "RPC_NT_CANNOT_SUPPORT" }, + { 0xC0020042, "RPC_NT_NO_CONTEXT_AVAILABLE" }, + { 0xC0020043, "RPC_NT_INTERNAL_ERROR" }, + { 0xC0020044, "RPC_NT_ZERO_DIVIDE" }, + { 0xC0020045, "RPC_NT_ADDRESS_ERROR" }, + { 0xC0020046, "RPC_NT_FP_DIV_ZERO" }, + { 0xC0020047, "RPC_NT_FP_UNDERFLOW" }, + { 0xC0020048, "RPC_NT_FP_OVERFLOW" }, + { 0xC0020049, "RPC_NT_CALL_IN_PROGRESS" }, + { 0xC002004A, "RPC_NT_NO_MORE_BINDINGS" }, + { 0xC002004B, "RPC_NT_GROUP_MEMBER_NOT_FOUND" }, + { 0xC002004C, "EPT_NT_CANT_CREATE" }, + { 0xC002004D, "RPC_NT_INVALID_OBJECT" }, + { 0xC002004F, "RPC_NT_NO_INTERFACES" }, + { 0xC0020050, "RPC_NT_CALL_CANCELLED" }, + { 0xC0020051, "RPC_NT_BINDING_INCOMPLETE" }, + { 0xC0020052, "RPC_NT_COMM_FAILURE" }, + { 0xC0020053, "RPC_NT_UNSUPPORTED_AUTHN_LEVEL" }, + { 0xC0020054, "RPC_NT_NO_PRINC_NAME" }, + { 0xC0020055, "RPC_NT_NOT_RPC_ERROR" }, + { 0xC0020057, "RPC_NT_SEC_PKG_ERROR" }, + { 0xC0020058, "RPC_NT_NOT_CANCELLED" }, + { 0xC0020062, "RPC_NT_INVALID_ASYNC_HANDLE" }, + { 0xC0020063, "RPC_NT_INVALID_ASYNC_CALL" }, + { 0xC0020064, "RPC_NT_PROXY_ACCESS_DENIED" }, + { 0xC0030001, "RPC_NT_NO_MORE_ENTRIES" }, + { 0xC0030002, "RPC_NT_SS_CHAR_TRANS_OPEN_FAIL" }, + { 0xC0030003, "RPC_NT_SS_CHAR_TRANS_SHORT_FILE" }, + { 0xC0030004, "RPC_NT_SS_IN_NULL_CONTEXT" }, + { 0xC0030005, "RPC_NT_SS_CONTEXT_MISMATCH" }, + { 0xC0030006, "RPC_NT_SS_CONTEXT_DAMAGED" }, + { 0xC0030007, "RPC_NT_SS_HANDLES_MISMATCH" }, + { 0xC0030008, "RPC_NT_SS_CANNOT_GET_CALL_HANDLE" }, + { 0xC0030009, "RPC_NT_NULL_REF_POINTER" }, + { 0xC003000A, "RPC_NT_ENUM_VALUE_OUT_OF_RANGE" }, + { 0xC003000B, "RPC_NT_BYTE_COUNT_TOO_SMALL" }, + { 0xC003000C, "RPC_NT_BAD_STUB_DATA" }, + { 0xC0030059, "RPC_NT_INVALID_ES_ACTION" }, + { 0xC003005A, "RPC_NT_WRONG_ES_VERSION" }, + { 0xC003005B, "RPC_NT_WRONG_STUB_VERSION" }, + { 0xC003005C, "RPC_NT_INVALID_PIPE_OBJECT" }, + { 0xC003005D, "RPC_NT_INVALID_PIPE_OPERATION" }, + { 0xC003005E, "RPC_NT_WRONG_PIPE_VERSION" }, + { 0xC003005F, "RPC_NT_PIPE_CLOSED" }, + { 0xC0030060, "RPC_NT_PIPE_DISCIPLINE_ERROR" }, + { 0xC0030061, "RPC_NT_PIPE_EMPTY" }, + { 0xC0040035, "STATUS_PNP_BAD_MPS_TABLE" }, + { 0xC0040036, "STATUS_PNP_TRANSLATION_FAILED" }, + { 0xC0040037, "STATUS_PNP_IRQ_TRANSLATION_FAILED" }, + { 0xC0040038, "STATUS_PNP_INVALID_ID" }, + { 0xC0040039, "STATUS_IO_REISSUE_AS_CACHED" }, + { 0xC00A0001, "STATUS_CTX_WINSTATION_NAME_INVALID" }, + { 0xC00A0002, "STATUS_CTX_INVALID_PD" }, + { 0xC00A0003, "STATUS_CTX_PD_NOT_FOUND" }, + { 0xC00A0006, "STATUS_CTX_CLOSE_PENDING" }, + { 0xC00A0007, "STATUS_CTX_NO_OUTBUF" }, + { 0xC00A0008, "STATUS_CTX_MODEM_INF_NOT_FOUND" }, + { 0xC00A0009, "STATUS_CTX_INVALID_MODEMNAME" }, + { 0xC00A000A, "STATUS_CTX_RESPONSE_ERROR" }, + { 0xC00A000B, "STATUS_CTX_MODEM_RESPONSE_TIMEOUT" }, + { 0xC00A000C, "STATUS_CTX_MODEM_RESPONSE_NO_CARRIER" }, + { 0xC00A000D, "STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE" }, + { 0xC00A000E, "STATUS_CTX_MODEM_RESPONSE_BUSY" }, + { 0xC00A000F, "STATUS_CTX_MODEM_RESPONSE_VOICE" }, + { 0xC00A0010, "STATUS_CTX_TD_ERROR" }, + { 0xC00A0012, "STATUS_CTX_LICENSE_CLIENT_INVALID" }, + { 0xC00A0013, "STATUS_CTX_LICENSE_NOT_AVAILABLE" }, + { 0xC00A0014, "STATUS_CTX_LICENSE_EXPIRED" }, + { 0xC00A0015, "STATUS_CTX_WINSTATION_NOT_FOUND" }, + { 0xC00A0016, "STATUS_CTX_WINSTATION_NAME_COLLISION" }, + { 0xC00A0017, "STATUS_CTX_WINSTATION_BUSY" }, + { 0xC00A0018, "STATUS_CTX_BAD_VIDEO_MODE" }, + { 0xC00A0022, "STATUS_CTX_GRAPHICS_INVALID" }, + { 0xC00A0024, "STATUS_CTX_NOT_CONSOLE" }, + { 0xC00A0026, "STATUS_CTX_CLIENT_QUERY_TIMEOUT" }, + { 0xC00A0027, "STATUS_CTX_CONSOLE_DISCONNECT" }, + { 0xC00A0028, "STATUS_CTX_CONSOLE_CONNECT" }, + { 0xC00A002A, "STATUS_CTX_SHADOW_DENIED" }, + { 0xC00A002B, "STATUS_CTX_WINSTATION_ACCESS_DENIED" }, + { 0xC00A002E, "STATUS_CTX_INVALID_WD" }, + { 0xC00A002F, "STATUS_CTX_WD_NOT_FOUND" }, + { 0xC00A0030, "STATUS_CTX_SHADOW_INVALID" }, + { 0xC00A0031, "STATUS_CTX_SHADOW_DISABLED" }, + { 0xC00A0032, "STATUS_RDP_PROTOCOL_ERROR" }, + { 0xC00A0033, "STATUS_CTX_CLIENT_LICENSE_NOT_SET" }, + { 0xC00A0034, "STATUS_CTX_CLIENT_LICENSE_IN_USE" }, + { 0xC00A0035, "STATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE" }, + { 0xC00A0036, "STATUS_CTX_SHADOW_NOT_RUNNING" }, + { 0xC00A0037, "STATUS_CTX_LOGON_DISABLED" }, + { 0xC00A0038, "STATUS_CTX_SECURITY_LAYER_ERROR" }, + { 0xC00A0039, "STATUS_TS_INCOMPATIBLE_SESSIONS" }, + { 0xC00B0001, "STATUS_MUI_FILE_NOT_FOUND" }, + { 0xC00B0002, "STATUS_MUI_INVALID_FILE" }, + { 0xC00B0003, "STATUS_MUI_INVALID_RC_CONFIG" }, + { 0xC00B0004, "STATUS_MUI_INVALID_LOCALE_NAME" }, + { 0xC00B0005, "STATUS_MUI_INVALID_ULTIMATEFALLBACK_NAME" }, + { 0xC00B0006, "STATUS_MUI_FILE_NOT_LOADED" }, + { 0xC00B0007, "STATUS_RESOURCE_ENUM_USER_STOP" }, + { 0xC0130001, "STATUS_CLUSTER_INVALID_NODE" }, + { 0xC0130002, "STATUS_CLUSTER_NODE_EXISTS" }, + { 0xC0130003, "STATUS_CLUSTER_JOIN_IN_PROGRESS" }, + { 0xC0130004, "STATUS_CLUSTER_NODE_NOT_FOUND" }, + { 0xC0130005, "STATUS_CLUSTER_LOCAL_NODE_NOT_FOUND" }, + { 0xC0130006, "STATUS_CLUSTER_NETWORK_EXISTS" }, + { 0xC0130007, "STATUS_CLUSTER_NETWORK_NOT_FOUND" }, + { 0xC0130008, "STATUS_CLUSTER_NETINTERFACE_EXISTS" }, + { 0xC0130009, "STATUS_CLUSTER_NETINTERFACE_NOT_FOUND" }, + { 0xC013000A, "STATUS_CLUSTER_INVALID_REQUEST" }, + { 0xC013000B, "STATUS_CLUSTER_INVALID_NETWORK_PROVIDER" }, + { 0xC013000C, "STATUS_CLUSTER_NODE_DOWN" }, + { 0xC013000D, "STATUS_CLUSTER_NODE_UNREACHABLE" }, + { 0xC013000E, "STATUS_CLUSTER_NODE_NOT_MEMBER" }, + { 0xC013000F, "STATUS_CLUSTER_JOIN_NOT_IN_PROGRESS" }, + { 0xC0130010, "STATUS_CLUSTER_INVALID_NETWORK" }, + { 0xC0130011, "STATUS_CLUSTER_NO_NET_ADAPTERS" }, + { 0xC0130012, "STATUS_CLUSTER_NODE_UP" }, + { 0xC0130013, "STATUS_CLUSTER_NODE_PAUSED" }, + { 0xC0130014, "STATUS_CLUSTER_NODE_NOT_PAUSED" }, + { 0xC0130015, "STATUS_CLUSTER_NO_SECURITY_CONTEXT" }, + { 0xC0130016, "STATUS_CLUSTER_NETWORK_NOT_INTERNAL" }, + { 0xC0130017, "STATUS_CLUSTER_POISONED" }, + { 0xC0140001, "STATUS_ACPI_INVALID_OPCODE" }, + { 0xC0140002, "STATUS_ACPI_STACK_OVERFLOW" }, + { 0xC0140003, "STATUS_ACPI_ASSERT_FAILED" }, + { 0xC0140004, "STATUS_ACPI_INVALID_INDEX" }, + { 0xC0140005, "STATUS_ACPI_INVALID_ARGUMENT" }, + { 0xC0140006, "STATUS_ACPI_FATAL" }, + { 0xC0140007, "STATUS_ACPI_INVALID_SUPERNAME" }, + { 0xC0140008, "STATUS_ACPI_INVALID_ARGTYPE" }, + { 0xC0140009, "STATUS_ACPI_INVALID_OBJTYPE" }, + { 0xC014000A, "STATUS_ACPI_INVALID_TARGETTYPE" }, + { 0xC014000B, "STATUS_ACPI_INCORRECT_ARGUMENT_COUNT" }, + { 0xC014000C, "STATUS_ACPI_ADDRESS_NOT_MAPPED" }, + { 0xC014000D, "STATUS_ACPI_INVALID_EVENTTYPE" }, + { 0xC014000E, "STATUS_ACPI_HANDLER_COLLISION" }, + { 0xC014000F, "STATUS_ACPI_INVALID_DATA" }, + { 0xC0140010, "STATUS_ACPI_INVALID_REGION" }, + { 0xC0140011, "STATUS_ACPI_INVALID_ACCESS_SIZE" }, + { 0xC0140012, "STATUS_ACPI_ACQUIRE_GLOBAL_LOCK" }, + { 0xC0140013, "STATUS_ACPI_ALREADY_INITIALIZED" }, + { 0xC0140014, "STATUS_ACPI_NOT_INITIALIZED" }, + { 0xC0140015, "STATUS_ACPI_INVALID_MUTEX_LEVEL" }, + { 0xC0140016, "STATUS_ACPI_MUTEX_NOT_OWNED" }, + { 0xC0140017, "STATUS_ACPI_MUTEX_NOT_OWNER" }, + { 0xC0140018, "STATUS_ACPI_RS_ACCESS" }, + { 0xC0140019, "STATUS_ACPI_INVALID_TABLE" }, + { 0xC0140020, "STATUS_ACPI_REG_HANDLER_FAILED" }, + { 0xC0140021, "STATUS_ACPI_POWER_REQUEST_FAILED" }, + { 0xC0150001, "STATUS_SXS_SECTION_NOT_FOUND" }, + { 0xC0150002, "STATUS_SXS_CANT_GEN_ACTCTX" }, + { 0xC0150003, "STATUS_SXS_INVALID_ACTCTXDATA_FORMAT" }, + { 0xC0150004, "STATUS_SXS_ASSEMBLY_NOT_FOUND" }, + { 0xC0150005, "STATUS_SXS_MANIFEST_FORMAT_ERROR" }, + { 0xC0150006, "STATUS_SXS_MANIFEST_PARSE_ERROR" }, + { 0xC0150007, "STATUS_SXS_ACTIVATION_CONTEXT_DISABLED" }, + { 0xC0150008, "STATUS_SXS_KEY_NOT_FOUND" }, + { 0xC0150009, "STATUS_SXS_VERSION_CONFLICT" }, + { 0xC015000A, "STATUS_SXS_WRONG_SECTION_TYPE" }, + { 0xC015000B, "STATUS_SXS_THREAD_QUERIES_DISABLED" }, + { 0xC015000C, "STATUS_SXS_ASSEMBLY_MISSING" }, + { 0xC015000E, "STATUS_SXS_PROCESS_DEFAULT_ALREADY_SET" }, + { 0xC015000F, "STATUS_SXS_EARLY_DEACTIVATION" }, + { 0xC0150010, "STATUS_SXS_INVALID_DEACTIVATION" }, + { 0xC0150011, "STATUS_SXS_MULTIPLE_DEACTIVATION" }, + { 0xC0150012, "STATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY" }, + { 0xC0150013, "STATUS_SXS_PROCESS_TERMINATION_REQUESTED" }, + { 0xC0150014, "STATUS_SXS_CORRUPT_ACTIVATION_STACK" }, + { 0xC0150015, "STATUS_SXS_CORRUPTION" }, + { 0xC0150016, "STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE" }, + { 0xC0150017, "STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME" }, + { 0xC0150018, "STATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE" }, + { 0xC0150019, "STATUS_SXS_IDENTITY_PARSE_ERROR" }, + { 0xC015001A, "STATUS_SXS_COMPONENT_STORE_CORRUPT" }, + { 0xC015001B, "STATUS_SXS_FILE_HASH_MISMATCH" }, + { 0xC015001C, "STATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT" }, + { 0xC015001D, "STATUS_SXS_IDENTITIES_DIFFERENT" }, + { 0xC015001E, "STATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT" }, + { 0xC015001F, "STATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY" }, + { 0xC0150020, "STATUS_ADVANCED_INSTALLER_FAILED" }, + { 0xC0150021, "STATUS_XML_ENCODING_MISMATCH" }, + { 0xC0150022, "STATUS_SXS_MANIFEST_TOO_BIG" }, + { 0xC0150023, "STATUS_SXS_SETTING_NOT_REGISTERED" }, + { 0xC0150024, "STATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE" }, + { 0xC0150025, "STATUS_SMI_PRIMITIVE_INSTALLER_FAILED" }, + { 0xC0150026, "STATUS_GENERIC_COMMAND_FAILED" }, + { 0xC0150027, "STATUS_SXS_FILE_HASH_MISSING" }, + { 0xC0190001, "STATUS_TRANSACTIONAL_CONFLICT" }, + { 0xC0190002, "STATUS_INVALID_TRANSACTION" }, + { 0xC0190003, "STATUS_TRANSACTION_NOT_ACTIVE" }, + { 0xC0190004, "STATUS_TM_INITIALIZATION_FAILED" }, + { 0xC0190005, "STATUS_RM_NOT_ACTIVE" }, + { 0xC0190006, "STATUS_RM_METADATA_CORRUPT" }, + { 0xC0190007, "STATUS_TRANSACTION_NOT_JOINED" }, + { 0xC0190008, "STATUS_DIRECTORY_NOT_RM" }, + { 0xC019000A, "STATUS_TRANSACTIONS_UNSUPPORTED_REMOTE" }, + { 0xC019000B, "STATUS_LOG_RESIZE_INVALID_SIZE" }, + { 0xC019000C, "STATUS_REMOTE_FILE_VERSION_MISMATCH" }, + { 0xC019000F, "STATUS_CRM_PROTOCOL_ALREADY_EXISTS" }, + { 0xC0190010, "STATUS_TRANSACTION_PROPAGATION_FAILED" }, + { 0xC0190011, "STATUS_CRM_PROTOCOL_NOT_FOUND" }, + { 0xC0190012, "STATUS_TRANSACTION_SUPERIOR_EXISTS" }, + { 0xC0190013, "STATUS_TRANSACTION_REQUEST_NOT_VALID" }, + { 0xC0190014, "STATUS_TRANSACTION_NOT_REQUESTED" }, + { 0xC0190015, "STATUS_TRANSACTION_ALREADY_ABORTED" }, + { 0xC0190016, "STATUS_TRANSACTION_ALREADY_COMMITTED" }, + { 0xC0190017, "STATUS_TRANSACTION_INVALID_MARSHALL_BUFFER" }, + { 0xC0190018, "STATUS_CURRENT_TRANSACTION_NOT_VALID" }, + { 0xC0190019, "STATUS_LOG_GROWTH_FAILED" }, + { 0xC0190021, "STATUS_OBJECT_NO_LONGER_EXISTS" }, + { 0xC0190022, "STATUS_STREAM_MINIVERSION_NOT_FOUND" }, + { 0xC0190023, "STATUS_STREAM_MINIVERSION_NOT_VALID" }, + { 0xC0190024, "STATUS_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION" }, + { 0xC0190025, "STATUS_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT" }, + { 0xC0190026, "STATUS_CANT_CREATE_MORE_STREAM_MINIVERSIONS" }, + { 0xC0190028, "STATUS_HANDLE_NO_LONGER_VALID" }, + { 0xC0190030, "STATUS_LOG_CORRUPTION_DETECTED" }, + { 0xC0190032, "STATUS_RM_DISCONNECTED" }, + { 0xC0190033, "STATUS_ENLISTMENT_NOT_SUPERIOR" }, + { 0xC0190036, "STATUS_FILE_IDENTITY_NOT_PERSISTENT" }, + { 0xC0190037, "STATUS_CANT_BREAK_TRANSACTIONAL_DEPENDENCY" }, + { 0xC0190038, "STATUS_CANT_CROSS_RM_BOUNDARY" }, + { 0xC0190039, "STATUS_TXF_DIR_NOT_EMPTY" }, + { 0xC019003A, "STATUS_INDOUBT_TRANSACTIONS_EXIST" }, + { 0xC019003B, "STATUS_TM_VOLATILE" }, + { 0xC019003C, "STATUS_ROLLBACK_TIMER_EXPIRED" }, + { 0xC019003D, "STATUS_TXF_ATTRIBUTE_CORRUPT" }, + { 0xC019003E, "STATUS_EFS_NOT_ALLOWED_IN_TRANSACTION" }, + { 0xC019003F, "STATUS_TRANSACTIONAL_OPEN_NOT_ALLOWED" }, + { 0xC0190040, "STATUS_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE" }, + { 0xC0190043, "STATUS_TRANSACTION_REQUIRED_PROMOTION" }, + { 0xC0190044, "STATUS_CANNOT_EXECUTE_FILE_IN_TRANSACTION" }, + { 0xC0190045, "STATUS_TRANSACTIONS_NOT_FROZEN" }, + { 0xC0190046, "STATUS_TRANSACTION_FREEZE_IN_PROGRESS" }, + { 0xC0190047, "STATUS_NOT_SNAPSHOT_VOLUME" }, + { 0xC0190048, "STATUS_NO_SAVEPOINT_WITH_OPEN_FILES" }, + { 0xC0190049, "STATUS_SPARSE_NOT_ALLOWED_IN_TRANSACTION" }, + { 0xC019004A, "STATUS_TM_IDENTITY_MISMATCH" }, + { 0xC019004B, "STATUS_FLOATED_SECTION" }, + { 0xC019004C, "STATUS_CANNOT_ACCEPT_TRANSACTED_WORK" }, + { 0xC019004D, "STATUS_CANNOT_ABORT_TRANSACTIONS" }, + { 0xC019004E, "STATUS_TRANSACTION_NOT_FOUND" }, + { 0xC019004F, "STATUS_RESOURCEMANAGER_NOT_FOUND" }, + { 0xC0190050, "STATUS_ENLISTMENT_NOT_FOUND" }, + { 0xC0190051, "STATUS_TRANSACTIONMANAGER_NOT_FOUND" }, + { 0xC0190052, "STATUS_TRANSACTIONMANAGER_NOT_ONLINE" }, + { 0xC0190053, "STATUS_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION" }, + { 0xC0190054, "STATUS_TRANSACTION_NOT_ROOT" }, + { 0xC0190055, "STATUS_TRANSACTION_OBJECT_EXPIRED" }, + { 0xC0190056, "STATUS_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION" }, + { 0xC0190057, "STATUS_TRANSACTION_RESPONSE_NOT_ENLISTED" }, + { 0xC0190058, "STATUS_TRANSACTION_RECORD_TOO_LONG" }, + { 0xC0190059, "STATUS_NO_LINK_TRACKING_IN_TRANSACTION" }, + { 0xC019005A, "STATUS_OPERATION_NOT_SUPPORTED_IN_TRANSACTION" }, + { 0xC019005B, "STATUS_TRANSACTION_INTEGRITY_VIOLATED" }, + { 0xC0190060, "STATUS_EXPIRED_HANDLE" }, + { 0xC0190061, "STATUS_TRANSACTION_NOT_ENLISTED" }, + { 0xC01A0001, "STATUS_LOG_SECTOR_INVALID" }, + { 0xC01A0002, "STATUS_LOG_SECTOR_PARITY_INVALID" }, + { 0xC01A0003, "STATUS_LOG_SECTOR_REMAPPED" }, + { 0xC01A0004, "STATUS_LOG_BLOCK_INCOMPLETE" }, + { 0xC01A0005, "STATUS_LOG_INVALID_RANGE" }, + { 0xC01A0006, "STATUS_LOG_BLOCKS_EXHAUSTED" }, + { 0xC01A0007, "STATUS_LOG_READ_CONTEXT_INVALID" }, + { 0xC01A0008, "STATUS_LOG_RESTART_INVALID" }, + { 0xC01A0009, "STATUS_LOG_BLOCK_VERSION" }, + { 0xC01A000A, "STATUS_LOG_BLOCK_INVALID" }, + { 0xC01A000B, "STATUS_LOG_READ_MODE_INVALID" }, + { 0xC01A000D, "STATUS_LOG_METADATA_CORRUPT" }, + { 0xC01A000E, "STATUS_LOG_METADATA_INVALID" }, + { 0xC01A000F, "STATUS_LOG_METADATA_INCONSISTENT" }, + { 0xC01A0010, "STATUS_LOG_RESERVATION_INVALID" }, + { 0xC01A0011, "STATUS_LOG_CANT_DELETE" }, + { 0xC01A0012, "STATUS_LOG_CONTAINER_LIMIT_EXCEEDED" }, + { 0xC01A0013, "STATUS_LOG_START_OF_LOG" }, + { 0xC01A0014, "STATUS_LOG_POLICY_ALREADY_INSTALLED" }, + { 0xC01A0015, "STATUS_LOG_POLICY_NOT_INSTALLED" }, + { 0xC01A0016, "STATUS_LOG_POLICY_INVALID" }, + { 0xC01A0017, "STATUS_LOG_POLICY_CONFLICT" }, + { 0xC01A0018, "STATUS_LOG_PINNED_ARCHIVE_TAIL" }, + { 0xC01A0019, "STATUS_LOG_RECORD_NONEXISTENT" }, + { 0xC01A001A, "STATUS_LOG_RECORDS_RESERVED_INVALID" }, + { 0xC01A001B, "STATUS_LOG_SPACE_RESERVED_INVALID" }, + { 0xC01A001C, "STATUS_LOG_TAIL_INVALID" }, + { 0xC01A001D, "STATUS_LOG_FULL" }, + { 0xC01A001E, "STATUS_LOG_MULTIPLEXED" }, + { 0xC01A001F, "STATUS_LOG_DEDICATED" }, + { 0xC01A0020, "STATUS_LOG_ARCHIVE_NOT_IN_PROGRESS" }, + { 0xC01A0021, "STATUS_LOG_ARCHIVE_IN_PROGRESS" }, + { 0xC01A0022, "STATUS_LOG_EPHEMERAL" }, + { 0xC01A0023, "STATUS_LOG_NOT_ENOUGH_CONTAINERS" }, + { 0xC01A0024, "STATUS_LOG_CLIENT_ALREADY_REGISTERED" }, + { 0xC01A0025, "STATUS_LOG_CLIENT_NOT_REGISTERED" }, + { 0xC01A0026, "STATUS_LOG_FULL_HANDLER_IN_PROGRESS" }, + { 0xC01A0027, "STATUS_LOG_CONTAINER_READ_FAILED" }, + { 0xC01A0028, "STATUS_LOG_CONTAINER_WRITE_FAILED" }, + { 0xC01A0029, "STATUS_LOG_CONTAINER_OPEN_FAILED" }, + { 0xC01A002A, "STATUS_LOG_CONTAINER_STATE_INVALID" }, + { 0xC01A002B, "STATUS_LOG_STATE_INVALID" }, + { 0xC01A002C, "STATUS_LOG_PINNED" }, + { 0xC01A002D, "STATUS_LOG_METADATA_FLUSH_FAILED" }, + { 0xC01A002E, "STATUS_LOG_INCONSISTENT_SECURITY" }, + { 0xC01A002F, "STATUS_LOG_APPENDED_FLUSH_FAILED" }, + { 0xC01A0030, "STATUS_LOG_PINNED_RESERVATION" }, + { 0xC01B00EA, "STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD" }, + { 0xC01C0001, "STATUS_FLT_NO_HANDLER_DEFINED" }, + { 0xC01C0002, "STATUS_FLT_CONTEXT_ALREADY_DEFINED" }, + { 0xC01C0003, "STATUS_FLT_INVALID_ASYNCHRONOUS_REQUEST" }, + { 0xC01C0004, "STATUS_FLT_DISALLOW_FAST_IO" }, + { 0xC01C0005, "STATUS_FLT_INVALID_NAME_REQUEST" }, + { 0xC01C0006, "STATUS_FLT_NOT_SAFE_TO_POST_OPERATION" }, + { 0xC01C0007, "STATUS_FLT_NOT_INITIALIZED" }, + { 0xC01C0008, "STATUS_FLT_FILTER_NOT_READY" }, + { 0xC01C0009, "STATUS_FLT_POST_OPERATION_CLEANUP" }, + { 0xC01C000A, "STATUS_FLT_INTERNAL_ERROR" }, + { 0xC01C000B, "STATUS_FLT_DELETING_OBJECT" }, + { 0xC01C000C, "STATUS_FLT_MUST_BE_NONPAGED_POOL" }, + { 0xC01C000D, "STATUS_FLT_DUPLICATE_ENTRY" }, + { 0xC01C000E, "STATUS_FLT_CBDQ_DISABLED" }, + { 0xC01C000F, "STATUS_FLT_DO_NOT_ATTACH" }, + { 0xC01C0010, "STATUS_FLT_DO_NOT_DETACH" }, + { 0xC01C0011, "STATUS_FLT_INSTANCE_ALTITUDE_COLLISION" }, + { 0xC01C0012, "STATUS_FLT_INSTANCE_NAME_COLLISION" }, + { 0xC01C0013, "STATUS_FLT_FILTER_NOT_FOUND" }, + { 0xC01C0014, "STATUS_FLT_VOLUME_NOT_FOUND" }, + { 0xC01C0015, "STATUS_FLT_INSTANCE_NOT_FOUND" }, + { 0xC01C0016, "STATUS_FLT_CONTEXT_ALLOCATION_NOT_FOUND" }, + { 0xC01C0017, "STATUS_FLT_INVALID_CONTEXT_REGISTRATION" }, + { 0xC01C0018, "STATUS_FLT_NAME_CACHE_MISS" }, + { 0xC01C0019, "STATUS_FLT_NO_DEVICE_OBJECT" }, + { 0xC01C001A, "STATUS_FLT_VOLUME_ALREADY_MOUNTED" }, + { 0xC01C001B, "STATUS_FLT_ALREADY_ENLISTED" }, + { 0xC01C001C, "STATUS_FLT_CONTEXT_ALREADY_LINKED" }, + { 0xC01C0020, "STATUS_FLT_NO_WAITER_FOR_REPLY" }, + { 0xC01D0001, "STATUS_MONITOR_NO_DESCRIPTOR" }, + { 0xC01D0002, "STATUS_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT" }, + { 0xC01D0003, "STATUS_MONITOR_INVALID_DESCRIPTOR_CHECKSUM" }, + { 0xC01D0004, "STATUS_MONITOR_INVALID_STANDARD_TIMING_BLOCK" }, + { 0xC01D0005, "STATUS_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED" }, + { 0xC01D0006, "STATUS_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK" }, + { 0xC01D0007, "STATUS_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK" }, + { 0xC01D0008, "STATUS_MONITOR_NO_MORE_DESCRIPTOR_DATA" }, + { 0xC01D0009, "STATUS_MONITOR_INVALID_DETAILED_TIMING_BLOCK" }, + { 0xC01D000A, "STATUS_MONITOR_INVALID_MANUFACTURE_DATE" }, + { 0xC01E0000, "STATUS_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER" }, + { 0xC01E0001, "STATUS_GRAPHICS_INSUFFICIENT_DMA_BUFFER" }, + { 0xC01E0002, "STATUS_GRAPHICS_INVALID_DISPLAY_ADAPTER" }, + { 0xC01E0003, "STATUS_GRAPHICS_ADAPTER_WAS_RESET" }, + { 0xC01E0004, "STATUS_GRAPHICS_INVALID_DRIVER_MODEL" }, + { 0xC01E0005, "STATUS_GRAPHICS_PRESENT_MODE_CHANGED" }, + { 0xC01E0006, "STATUS_GRAPHICS_PRESENT_OCCLUDED" }, + { 0xC01E0007, "STATUS_GRAPHICS_PRESENT_DENIED" }, + { 0xC01E0008, "STATUS_GRAPHICS_CANNOTCOLORCONVERT" }, + { 0xC01E000B, "STATUS_GRAPHICS_PRESENT_REDIRECTION_DISABLED" }, + { 0xC01E000C, "STATUS_GRAPHICS_PRESENT_UNOCCLUDED" }, + { 0xC01E0100, "STATUS_GRAPHICS_NO_VIDEO_MEMORY" }, + { 0xC01E0101, "STATUS_GRAPHICS_CANT_LOCK_MEMORY" }, + { 0xC01E0102, "STATUS_GRAPHICS_ALLOCATION_BUSY" }, + { 0xC01E0103, "STATUS_GRAPHICS_TOO_MANY_REFERENCES" }, + { 0xC01E0104, "STATUS_GRAPHICS_TRY_AGAIN_LATER" }, + { 0xC01E0105, "STATUS_GRAPHICS_TRY_AGAIN_NOW" }, + { 0xC01E0106, "STATUS_GRAPHICS_ALLOCATION_INVALID" }, + { 0xC01E0107, "STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE" }, + { 0xC01E0108, "STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED" }, + { 0xC01E0109, "STATUS_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION" }, + { 0xC01E0110, "STATUS_GRAPHICS_INVALID_ALLOCATION_USAGE" }, + { 0xC01E0111, "STATUS_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION" }, + { 0xC01E0112, "STATUS_GRAPHICS_ALLOCATION_CLOSED" }, + { 0xC01E0113, "STATUS_GRAPHICS_INVALID_ALLOCATION_INSTANCE" }, + { 0xC01E0114, "STATUS_GRAPHICS_INVALID_ALLOCATION_HANDLE" }, + { 0xC01E0115, "STATUS_GRAPHICS_WRONG_ALLOCATION_DEVICE" }, + { 0xC01E0116, "STATUS_GRAPHICS_ALLOCATION_CONTENT_LOST" }, + { 0xC01E0200, "STATUS_GRAPHICS_GPU_EXCEPTION_ON_DEVICE" }, + { 0xC01E0300, "STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY" }, + { 0xC01E0301, "STATUS_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED" }, + { 0xC01E0302, "STATUS_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED" }, + { 0xC01E0303, "STATUS_GRAPHICS_INVALID_VIDPN" }, + { 0xC01E0304, "STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE" }, + { 0xC01E0305, "STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET" }, + { 0xC01E0306, "STATUS_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED" }, + { 0xC01E0308, "STATUS_GRAPHICS_INVALID_VIDPN_SOURCEMODESET" }, + { 0xC01E0309, "STATUS_GRAPHICS_INVALID_VIDPN_TARGETMODESET" }, + { 0xC01E030A, "STATUS_GRAPHICS_INVALID_FREQUENCY" }, + { 0xC01E030B, "STATUS_GRAPHICS_INVALID_ACTIVE_REGION" }, + { 0xC01E030C, "STATUS_GRAPHICS_INVALID_TOTAL_REGION" }, + { 0xC01E0310, "STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE" }, + { 0xC01E0311, "STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE" }, + { 0xC01E0312, "STATUS_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET" }, + { 0xC01E0313, "STATUS_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY" }, + { 0xC01E0314, "STATUS_GRAPHICS_MODE_ALREADY_IN_MODESET" }, + { 0xC01E0315, "STATUS_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET" }, + { 0xC01E0316, "STATUS_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET" }, + { 0xC01E0317, "STATUS_GRAPHICS_SOURCE_ALREADY_IN_SET" }, + { 0xC01E0318, "STATUS_GRAPHICS_TARGET_ALREADY_IN_SET" }, + { 0xC01E0319, "STATUS_GRAPHICS_INVALID_VIDPN_PRESENT_PATH" }, + { 0xC01E031A, "STATUS_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY" }, + { 0xC01E031B, "STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET" }, + { 0xC01E031C, "STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE" }, + { 0xC01E031D, "STATUS_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET" }, + { 0xC01E031F, "STATUS_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET" }, + { 0xC01E0320, "STATUS_GRAPHICS_STALE_MODESET" }, + { 0xC01E0321, "STATUS_GRAPHICS_INVALID_MONITOR_SOURCEMODESET" }, + { 0xC01E0322, "STATUS_GRAPHICS_INVALID_MONITOR_SOURCE_MODE" }, + { 0xC01E0323, "STATUS_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN" }, + { 0xC01E0324, "STATUS_GRAPHICS_MODE_ID_MUST_BE_UNIQUE" }, + { 0xC01E0325, "STATUS_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION" }, + { 0xC01E0326, "STATUS_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES" }, + { 0xC01E0327, "STATUS_GRAPHICS_PATH_NOT_IN_TOPOLOGY" }, + { 0xC01E0328, "STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE" }, + { 0xC01E0329, "STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET" }, + { 0xC01E032A, "STATUS_GRAPHICS_INVALID_MONITORDESCRIPTORSET" }, + { 0xC01E032B, "STATUS_GRAPHICS_INVALID_MONITORDESCRIPTOR" }, + { 0xC01E032C, "STATUS_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET" }, + { 0xC01E032D, "STATUS_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET" }, + { 0xC01E032E, "STATUS_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE" }, + { 0xC01E032F, "STATUS_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE" }, + { 0xC01E0330, "STATUS_GRAPHICS_RESOURCES_NOT_RELATED" }, + { 0xC01E0331, "STATUS_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE" }, + { 0xC01E0332, "STATUS_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE" }, + { 0xC01E0333, "STATUS_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET" }, + { 0xC01E0334, "STATUS_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER" }, + { 0xC01E0335, "STATUS_GRAPHICS_NO_VIDPNMGR" }, + { 0xC01E0336, "STATUS_GRAPHICS_NO_ACTIVE_VIDPN" }, + { 0xC01E0337, "STATUS_GRAPHICS_STALE_VIDPN_TOPOLOGY" }, + { 0xC01E0338, "STATUS_GRAPHICS_MONITOR_NOT_CONNECTED" }, + { 0xC01E0339, "STATUS_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY" }, + { 0xC01E033A, "STATUS_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE" }, + { 0xC01E033B, "STATUS_GRAPHICS_INVALID_VISIBLEREGION_SIZE" }, + { 0xC01E033C, "STATUS_GRAPHICS_INVALID_STRIDE" }, + { 0xC01E033D, "STATUS_GRAPHICS_INVALID_PIXELFORMAT" }, + { 0xC01E033E, "STATUS_GRAPHICS_INVALID_COLORBASIS" }, + { 0xC01E033F, "STATUS_GRAPHICS_INVALID_PIXELVALUEACCESSMODE" }, + { 0xC01E0340, "STATUS_GRAPHICS_TARGET_NOT_IN_TOPOLOGY" }, + { 0xC01E0341, "STATUS_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT" }, + { 0xC01E0342, "STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE" }, + { 0xC01E0343, "STATUS_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN" }, + { 0xC01E0344, "STATUS_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL" }, + { 0xC01E0345, "STATUS_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION" }, + { 0xC01E0346, "STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED" }, + { 0xC01E0347, "STATUS_GRAPHICS_INVALID_GAMMA_RAMP" }, + { 0xC01E0348, "STATUS_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED" }, + { 0xC01E0349, "STATUS_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED" }, + { 0xC01E034A, "STATUS_GRAPHICS_MODE_NOT_IN_MODESET" }, + { 0xC01E034D, "STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON" }, + { 0xC01E034E, "STATUS_GRAPHICS_INVALID_PATH_CONTENT_TYPE" }, + { 0xC01E034F, "STATUS_GRAPHICS_INVALID_COPYPROTECTION_TYPE" }, + { 0xC01E0350, "STATUS_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS" }, + { 0xC01E0352, "STATUS_GRAPHICS_INVALID_SCANLINE_ORDERING" }, + { 0xC01E0353, "STATUS_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED" }, + { 0xC01E0354, "STATUS_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS" }, + { 0xC01E0355, "STATUS_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT" }, + { 0xC01E0356, "STATUS_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM" }, + { 0xC01E0357, "STATUS_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN" }, + { 0xC01E0358, "STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT" }, + { 0xC01E0359, "STATUS_GRAPHICS_MAX_NUM_PATHS_REACHED" }, + { 0xC01E035A, "STATUS_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION" }, + { 0xC01E035B, "STATUS_GRAPHICS_INVALID_CLIENT_TYPE" }, + { 0xC01E035C, "STATUS_GRAPHICS_CLIENTVIDPN_NOT_SET" }, + { 0xC01E0400, "STATUS_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED" }, + { 0xC01E0401, "STATUS_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED" }, + { 0xC01E0430, "STATUS_GRAPHICS_NOT_A_LINKED_ADAPTER" }, + { 0xC01E0431, "STATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED" }, + { 0xC01E0432, "STATUS_GRAPHICS_CHAINLINKS_NOT_ENUMERATED" }, + { 0xC01E0433, "STATUS_GRAPHICS_ADAPTER_CHAIN_NOT_READY" }, + { 0xC01E0434, "STATUS_GRAPHICS_CHAINLINKS_NOT_STARTED" }, + { 0xC01E0435, "STATUS_GRAPHICS_CHAINLINKS_NOT_POWERED_ON" }, + { 0xC01E0436, "STATUS_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE" }, + { 0xC01E0438, "STATUS_GRAPHICS_NOT_POST_DEVICE_DRIVER" }, + { 0xC01E043B, "STATUS_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED" }, + { 0xC01E0500, "STATUS_GRAPHICS_OPM_NOT_SUPPORTED" }, + { 0xC01E0501, "STATUS_GRAPHICS_COPP_NOT_SUPPORTED" }, + { 0xC01E0502, "STATUS_GRAPHICS_UAB_NOT_SUPPORTED" }, + { 0xC01E0503, "STATUS_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS" }, + { 0xC01E0504, "STATUS_GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL" }, + { 0xC01E0505, "STATUS_GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST" }, + { 0xC01E0506, "STATUS_GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME" }, + { 0xC01E0507, "STATUS_GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP" }, + { 0xC01E0508, "STATUS_GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED" }, + { 0xC01E050A, "STATUS_GRAPHICS_OPM_INVALID_POINTER" }, + { 0xC01E050B, "STATUS_GRAPHICS_OPM_INTERNAL_ERROR" }, + { 0xC01E050C, "STATUS_GRAPHICS_OPM_INVALID_HANDLE" }, + { 0xC01E050D, "STATUS_GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE" }, + { 0xC01E050E, "STATUS_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH" }, + { 0xC01E050F, "STATUS_GRAPHICS_OPM_SPANNING_MODE_ENABLED" }, + { 0xC01E0510, "STATUS_GRAPHICS_OPM_THEATER_MODE_ENABLED" }, + { 0xC01E0511, "STATUS_GRAPHICS_PVP_HFS_FAILED" }, + { 0xC01E0512, "STATUS_GRAPHICS_OPM_INVALID_SRM" }, + { 0xC01E0513, "STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP" }, + { 0xC01E0514, "STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP" }, + { 0xC01E0515, "STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA" }, + { 0xC01E0516, "STATUS_GRAPHICS_OPM_HDCP_SRM_NEVER_SET" }, + { 0xC01E0517, "STATUS_GRAPHICS_OPM_RESOLUTION_TOO_HIGH" }, + { 0xC01E0518, "STATUS_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE" }, + { 0xC01E051A, "STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS" }, + { 0xC01E051B, "STATUS_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS" }, + { 0xC01E051C, "STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS" }, + { 0xC01E051D, "STATUS_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST" }, + { 0xC01E051E, "STATUS_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR" }, + { 0xC01E051F, "STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS" }, + { 0xC01E0520, "STATUS_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED" }, + { 0xC01E0521, "STATUS_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST" }, + { 0xC01E0580, "STATUS_GRAPHICS_I2C_NOT_SUPPORTED" }, + { 0xC01E0581, "STATUS_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST" }, + { 0xC01E0582, "STATUS_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA" }, + { 0xC01E0583, "STATUS_GRAPHICS_I2C_ERROR_RECEIVING_DATA" }, + { 0xC01E0584, "STATUS_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED" }, + { 0xC01E0585, "STATUS_GRAPHICS_DDCCI_INVALID_DATA" }, + { 0xC01E0586, "STATUS_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE" }, + { 0xC01E0587, "STATUS_GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING" }, + { 0xC01E0588, "STATUS_GRAPHICS_MCA_INTERNAL_ERROR" }, + { 0xC01E0589, "STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND" }, + { 0xC01E058A, "STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH" }, + { 0xC01E058B, "STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM" }, + { 0xC01E058C, "STATUS_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE" }, + { 0xC01E058D, "STATUS_GRAPHICS_MONITOR_NO_LONGER_EXISTS" }, + { 0xC01E05E0, "STATUS_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED" }, + { 0xC01E05E1, "STATUS_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME" }, + { 0xC01E05E2, "STATUS_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP" }, + { 0xC01E05E3, "STATUS_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED" }, + { 0xC01E05E4, "STATUS_GRAPHICS_INVALID_POINTER" }, + { 0xC01E05E5, "STATUS_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE" }, + { 0xC01E05E6, "STATUS_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL" }, + { 0xC01E05E7, "STATUS_GRAPHICS_INTERNAL_ERROR" }, + { 0xC01E05E8, "STATUS_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS" }, + { 0xC0210000, "STATUS_FVE_LOCKED_VOLUME" }, + { 0xC0210001, "STATUS_FVE_NOT_ENCRYPTED" }, + { 0xC0210002, "STATUS_FVE_BAD_INFORMATION" }, + { 0xC0210003, "STATUS_FVE_TOO_SMALL" }, + { 0xC0210004, "STATUS_FVE_FAILED_WRONG_FS" }, + { 0xC0210005, "STATUS_FVE_FAILED_BAD_FS" }, + { 0xC0210006, "STATUS_FVE_FS_NOT_EXTENDED" }, + { 0xC0210007, "STATUS_FVE_FS_MOUNTED" }, + { 0xC0210008, "STATUS_FVE_NO_LICENSE" }, + { 0xC0210009, "STATUS_FVE_ACTION_NOT_ALLOWED" }, + { 0xC021000A, "STATUS_FVE_BAD_DATA" }, + { 0xC021000B, "STATUS_FVE_VOLUME_NOT_BOUND" }, + { 0xC021000C, "STATUS_FVE_NOT_DATA_VOLUME" }, + { 0xC021000D, "STATUS_FVE_CONV_READ_ERROR" }, + { 0xC021000E, "STATUS_FVE_CONV_WRITE_ERROR" }, + { 0xC021000F, "STATUS_FVE_OVERLAPPED_UPDATE" }, + { 0xC0210010, "STATUS_FVE_FAILED_SECTOR_SIZE" }, + { 0xC0210011, "STATUS_FVE_FAILED_AUTHENTICATION" }, + { 0xC0210012, "STATUS_FVE_NOT_OS_VOLUME" }, + { 0xC0210013, "STATUS_FVE_KEYFILE_NOT_FOUND" }, + { 0xC0210014, "STATUS_FVE_KEYFILE_INVALID" }, + { 0xC0210015, "STATUS_FVE_KEYFILE_NO_VMK" }, + { 0xC0210016, "STATUS_FVE_TPM_DISABLED" }, + { 0xC0210017, "STATUS_FVE_TPM_SRK_AUTH_NOT_ZERO" }, + { 0xC0210018, "STATUS_FVE_TPM_INVALID_PCR" }, + { 0xC0210019, "STATUS_FVE_TPM_NO_VMK" }, + { 0xC021001A, "STATUS_FVE_PIN_INVALID" }, + { 0xC021001B, "STATUS_FVE_AUTH_INVALID_APPLICATION" }, + { 0xC021001C, "STATUS_FVE_AUTH_INVALID_CONFIG" }, + { 0xC021001D, "STATUS_FVE_DEBUGGER_ENABLED" }, + { 0xC021001E, "STATUS_FVE_DRY_RUN_FAILED" }, + { 0xC021001F, "STATUS_FVE_BAD_METADATA_POINTER" }, + { 0xC0210020, "STATUS_FVE_OLD_METADATA_COPY" }, + { 0xC0210021, "STATUS_FVE_REBOOT_REQUIRED" }, + { 0xC0210022, "STATUS_FVE_RAW_ACCESS" }, + { 0xC0210023, "STATUS_FVE_RAW_BLOCKED" }, + { 0xC0210026, "STATUS_FVE_NO_FEATURE_LICENSE" }, + { 0xC0210027, "STATUS_FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED" }, + { 0xC0210028, "STATUS_FVE_CONV_RECOVERY_FAILED" }, + { 0xC0210029, "STATUS_FVE_VIRTUALIZED_SPACE_TOO_BIG" }, + { 0xC0210030, "STATUS_FVE_VOLUME_TOO_SMALL" }, + { 0xC0220001, "STATUS_FWP_CALLOUT_NOT_FOUND" }, + { 0xC0220002, "STATUS_FWP_CONDITION_NOT_FOUND" }, + { 0xC0220003, "STATUS_FWP_FILTER_NOT_FOUND" }, + { 0xC0220004, "STATUS_FWP_LAYER_NOT_FOUND" }, + { 0xC0220005, "STATUS_FWP_PROVIDER_NOT_FOUND" }, + { 0xC0220006, "STATUS_FWP_PROVIDER_CONTEXT_NOT_FOUND" }, + { 0xC0220007, "STATUS_FWP_SUBLAYER_NOT_FOUND" }, + { 0xC0220008, "STATUS_FWP_NOT_FOUND" }, + { 0xC0220009, "STATUS_FWP_ALREADY_EXISTS" }, + { 0xC022000A, "STATUS_FWP_IN_USE" }, + { 0xC022000B, "STATUS_FWP_DYNAMIC_SESSION_IN_PROGRESS" }, + { 0xC022000C, "STATUS_FWP_WRONG_SESSION" }, + { 0xC022000D, "STATUS_FWP_NO_TXN_IN_PROGRESS" }, + { 0xC022000E, "STATUS_FWP_TXN_IN_PROGRESS" }, + { 0xC022000F, "STATUS_FWP_TXN_ABORTED" }, + { 0xC0220010, "STATUS_FWP_SESSION_ABORTED" }, + { 0xC0220011, "STATUS_FWP_INCOMPATIBLE_TXN" }, + { 0xC0220012, "STATUS_FWP_TIMEOUT" }, + { 0xC0220013, "STATUS_FWP_NET_EVENTS_DISABLED" }, + { 0xC0220014, "STATUS_FWP_INCOMPATIBLE_LAYER" }, + { 0xC0220015, "STATUS_FWP_KM_CLIENTS_ONLY" }, + { 0xC0220016, "STATUS_FWP_LIFETIME_MISMATCH" }, + { 0xC0220017, "STATUS_FWP_BUILTIN_OBJECT" }, + { 0xC0220018, "STATUS_FWP_TOO_MANY_BOOTTIME_FILTERS" }, + { 0xC0220018, "STATUS_FWP_TOO_MANY_CALLOUTS" }, + { 0xC0220019, "STATUS_FWP_NOTIFICATION_DROPPED" }, + { 0xC022001A, "STATUS_FWP_TRAFFIC_MISMATCH" }, + { 0xC022001B, "STATUS_FWP_INCOMPATIBLE_SA_STATE" }, + { 0xC022001C, "STATUS_FWP_NULL_POINTER" }, + { 0xC022001D, "STATUS_FWP_INVALID_ENUMERATOR" }, + { 0xC022001E, "STATUS_FWP_INVALID_FLAGS" }, + { 0xC022001F, "STATUS_FWP_INVALID_NET_MASK" }, + { 0xC0220020, "STATUS_FWP_INVALID_RANGE" }, + { 0xC0220021, "STATUS_FWP_INVALID_INTERVAL" }, + { 0xC0220022, "STATUS_FWP_ZERO_LENGTH_ARRAY" }, + { 0xC0220023, "STATUS_FWP_NULL_DISPLAY_NAME" }, + { 0xC0220024, "STATUS_FWP_INVALID_ACTION_TYPE" }, + { 0xC0220025, "STATUS_FWP_INVALID_WEIGHT" }, + { 0xC0220026, "STATUS_FWP_MATCH_TYPE_MISMATCH" }, + { 0xC0220027, "STATUS_FWP_TYPE_MISMATCH" }, + { 0xC0220028, "STATUS_FWP_OUT_OF_BOUNDS" }, + { 0xC0220029, "STATUS_FWP_RESERVED" }, + { 0xC022002A, "STATUS_FWP_DUPLICATE_CONDITION" }, + { 0xC022002B, "STATUS_FWP_DUPLICATE_KEYMOD" }, + { 0xC022002C, "STATUS_FWP_ACTION_INCOMPATIBLE_WITH_LAYER" }, + { 0xC022002D, "STATUS_FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER" }, + { 0xC022002E, "STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER" }, + { 0xC022002F, "STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT" }, + { 0xC0220030, "STATUS_FWP_INCOMPATIBLE_AUTH_METHOD" }, + { 0xC0220031, "STATUS_FWP_INCOMPATIBLE_DH_GROUP" }, + { 0xC0220032, "STATUS_FWP_EM_NOT_SUPPORTED" }, + { 0xC0220033, "STATUS_FWP_NEVER_MATCH" }, + { 0xC0220034, "STATUS_FWP_PROVIDER_CONTEXT_MISMATCH" }, + { 0xC0220035, "STATUS_FWP_INVALID_PARAMETER" }, + { 0xC0220036, "STATUS_FWP_TOO_MANY_SUBLAYERS" }, + { 0xC0220037, "STATUS_FWP_CALLOUT_NOTIFICATION_FAILED" }, + { 0xC0220038, "STATUS_FWP_INCOMPATIBLE_AUTH_CONFIG" }, + { 0xC0220039, "STATUS_FWP_INCOMPATIBLE_CIPHER_CONFIG" }, + { 0xC022003C, "STATUS_FWP_DUPLICATE_AUTH_METHOD" }, + { 0xC0220100, "STATUS_FWP_TCPIP_NOT_READY" }, + { 0xC0220101, "STATUS_FWP_INJECT_HANDLE_CLOSING" }, + { 0xC0220102, "STATUS_FWP_INJECT_HANDLE_STALE" }, + { 0xC0220103, "STATUS_FWP_CANNOT_PEND" }, + { 0xC0230002, "STATUS_NDIS_CLOSING" }, + { 0xC0230004, "STATUS_NDIS_BAD_VERSION" }, + { 0xC0230005, "STATUS_NDIS_BAD_CHARACTERISTICS" }, + { 0xC0230006, "STATUS_NDIS_ADAPTER_NOT_FOUND" }, + { 0xC0230007, "STATUS_NDIS_OPEN_FAILED" }, + { 0xC0230008, "STATUS_NDIS_DEVICE_FAILED" }, + { 0xC0230009, "STATUS_NDIS_MULTICAST_FULL" }, + { 0xC023000A, "STATUS_NDIS_MULTICAST_EXISTS" }, + { 0xC023000B, "STATUS_NDIS_MULTICAST_NOT_FOUND" }, + { 0xC023000C, "STATUS_NDIS_REQUEST_ABORTED" }, + { 0xC023000D, "STATUS_NDIS_RESET_IN_PROGRESS" }, + { 0xC023000F, "STATUS_NDIS_INVALID_PACKET" }, + { 0xC0230010, "STATUS_NDIS_INVALID_DEVICE_REQUEST" }, + { 0xC0230011, "STATUS_NDIS_ADAPTER_NOT_READY" }, + { 0xC0230014, "STATUS_NDIS_INVALID_LENGTH" }, + { 0xC0230015, "STATUS_NDIS_INVALID_DATA" }, + { 0xC0230016, "STATUS_NDIS_BUFFER_TOO_SHORT" }, + { 0xC0230017, "STATUS_NDIS_INVALID_OID" }, + { 0xC0230018, "STATUS_NDIS_ADAPTER_REMOVED" }, + { 0xC0230019, "STATUS_NDIS_UNSUPPORTED_MEDIA" }, + { 0xC023001A, "STATUS_NDIS_GROUP_ADDRESS_IN_USE" }, + { 0xC023001B, "STATUS_NDIS_FILE_NOT_FOUND" }, + { 0xC023001C, "STATUS_NDIS_ERROR_READING_FILE" }, + { 0xC023001D, "STATUS_NDIS_ALREADY_MAPPED" }, + { 0xC023001E, "STATUS_NDIS_RESOURCE_CONFLICT" }, + { 0xC023001F, "STATUS_NDIS_MEDIA_DISCONNECTED" }, + { 0xC0230022, "STATUS_NDIS_INVALID_ADDRESS" }, + { 0xC023002A, "STATUS_NDIS_PAUSED" }, + { 0xC023002B, "STATUS_NDIS_INTERFACE_NOT_FOUND" }, + { 0xC023002C, "STATUS_NDIS_UNSUPPORTED_REVISION" }, + { 0xC023002D, "STATUS_NDIS_INVALID_PORT" }, + { 0xC023002E, "STATUS_NDIS_INVALID_PORT_STATE" }, + { 0xC023002F, "STATUS_NDIS_LOW_POWER_STATE" }, + { 0xC02300BB, "STATUS_NDIS_NOT_SUPPORTED" }, + { 0xC023100F, "STATUS_NDIS_OFFLOAD_POLICY" }, + { 0xC0231012, "STATUS_NDIS_OFFLOAD_CONNECTION_REJECTED" }, + { 0xC0231013, "STATUS_NDIS_OFFLOAD_PATH_REJECTED" }, + { 0xC0232000, "STATUS_NDIS_DOT11_AUTO_CONFIG_ENABLED" }, + { 0xC0232001, "STATUS_NDIS_DOT11_MEDIA_IN_USE" }, + { 0xC0232002, "STATUS_NDIS_DOT11_POWER_STATE_INVALID" }, + { 0xC0232003, "STATUS_NDIS_PM_WOL_PATTERN_LIST_FULL" }, + { 0xC0232004, "STATUS_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL" }, + { 0xC0360001, "STATUS_IPSEC_BAD_SPI" }, + { 0xC0360002, "STATUS_IPSEC_SA_LIFETIME_EXPIRED" }, + { 0xC0360003, "STATUS_IPSEC_WRONG_SA" }, + { 0xC0360004, "STATUS_IPSEC_REPLAY_CHECK_FAILED" }, + { 0xC0360005, "STATUS_IPSEC_INVALID_PACKET" }, + { 0xC0360006, "STATUS_IPSEC_INTEGRITY_CHECK_FAILED" }, + { 0xC0360007, "STATUS_IPSEC_CLEAR_TEXT_DROP" }, + { 0xC0360008, "STATUS_IPSEC_AUTH_FIREWALL_DROP" }, + { 0xC0360009, "STATUS_IPSEC_THROTTLE_DROP" }, + { 0xC0368000, "STATUS_IPSEC_DOSP_BLOCK" }, + { 0xC0368001, "STATUS_IPSEC_DOSP_RECEIVED_MULTICAST" }, + { 0xC0368002, "STATUS_IPSEC_DOSP_INVALID_PACKET" }, + { 0xC0368003, "STATUS_IPSEC_DOSP_STATE_LOOKUP_FAILED" }, + { 0xC0368004, "STATUS_IPSEC_DOSP_MAX_ENTRIES" }, + { 0xC0368005, "STATUS_IPSEC_DOSP_KEYMOD_NOT_ALLOWED" }, + { 0xC0368006, "STATUS_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES" }, + { 0xC038005B, "STATUS_VOLMGR_MIRROR_NOT_SUPPORTED" }, + { 0xC038005C, "STATUS_VOLMGR_RAID5_NOT_SUPPORTED" }, + { 0xC03A0014, "STATUS_VIRTDISK_PROVIDER_NOT_FOUND" }, + { 0xC03A0015, "STATUS_VIRTDISK_NOT_VIRTUAL_DISK" }, + { 0xC03A0016, "STATUS_VHD_PARENT_VHD_ACCESS_DENIED" }, + { 0xC03A0017, "STATUS_VHD_CHILD_PARENT_SIZE_MISMATCH" }, + { 0xC03A0018, "STATUS_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED" }, + { 0xC03A0019, "STATUS_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT" } +}; + +static int ntstatus_compare(const void* pKey, const void* pValue) +{ + const DWORD* key = (const DWORD*)pKey; + const struct ntstatus_map* cur = (const struct ntstatus_map*)pValue; + if (*key == cur->code) + return 0; + return *key < cur->code ? -1 : 1; +} + +const char* NtStatus2Tag(NTSTATUS ntstatus) +{ + +#if 1 /* Requires sorted struct */ + size_t count = ARRAYSIZE(ntstatusmap); + size_t base = sizeof(ntstatusmap[0]); + const struct ntstatus_map* found = + bsearch(&ntstatus, ntstatusmap, count, base, ntstatus_compare); + if (!found) + return NULL; + return found->tag; +#else + for (size_t x = 0; x < ARRAYSIZE(ntstatusmap); x++) + { + const struct ntstatus_map* cur = &ntstatusmap[x]; + if (cur->code == ntstatus) + return cur->tag; + } + + return NULL; +#endif +} + +const char* Win32ErrorCode2Tag(UINT16 code) +{ +#if 1 /* Requires sorted struct */ + DWORD ntstatus = code; + size_t count = ARRAYSIZE(win32errmap); + size_t base = sizeof(win32errmap[0]); + const struct ntstatus_map* found = + bsearch(&ntstatus, win32errmap, count, base, ntstatus_compare); + if (!found) + return NULL; + return found->tag; +#else + for (size_t x = 0; x < ARRAYSIZE(win32errmap); x++) + { + const struct ntstatus_map* cur = &win32errmap[x]; + if (cur->code == ntstatus) + return cur->tag; + } + + return NULL; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9658e66b01e7e979df83e078e76df45568564305 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestNt") +set(MODULE_PREFIX "TEST_NT") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestNtCurrentTeb.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/TestNtCurrentTeb.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/TestNtCurrentTeb.c new file mode 100644 index 0000000000000000000000000000000000000000..6ee383638e57ecb60bb8124e9e7c91bd490237f9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/nt/test/TestNtCurrentTeb.c @@ -0,0 +1,24 @@ + +#include + +#include + +int TestNtCurrentTeb(int argc, char* argv[]) +{ +#ifndef _WIN32 + PTEB teb = NULL; + + teb = NtCurrentTeb(); + + if (!teb) + { + printf("NtCurrentTeb() returned NULL\n"); + return -1; + } +#endif + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..404c0ff233041d09903efa7b513b9929fb7d7088 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/CMakeLists.txt @@ -0,0 +1,30 @@ +# WinPR: Windows Portable Runtime +# libwinpr-path cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(path.c shell.c) + +if(MSVC OR MINGW) + winpr_library_add_public(shlwapi) +endif() + +if(IOS) + winpr_module_add(shell_ios.m) +endif(IOS) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..b0a53dae439e023a0add0ae3002b4ac6c6549340 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/ModuleOptions.cmake @@ -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 "path") +set(MINWIN_LONG_NAME "Path Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathAllocCombine.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathAllocCombine.h new file mode 100644 index 0000000000000000000000000000000000000000..a103d3dfac2f4ab081fad7862b60ba715786f232 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathAllocCombine.h @@ -0,0 +1,173 @@ + +/* +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR '\\' +#define CUR_PATH_SEPARATOR_STR "\\" +#define PATH_ALLOC_COMBINE PathAllocCombineA +*/ + +/** + * FIXME: These implementations of the PathAllocCombine functions have + * several issues: + * - pszPathIn or pszMore may be NULL (but not both) + * - no check if pszMore is fully qualified (if so, it must be directly + * copied to the output buffer without being combined with pszPathIn. + * - if pszMore begins with a _single_ backslash it must be combined with + * only the root of the path pointed to by pszPathIn and there's no code + * to extract the root of pszPathIn. + * - the function will crash with some short string lengths of the parameters + */ + +#include +#include + +#include +#include +#include + +#if DEFINE_UNICODE + +HRESULT PATH_ALLOC_COMBINE(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags, + PWSTR* ppszPathOut) +{ + WLog_WARN(TAG, "has known bugs and needs fixing."); + + if (!ppszPathOut) + return E_INVALIDARG; + + if (!pszPathIn && !pszMore) + return E_INVALIDARG; + + if (!pszMore) + return E_FAIL; /* valid but not implemented, see top comment */ + + if (!pszPathIn) + return E_FAIL; /* valid but not implemented, see top comment */ + + const size_t pszPathInLength = _wcslen(pszPathIn); + const size_t pszMoreLength = _wcslen(pszMore); + + /* prevent segfaults - the complete implementation below is buggy */ + if (pszPathInLength < 3) + return E_FAIL; + + const BOOL backslashIn = + (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + + if (backslashMore) + { + if ((pszPathIn[1] == ':') && (pszPathIn[2] == CUR_PATH_SEPARATOR_CHR)) + { + const WCHAR colon[] = { ':', '\0' }; + const size_t pszPathOutLength = sizeof(WCHAR) + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * sizeof(WCHAR); + PWSTR pszPathOut = (PWSTR)calloc(sizeOfBuffer, sizeof(WCHAR)); + + if (!pszPathOut) + return E_OUTOFMEMORY; + + _wcsncat(pszPathOut, &pszPathIn[0], 1); + _wcsncat(pszPathOut, colon, ARRAYSIZE(colon)); + _wcsncat(pszPathOut, pszMore, pszMoreLength); + *ppszPathOut = pszPathOut; + return S_OK; + } + } + else + { + const WCHAR sep[] = CUR_PATH_SEPARATOR_STR; + const size_t pszPathOutLength = pszPathInLength + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PWSTR pszPathOut = (PWSTR)calloc(sizeOfBuffer, 2); + + if (!pszPathOut) + return E_OUTOFMEMORY; + + _wcsncat(pszPathOut, pszPathIn, pszPathInLength); + if (!backslashIn) + _wcsncat(pszPathOut, sep, ARRAYSIZE(sep)); + _wcsncat(pszPathOut, pszMore, pszMoreLength); + + *ppszPathOut = pszPathOut; + return S_OK; + } + + return E_FAIL; +} + +#else + +HRESULT PATH_ALLOC_COMBINE(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags, PSTR* ppszPathOut) +{ + WLog_WARN(TAG, "has known bugs and needs fixing."); + + if (!ppszPathOut) + return E_INVALIDARG; + + if (!pszPathIn && !pszMore) + return E_INVALIDARG; + + if (!pszMore) + return E_FAIL; /* valid but not implemented, see top comment */ + + if (!pszPathIn) + return E_FAIL; /* valid but not implemented, see top comment */ + + const size_t pszPathInLength = strlen(pszPathIn); + const size_t pszMoreLength = strlen(pszMore); + + /* prevent segfaults - the complete implementation below is buggy */ + if (pszPathInLength < 3) + return E_FAIL; + + const BOOL backslashIn = + (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + + if (backslashMore) + { + if ((pszPathIn[1] == ':') && (pszPathIn[2] == CUR_PATH_SEPARATOR_CHR)) + { + const size_t pszPathOutLength = 2 + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PSTR pszPathOut = calloc(sizeOfBuffer, 2); + + if (!pszPathOut) + return E_OUTOFMEMORY; + + sprintf_s(pszPathOut, sizeOfBuffer, "%c:%s", pszPathIn[0], pszMore); + *ppszPathOut = pszPathOut; + return S_OK; + } + } + else + { + const size_t pszPathOutLength = pszPathInLength + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PSTR pszPathOut = calloc(sizeOfBuffer, 2); + + if (!pszPathOut) + return E_OUTOFMEMORY; + + if (backslashIn) + sprintf_s(pszPathOut, sizeOfBuffer, "%s%s", pszPathIn, pszMore); + else + sprintf_s(pszPathOut, sizeOfBuffer, "%s" CUR_PATH_SEPARATOR_STR "%s", pszPathIn, + pszMore); + + *ppszPathOut = pszPathOut; + return S_OK; + } + + return E_FAIL; +} + +#endif + +/* +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE +*/ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddExtension.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddExtension.h new file mode 100644 index 0000000000000000000000000000000000000000..498cfab989b0a0cfe2e5e567c8510375b3a9f57a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddExtension.h @@ -0,0 +1,101 @@ + +/* +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR '\\' +#define PATH_CCH_ADD_EXTENSION PathCchAddExtensionA +*/ + +#if DEFINE_UNICODE + +HRESULT PATH_CCH_ADD_EXTENSION(PWSTR pszPath, size_t cchPath, PCWSTR pszExt) +{ + LPWSTR pDot; + BOOL bExtDot; + LPWSTR pBackslash; + size_t pszExtLength; + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + if (!pszExt) + return E_INVALIDARG; + + pszExtLength = _wcslen(pszExt); + pszPathLength = _wcslen(pszPath); + bExtDot = (pszExt[0] == '.') ? TRUE : FALSE; + + pDot = _wcsrchr(pszPath, '.'); + pBackslash = _wcsrchr(pszPath, CUR_PATH_SEPARATOR_CHR); + + if (pDot && pBackslash) + { + if (pDot > pBackslash) + return S_FALSE; + } + + if (cchPath > pszPathLength + pszExtLength + ((bExtDot) ? 0 : 1)) + { + const WCHAR dot[] = { '.', '\0' }; + WCHAR* ptr = &pszPath[pszPathLength]; + *ptr = '\0'; + + if (!bExtDot) + _wcsncat(ptr, dot, _wcslen(dot)); + _wcsncat(ptr, pszExt, pszExtLength); + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#else + +HRESULT PATH_CCH_ADD_EXTENSION(PSTR pszPath, size_t cchPath, PCSTR pszExt) +{ + CHAR* pDot; + BOOL bExtDot; + CHAR* pBackslash; + size_t pszExtLength; + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + if (!pszExt) + return E_INVALIDARG; + + pszExtLength = strlen(pszExt); + pszPathLength = strlen(pszPath); + bExtDot = (pszExt[0] == '.') ? TRUE : FALSE; + + pDot = strrchr(pszPath, '.'); + pBackslash = strrchr(pszPath, CUR_PATH_SEPARATOR_CHR); + + if (pDot && pBackslash) + { + if (pDot > pBackslash) + return S_FALSE; + } + + if (cchPath > pszPathLength + pszExtLength + ((bExtDot) ? 0 : 1)) + { + if (bExtDot) + sprintf_s(&pszPath[pszPathLength], cchPath - pszPathLength, "%s", pszExt); + else + sprintf_s(&pszPath[pszPathLength], cchPath - pszPathLength, ".%s", pszExt); + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#endif + +/* +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION +*/ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparator.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparator.h new file mode 100644 index 0000000000000000000000000000000000000000..0ef391c31cd0c41e68dd30265ee08b802e5f5cdc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparator.h @@ -0,0 +1,64 @@ + +/* +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR '\\' +#define PATH_CCH_ADD_SEPARATOR PathCchAddBackslashA +*/ + +#if DEFINE_UNICODE + +HRESULT PATH_CCH_ADD_SEPARATOR(PWSTR pszPath, size_t cchPath) +{ + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + pszPathLength = _wcslen(pszPath); + + if (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) + return S_FALSE; + + if (cchPath > (pszPathLength + 1)) + { + pszPath[pszPathLength] = CUR_PATH_SEPARATOR_CHR; + pszPath[pszPathLength + 1] = '\0'; + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#else + +HRESULT PATH_CCH_ADD_SEPARATOR(PSTR pszPath, size_t cchPath) +{ + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + pszPathLength = strlen(pszPath); + + if (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) + return S_FALSE; + + if (cchPath > (pszPathLength + 1)) + { + pszPath[pszPathLength] = CUR_PATH_SEPARATOR_CHR; + pszPath[pszPathLength + 1] = '\0'; + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#endif + +/* +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR +*/ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparatorEx.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparatorEx.h new file mode 100644 index 0000000000000000000000000000000000000000..02832d858c5e94e844eff8db30ea26153a628741 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAddSeparatorEx.h @@ -0,0 +1,66 @@ + +/* +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR '\\' +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddBackslashExA +*/ + +#if DEFINE_UNICODE + +HRESULT PATH_CCH_ADD_SEPARATOR_EX(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd, + size_t* pcchRemaining) +{ + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + pszPathLength = _wcslen(pszPath); + + if (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) + return S_FALSE; + + if (cchPath > (pszPathLength + 1)) + { + pszPath[pszPathLength] = CUR_PATH_SEPARATOR_CHR; + pszPath[pszPathLength + 1] = '\0'; + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#else + +HRESULT PATH_CCH_ADD_SEPARATOR_EX(PSTR pszPath, size_t cchPath, PSTR* ppszEnd, + size_t* pcchRemaining) +{ + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + pszPathLength = strlen(pszPath); + + if (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) + return S_FALSE; + + if (cchPath > (pszPathLength + 1)) + { + pszPath[pszPathLength] = CUR_PATH_SEPARATOR_CHR; + pszPath[pszPathLength + 1] = '\0'; + + return S_OK; + } + + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +} + +#endif + +/* +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX +*/ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAppend.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAppend.h new file mode 100644 index 0000000000000000000000000000000000000000..a4f58cb5229cf43bb54567aac860fe8397c2da8b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/include/PathCchAppend.h @@ -0,0 +1,131 @@ + +/* +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR '\\' +#define CUR_PATH_SEPARATOR_STR "\\" +#define PATH_CCH_APPEND PathCchAppendA +*/ + +#if DEFINE_UNICODE + +HRESULT PATH_CCH_APPEND(PWSTR pszPath, size_t cchPath, PCWSTR pszMore) +{ + BOOL pathBackslash; + BOOL moreBackslash; + size_t pszMoreLength; + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + if (!pszMore) + return E_INVALIDARG; + + if (cchPath == 0 || cchPath > PATHCCH_MAX_CCH) + return E_INVALIDARG; + + pszMoreLength = _wcslen(pszMore); + pszPathLength = _wcslen(pszPath); + + pathBackslash = (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + moreBackslash = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + + if (pathBackslash && moreBackslash) + { + if ((pszPathLength + pszMoreLength - 1) < cchPath) + { + WCHAR* ptr = &pszPath[pszPathLength]; + *ptr = '\0'; + _wcsncat(ptr, &pszMore[1], _wcslen(&pszMore[1])); + return S_OK; + } + } + else if ((pathBackslash && !moreBackslash) || (!pathBackslash && moreBackslash)) + { + if ((pszPathLength + pszMoreLength) < cchPath) + { + WCHAR* ptr = &pszPath[pszPathLength]; + *ptr = '\0'; + _wcsncat(ptr, pszMore, _wcslen(pszMore)); + return S_OK; + } + } + else if (!pathBackslash && !moreBackslash) + { + if ((pszPathLength + pszMoreLength + 1) < cchPath) + { + const WCHAR sep[] = CUR_PATH_SEPARATOR_STR; + WCHAR* ptr = &pszPath[pszPathLength]; + *ptr = '\0'; + _wcsncat(ptr, sep, _wcslen(sep)); + _wcsncat(ptr, pszMore, _wcslen(pszMore)); + return S_OK; + } + } + + return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE); +} + +#else + +HRESULT PATH_CCH_APPEND(PSTR pszPath, size_t cchPath, PCSTR pszMore) +{ + BOOL pathBackslash = FALSE; + BOOL moreBackslash = FALSE; + size_t pszMoreLength; + size_t pszPathLength; + + if (!pszPath) + return E_INVALIDARG; + + if (!pszMore) + return E_INVALIDARG; + + if (cchPath == 0 || cchPath > PATHCCH_MAX_CCH) + return E_INVALIDARG; + + pszPathLength = strlen(pszPath); + if (pszPathLength > 0) + pathBackslash = (pszPath[pszPathLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + + pszMoreLength = strlen(pszMore); + if (pszMoreLength > 0) + moreBackslash = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + + if (pathBackslash && moreBackslash) + { + if ((pszPathLength + pszMoreLength - 1) < cchPath) + { + sprintf_s(&pszPath[pszPathLength], cchPath - pszPathLength, "%s", &pszMore[1]); + return S_OK; + } + } + else if ((pathBackslash && !moreBackslash) || (!pathBackslash && moreBackslash)) + { + if ((pszPathLength + pszMoreLength) < cchPath) + { + sprintf_s(&pszPath[pszPathLength], cchPath - pszPathLength, "%s", pszMore); + return S_OK; + } + } + else if (!pathBackslash && !moreBackslash) + { + if ((pszPathLength + pszMoreLength + 1) < cchPath) + { + sprintf_s(&pszPath[pszPathLength], cchPath - pszPathLength, CUR_PATH_SEPARATOR_STR "%s", + pszMore); + return S_OK; + } + } + + return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE); +} + +#endif + +/* +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND +*/ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/path.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/path.c new file mode 100644 index 0000000000000000000000000000000000000000..c6929697aaf0e3ee7e43f7a91bd0b99bf6959d42 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/path.c @@ -0,0 +1,1216 @@ +/** + * WinPR: Windows Portable Runtime + * Path Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include + +#include +#include + +#define STR(x) #x + +#define PATH_SLASH_CHR '/' +#define PATH_SLASH_STR "/" + +#define PATH_BACKSLASH_CHR '\\' +#define PATH_BACKSLASH_STR "\\" + +#ifdef _WIN32 +#define PATH_SLASH_STR_W L"/" +#define PATH_BACKSLASH_STR_W L"\\" +#else +#define PATH_SLASH_STR_W \ + { \ + '/', '\0' \ + } +#define PATH_BACKSLASH_STR_W \ + { \ + '\\', '\0' \ + } +#endif + +#ifdef _WIN32 +#define PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_SEPARATOR_STR PATH_BACKSLASH_STR +#define PATH_SEPARATOR_STR_W PATH_BACKSLASH_STR_W +#else +#define PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_SEPARATOR_STR PATH_SLASH_STR +#define PATH_SEPARATOR_STR_W PATH_SLASH_STR_W +#endif + +#define SHARED_LIBRARY_EXT_DLL "dll" +#define SHARED_LIBRARY_EXT_SO "so" +#define SHARED_LIBRARY_EXT_DYLIB "dylib" + +#ifdef _WIN32 +#define SHARED_LIBRARY_EXT SHARED_LIBRARY_EXT_DLL +#elif defined(__APPLE__) +#define SHARED_LIBRARY_EXT SHARED_LIBRARY_EXT_DYLIB +#else +#define SHARED_LIBRARY_EXT SHARED_LIBRARY_EXT_SO +#endif + +#include "../log.h" +#define TAG WINPR_TAG("path") + +/* + * PathCchAddBackslash + */ + +/* Windows-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddBackslashA +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddBackslashW +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +/* Unix-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddSlashA +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddSlashW +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +/* Native-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddSeparatorA +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_SEPARATOR PathCchAddSeparatorW +#include "include/PathCchAddSeparator.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR + +/* + * PathCchRemoveBackslash + */ + +HRESULT PathCchRemoveBackslashA(PSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchRemoveBackslashW(PWSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchAddBackslashEx + */ + +/* Windows-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddBackslashExA +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddBackslashExW +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +/* Unix-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddSlashExA +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddSlashExW +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +/* Native-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddSeparatorExA +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_SEPARATOR_EX PathCchAddSeparatorExW +#include "include/PathCchAddSeparatorEx.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_SEPARATOR_EX + +HRESULT PathCchRemoveBackslashExA(PSTR pszPath, size_t cchPath, PSTR* ppszEnd, + size_t* pcchRemaining) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchRemoveBackslashExW(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd, + size_t* pcchRemaining) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchAddExtension + */ + +/* Windows-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_EXTENSION PathCchAddExtensionA +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define PATH_CCH_ADD_EXTENSION PathCchAddExtensionW +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +/* Unix-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_EXTENSION UnixPathCchAddExtensionA +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define PATH_CCH_ADD_EXTENSION UnixPathCchAddExtensionW +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +/* Native-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_EXTENSION NativePathCchAddExtensionA +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define PATH_CCH_ADD_EXTENSION NativePathCchAddExtensionW +#include "include/PathCchAddExtension.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef PATH_CCH_ADD_EXTENSION + +/* + * PathCchAppend + */ + +/* Windows-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_BACKSLASH_STR +#define PATH_CCH_APPEND PathCchAppendA +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_BACKSLASH_STR_W +#define PATH_CCH_APPEND PathCchAppendW +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +/* Unix-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SLASH_STR +#define PATH_CCH_APPEND UnixPathCchAppendA +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SLASH_STR_W +#define PATH_CCH_APPEND UnixPathCchAppendW +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +/* Native-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SEPARATOR_STR +#define PATH_CCH_APPEND NativePathCchAppendA +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SEPARATOR_STR_W +#define PATH_CCH_APPEND NativePathCchAppendW +#include "include/PathCchAppend.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_CCH_APPEND + +/* + * PathCchAppendEx + */ + +HRESULT PathCchAppendExA(PSTR pszPath, size_t cchPath, PCSTR pszMore, unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchAppendExW(PWSTR pszPath, size_t cchPath, PCWSTR pszMore, unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchCanonicalize + */ + +HRESULT PathCchCanonicalizeA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchCanonicalizeW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchCanonicalizeEx + */ + +HRESULT PathCchCanonicalizeExA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn, + unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchCanonicalizeExW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, + unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathAllocCanonicalize + */ + +HRESULT PathAllocCanonicalizeA(PCSTR pszPathIn, unsigned long dwFlags, PSTR* ppszPathOut) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathAllocCanonicalizeW(PCWSTR pszPathIn, unsigned long dwFlags, PWSTR* ppszPathOut) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchCombine + */ + +HRESULT PathCchCombineA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn, PCSTR pszMore) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchCombineW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathCchCombineEx + */ + +HRESULT PathCchCombineExA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn, PCSTR pszMore, + unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchCombineExW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore, + unsigned long dwFlags) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * PathAllocCombine + */ + +/* Windows-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_BACKSLASH_STR +#define PATH_ALLOC_COMBINE PathAllocCombineA +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_BACKSLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_BACKSLASH_STR_W +#define PATH_ALLOC_COMBINE PathAllocCombineW +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +/* Unix-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SLASH_STR +#define PATH_ALLOC_COMBINE UnixPathAllocCombineA +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SLASH_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SLASH_STR_W +#define PATH_ALLOC_COMBINE UnixPathAllocCombineW +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +/* Native-style Paths */ + +#define DEFINE_UNICODE FALSE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SEPARATOR_STR +#define PATH_ALLOC_COMBINE NativePathAllocCombineA +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +#define DEFINE_UNICODE TRUE +#define CUR_PATH_SEPARATOR_CHR PATH_SEPARATOR_CHR +#define CUR_PATH_SEPARATOR_STR PATH_SEPARATOR_STR_W +#define PATH_ALLOC_COMBINE NativePathAllocCombineW +#include "include/PathAllocCombine.h" +#undef DEFINE_UNICODE +#undef CUR_PATH_SEPARATOR_CHR +#undef CUR_PATH_SEPARATOR_STR +#undef PATH_ALLOC_COMBINE + +/** + * PathCchFindExtension + */ + +HRESULT PathCchFindExtensionA(PCSTR pszPath, size_t cchPath, PCSTR* ppszExt) +{ + const char* p = (const char*)pszPath; + + if (!pszPath || !cchPath || !ppszExt) + return E_INVALIDARG; + + /* find end of string */ + + while (*p && --cchPath) + { + p++; + } + + if (*p) + { + /* pszPath is not null terminated within the cchPath range */ + return E_INVALIDARG; + } + + /* If no extension is found, ppszExt must point to the string's terminating null */ + *ppszExt = p; + + /* search backwards for '.' */ + + while (p > pszPath) + { + if (*p == '.') + { + *ppszExt = (PCSTR)p; + break; + } + + if ((*p == '\\') || (*p == '/') || (*p == ':')) + break; + + p--; + } + + return S_OK; +} + +HRESULT PathCchFindExtensionW(PCWSTR pszPath, size_t cchPath, PCWSTR* ppszExt) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/** + * PathCchRenameExtension + */ + +HRESULT PathCchRenameExtensionA(PSTR pszPath, size_t cchPath, PCSTR pszExt) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchRenameExtensionW(PWSTR pszPath, size_t cchPath, PCWSTR pszExt) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/** + * PathCchRemoveExtension + */ + +HRESULT PathCchRemoveExtensionA(PSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchRemoveExtensionW(PWSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/** + * PathCchIsRoot + */ + +BOOL PathCchIsRootA(PCSTR pszPath) +{ + WLog_ERR(TAG, "not implemented"); + return FALSE; +} + +BOOL PathCchIsRootW(PCWSTR pszPath) +{ + WLog_ERR(TAG, "not implemented"); + return FALSE; +} + +/** + * PathIsUNCEx + */ + +BOOL PathIsUNCExA(PCSTR pszPath, PCSTR* ppszServer) +{ + if (!pszPath) + return FALSE; + + if ((pszPath[0] == '\\') && (pszPath[1] == '\\')) + { + *ppszServer = &pszPath[2]; + return TRUE; + } + + return FALSE; +} + +BOOL PathIsUNCExW(PCWSTR pszPath, PCWSTR* ppszServer) +{ + if (!pszPath) + return FALSE; + + if ((pszPath[0] == '\\') && (pszPath[1] == '\\')) + { + *ppszServer = &pszPath[2]; + return TRUE; + } + + return FALSE; +} + +/** + * PathCchSkipRoot + */ + +HRESULT PathCchSkipRootA(PCSTR pszPath, PCSTR* ppszRootEnd) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchSkipRootW(PCWSTR pszPath, PCWSTR* ppszRootEnd) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/** + * PathCchStripToRoot + */ + +HRESULT PathCchStripToRootA(PSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchStripToRootW(PWSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/** + * PathCchStripPrefix + */ + +HRESULT PathCchStripPrefixA(PSTR pszPath, size_t cchPath) +{ + BOOL hasPrefix = 0; + + if (!pszPath) + return E_INVALIDARG; + + if (cchPath < 4 || cchPath > PATHCCH_MAX_CCH) + return E_INVALIDARG; + + hasPrefix = ((pszPath[0] == '\\') && (pszPath[1] == '\\') && (pszPath[2] == '?') && + (pszPath[3] == '\\')) + ? TRUE + : FALSE; + + if (hasPrefix) + { + if (cchPath < 6) + return S_FALSE; + + if (IsCharAlpha(pszPath[4]) && (pszPath[5] == ':')) /* like C: */ + { + memmove_s(pszPath, cchPath, &pszPath[4], cchPath - 4); + /* since the passed pszPath must not necessarily be null terminated + * and we always have enough space after the strip we can always + * ensure the null termination of the stripped result + */ + pszPath[cchPath - 4] = 0; + return S_OK; + } + } + + return S_FALSE; +} + +HRESULT PathCchStripPrefixW(PWSTR pszPath, size_t cchPath) +{ + BOOL hasPrefix = 0; + + if (!pszPath) + return E_INVALIDARG; + + if (cchPath < 4 || cchPath > PATHCCH_MAX_CCH) + return E_INVALIDARG; + + hasPrefix = ((pszPath[0] == '\\') && (pszPath[1] == '\\') && (pszPath[2] == '?') && + (pszPath[3] == '\\')) + ? TRUE + : FALSE; + + if (hasPrefix) + { + if (cchPath < 6) + return S_FALSE; + + const size_t rc = (_wcslen(&pszPath[4]) + 1); + if (cchPath < rc) + return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + + if (IsCharAlphaW(pszPath[4]) && (pszPath[5] == L':')) /* like C: */ + { + wmemmove_s(pszPath, cchPath, &pszPath[4], cchPath - 4); + /* since the passed pszPath must not necessarily be null terminated + * and we always have enough space after the strip we can always + * ensure the null termination of the stripped result + */ + pszPath[cchPath - 4] = 0; + return S_OK; + } + } + + return S_FALSE; +} + +/** + * PathCchRemoveFileSpec + */ + +HRESULT PathCchRemoveFileSpecA(PSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +HRESULT PathCchRemoveFileSpecW(PWSTR pszPath, size_t cchPath) +{ + WLog_ERR(TAG, "not implemented"); + return E_NOTIMPL; +} + +/* + * Path Portability Functions + */ + +/** + * PathCchConvertStyle + */ + +HRESULT PathCchConvertStyleA(PSTR pszPath, size_t cchPath, unsigned long dwFlags) +{ + if (dwFlags == PATH_STYLE_WINDOWS) + { + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_SLASH_CHR) + pszPath[index] = PATH_BACKSLASH_CHR; + } + } + else if (dwFlags == PATH_STYLE_UNIX) + { + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_BACKSLASH_CHR) + pszPath[index] = PATH_SLASH_CHR; + } + } + else if (dwFlags == PATH_STYLE_NATIVE) + { +#if (PATH_SEPARATOR_CHR == PATH_BACKSLASH_CHR) + /* Unix-style to Windows-style */ + + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_SLASH_CHR) + pszPath[index] = PATH_BACKSLASH_CHR; + } +#elif (PATH_SEPARATOR_CHR == PATH_SLASH_CHR) + /* Windows-style to Unix-style */ + + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_BACKSLASH_CHR) + pszPath[index] = PATH_SLASH_CHR; + } +#else + /* Unexpected error */ + return E_FAIL; +#endif + } + else + { + /* Gangnam style? */ + return E_FAIL; + } + + return S_OK; +} + +HRESULT PathCchConvertStyleW(PWSTR pszPath, size_t cchPath, unsigned long dwFlags) +{ + if (dwFlags == PATH_STYLE_WINDOWS) + { + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_SLASH_CHR) + pszPath[index] = PATH_BACKSLASH_CHR; + } + } + else if (dwFlags == PATH_STYLE_UNIX) + { + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_BACKSLASH_CHR) + pszPath[index] = PATH_SLASH_CHR; + } + } + else if (dwFlags == PATH_STYLE_NATIVE) + { +#if (PATH_SEPARATOR_CHR == PATH_BACKSLASH_CHR) + { + /* Unix-style to Windows-style */ + + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_SLASH_CHR) + pszPath[index] = PATH_BACKSLASH_CHR; + } + } +#elif (PATH_SEPARATOR_CHR == PATH_SLASH_CHR) + { + /* Windows-style to Unix-style */ + + for (size_t index = 0; index < cchPath; index++) + { + if (pszPath[index] == PATH_BACKSLASH_CHR) + pszPath[index] = PATH_SLASH_CHR; + } + } +#else + { + /* Unexpected error */ + return E_FAIL; + } +#endif + } + else + { + /* Gangnam style? */ + return E_FAIL; + } + + return S_OK; +} + +/** + * PathGetSeparator + */ + +char PathGetSeparatorA(unsigned long dwFlags) +{ + char separator = PATH_SEPARATOR_CHR; + + if (!dwFlags) + dwFlags = PATH_STYLE_NATIVE; + + if (dwFlags == PATH_STYLE_WINDOWS) + separator = PATH_SEPARATOR_CHR; + else if (dwFlags == PATH_STYLE_UNIX) + separator = PATH_SEPARATOR_CHR; + else if (dwFlags == PATH_STYLE_NATIVE) + separator = PATH_SEPARATOR_CHR; + + return separator; +} + +WCHAR PathGetSeparatorW(unsigned long dwFlags) +{ + union + { + WCHAR w; + char c[2]; + } cnv; + + cnv.c[0] = PATH_SEPARATOR_CHR; + cnv.c[1] = '\0'; + + if (!dwFlags) + dwFlags = PATH_STYLE_NATIVE; + + if (dwFlags == PATH_STYLE_WINDOWS) + cnv.c[0] = PATH_SEPARATOR_CHR; + else if (dwFlags == PATH_STYLE_UNIX) + cnv.c[0] = PATH_SEPARATOR_CHR; + else if (dwFlags == PATH_STYLE_NATIVE) + cnv.c[0] = PATH_SEPARATOR_CHR; + + return cnv.w; +} + +/** + * PathGetSharedLibraryExtension + */ +static const CHAR SharedLibraryExtensionDllA[] = "dll"; +static const CHAR SharedLibraryExtensionSoA[] = "so"; +static const CHAR SharedLibraryExtensionDylibA[] = "dylib"; + +static const CHAR SharedLibraryExtensionDotDllA[] = ".dll"; +static const CHAR SharedLibraryExtensionDotSoA[] = ".so"; +static const CHAR SharedLibraryExtensionDotDylibA[] = ".dylib"; +PCSTR PathGetSharedLibraryExtensionA(unsigned long dwFlags) +{ + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT) + { + if (dwFlags & PATH_SHARED_LIB_EXT_WITH_DOT) + { + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DLL) + return SharedLibraryExtensionDotDllA; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_SO) + return SharedLibraryExtensionDotSoA; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DYLIB) + return SharedLibraryExtensionDotDylibA; + } + else + { + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DLL) + return SharedLibraryExtensionDllA; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_SO) + return SharedLibraryExtensionSoA; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DYLIB) + return SharedLibraryExtensionDylibA; + } + } + + if (dwFlags & PATH_SHARED_LIB_EXT_WITH_DOT) + { +#ifdef _WIN32 + return SharedLibraryExtensionDotDllA; +#elif defined(__APPLE__) + if (dwFlags & PATH_SHARED_LIB_EXT_APPLE_SO) + return SharedLibraryExtensionDotSoA; + else + return SharedLibraryExtensionDotDylibA; +#else + return SharedLibraryExtensionDotSoA; +#endif + } + else + { +#ifdef _WIN32 + return SharedLibraryExtensionDllA; +#elif defined(__APPLE__) + if (dwFlags & PATH_SHARED_LIB_EXT_APPLE_SO) + return SharedLibraryExtensionSoA; + else + return SharedLibraryExtensionDylibA; +#else + return SharedLibraryExtensionSoA; +#endif + } + + return NULL; +} + +PCWSTR PathGetSharedLibraryExtensionW(unsigned long dwFlags) +{ + static WCHAR buffer[6][16] = { 0 }; + const WCHAR* SharedLibraryExtensionDotDllW = InitializeConstWCharFromUtf8( + SharedLibraryExtensionDotDllA, buffer[0], ARRAYSIZE(buffer[0])); + const WCHAR* SharedLibraryExtensionDotSoW = + InitializeConstWCharFromUtf8(SharedLibraryExtensionDotSoA, buffer[1], ARRAYSIZE(buffer[1])); + const WCHAR* SharedLibraryExtensionDotDylibW = InitializeConstWCharFromUtf8( + SharedLibraryExtensionDotDylibA, buffer[2], ARRAYSIZE(buffer[2])); + const WCHAR* SharedLibraryExtensionDllW = + InitializeConstWCharFromUtf8(SharedLibraryExtensionDllA, buffer[3], ARRAYSIZE(buffer[3])); + const WCHAR* SharedLibraryExtensionSoW = + InitializeConstWCharFromUtf8(SharedLibraryExtensionSoA, buffer[4], ARRAYSIZE(buffer[4])); + const WCHAR* SharedLibraryExtensionDylibW = + InitializeConstWCharFromUtf8(SharedLibraryExtensionDylibA, buffer[5], ARRAYSIZE(buffer[5])); + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT) + { + if (dwFlags & PATH_SHARED_LIB_EXT_WITH_DOT) + { + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DLL) + return SharedLibraryExtensionDotDllW; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_SO) + return SharedLibraryExtensionDotSoW; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DYLIB) + return SharedLibraryExtensionDotDylibW; + } + else + { + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DLL) + return SharedLibraryExtensionDllW; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_SO) + return SharedLibraryExtensionSoW; + + if (dwFlags & PATH_SHARED_LIB_EXT_EXPLICIT_DYLIB) + return SharedLibraryExtensionDylibW; + } + } + + if (dwFlags & PATH_SHARED_LIB_EXT_WITH_DOT) + { +#ifdef _WIN32 + return SharedLibraryExtensionDotDllW; +#elif defined(__APPLE__) + if (dwFlags & PATH_SHARED_LIB_EXT_APPLE_SO) + return SharedLibraryExtensionDotSoW; + else + return SharedLibraryExtensionDotDylibW; +#else + return SharedLibraryExtensionDotSoW; +#endif + } + else + { +#ifdef _WIN32 + return SharedLibraryExtensionDllW; +#elif defined(__APPLE__) + if (dwFlags & PATH_SHARED_LIB_EXT_APPLE_SO) + return SharedLibraryExtensionSoW; + else + return SharedLibraryExtensionDylibW; +#else + return SharedLibraryExtensionSoW; +#endif + } + + return NULL; +} + +const char* GetKnownPathIdString(int id) +{ + switch (id) + { + case KNOWN_PATH_HOME: + return "KNOWN_PATH_HOME"; + case KNOWN_PATH_TEMP: + return "KNOWN_PATH_TEMP"; + case KNOWN_PATH_XDG_DATA_HOME: + return "KNOWN_PATH_XDG_DATA_HOME"; + case KNOWN_PATH_XDG_CONFIG_HOME: + return "KNOWN_PATH_XDG_CONFIG_HOME"; + case KNOWN_PATH_XDG_CACHE_HOME: + return "KNOWN_PATH_XDG_CACHE_HOME"; + case KNOWN_PATH_XDG_RUNTIME_DIR: + return "KNOWN_PATH_XDG_RUNTIME_DIR"; + case KNOWN_PATH_SYSTEM_CONFIG_HOME: + return "KNOWN_PATH_SYSTEM_CONFIG_HOME"; + default: + return "KNOWN_PATH_UNKNOWN_ID"; + } +} + +static WCHAR* concat(const WCHAR* path, size_t pathlen, const WCHAR* name, size_t namelen) +{ + WCHAR* str = calloc(pathlen + namelen + 1, sizeof(WCHAR)); + if (!str) + return NULL; + + _wcsncat(str, path, pathlen); + _wcsncat(str, name, namelen); + return str; +} + +BOOL winpr_RemoveDirectory_RecursiveA(LPCSTR lpPathName) +{ + WCHAR* name = ConvertUtf8ToWCharAlloc(lpPathName, NULL); + if (!name) + return FALSE; + const BOOL rc = winpr_RemoveDirectory_RecursiveW(name); + free(name); + return rc; +} + +BOOL winpr_RemoveDirectory_RecursiveW(LPCWSTR lpPathName) +{ + BOOL ret = FALSE; + + if (!lpPathName) + return FALSE; + + const size_t pathnamelen = _wcslen(lpPathName); + const size_t path_slash_len = pathnamelen + 3; + WCHAR* path_slash = calloc(pathnamelen + 4, sizeof(WCHAR)); + if (!path_slash) + return FALSE; + _wcsncat(path_slash, lpPathName, pathnamelen); + + WCHAR starbuffer[8] = { 0 }; + const WCHAR* star = InitializeConstWCharFromUtf8("*", starbuffer, ARRAYSIZE(starbuffer)); + const HRESULT hr = NativePathCchAppendW(path_slash, path_slash_len, star); + HANDLE dir = INVALID_HANDLE_VALUE; + if (FAILED(hr)) + goto fail; + + WIN32_FIND_DATAW findFileData = { 0 }; + dir = FindFirstFileW(path_slash, &findFileData); + + if (dir == INVALID_HANDLE_VALUE) + goto fail; + + ret = TRUE; + path_slash[path_slash_len - 1] = '\0'; /* remove trailing '*' */ + do + { + const size_t len = _wcsnlen(findFileData.cFileName, ARRAYSIZE(findFileData.cFileName)); + + if ((len == 1 && findFileData.cFileName[0] == '.') || + (len == 2 && findFileData.cFileName[0] == '.' && findFileData.cFileName[1] == '.')) + { + continue; + } + + WCHAR* fullpath = concat(path_slash, path_slash_len, findFileData.cFileName, len); + if (!fullpath) + goto fail; + + if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + ret = winpr_RemoveDirectory_RecursiveW(fullpath); + else + ret = DeleteFileW(fullpath); + + free(fullpath); + + if (!ret) + break; + } while (ret && FindNextFileW(dir, &findFileData) != 0); + + if (ret) + { + if (!RemoveDirectoryW(lpPathName)) + ret = FALSE; + } + +fail: + FindClose(dir); + free(path_slash); + return ret; +} + +char* winpr_GetConfigFilePath(BOOL system, const char* filename) +{ + eKnownPathTypes id = system ? KNOWN_PATH_SYSTEM_CONFIG_HOME : KNOWN_PATH_XDG_CONFIG_HOME; + +#if defined(WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR) + char* vendor = GetKnownSubPath(id, WINPR_VENDOR_STRING); + if (!vendor) + return NULL; +#if defined(WITH_RESOURCE_VERSIONING) + const char* prod = WINPR_PRODUCT_STRING STR(WINPR_VERSION_MAJOR); +#else + const char* prod = WINPR_PRODUCT_STRING; +#endif + char* base = GetCombinedPath(vendor, prod); + free(vendor); +#else + char* base = GetKnownSubPath(id, "winpr"); +#endif + + if (!base) + return NULL; + if (!filename) + return base; + + char* path = GetCombinedPath(base, filename); + free(base); + + return path; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell.c new file mode 100644 index 0000000000000000000000000000000000000000..03edec2422659fd9864a8ad3d98ab4f0a219880e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell.c @@ -0,0 +1,842 @@ +/** + * WinPR: Windows Portable Runtime + * Path Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2016 David PHAM-VAN + * + * 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 +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "../log.h" +#define TAG WINPR_TAG("path.shell") + +#if defined(__IOS__) +#include "shell_ios.h" +#endif + +#if defined(WIN32) +#include +#include +#else +#include +#include +#endif + +static char* GetPath_XDG_CONFIG_HOME(void); +static char* GetPath_XDG_RUNTIME_DIR(void); + +/** + * SHGetKnownFolderPath function: + * http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188/ + */ + +/** + * XDG Base Directory Specification: + * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + */ + +char* GetEnvAlloc(LPCSTR lpName) +{ + DWORD nSize = 0; + DWORD nStatus = 0; + char* env = NULL; + + nSize = GetEnvironmentVariableX(lpName, NULL, 0); + + if (nSize > 0) + { + env = malloc(nSize); + + if (!env) + return NULL; + + nStatus = GetEnvironmentVariableX(lpName, env, nSize); + + if (nStatus != (nSize - 1)) + { + free(env); + return NULL; + } + } + + return env; +} + +static char* GetPath_HOME(void) +{ + char* path = NULL; +#ifdef _WIN32 + path = GetEnvAlloc("UserProfile"); +#elif defined(__IOS__) + path = ios_get_home(); +#else + path = GetEnvAlloc("HOME"); +#endif + return path; +} + +static char* GetPath_TEMP(void) +{ + char* path = NULL; +#ifdef _WIN32 + path = GetEnvAlloc("TEMP"); +#elif defined(__IOS__) + path = ios_get_temp(); +#else + path = GetEnvAlloc("TMPDIR"); + + if (!path) + path = _strdup("/tmp"); + +#endif + return path; +} + +static char* GetPath_XDG_DATA_HOME(void) +{ + char* path = NULL; +#if defined(WIN32) || defined(__IOS__) + path = GetPath_XDG_CONFIG_HOME(); +#else + size_t size = 0; + char* home = NULL; + /** + * There is a single base directory relative to which user-specific data files should be + * written. This directory is defined by the environment variable $XDG_DATA_HOME. + * + * $XDG_DATA_HOME defines the base directory relative to which user specific data files should + * be stored. If $XDG_DATA_HOME is either not set or empty, a default equal to + * $HOME/.local/share should be used. + */ + path = GetEnvAlloc("XDG_DATA_HOME"); + + if (path) + return path; + + home = GetPath_HOME(); + + if (!home) + return NULL; + + size = strlen(home) + strlen("/.local/share") + 1; + path = (char*)malloc(size); + + if (!path) + { + free(home); + return NULL; + } + + (void)sprintf_s(path, size, "%s%s", home, "/.local/share"); + free(home); +#endif + return path; +} + +static char* GetPath_XDG_CONFIG_HOME(void) +{ + char* path = NULL; +#if defined(WIN32) && !defined(_UWP) + path = calloc(MAX_PATH, sizeof(char)); + + if (!path) + return NULL; + + if (FAILED(SHGetFolderPathA(0, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path))) + { + free(path); + return NULL; + } + +#elif defined(__IOS__) + path = ios_get_data(); +#else + size_t size = 0; + char* home = NULL; + /** + * There is a single base directory relative to which user-specific configuration files should + * be written. This directory is defined by the environment variable $XDG_CONFIG_HOME. + * + * $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration + * files should be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to + * $HOME/.config should be used. + */ + path = GetEnvAlloc("XDG_CONFIG_HOME"); + + if (path) + return path; + + home = GetPath_HOME(); + + if (!home) + home = GetPath_TEMP(); + + if (!home) + return NULL; + + size = strlen(home) + strlen("/.config") + 1; + path = (char*)malloc(size); + + if (!path) + { + free(home); + return NULL; + } + + (void)sprintf_s(path, size, "%s%s", home, "/.config"); + free(home); +#endif + return path; +} + +static char* GetPath_SYSTEM_CONFIG_HOME(void) +{ + char* path = NULL; +#if defined(WIN32) && !defined(_UWP) + + WCHAR* wpath = NULL; + if (FAILED(SHGetKnownFolderPath(&FOLDERID_ProgramData, 0, (HANDLE)-1, &wpath))) + return NULL; + + if (wpath) + path = ConvertWCharToUtf8Alloc(wpath, NULL); + CoTaskMemFree(wpath); + +#elif defined(__IOS__) + path = ios_get_data(); +#else + path = _strdup(WINPR_INSTALL_SYSCONFDIR); +#endif + return path; +} + +static char* GetPath_XDG_CACHE_HOME(void) +{ + char* path = NULL; +#if defined(WIN32) + { + char* home = GetPath_XDG_RUNTIME_DIR(); + + if (home) + { + path = GetCombinedPath(home, "cache"); + + if (!winpr_PathFileExists(path)) + if (!CreateDirectoryA(path, NULL)) + path = NULL; + } + + free(home); + } +#elif defined(__IOS__) + path = ios_get_cache(); +#else + size_t size = 0; + /** + * There is a single base directory relative to which user-specific non-essential (cached) data + * should be written. This directory is defined by the environment variable $XDG_CACHE_HOME. + * + * $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data + * files should be stored. If $XDG_CACHE_HOME is either not set or empty, a default equal to + * $HOME/.cache should be used. + */ + path = GetEnvAlloc("XDG_CACHE_HOME"); + + if (path) + return path; + + char* home = GetPath_HOME(); + + if (!home) + return NULL; + + size = strlen(home) + strlen("/.cache") + 1; + path = (char*)malloc(size); + + if (!path) + { + free(home); + return NULL; + } + + (void)sprintf_s(path, size, "%s%s", home, "/.cache"); + free(home); +#endif + return path; +} + +char* GetPath_XDG_RUNTIME_DIR(void) +{ + char* path = NULL; +#if defined(WIN32) && !defined(_UWP) + path = calloc(MAX_PATH, sizeof(char)); + + if (!path) + return NULL; + + if (FAILED(SHGetFolderPathA(0, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path))) + { + free(path); + return NULL; + } + +#else + /** + * There is a single base directory relative to which user-specific runtime files and other file + * objects should be placed. This directory is defined by the environment variable + * $XDG_RUNTIME_DIR. + * + * $XDG_RUNTIME_DIR defines the base directory relative to which user-specific non-essential + * runtime files and other file objects (such as sockets, named pipes, ...) should be stored. + * The directory MUST be owned by the user, and he MUST be the only one having read and write + * access to it. Its Unix access mode MUST be 0700. + * + * The lifetime of the directory MUST be bound to the user being logged in. It MUST be created + * when the user first logs in and if the user fully logs out the directory MUST be removed. If + * the user logs in more than once he should get pointed to the same directory, and it is + * mandatory that the directory continues to exist from his first login to his last logout on + * the system, and not removed in between. Files in the directory MUST not survive reboot or a + * full logout/login cycle. + * + * The directory MUST be on a local file system and not shared with any other system. The + * directory MUST by fully-featured by the standards of the operating system. More specifically, + * on Unix-like operating systems AF_UNIX sockets, symbolic links, hard links, proper + * permissions, file locking, sparse files, memory mapping, file change notifications, a + * reliable hard link count must be supported, and no restrictions on the file name character + * set should be imposed. Files in this directory MAY be subjected to periodic clean-up. To + * ensure that your files are not removed, they should have their access time timestamp modified + * at least once every 6 hours of monotonic time or the 'sticky' bit should be set on the file. + * + * If $XDG_RUNTIME_DIR is not set applications should fall back to a replacement directory with + * similar capabilities and print a warning message. Applications should use this directory for + * communication and synchronization purposes and should not place larger files in it, since it + * might reside in runtime memory and cannot necessarily be swapped out to disk. + */ + path = GetEnvAlloc("XDG_RUNTIME_DIR"); +#endif + + if (path) + return path; + + path = GetPath_TEMP(); + return path; +} + +char* GetKnownPath(eKnownPathTypes id) +{ + char* path = NULL; + + switch (id) + { + case KNOWN_PATH_HOME: + path = GetPath_HOME(); + break; + + case KNOWN_PATH_TEMP: + path = GetPath_TEMP(); + break; + + case KNOWN_PATH_XDG_DATA_HOME: + path = GetPath_XDG_DATA_HOME(); + break; + + case KNOWN_PATH_XDG_CONFIG_HOME: + path = GetPath_XDG_CONFIG_HOME(); + break; + + case KNOWN_PATH_XDG_CACHE_HOME: + path = GetPath_XDG_CACHE_HOME(); + break; + + case KNOWN_PATH_XDG_RUNTIME_DIR: + path = GetPath_XDG_RUNTIME_DIR(); + break; + + case KNOWN_PATH_SYSTEM_CONFIG_HOME: + path = GetPath_SYSTEM_CONFIG_HOME(); + break; + + default: + path = NULL; + break; + } + + if (!path) + WLog_WARN(TAG, "Path %s is %p", GetKnownPathIdString(WINPR_ASSERTING_INT_CAST(int, id)), + path); + return path; +} + +char* GetKnownSubPath(eKnownPathTypes id, const char* path) +{ + char* knownPath = GetKnownPath(id); + if (!knownPath) + return NULL; + + char* subPath = GetCombinedPath(knownPath, path); + free(knownPath); + return subPath; +} + +char* GetEnvironmentPath(char* name) +{ + char* env = NULL; + DWORD nSize = 0; + DWORD nStatus = 0; + nSize = GetEnvironmentVariableX(name, NULL, 0); + + if (nSize) + { + env = (LPSTR)malloc(nSize); + + if (!env) + return NULL; + + nStatus = GetEnvironmentVariableX(name, env, nSize); + + if (nStatus != (nSize - 1)) + { + free(env); + return NULL; + } + } + + return env; +} + +char* GetEnvironmentSubPath(char* name, const char* path) +{ + char* env = NULL; + char* subpath = NULL; + env = GetEnvironmentPath(name); + + if (!env) + return NULL; + + subpath = GetCombinedPath(env, path); + free(env); + return subpath; +} + +char* GetCombinedPath(const char* basePath, const char* subPath) +{ + size_t length = 0; + HRESULT status = 0; + char* path = NULL; + char* subPathCpy = NULL; + size_t basePathLength = 0; + size_t subPathLength = 0; + + if (basePath) + basePathLength = strlen(basePath); + + if (subPath) + subPathLength = strlen(subPath); + + length = basePathLength + subPathLength + 1; + path = (char*)calloc(1, length + 1); + + if (!path) + goto fail; + + if (basePath) + CopyMemory(path, basePath, basePathLength); + + if (FAILED(PathCchConvertStyleA(path, basePathLength, PATH_STYLE_NATIVE))) + goto fail; + + if (!subPath) + return path; + + subPathCpy = _strdup(subPath); + + if (!subPathCpy) + goto fail; + + if (FAILED(PathCchConvertStyleA(subPathCpy, subPathLength, PATH_STYLE_NATIVE))) + goto fail; + + status = NativePathCchAppendA(path, length + 1, subPathCpy); + if (FAILED(status)) + goto fail; + + free(subPathCpy); + return path; + +fail: + free(path); + free(subPathCpy); + return NULL; +} + +BOOL PathMakePathA(LPCSTR path, LPSECURITY_ATTRIBUTES lpAttributes) +{ +#if defined(_UWP) + return FALSE; +#elif defined(_WIN32) + return (SHCreateDirectoryExA(NULL, path, lpAttributes) == ERROR_SUCCESS); +#else + const char delim = PathGetSeparatorA(PATH_STYLE_NATIVE); + char* dup = NULL; + BOOL result = TRUE; + /* we only operate on a non-null, absolute path */ +#if defined(__OS2__) + + if (!path) + return FALSE; + +#else + + if (!path || *path != delim) + return FALSE; + +#endif + + if (!(dup = _strdup(path))) + return FALSE; + +#ifdef __OS2__ + p = (strlen(dup) > 3) && (dup[1] == ':') && (dup[2] == delim)) ? &dup[3] : dup; + + while (p) +#else + for (char* p = dup; p;) +#endif + { + if ((p = strchr(p + 1, delim))) + *p = '\0'; + + if (mkdir(dup, 0777) != 0) + if (errno != EEXIST) + { + result = FALSE; + break; + } + + if (p) + *p = delim; + } + + free(dup); + return (result); +#endif +} + +BOOL PathMakePathW(LPCWSTR path, LPSECURITY_ATTRIBUTES lpAttributes) +{ +#if defined(_UWP) + return FALSE; +#elif defined(_WIN32) + return (SHCreateDirectoryExW(NULL, path, lpAttributes) == ERROR_SUCCESS); +#else + const WCHAR wdelim = PathGetSeparatorW(PATH_STYLE_NATIVE); + const char delim = PathGetSeparatorA(PATH_STYLE_NATIVE); + char* dup = NULL; + BOOL result = TRUE; + /* we only operate on a non-null, absolute path */ +#if defined(__OS2__) + + if (!path) + return FALSE; + +#else + + if (!path || *path != wdelim) + return FALSE; + +#endif + + dup = ConvertWCharToUtf8Alloc(path, NULL); + if (!dup) + return FALSE; + +#ifdef __OS2__ + p = (strlen(dup) > 3) && (dup[1] == ':') && (dup[2] == delim)) ? &dup[3] : dup; + + while (p) +#else + for (char* p = dup; p;) +#endif + { + if ((p = strchr(p + 1, delim))) + *p = '\0'; + + if (mkdir(dup, 0777) != 0) + if (errno != EEXIST) + { + result = FALSE; + break; + } + + if (p) + *p = delim; + } + + free(dup); + return (result); +#endif +} + +#if !defined(_WIN32) || defined(_UWP) + +BOOL PathIsRelativeA(LPCSTR pszPath) +{ + if (!pszPath) + return FALSE; + + return pszPath[0] != '/'; +} + +BOOL PathIsRelativeW(LPCWSTR pszPath) +{ + LPSTR lpFileNameA = NULL; + BOOL ret = FALSE; + + if (!pszPath) + goto fail; + + lpFileNameA = ConvertWCharToUtf8Alloc(pszPath, NULL); + if (!lpFileNameA) + goto fail; + ret = PathIsRelativeA(lpFileNameA); +fail: + free(lpFileNameA); + return ret; +} + +BOOL PathFileExistsA(LPCSTR pszPath) +{ + struct stat stat_info; + + if (stat(pszPath, &stat_info) != 0) + return FALSE; + + return TRUE; +} + +BOOL PathFileExistsW(LPCWSTR pszPath) +{ + LPSTR lpFileNameA = NULL; + BOOL ret = FALSE; + + if (!pszPath) + goto fail; + lpFileNameA = ConvertWCharToUtf8Alloc(pszPath, NULL); + if (!lpFileNameA) + goto fail; + + ret = winpr_PathFileExists(lpFileNameA); +fail: + free(lpFileNameA); + return ret; +} + +BOOL PathIsDirectoryEmptyA(LPCSTR pszPath) +{ + struct dirent* dp = NULL; + int empty = 1; + DIR* dir = opendir(pszPath); + + if (dir == NULL) /* Not a directory or doesn't exist */ + return 1; + + // NOLINTNEXTLINE(concurrency-mt-unsafe) + while ((dp = readdir(dir)) != NULL) + { + if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) + continue; /* Skip . and .. */ + + empty = 0; + break; + } + + closedir(dir); + return empty; +} + +BOOL PathIsDirectoryEmptyW(LPCWSTR pszPath) +{ + LPSTR lpFileNameA = NULL; + BOOL ret = FALSE; + if (!pszPath) + goto fail; + lpFileNameA = ConvertWCharToUtf8Alloc(pszPath, NULL); + if (!lpFileNameA) + goto fail; + ret = PathIsDirectoryEmptyA(lpFileNameA); +fail: + free(lpFileNameA); + return ret; +} + +#endif + +BOOL winpr_MoveFile(LPCSTR lpExistingFileName, LPCSTR lpNewFileName) +{ +#ifndef _WIN32 + return MoveFileA(lpExistingFileName, lpNewFileName); +#else + BOOL result = FALSE; + LPWSTR lpExistingFileNameW = NULL; + LPWSTR lpNewFileNameW = NULL; + + if (!lpExistingFileName || !lpNewFileName) + return FALSE; + + lpExistingFileNameW = ConvertUtf8ToWCharAlloc(lpExistingFileName, NULL); + if (!lpExistingFileNameW) + goto cleanup; + lpNewFileNameW = ConvertUtf8ToWCharAlloc(lpNewFileName, NULL); + if (!lpNewFileNameW) + goto cleanup; + + result = MoveFileW(lpExistingFileNameW, lpNewFileNameW); + +cleanup: + free(lpExistingFileNameW); + free(lpNewFileNameW); + return result; +#endif +} + +BOOL winpr_MoveFileEx(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags) +{ +#ifndef _WIN32 + return MoveFileExA(lpExistingFileName, lpNewFileName, dwFlags); +#else + BOOL result = FALSE; + LPWSTR lpExistingFileNameW = NULL; + LPWSTR lpNewFileNameW = NULL; + + if (!lpExistingFileName || !lpNewFileName) + return FALSE; + + lpExistingFileNameW = ConvertUtf8ToWCharAlloc(lpExistingFileName, NULL); + if (!lpExistingFileNameW) + goto cleanup; + lpNewFileNameW = ConvertUtf8ToWCharAlloc(lpNewFileName, NULL); + if (!lpNewFileNameW) + goto cleanup; + + result = MoveFileExW(lpExistingFileNameW, lpNewFileNameW, dwFlags); + +cleanup: + free(lpExistingFileNameW); + free(lpNewFileNameW); + return result; +#endif +} + +BOOL winpr_DeleteFile(const char* lpFileName) +{ +#ifndef _WIN32 + return DeleteFileA(lpFileName); +#else + LPWSTR lpFileNameW = NULL; + BOOL result = FALSE; + + if (lpFileName) + { + lpFileNameW = ConvertUtf8ToWCharAlloc(lpFileName, NULL); + if (!lpFileNameW) + goto cleanup; + } + + result = DeleteFileW(lpFileNameW); + +cleanup: + free(lpFileNameW); + return result; +#endif +} + +BOOL winpr_RemoveDirectory(LPCSTR lpPathName) +{ +#ifndef _WIN32 + return RemoveDirectoryA(lpPathName); +#else + LPWSTR lpPathNameW = NULL; + BOOL result = FALSE; + + if (lpPathName) + { + lpPathNameW = ConvertUtf8ToWCharAlloc(lpPathName, NULL); + if (!lpPathNameW) + goto cleanup; + } + + result = RemoveDirectoryW(lpPathNameW); + +cleanup: + free(lpPathNameW); + return result; +#endif +} + +BOOL winpr_PathFileExists(const char* pszPath) +{ + if (!pszPath) + return FALSE; +#ifndef _WIN32 + return PathFileExistsA(pszPath); +#else + WCHAR* pathW = ConvertUtf8ToWCharAlloc(pszPath, NULL); + BOOL result = FALSE; + + if (!pathW) + return FALSE; + + result = PathFileExistsW(pathW); + free(pathW); + + return result; +#endif +} + +BOOL winpr_PathMakePath(const char* path, LPSECURITY_ATTRIBUTES lpAttributes) +{ + if (!path) + return FALSE; +#ifndef _WIN32 + return PathMakePathA(path, lpAttributes); +#else + WCHAR* pathW = ConvertUtf8ToWCharAlloc(path, NULL); + BOOL result = FALSE; + + if (!pathW) + return FALSE; + + result = SHCreateDirectoryExW(NULL, pathW, lpAttributes) == ERROR_SUCCESS; + free(pathW); + + return result; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.h new file mode 100644 index 0000000000000000000000000000000000000000..3144d8dd0a4b446c28554c4789df327c0a52bb3a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.h @@ -0,0 +1,9 @@ +#ifndef SHELL_IOS_H_ +#define SHELL_IOS_H_ + +char* ios_get_home(void); +char* ios_get_temp(void); +char* ios_get_data(void); +char* ios_get_cache(void); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.m b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.m new file mode 100644 index 0000000000000000000000000000000000000000..37353df6e53bb9e4d3a444112b4f5cf4136d57fa --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/shell_ios.m @@ -0,0 +1,54 @@ +/** + * WinPR: Windows Portable Runtime + * Path Functions + * + * Copyright 2016 Armin Novak + * Copyright 2016 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. + */ + +#import + +#include + +#include "shell_ios.h" + +static NSString *ios_get_directory_for_search_path(NSSearchPathDirectory searchPath) +{ + return [NSSearchPathForDirectoriesInDomains(searchPath, NSUserDomainMask, YES) lastObject]; +} + +char *ios_get_home(void) +{ + NSString *path = ios_get_directory_for_search_path(NSDocumentDirectory); + return strdup([path UTF8String]); +} + +char *ios_get_temp(void) +{ + NSString *tmp_path = NSTemporaryDirectory(); + return strdup([tmp_path UTF8String]); +} + +char *ios_get_data(void) +{ + NSString *path = ios_get_directory_for_search_path(NSApplicationSupportDirectory); + return strdup([path UTF8String]); +} + +char *ios_get_cache(void) +{ + NSString *path = ios_get_directory_for_search_path(NSCachesDirectory); + return strdup([path UTF8String]); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c552f9f0c56c4af3fa1dad381e2e6101304127bb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/CMakeLists.txt @@ -0,0 +1,48 @@ +set(MODULE_NAME "TestPath") +set(MODULE_PREFIX "TEST_PATH") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS + TestPathCchAddBackslash.c + TestPathCchRemoveBackslash.c + TestPathCchAddBackslashEx.c + TestPathCchRemoveBackslashEx.c + TestPathCchAddExtension.c + TestPathCchAppend.c + TestPathCchAppendEx.c + TestPathCchCanonicalize.c + TestPathCchCanonicalizeEx.c + TestPathAllocCanonicalize.c + TestPathCchCombine.c + TestPathCchCombineEx.c + TestPathAllocCombine.c + TestPathCchFindExtension.c + TestPathCchRenameExtension.c + TestPathCchRemoveExtension.c + TestPathCchIsRoot.c + TestPathIsUNCEx.c + TestPathCchSkipRoot.c + TestPathCchStripToRoot.c + TestPathCchStripPrefix.c + TestPathCchRemoveFileSpec.c + TestPathShell.c + TestPathMakePath.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCanonicalize.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCanonicalize.c new file mode 100644 index 0000000000000000000000000000000000000000..d04fff1eb7733076f11ca0d9687dec45fc0b8395 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCanonicalize.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathAllocCanonicalize(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCombine.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCombine.c new file mode 100644 index 0000000000000000000000000000000000000000..4630df0012461ac9cac7d0f5f0f61e7689a0c763 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathAllocCombine.c @@ -0,0 +1,98 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testBasePathBackslash[] = _T("C:\\Program Files\\"); +static const TCHAR testBasePathNoBackslash[] = _T("C:\\Program Files"); +static const TCHAR testMorePathBackslash[] = _T("\\Microsoft Visual Studio 11.0"); +static const TCHAR testMorePathNoBackslash[] = _T("Microsoft Visual Studio 11.0"); +static const TCHAR testPathOut[] = _T("C:\\Program Files\\Microsoft Visual Studio 11.0"); +static const TCHAR testPathOutMorePathBackslash[] = _T("C:\\Microsoft Visual Studio 11.0"); + +int TestPathAllocCombine(int argc, char* argv[]) +{ + HRESULT status = 0; + LPTSTR PathOut = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Base Path: Backslash, More Path: No Backslash */ + + status = PathAllocCombine(testBasePathBackslash, testMorePathNoBackslash, 0, &PathOut); + + if (status != S_OK) + { + _tprintf(_T("PathAllocCombine status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcscmp(PathOut, testPathOut) != 0) + { + _tprintf(_T("Path Mismatch 1: Actual: %s, Expected: %s\n"), PathOut, testPathOut); + return -1; + } + + free(PathOut); + + /* Base Path: Backslash, More Path: Backslash */ + + status = PathAllocCombine(testBasePathBackslash, testMorePathBackslash, 0, &PathOut); + + if (status != S_OK) + { + _tprintf(_T("PathAllocCombine status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcscmp(PathOut, testPathOutMorePathBackslash) != 0) + { + _tprintf(_T("Path Mismatch 2: Actual: %s, Expected: %s\n"), PathOut, + testPathOutMorePathBackslash); + return -1; + } + + free(PathOut); + + /* Base Path: No Backslash, More Path: Backslash */ + + status = PathAllocCombine(testBasePathNoBackslash, testMorePathBackslash, 0, &PathOut); + + if (status != S_OK) + { + _tprintf(_T("PathAllocCombine status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcscmp(PathOut, testPathOutMorePathBackslash) != 0) + { + _tprintf(_T("Path Mismatch 3: Actual: %s, Expected: %s\n"), PathOut, + testPathOutMorePathBackslash); + return -1; + } + + free(PathOut); + + /* Base Path: No Backslash, More Path: No Backslash */ + + status = PathAllocCombine(testBasePathNoBackslash, testMorePathNoBackslash, 0, &PathOut); + + if (status != S_OK) + { + _tprintf(_T("PathAllocCombine status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcscmp(PathOut, testPathOut) != 0) + { + _tprintf(_T("Path Mismatch 4: Actual: %s, Expected: %s\n"), PathOut, testPathOut); + return -1; + } + + free(PathOut); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslash.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslash.c new file mode 100644 index 0000000000000000000000000000000000000000..55309d63fdfed473c732eaa01316e6681c4e8800 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslash.c @@ -0,0 +1,101 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testPathBackslash[] = _T("C:\\Program Files\\"); +static const TCHAR testPathNoBackslash[] = _T("C:\\Program Files"); + +int TestPathCchAddBackslash(int argc, char* argv[]) +{ + HRESULT status = 0; + TCHAR Path[PATHCCH_MAX_CCH] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /** + * PathCchAddBackslash returns S_OK if the function was successful, + * S_FALSE if the path string already ends in a backslash, + * or an error code otherwise. + */ + + _tcsncpy(Path, testPathNoBackslash, ARRAYSIZE(Path)); + + /* Add a backslash to a path without a trailing backslash, expect S_OK */ + + status = PathCchAddBackslash(Path, PATHCCH_MAX_CCH); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddBackslash status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathBackslash, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathBackslash); + return -1; + } + + /* Add a backslash to a path with a trailing backslash, expect S_FALSE */ + + _tcsncpy(Path, testPathBackslash, ARRAYSIZE(Path)); + + status = PathCchAddBackslash(Path, PATHCCH_MAX_CCH); + + if (status != S_FALSE) + { + _tprintf(_T("PathCchAddBackslash status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathBackslash, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathBackslash); + return -1; + } + + /* Use NULL PSTR, expect FAILED(status) */ + + status = PathCchAddBackslash(NULL, PATHCCH_MAX_CCH); + + if (SUCCEEDED(status)) + { + _tprintf( + _T("PathCchAddBackslash unexpectedly succeeded with null buffer. Status: 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + + /* Use insufficient size value, expect FAILED(status) */ + + _tcsncpy(Path, _T("C:\\tmp"), ARRAYSIZE(Path)); + + status = PathCchAddBackslash(Path, 7); + + if (SUCCEEDED(status)) + { + _tprintf(_T("PathCchAddBackslash unexpectedly succeeded with insufficient buffer size. ") + _T("Status: 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + /* Use minimum required size value, expect S_OK */ + + _tcsncpy(Path, _T("C:\\tmp"), ARRAYSIZE(Path)); + + status = PathCchAddBackslash(Path, 8); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddBackslash failed with status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslashEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslashEx.c new file mode 100644 index 0000000000000000000000000000000000000000..d9d09c49fc5f851c58aa59902125df22949d89fc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddBackslashEx.c @@ -0,0 +1,103 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testPathBackslash[] = _T("C:\\Program Files\\"); +static const TCHAR testPathNoBackslash[] = _T("C:\\Program Files"); + +int TestPathCchAddBackslashEx(int argc, char* argv[]) +{ + HRESULT status = 0; + LPTSTR pszEnd = NULL; + size_t cchRemaining = 0; + TCHAR Path[PATHCCH_MAX_CCH] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /** + * PathCchAddBackslashEx returns S_OK if the function was successful, + * S_FALSE if the path string already ends in a backslash, + * or an error code otherwise. + */ + + _tcsncpy(Path, testPathNoBackslash, ARRAYSIZE(Path)); + + /* Add a backslash to a path without a trailing backslash, expect S_OK */ + + status = PathCchAddBackslashEx(Path, sizeof(Path) / sizeof(TCHAR), &pszEnd, &cchRemaining); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddBackslash status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathBackslash, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathBackslash); + return -1; + } + + /* Add a backslash to a path with a trailing backslash, expect S_FALSE */ + + _tcsncpy(Path, testPathBackslash, ARRAYSIZE(Path)); + + status = PathCchAddBackslashEx(Path, sizeof(Path) / sizeof(TCHAR), &pszEnd, &cchRemaining); + + if (status != S_FALSE) + { + _tprintf(_T("PathCchAddBackslash status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathBackslash, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathBackslash); + return -1; + } + + /* Use NULL PSTR, expect FAILED(status) */ + + status = PathCchAddBackslashEx(NULL, PATHCCH_MAX_CCH, NULL, NULL); + + if (SUCCEEDED(status)) + { + _tprintf( + _T("PathCchAddBackslashEx unexpectedly succeeded with null buffer. Status: 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + + /* Use insufficient size value, expect FAILED(status) */ + + _tcsncpy(Path, _T("C:\\tmp"), ARRAYSIZE(Path)); + + status = PathCchAddBackslashEx(Path, 7, NULL, NULL); + + if (SUCCEEDED(status)) + { + _tprintf(_T("PathCchAddBackslashEx unexpectedly succeeded with insufficient buffer size. ") + _T("Status: 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + /* Use minimum required size value, expect S_OK */ + + _tcsncpy(Path, _T("C:\\tmp"), ARRAYSIZE(Path)); + + status = PathCchAddBackslashEx(Path, 8, NULL, NULL); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddBackslashEx failed with status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddExtension.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddExtension.c new file mode 100644 index 0000000000000000000000000000000000000000..a641dbf00c2d03f629c6e342b19be67042ad63de --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAddExtension.c @@ -0,0 +1,140 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testExtDot[] = _T(".exe"); +static const TCHAR testExtNoDot[] = _T("exe"); +static const TCHAR testPathNoExtension[] = _T("C:\\Windows\\System32\\cmd"); +static const TCHAR testPathExtension[] = _T("C:\\Windows\\System32\\cmd.exe"); + +int TestPathCchAddExtension(int argc, char* argv[]) +{ + HRESULT status = 0; + TCHAR Path[PATHCCH_MAX_CCH] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Path: no extension, Extension: dot */ + + _tcsncpy(Path, testPathNoExtension, ARRAYSIZE(Path)); + + status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddExtension status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathExtension, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); + return -1; + } + + /* Path: no extension, Extension: no dot */ + + _tcsncpy(Path, testPathNoExtension, ARRAYSIZE(Path)); + + status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtNoDot); + + if (status != S_OK) + { + _tprintf(_T("PathCchAddExtension status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathExtension, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); + return -1; + } + + /* Path: extension, Extension: dot */ + + _tcsncpy(Path, testPathExtension, ARRAYSIZE(Path)); + + status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); + + if (status != S_FALSE) + { + _tprintf(_T("PathCchAddExtension status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathExtension, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); + return -1; + } + + /* Path: extension, Extension: no dot */ + + _tcsncpy(Path, testPathExtension, ARRAYSIZE(Path)); + + status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); + + if (status != S_FALSE) + { + _tprintf(_T("PathCchAddExtension status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathExtension, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); + return -1; + } + + /* Path: NULL */ + + status = PathCchAddExtension(NULL, PATHCCH_MAX_CCH, testExtDot); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAddExtension with null buffer returned status: 0x%08") _T( + PRIX32) _T(" (expected E_INVALIDARG)\n"), + status); + return -1; + } + + /* Extension: NULL */ + + status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, NULL); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAddExtension with null extension returned status: 0x%08") _T( + PRIX32) _T(" (expected E_INVALIDARG)\n"), + status); + return -1; + } + + /* Insufficient Buffer size */ + + _tcsncpy(Path, _T("C:\\456789"), ARRAYSIZE(Path)); + status = PathCchAddExtension(Path, 9 + 4, _T(".jpg")); + if (SUCCEEDED(status)) + { + _tprintf(_T("PathCchAddExtension with insufficient buffer unexpectedly succeeded with ") + _T("status: 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + /* Minimum required buffer size */ + + _tcsncpy(Path, _T("C:\\456789"), ARRAYSIZE(Path)); + status = PathCchAddExtension(Path, 9 + 4 + 1, _T(".jpg")); + if (FAILED(status)) + { + _tprintf(_T("PathCchAddExtension with sufficient buffer unexpectedly failed with status: ") + _T("0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppend.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppend.c new file mode 100644 index 0000000000000000000000000000000000000000..bd47b1dce6cea78492228756d20319e8fbdb0c2b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppend.c @@ -0,0 +1,151 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testBasePathBackslash[] = _T("C:\\Program Files\\"); +static const TCHAR testBasePathNoBackslash[] = _T("C:\\Program Files"); +static const TCHAR testMorePathBackslash[] = _T("\\Microsoft Visual Studio 11.0"); +static const TCHAR testMorePathNoBackslash[] = _T("Microsoft Visual Studio 11.0"); +static const TCHAR testPathOut[] = _T("C:\\Program Files\\Microsoft Visual Studio 11.0"); + +int TestPathCchAppend(int argc, char* argv[]) +{ + HRESULT status = 0; + TCHAR Path[PATHCCH_MAX_CCH]; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Base Path: Backslash, More Path: No Backslash */ + + _tcsncpy(Path, testBasePathBackslash, ARRAYSIZE(Path)); + + status = PathCchAppend(Path, PATHCCH_MAX_CCH, testMorePathNoBackslash); + + if (status != S_OK) + { + _tprintf(_T("PathCchAppend status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathOut, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathOut); + return -1; + } + + /* Base Path: Backslash, More Path: Backslash */ + + _tcsncpy(Path, testBasePathBackslash, ARRAYSIZE(Path)); + + status = PathCchAppend(Path, PATHCCH_MAX_CCH, testMorePathBackslash); + + if (status != S_OK) + { + _tprintf(_T("PathCchAppend status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathOut, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathOut); + return -1; + } + + /* Base Path: No Backslash, More Path: Backslash */ + + _tcsncpy(Path, testBasePathNoBackslash, ARRAYSIZE(Path)); + + status = PathCchAppend(Path, PATHCCH_MAX_CCH, testMorePathBackslash); + + if (status != S_OK) + { + _tprintf(_T("PathCchAppend status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathOut, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathOut); + return -1; + } + + /* Base Path: No Backslash, More Path: No Backslash */ + + _tcsncpy(Path, testBasePathNoBackslash, ARRAYSIZE(Path)); + + status = PathCchAppend(Path, PATHCCH_MAX_CCH, testMorePathNoBackslash); + + if (status != S_OK) + { + _tprintf(_T("PathCchAppend status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathOut, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathOut); + return -1; + } + + /* According to msdn a NULL Path is an invalid argument */ + status = PathCchAppend(NULL, PATHCCH_MAX_CCH, testMorePathNoBackslash); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAppend with NULL path unexpectedly returned status: 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + + /* According to msdn a NULL pszMore is an invalid argument (although optional !?) */ + _tcsncpy(Path, testBasePathNoBackslash, ARRAYSIZE(Path)); + status = PathCchAppend(Path, PATHCCH_MAX_CCH, NULL); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAppend with NULL pszMore unexpectedly returned status: 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + + /* According to msdn cchPath must be > 0 and <= PATHCCH_MAX_CCH */ + _tcsncpy(Path, testBasePathNoBackslash, ARRAYSIZE(Path)); + status = PathCchAppend(Path, 0, testMorePathNoBackslash); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAppend with cchPath value 0 unexpectedly returned status: 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + _tcsncpy(Path, testBasePathNoBackslash, ARRAYSIZE(Path)); + status = PathCchAppend(Path, PATHCCH_MAX_CCH + 1, testMorePathNoBackslash); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchAppend with cchPath value > PATHCCH_MAX_CCH unexpectedly returned ") + _T("status: 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + /* Resulting file must not exceed PATHCCH_MAX_CCH */ + + for (size_t i = 0; i < PATHCCH_MAX_CCH - 1; i++) + Path[i] = _T('X'); + + Path[PATHCCH_MAX_CCH - 1] = 0; + + status = PathCchAppend(Path, PATHCCH_MAX_CCH, _T("\\This cannot be appended to Path")); + if (SUCCEEDED(status)) + { + _tprintf(_T("PathCchAppend unexpectedly succeeded with status: 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppendEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppendEx.c new file mode 100644 index 0000000000000000000000000000000000000000..b6d83f5b739f93835f06dc309f3331146dee52ee --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchAppendEx.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchAppendEx(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalize.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalize.c new file mode 100644 index 0000000000000000000000000000000000000000..a7fa4ce4d24acbdb1d7f86582d81a32022b6db96 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalize.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchCanonicalize(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalizeEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalizeEx.c new file mode 100644 index 0000000000000000000000000000000000000000..2d670eb0b99a19b767436c2eb93a16444676a448 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCanonicalizeEx.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchCanonicalizeEx(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombine.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombine.c new file mode 100644 index 0000000000000000000000000000000000000000..4b6f4e487f284b1b0183b8d003a721ee96f0e9f8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombine.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchCombine(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombineEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombineEx.c new file mode 100644 index 0000000000000000000000000000000000000000..89b794f6f92852fc37d64f2edbb468ea036054bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchCombineEx.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchCombineEx(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchFindExtension.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchFindExtension.c new file mode 100644 index 0000000000000000000000000000000000000000..5478b019603de1f2d94fa4239219ef667a572d45 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchFindExtension.c @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include + +static const char testPathExtension[] = "C:\\Windows\\System32\\cmd.exe"; + +int TestPathCchFindExtension(int argc, char* argv[]) +{ + PCSTR pszExt = NULL; + PCSTR pszTmp = NULL; + HRESULT hr = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Test invalid args */ + + hr = PathCchFindExtensionA(NULL, sizeof(testPathExtension), &pszExt); + if (SUCCEEDED(hr)) + { + printf( + "PathCchFindExtensionA unexpectedly succeeded with pszPath = NULL. result: 0x%08" PRIX32 + "\n", + hr); + return -1; + } + + hr = PathCchFindExtensionA(testPathExtension, 0, &pszExt); + if (SUCCEEDED(hr)) + { + printf("PathCchFindExtensionA unexpectedly succeeded with cchPath = 0. result: 0x%08" PRIX32 + "\n", + hr); + return -1; + } + + hr = PathCchFindExtensionA(testPathExtension, sizeof(testPathExtension), NULL); + if (SUCCEEDED(hr)) + { + printf( + "PathCchFindExtensionA unexpectedly succeeded with ppszExt = NULL. result: 0x%08" PRIX32 + "\n", + hr); + return -1; + } + + /* Test missing null-termination of pszPath */ + + hr = PathCchFindExtensionA("c:\\45.789", 9, &pszExt); /* nb: correct would be 10 */ + if (SUCCEEDED(hr)) + { + printf("PathCchFindExtensionA unexpectedly succeeded with unterminated pszPath. result: " + "0x%08" PRIX32 "\n", + hr); + return -1; + } + + /* Test passing of an empty terminated string (must succeed) */ + + pszExt = NULL; + pszTmp = ""; + hr = PathCchFindExtensionA(pszTmp, 1, &pszExt); + if (hr != S_OK) + { + printf("PathCchFindExtensionA failed with an empty terminated string. result: 0x%08" PRIX32 + "\n", + hr); + return -1; + } + /* pszExt must point to the strings terminating 0 now */ + if (pszExt != pszTmp) + { + printf("PathCchFindExtensionA failed with an empty terminated string: pszExt pointer " + "mismatch\n"); + return -1; + } + + /* Test a path without file extension (must succeed) */ + + pszExt = NULL; + pszTmp = "c:\\4.678\\"; + hr = PathCchFindExtensionA(pszTmp, 10, &pszExt); + if (hr != S_OK) + { + printf("PathCchFindExtensionA failed with a directory path. result: 0x%08" PRIX32 "\n", hr); + return -1; + } + /* The extension must not have been found and pszExt must point to the + * strings terminating NULL now */ + if (pszExt != &pszTmp[9]) + { + printf("PathCchFindExtensionA failed with a directory path: pszExt pointer mismatch\n"); + return -1; + } + + /* Non-special tests */ + + pszExt = NULL; + if (PathCchFindExtensionA(testPathExtension, sizeof(testPathExtension), &pszExt) != S_OK) + { + printf("PathCchFindExtensionA failure: expected S_OK\n"); + return -1; + } + + if (!pszExt || strcmp(pszExt, ".exe") != 0) + { + printf("PathCchFindExtensionA failure: unexpected extension\n"); + return -1; + } + + printf("Extension: %s\n", pszExt); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchIsRoot.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchIsRoot.c new file mode 100644 index 0000000000000000000000000000000000000000..1ffda378b5e28b1d37c64e71faa22f69cacd0c6b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchIsRoot.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchIsRoot(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslash.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslash.c new file mode 100644 index 0000000000000000000000000000000000000000..f23e72b98a04a8558f5845db256a28a94704fbd3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslash.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchRemoveBackslash(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslashEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslashEx.c new file mode 100644 index 0000000000000000000000000000000000000000..80eb1aadfb19670e3a05dc61804e6d69b427b5c6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveBackslashEx.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchRemoveBackslashEx(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveExtension.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveExtension.c new file mode 100644 index 0000000000000000000000000000000000000000..bd315cbd476c755204a9fe4b0a2ea5de47424f90 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveExtension.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchRemoveExtension(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveFileSpec.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveFileSpec.c new file mode 100644 index 0000000000000000000000000000000000000000..686e3675003de06043ad6f9bf4c55a359634ed20 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRemoveFileSpec.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchRemoveFileSpec(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRenameExtension.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRenameExtension.c new file mode 100644 index 0000000000000000000000000000000000000000..cf021b134fd5a0085f973a08097da0970529f0f2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchRenameExtension.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchRenameExtension(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchSkipRoot.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchSkipRoot.c new file mode 100644 index 0000000000000000000000000000000000000000..dca5ad97169a48b62d9e251fbf8c50de8a192c81 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchSkipRoot.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchSkipRoot(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripPrefix.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripPrefix.c new file mode 100644 index 0000000000000000000000000000000000000000..b2b7d5d069cd060b627bb2d5a3c0cb66d2d0b01c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripPrefix.c @@ -0,0 +1,128 @@ + +#include +#include +#include +#include +#include + +/** + * Naming Files, Paths, and Namespaces: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247/ + */ + +static const TCHAR testPathPrefixFileNamespace[] = _T("\\\\?\\C:\\Program Files\\"); +static const TCHAR testPathNoPrefixFileNamespace[] = _T("C:\\Program Files\\"); +static const TCHAR testPathPrefixFileNamespaceMinimum[] = _T("\\\\?\\C:"); +static const TCHAR testPathNoPrefixFileNamespaceMinimum[] = _T("C:"); + +static const TCHAR testPathPrefixDeviceNamespace[] = _T("\\\\?\\GLOBALROOT"); + +int TestPathCchStripPrefix(int argc, char* argv[]) +{ + HRESULT status = 0; + TCHAR Path[PATHCCH_MAX_CCH] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /** + * PathCchStripPrefix returns S_OK if the prefix was removed, S_FALSE if + * the path did not have a prefix to remove, or an HRESULT failure code. + */ + + /* Path with prefix (File Namespace) */ + + _tcsncpy(Path, testPathPrefixFileNamespace, ARRAYSIZE(Path)); + + status = PathCchStripPrefix(Path, sizeof(testPathPrefixFileNamespace) / sizeof(TCHAR)); + + if (status != S_OK) + { + _tprintf(_T("PathCchStripPrefix status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathNoPrefixFileNamespace, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, + testPathNoPrefixFileNamespace); + return -1; + } + + /* Path with prefix (Device Namespace) */ + + _tcsncpy(Path, testPathPrefixDeviceNamespace, ARRAYSIZE(Path)); + + status = PathCchStripPrefix(Path, ARRAYSIZE(testPathPrefixDeviceNamespace)); + + if (status != S_FALSE) + { + _tprintf(_T("PathCchStripPrefix status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + if (_tcsncmp(Path, testPathPrefixDeviceNamespace, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, + testPathPrefixDeviceNamespace); + return -1; + } + + /* NULL Path */ + status = PathCchStripPrefix(NULL, PATHCCH_MAX_CCH); + if (status != E_INVALIDARG) + { + _tprintf( + _T("PathCchStripPrefix with null path unexpectedly succeeded with status 0x%08") _T( + PRIX32) _T("\n"), + status); + return -1; + } + + /* Invalid cchPath values: 0, 1, 2, 3 and > PATHCCH_MAX_CCH */ + for (int i = 0; i < 5; i++) + { + _tcsncpy(Path, testPathPrefixFileNamespace, ARRAYSIZE(Path)); + if (i == 4) + i = PATHCCH_MAX_CCH + 1; + status = PathCchStripPrefix(Path, i); + if (status != E_INVALIDARG) + { + _tprintf(_T("PathCchStripPrefix with invalid cchPath value %d unexpectedly succeeded ") + _T("with status 0x%08") _T(PRIX32) _T("\n"), + i, status); + return -1; + } + } + + /* Minimum Path that would get successfully stripped on windows */ + _tcsncpy(Path, testPathPrefixFileNamespaceMinimum, ARRAYSIZE(Path)); + size_t i = ARRAYSIZE(testPathPrefixFileNamespaceMinimum); + i = i - 1; /* include testing of a non-null terminated string */ + status = PathCchStripPrefix(Path, i); + if (status != S_OK) + { + _tprintf(_T("PathCchStripPrefix with minimum valid strippable path length unexpectedly ") + _T("returned status 0x%08") _T(PRIX32) _T("\n"), + status); + return -1; + } + if (_tcsncmp(Path, testPathNoPrefixFileNamespaceMinimum, ARRAYSIZE(Path)) != 0) + { + _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, + testPathNoPrefixFileNamespaceMinimum); + return -1; + } + + /* Invalid drive letter symbol */ + _tcsncpy(Path, _T("\\\\?\\5:"), ARRAYSIZE(Path)); + status = PathCchStripPrefix(Path, 6); + if (status == S_OK) + { + _tprintf( + _T("PathCchStripPrefix with invalid drive letter symbol unexpectedly succeeded\n")); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripToRoot.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripToRoot.c new file mode 100644 index 0000000000000000000000000000000000000000..3b96e5c168da3eb0d15fc420e58d1d7a5da82a14 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathCchStripToRoot.c @@ -0,0 +1,12 @@ + +#include +#include +#include +#include +#include + +int TestPathCchStripToRoot(int argc, char* argv[]) +{ + printf("Warning: %s is not implemented!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathIsUNCEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathIsUNCEx.c new file mode 100644 index 0000000000000000000000000000000000000000..a2edc51691e24f95dec68bb0319a7838af6afdad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathIsUNCEx.c @@ -0,0 +1,52 @@ + +#include +#include +#include +#include +#include + +static const TCHAR testServer[] = _T("server\\share\\path\\file"); +static const TCHAR testPathUNC[] = _T("\\\\server\\share\\path\\file"); +static const TCHAR testPathNotUNC[] = _T("C:\\share\\path\\file"); + +int TestPathIsUNCEx(int argc, char* argv[]) +{ + BOOL status = 0; + LPCTSTR Server = NULL; + TCHAR Path[PATHCCH_MAX_CCH] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* Path is UNC */ + + _tcsncpy(Path, testPathUNC, ARRAYSIZE(Path)); + + status = PathIsUNCEx(Path, &Server); + + if (!status) + { + _tprintf(_T("PathIsUNCEx status: 0x%d\n"), status); + return -1; + } + + if (_tcsncmp(Server, testServer, ARRAYSIZE(testServer)) != 0) + { + _tprintf(_T("Server Name Mismatch: Actual: %s, Expected: %s\n"), Server, testServer); + return -1; + } + + /* Path is not UNC */ + + _tcsncpy(Path, testPathNotUNC, ARRAYSIZE(Path)); + + status = PathIsUNCEx(Path, &Server); + + if (status) + { + _tprintf(_T("PathIsUNCEx status: 0x%08") _T(PRIX32) _T("\n"), status); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathMakePath.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathMakePath.c new file mode 100644 index 0000000000000000000000000000000000000000..36fbaaf05326be5def6adc4d393931c18bc1c0b7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathMakePath.c @@ -0,0 +1,92 @@ +#include +#include +#include + +#include +#include +#include +#include + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +int TestPathMakePath(int argc, char* argv[]) +{ + size_t baseLen = 0; + BOOL success = 0; + char tmp[64] = { 0 }; + char* path = NULL; + char* cur = NULL; + char delim = PathGetSeparatorA(0); + char* base = GetKnownPath(KNOWN_PATH_TEMP); + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!base) + { + (void)fprintf(stderr, "Failed to get temporary directory!\n"); + return -1; + } + + baseLen = strlen(base); + + for (int x = 0; x < 5; x++) + { + (void)sprintf_s(tmp, ARRAYSIZE(tmp), "%08" PRIX32, prand(UINT32_MAX)); + path = GetCombinedPath(base, tmp); + free(base); + + if (!path) + { + (void)fprintf(stderr, "GetCombinedPath failed!\n"); + return -1; + } + + base = path; + } + + printf("Creating path %s\n", path); + success = winpr_PathMakePath(path, NULL); + + if (!success) + { + (void)fprintf(stderr, "MakePath failed!\n"); + free(path); + return -1; + } + + success = winpr_PathFileExists(path); + + if (!success) + { + (void)fprintf(stderr, "MakePath lied about success!\n"); + free(path); + return -1; + } + + while (strlen(path) > baseLen) + { + if (!winpr_RemoveDirectory(path)) + { + (void)fprintf(stderr, "winpr_RemoveDirectory %s failed!\n", path); + free(path); + return -1; + } + + cur = strrchr(path, delim); + + if (cur) + *cur = '\0'; + } + + free(path); + printf("%s success!\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathShell.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathShell.c new file mode 100644 index 0000000000000000000000000000000000000000..87af3f2eb4f47f402779f1d830cc463ddabd203f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/path/test/TestPathShell.c @@ -0,0 +1,58 @@ + +#include +#include +#include +#include +#include + +int TestPathShell(int argc, char* argv[]) +{ + const int paths[] = { KNOWN_PATH_HOME, KNOWN_PATH_TEMP, + KNOWN_PATH_XDG_DATA_HOME, KNOWN_PATH_XDG_CONFIG_HOME, + KNOWN_PATH_XDG_CACHE_HOME, KNOWN_PATH_XDG_RUNTIME_DIR, + KNOWN_PATH_XDG_CONFIG_HOME }; + const char* names[] = { "KNOWN_PATH_HOME", "KNOWN_PATH_TEMP", + "KNOWN_PATH_XDG_DATA_HOME", "KNOWN_PATH_XDG_CONFIG_HOME", + "KNOWN_PATH_XDG_CACHE_HOME", "KNOWN_PATH_XDG_RUNTIME_DIR", + "KNOWN_PATH_XDG_CONFIG_HOME" }; + int rc = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + for (size_t x = 0; x < sizeof(paths) / sizeof(paths[0]); x++) + { + const int id = paths[x]; + const char* name = names[x]; + { + char* path = GetKnownPath(id); + + if (!path) + { + (void)fprintf(stderr, "GetKnownPath(%d) failed\n", id); + rc = -1; + } + else + { + printf("%s Path: %s\n", name, path); + } + free(path); + } + { + char* path = GetKnownSubPath(id, "freerdp"); + + if (!path) + { + (void)fprintf(stderr, "GetKnownSubPath(%d) failed\n", id); + rc = -1; + } + else + { + printf("%s SubPath: %s\n", name, path); + } + free(path); + } + } + + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c363912236bb6d30ad71f44bf6ef86d378f17d61 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-pipe cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(pipe.c pipe.h) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..731f49de2f38429aa44ec0dd721b9a32a79820bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "namedpipe") +set(MINWIN_LONG_NAME "Named Pipe Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..f1f76cb2eb6ffc1750c00a5c036b31595174d5bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.c @@ -0,0 +1,934 @@ +/** + * WinPR: Windows Portable Runtime + * Pipe Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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 + +#include +#include +#include +#include + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifndef _WIN32 + +#include "../handle/handle.h" + +#include +#include +#include +#include +#include + +#ifdef WINPR_HAVE_SYS_AIO_H +#undef WINPR_HAVE_SYS_AIO_H /* disable for now, incomplete */ +#endif + +#ifdef WINPR_HAVE_SYS_AIO_H +#include +#endif + +#include "pipe.h" + +#include "../log.h" +#define TAG WINPR_TAG("pipe") + +/* + * Since the WinPR implementation of named pipes makes use of UNIX domain + * sockets, it is not possible to bind the same name more than once (i.e., + * SO_REUSEADDR does not work with UNIX domain sockets). As a result, the + * first call to CreateNamedPipe with name n creates a "shared" UNIX domain + * socket descriptor that gets duplicated via dup() for the first and all + * subsequent calls to CreateNamedPipe with name n. + * + * The following array keeps track of the references to the shared socked + * descriptors. If an entry's reference count is zero the base socket + * descriptor gets closed and the entry is removed from the list. + */ + +static wArrayList* g_NamedPipeServerSockets = NULL; + +typedef struct +{ + char* name; + int serverfd; + int references; +} NamedPipeServerSocketEntry; + +static BOOL PipeIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_ANONYMOUS_PIPE, FALSE); +} + +static int PipeGetFd(HANDLE handle) +{ + WINPR_PIPE* pipe = (WINPR_PIPE*)handle; + + if (!PipeIsHandled(handle)) + return -1; + + return pipe->fd; +} + +static BOOL PipeCloseHandle(HANDLE handle) +{ + WINPR_PIPE* pipe = (WINPR_PIPE*)handle; + + if (!PipeIsHandled(handle)) + return FALSE; + + if (pipe->fd != -1) + { + close(pipe->fd); + pipe->fd = -1; + } + + free(handle); + return TRUE; +} + +static BOOL PipeRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) +{ + SSIZE_T io_status = 0; + WINPR_PIPE* pipe = NULL; + BOOL status = TRUE; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + pipe = (WINPR_PIPE*)Object; + + do + { + io_status = read(pipe->fd, lpBuffer, nNumberOfBytesToRead); + } while ((io_status < 0) && (errno == EINTR)); + + if (io_status < 0) + { + status = FALSE; + + switch (errno) + { + case EWOULDBLOCK: + SetLastError(ERROR_NO_DATA); + break; + default: + break; + } + } + + if (lpNumberOfBytesRead) + *lpNumberOfBytesRead = (DWORD)io_status; + + return status; +} + +static BOOL PipeWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) +{ + SSIZE_T io_status = 0; + WINPR_PIPE* pipe = NULL; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + pipe = (WINPR_PIPE*)Object; + + do + { + io_status = write(pipe->fd, lpBuffer, nNumberOfBytesToWrite); + } while ((io_status < 0) && (errno == EINTR)); + + if ((io_status < 0) && (errno == EWOULDBLOCK)) + io_status = 0; + + *lpNumberOfBytesWritten = (DWORD)io_status; + return TRUE; +} + +static HANDLE_OPS ops = { PipeIsHandled, + PipeCloseHandle, + PipeGetFd, + NULL, /* CleanupHandle */ + PipeRead, + NULL, /* FileReadEx */ + NULL, /* FileReadScatter */ + PipeWrite, + NULL, /* FileWriteEx */ + NULL, /* FileWriteGather */ + NULL, /* FileGetFileSize */ + NULL, /* FlushFileBuffers */ + NULL, /* FileSetEndOfFile */ + NULL, /* FileSetFilePointer */ + NULL, /* SetFilePointerEx */ + NULL, /* FileLockFile */ + NULL, /* FileLockFileEx */ + NULL, /* FileUnlockFile */ + NULL, /* FileUnlockFileEx */ + NULL /* SetFileTime */ + , + NULL }; + +static BOOL NamedPipeIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_NAMED_PIPE, TRUE); +} + +static int NamedPipeGetFd(HANDLE handle) +{ + WINPR_NAMED_PIPE* pipe = (WINPR_NAMED_PIPE*)handle; + + if (!NamedPipeIsHandled(handle)) + return -1; + + if (pipe->ServerMode) + return pipe->serverfd; + + return pipe->clientfd; +} + +static BOOL NamedPipeCloseHandle(HANDLE handle) +{ + WINPR_NAMED_PIPE* pNamedPipe = (WINPR_NAMED_PIPE*)handle; + + /* This check confuses the analyzer. Since not all handle + * types are handled here, it guesses that the memory of a + * NamedPipeHandle may leak. */ +#ifndef __clang_analyzer__ + if (!NamedPipeIsHandled(handle)) + return FALSE; +#endif + + if (pNamedPipe->pfnUnrefNamedPipe) + pNamedPipe->pfnUnrefNamedPipe(pNamedPipe); + + free(pNamedPipe->name); + free(pNamedPipe->lpFileName); + free(pNamedPipe->lpFilePath); + + if (pNamedPipe->serverfd != -1) + close(pNamedPipe->serverfd); + + if (pNamedPipe->clientfd != -1) + close(pNamedPipe->clientfd); + + free(pNamedPipe); + return TRUE; +} + +BOOL NamedPipeRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) +{ + SSIZE_T io_status = 0; + WINPR_NAMED_PIPE* pipe = NULL; + BOOL status = TRUE; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + pipe = (WINPR_NAMED_PIPE*)Object; + + if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) + { + if (pipe->clientfd == -1) + return FALSE; + + do + { + io_status = read(pipe->clientfd, lpBuffer, nNumberOfBytesToRead); + } while ((io_status < 0) && (errno == EINTR)); + + if (io_status == 0) + { + SetLastError(ERROR_BROKEN_PIPE); + status = FALSE; + } + else if (io_status < 0) + { + status = FALSE; + + switch (errno) + { + case EWOULDBLOCK: + SetLastError(ERROR_NO_DATA); + break; + + default: + SetLastError(ERROR_BROKEN_PIPE); + break; + } + } + + if (lpNumberOfBytesRead) + *lpNumberOfBytesRead = (DWORD)io_status; + } + else + { + /* Overlapped I/O */ + if (!lpOverlapped) + return FALSE; + + if (pipe->clientfd == -1) + return FALSE; + + pipe->lpOverlapped = lpOverlapped; +#ifdef WINPR_HAVE_SYS_AIO_H + { + int aio_status; + struct aiocb cb = { 0 }; + + cb.aio_fildes = pipe->clientfd; + cb.aio_buf = lpBuffer; + cb.aio_nbytes = nNumberOfBytesToRead; + cb.aio_offset = lpOverlapped->Offset; + cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; + cb.aio_sigevent.sigev_signo = SIGIO; + cb.aio_sigevent.sigev_value.sival_ptr = (void*)lpOverlapped; + InstallAioSignalHandler(); + aio_status = aio_read(&cb); + WLog_DBG(TAG, "aio_read status: %d", aio_status); + + if (aio_status < 0) + status = FALSE; + + return status; + } +#else + /* synchronous behavior */ + lpOverlapped->Internal = 0; + lpOverlapped->InternalHigh = (ULONG_PTR)nNumberOfBytesToRead; + lpOverlapped->DUMMYUNIONNAME.Pointer = (PVOID)lpBuffer; + (void)SetEvent(lpOverlapped->hEvent); +#endif + } + + return status; +} + +BOOL NamedPipeWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) +{ + SSIZE_T io_status = 0; + WINPR_NAMED_PIPE* pipe = NULL; + BOOL status = TRUE; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + pipe = (WINPR_NAMED_PIPE*)Object; + + if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) + { + if (pipe->clientfd == -1) + return FALSE; + + do + { + io_status = write(pipe->clientfd, lpBuffer, nNumberOfBytesToWrite); + } while ((io_status < 0) && (errno == EINTR)); + + if (io_status < 0) + { + *lpNumberOfBytesWritten = 0; + + switch (errno) + { + case EWOULDBLOCK: + io_status = 0; + status = TRUE; + break; + + default: + status = FALSE; + } + } + + *lpNumberOfBytesWritten = (DWORD)io_status; + return status; + } + else + { + /* Overlapped I/O */ + if (!lpOverlapped) + return FALSE; + + if (pipe->clientfd == -1) + return FALSE; + + pipe->lpOverlapped = lpOverlapped; +#ifdef WINPR_HAVE_SYS_AIO_H + { + struct aiocb cb = { 0 }; + + cb.aio_fildes = pipe->clientfd; + cb.aio_buf = (void*)lpBuffer; + cb.aio_nbytes = nNumberOfBytesToWrite; + cb.aio_offset = lpOverlapped->Offset; + cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; + cb.aio_sigevent.sigev_signo = SIGIO; + cb.aio_sigevent.sigev_value.sival_ptr = (void*)lpOverlapped; + InstallAioSignalHandler(); + io_status = aio_write(&cb); + WLog_DBG("aio_write status: %" PRIdz, io_status); + + if (io_status < 0) + status = FALSE; + + return status; + } +#else + /* synchronous behavior */ + lpOverlapped->Internal = 1; + lpOverlapped->InternalHigh = (ULONG_PTR)nNumberOfBytesToWrite; + { + union + { + LPCVOID cpv; + PVOID pv; + } cnv; + cnv.cpv = lpBuffer; + lpOverlapped->DUMMYUNIONNAME.Pointer = cnv.pv; + } + (void)SetEvent(lpOverlapped->hEvent); +#endif + } + + return TRUE; +} + +static HANDLE_OPS namedOps = { NamedPipeIsHandled, + NamedPipeCloseHandle, + NamedPipeGetFd, + NULL, /* CleanupHandle */ + NamedPipeRead, + NULL, + NULL, + NamedPipeWrite, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +static BOOL InitWinPRPipeModule(void) +{ + if (g_NamedPipeServerSockets) + return TRUE; + + g_NamedPipeServerSockets = ArrayList_New(FALSE); + return g_NamedPipeServerSockets != NULL; +} + +/* + * Unnamed pipe + */ + +BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, + DWORD nSize) +{ + int pipe_fd[2]; + WINPR_PIPE* pReadPipe = NULL; + WINPR_PIPE* pWritePipe = NULL; + + WINPR_UNUSED(lpPipeAttributes); + WINPR_UNUSED(nSize); + + pipe_fd[0] = -1; + pipe_fd[1] = -1; + + if (pipe(pipe_fd) < 0) + { + WLog_ERR(TAG, "failed to create pipe"); + return FALSE; + } + + pReadPipe = (WINPR_PIPE*)calloc(1, sizeof(WINPR_PIPE)); + pWritePipe = (WINPR_PIPE*)calloc(1, sizeof(WINPR_PIPE)); + + if (!pReadPipe || !pWritePipe) + { + free(pReadPipe); + free(pWritePipe); + return FALSE; + } + + pReadPipe->fd = pipe_fd[0]; + pWritePipe->fd = pipe_fd[1]; + WINPR_HANDLE_SET_TYPE_AND_MODE(pReadPipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); + pReadPipe->common.ops = &ops; + *((ULONG_PTR*)hReadPipe) = (ULONG_PTR)pReadPipe; + WINPR_HANDLE_SET_TYPE_AND_MODE(pWritePipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); + pWritePipe->common.ops = &ops; + *((ULONG_PTR*)hWritePipe) = (ULONG_PTR)pWritePipe; + return TRUE; +} + +/** + * Named pipe + */ + +static void winpr_unref_named_pipe(WINPR_NAMED_PIPE* pNamedPipe) +{ + NamedPipeServerSocketEntry* baseSocket = NULL; + + if (!pNamedPipe) + return; + + WINPR_ASSERT(pNamedPipe->name); + WINPR_ASSERT(g_NamedPipeServerSockets); + // WLog_VRB(TAG, "%p (%s)", (void*) pNamedPipe, pNamedPipe->name); + ArrayList_Lock(g_NamedPipeServerSockets); + + for (size_t index = 0; index < ArrayList_Count(g_NamedPipeServerSockets); index++) + { + baseSocket = + (NamedPipeServerSocketEntry*)ArrayList_GetItem(g_NamedPipeServerSockets, index); + WINPR_ASSERT(baseSocket->name); + + if (!strcmp(baseSocket->name, pNamedPipe->name)) + { + WINPR_ASSERT(baseSocket->references > 0); + WINPR_ASSERT(baseSocket->serverfd != -1); + + if (--baseSocket->references == 0) + { + // WLog_DBG(TAG, "removing shared server socked resource"); + // WLog_DBG(TAG, "closing shared serverfd %d", baseSocket->serverfd); + ArrayList_Remove(g_NamedPipeServerSockets, baseSocket); + close(baseSocket->serverfd); + free(baseSocket->name); + free(baseSocket); + } + + break; + } + } + + ArrayList_Unlock(g_NamedPipeServerSockets); +} + +HANDLE CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, + DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, + LPSECURITY_ATTRIBUTES lpSecurityAttributes) +{ + char* lpPipePath = NULL; + WINPR_NAMED_PIPE* pNamedPipe = NULL; + int serverfd = -1; + NamedPipeServerSocketEntry* baseSocket = NULL; + + WINPR_UNUSED(lpSecurityAttributes); + + if (dwOpenMode & FILE_FLAG_OVERLAPPED) + { + WLog_ERR(TAG, "WinPR does not support the FILE_FLAG_OVERLAPPED flag"); + SetLastError(ERROR_NOT_SUPPORTED); + return INVALID_HANDLE_VALUE; + } + + if (!lpName) + return INVALID_HANDLE_VALUE; + + if (!InitWinPRPipeModule()) + return INVALID_HANDLE_VALUE; + + pNamedPipe = (WINPR_NAMED_PIPE*)calloc(1, sizeof(WINPR_NAMED_PIPE)); + + if (!pNamedPipe) + return INVALID_HANDLE_VALUE; + + ArrayList_Lock(g_NamedPipeServerSockets); + WINPR_HANDLE_SET_TYPE_AND_MODE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE, WINPR_FD_READ); + pNamedPipe->serverfd = -1; + pNamedPipe->clientfd = -1; + + if (!(pNamedPipe->name = _strdup(lpName))) + goto out; + + if (!(pNamedPipe->lpFileName = GetNamedPipeNameWithoutPrefixA(lpName))) + goto out; + + if (!(pNamedPipe->lpFilePath = GetNamedPipeUnixDomainSocketFilePathA(lpName))) + goto out; + + pNamedPipe->dwOpenMode = dwOpenMode; + pNamedPipe->dwPipeMode = dwPipeMode; + pNamedPipe->nMaxInstances = nMaxInstances; + pNamedPipe->nOutBufferSize = nOutBufferSize; + pNamedPipe->nInBufferSize = nInBufferSize; + pNamedPipe->nDefaultTimeOut = nDefaultTimeOut; + pNamedPipe->dwFlagsAndAttributes = dwOpenMode; + pNamedPipe->clientfd = -1; + pNamedPipe->ServerMode = TRUE; + pNamedPipe->common.ops = &namedOps; + + for (size_t index = 0; index < ArrayList_Count(g_NamedPipeServerSockets); index++) + { + baseSocket = + (NamedPipeServerSocketEntry*)ArrayList_GetItem(g_NamedPipeServerSockets, index); + + if (!strcmp(baseSocket->name, lpName)) + { + serverfd = baseSocket->serverfd; + // WLog_DBG(TAG, "using shared socked resource for pipe %p (%s)", (void*) pNamedPipe, + // lpName); + break; + } + } + + /* If this is the first instance of the named pipe... */ + if (serverfd == -1) + { + struct sockaddr_un s = { 0 }; + /* Create the UNIX domain socket and start listening. */ + if (!(lpPipePath = GetNamedPipeUnixDomainSocketBaseFilePathA())) + goto out; + + if (!winpr_PathFileExists(lpPipePath)) + { + if (!CreateDirectoryA(lpPipePath, 0)) + { + free(lpPipePath); + goto out; + } + + UnixChangeFileMode(lpPipePath, 0xFFFF); + } + + free(lpPipePath); + + if (winpr_PathFileExists(pNamedPipe->lpFilePath)) + winpr_DeleteFile(pNamedPipe->lpFilePath); + + if ((serverfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "CreateNamedPipeA: socket error, %s", + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + goto out; + } + + s.sun_family = AF_UNIX; + (void)sprintf_s(s.sun_path, ARRAYSIZE(s.sun_path), "%s", pNamedPipe->lpFilePath); + + if (bind(serverfd, (struct sockaddr*)&s, sizeof(struct sockaddr_un)) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "CreateNamedPipeA: bind error, %s", + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + goto out; + } + + if (listen(serverfd, 2) == -1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "CreateNamedPipeA: listen error, %s", + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + goto out; + } + + UnixChangeFileMode(pNamedPipe->lpFilePath, 0xFFFF); + + if (!(baseSocket = (NamedPipeServerSocketEntry*)malloc(sizeof(NamedPipeServerSocketEntry)))) + goto out; + + if (!(baseSocket->name = _strdup(lpName))) + { + free(baseSocket); + goto out; + } + + baseSocket->serverfd = serverfd; + baseSocket->references = 0; + + if (!ArrayList_Append(g_NamedPipeServerSockets, baseSocket)) + { + free(baseSocket->name); + free(baseSocket); + goto out; + } + + // WLog_DBG(TAG, "created shared socked resource for pipe %p (%s). base serverfd = %d", + // (void*) pNamedPipe, lpName, serverfd); + } + + pNamedPipe->serverfd = dup(baseSocket->serverfd); + // WLog_DBG(TAG, "using serverfd %d (duplicated from %d)", pNamedPipe->serverfd, + // baseSocket->serverfd); + pNamedPipe->pfnUnrefNamedPipe = winpr_unref_named_pipe; + baseSocket->references++; + + if (dwOpenMode & FILE_FLAG_OVERLAPPED) + { +#if 0 + int flags = fcntl(pNamedPipe->serverfd, F_GETFL); + + if (flags != -1) + fcntl(pNamedPipe->serverfd, F_SETFL, flags | O_NONBLOCK); + +#endif + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): ArrayList_Append takes ownership of baseSocket + ArrayList_Unlock(g_NamedPipeServerSockets); + return pNamedPipe; +out: + NamedPipeCloseHandle(pNamedPipe); + + if (serverfd != -1) + close(serverfd); + + ArrayList_Unlock(g_NamedPipeServerSockets); + return INVALID_HANDLE_VALUE; +} + +HANDLE CreateNamedPipeW(LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, + DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, + LPSECURITY_ATTRIBUTES lpSecurityAttributes) +{ + WLog_ERR(TAG, "is not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +BOOL ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped) +{ + int status = 0; + socklen_t length = 0; + WINPR_NAMED_PIPE* pNamedPipe = NULL; + + if (lpOverlapped) + { + WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter"); + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + + if (!hNamedPipe) + return FALSE; + + pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; + + if (!(pNamedPipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)) + { + struct sockaddr_un s = { 0 }; + length = sizeof(struct sockaddr_un); + status = accept(pNamedPipe->serverfd, (struct sockaddr*)&s, &length); + + if (status < 0) + { + WLog_ERR(TAG, "ConnectNamedPipe: accept error"); + return FALSE; + } + + pNamedPipe->clientfd = status; + pNamedPipe->ServerMode = FALSE; + } + else + { + if (!lpOverlapped) + return FALSE; + + if (pNamedPipe->serverfd == -1) + return FALSE; + + pNamedPipe->lpOverlapped = lpOverlapped; + /* synchronous behavior */ + lpOverlapped->Internal = 2; + lpOverlapped->InternalHigh = (ULONG_PTR)0; + lpOverlapped->DUMMYUNIONNAME.Pointer = (PVOID)NULL; + (void)SetEvent(lpOverlapped->hEvent); + } + + return TRUE; +} + +BOOL DisconnectNamedPipe(HANDLE hNamedPipe) +{ + WINPR_NAMED_PIPE* pNamedPipe = NULL; + pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; + + if (pNamedPipe->clientfd != -1) + { + close(pNamedPipe->clientfd); + pNamedPipe->clientfd = -1; + } + + return TRUE; +} + +BOOL PeekNamedPipe(HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, + LPDWORD lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL TransactNamedPipe(HANDLE hNamedPipe, LPVOID lpInBuffer, DWORD nInBufferSize, + LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesRead, + LPOVERLAPPED lpOverlapped) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL WaitNamedPipeA(LPCSTR lpNamedPipeName, DWORD nTimeOut) +{ + BOOL status = 0; + DWORD nWaitTime = 0; + char* lpFilePath = NULL; + DWORD dwSleepInterval = 0; + + if (!lpNamedPipeName) + return FALSE; + + lpFilePath = GetNamedPipeUnixDomainSocketFilePathA(lpNamedPipeName); + + if (!lpFilePath) + return FALSE; + + if (nTimeOut == NMPWAIT_USE_DEFAULT_WAIT) + nTimeOut = 50; + + nWaitTime = 0; + status = TRUE; + dwSleepInterval = 10; + + while (!winpr_PathFileExists(lpFilePath)) + { + Sleep(dwSleepInterval); + nWaitTime += dwSleepInterval; + + if (nWaitTime >= nTimeOut) + { + status = FALSE; + break; + } + } + + free(lpFilePath); + return status; +} + +BOOL WaitNamedPipeW(LPCWSTR lpNamedPipeName, DWORD nTimeOut) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +// NOLINTBEGIN(readability-non-const-parameter) +BOOL SetNamedPipeHandleState(HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount, + LPDWORD lpCollectDataTimeout) +// NOLINTEND(readability-non-const-parameter) +{ + int fd = 0; + int flags = 0; + WINPR_NAMED_PIPE* pNamedPipe = NULL; + pNamedPipe = (WINPR_NAMED_PIPE*)hNamedPipe; + + if (lpMode) + { + pNamedPipe->dwPipeMode = *lpMode; + fd = (pNamedPipe->ServerMode) ? pNamedPipe->serverfd : pNamedPipe->clientfd; + + if (fd == -1) + return FALSE; + + flags = fcntl(fd, F_GETFL); + + if (flags < 0) + return FALSE; + + if (pNamedPipe->dwPipeMode & PIPE_NOWAIT) + flags = (flags | O_NONBLOCK); + else + flags = (flags & ~(O_NONBLOCK)); + + if (fcntl(fd, F_SETFL, flags) < 0) + return FALSE; + } + + if (lpMaxCollectionCount) + { + } + + if (lpCollectDataTimeout) + { + } + + return TRUE; +} + +BOOL ImpersonateNamedPipeClient(HANDLE hNamedPipe) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetNamedPipeClientComputerNameA(HANDLE Pipe, LPCSTR ClientComputerName, + ULONG ClientComputerNameLength) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +BOOL GetNamedPipeClientComputerNameW(HANDLE Pipe, LPCWSTR ClientComputerName, + ULONG ClientComputerNameLength) +{ + WLog_ERR(TAG, "Not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return FALSE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.h new file mode 100644 index 0000000000000000000000000000000000000000..192de06177e858a35635ed3c927c85e8cd34d55e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/pipe.h @@ -0,0 +1,75 @@ +/** + * WinPR: Windows Portable Runtime + * Pipe Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_PIPE_PRIVATE_H + +#ifndef _WIN32 + +#include +#include + +#include "../handle/handle.h" + +struct winpr_pipe +{ + WINPR_HANDLE common; + + int fd; +}; +typedef struct winpr_pipe WINPR_PIPE; + +typedef struct winpr_named_pipe WINPR_NAMED_PIPE; + +typedef void (*fnUnrefNamedPipe)(WINPR_NAMED_PIPE* pNamedPipe); + +struct winpr_named_pipe +{ + WINPR_HANDLE common; + + int clientfd; + int serverfd; + + char* name; + char* lpFileName; + char* lpFilePath; + + BOOL ServerMode; + DWORD dwOpenMode; + DWORD dwPipeMode; + DWORD nMaxInstances; + DWORD nOutBufferSize; + DWORD nInBufferSize; + DWORD nDefaultTimeOut; + DWORD dwFlagsAndAttributes; + LPOVERLAPPED lpOverlapped; + + fnUnrefNamedPipe pfnUnrefNamedPipe; +}; + +BOOL winpr_destroy_named_pipe(WINPR_NAMED_PIPE* pNamedPipe); + +BOOL NamedPipeRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); +BOOL NamedPipeWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); + +#endif + +#endif /* WINPR_PIPE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..92495e79be000538b2231bf8efedcb66008beac6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestPipe") +set(MODULE_PREFIX "TEST_PIPE") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestPipeCreatePipe.c TestPipeCreateNamedPipe.c TestPipeCreateNamedPipeOverlapped.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c new file mode 100644 index 0000000000000000000000000000000000000000..314a9c4e2c5510b8b4ed6dfe16f8ca54eb7cd14b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c @@ -0,0 +1,510 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef _WIN32 +#include +#endif +#include "../pipe.h" + +#define PIPE_BUFFER_SIZE 32 + +static HANDLE ReadyEvent; + +static LPTSTR lpszPipeNameMt = _T("\\\\.\\pipe\\winpr_test_pipe_mt"); +static LPTSTR lpszPipeNameSt = _T("\\\\.\\pipe\\winpr_test_pipe_st"); + +static BOOL testFailed = FALSE; + +static DWORD WINAPI named_pipe_client_thread(LPVOID arg) +{ + HANDLE hNamedPipe = NULL; + BYTE* lpReadBuffer = NULL; + BYTE* lpWriteBuffer = NULL; + BOOL fSuccess = FALSE; + DWORD nNumberOfBytesToRead = 0; + DWORD nNumberOfBytesToWrite = 0; + DWORD lpNumberOfBytesRead = 0; + DWORD lpNumberOfBytesWritten = 0; + (void)WaitForSingleObject(ReadyEvent, INFINITE); + hNamedPipe = + CreateFile(lpszPipeNameMt, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (hNamedPipe == INVALID_HANDLE_VALUE) + { + printf("%s: Named Pipe CreateFile failure: INVALID_HANDLE_VALUE\n", __func__); + goto out; + } + + if (!(lpReadBuffer = (BYTE*)malloc(PIPE_BUFFER_SIZE))) + { + printf("%s: Error allocating read buffer\n", __func__); + goto out; + } + + if (!(lpWriteBuffer = (BYTE*)malloc(PIPE_BUFFER_SIZE))) + { + printf("%s: Error allocating write buffer\n", __func__); + goto out; + } + + lpNumberOfBytesWritten = 0; + nNumberOfBytesToWrite = PIPE_BUFFER_SIZE; + FillMemory(lpWriteBuffer, PIPE_BUFFER_SIZE, 0x59); + + if (!WriteFile(hNamedPipe, lpWriteBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, + NULL) || + lpNumberOfBytesWritten != nNumberOfBytesToWrite) + { + printf("%s: Client NamedPipe WriteFile failure\n", __func__); + goto out; + } + + lpNumberOfBytesRead = 0; + nNumberOfBytesToRead = PIPE_BUFFER_SIZE; + ZeroMemory(lpReadBuffer, PIPE_BUFFER_SIZE); + + if (!ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, &lpNumberOfBytesRead, NULL) || + lpNumberOfBytesRead != nNumberOfBytesToRead) + { + printf("%s: Client NamedPipe ReadFile failure\n", __func__); + goto out; + } + + printf("Client ReadFile: %" PRIu32 " bytes\n", lpNumberOfBytesRead); + winpr_HexDump("pipe.test", WLOG_DEBUG, lpReadBuffer, lpNumberOfBytesRead); + fSuccess = TRUE; +out: + free(lpReadBuffer); + free(lpWriteBuffer); + (void)CloseHandle(hNamedPipe); + + if (!fSuccess) + testFailed = TRUE; + + ExitThread(0); + return 0; +} + +static DWORD WINAPI named_pipe_server_thread(LPVOID arg) +{ + HANDLE hNamedPipe = NULL; + BYTE* lpReadBuffer = NULL; + BYTE* lpWriteBuffer = NULL; + BOOL fSuccess = FALSE; + BOOL fConnected = FALSE; + DWORD nNumberOfBytesToRead = 0; + DWORD nNumberOfBytesToWrite = 0; + DWORD lpNumberOfBytesRead = 0; + DWORD lpNumberOfBytesWritten = 0; + hNamedPipe = CreateNamedPipe( + lpszPipeNameMt, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, PIPE_BUFFER_SIZE, PIPE_BUFFER_SIZE, 0, NULL); + + if (!hNamedPipe) + { + printf("%s: CreateNamedPipe failure: NULL handle\n", __func__); + goto out; + } + + if (hNamedPipe == INVALID_HANDLE_VALUE) + { + printf("%s: CreateNamedPipe failure: INVALID_HANDLE_VALUE\n", __func__); + goto out; + } + + (void)SetEvent(ReadyEvent); + + /** + * Note: + * If a client connects before ConnectNamedPipe is called, the function returns zero and + * GetLastError returns ERROR_PIPE_CONNECTED. This can happen if a client connects in the + * interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. + * In this situation, there is a good connection between client and server, even though + * the function returns zero. + */ + fConnected = + ConnectNamedPipe(hNamedPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); + + if (!fConnected) + { + printf("%s: ConnectNamedPipe failure\n", __func__); + goto out; + } + + if (!(lpReadBuffer = (BYTE*)calloc(1, PIPE_BUFFER_SIZE))) + { + printf("%s: Error allocating read buffer\n", __func__); + goto out; + } + + if (!(lpWriteBuffer = (BYTE*)malloc(PIPE_BUFFER_SIZE))) + { + printf("%s: Error allocating write buffer\n", __func__); + goto out; + } + + lpNumberOfBytesRead = 0; + nNumberOfBytesToRead = PIPE_BUFFER_SIZE; + + if (!ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, &lpNumberOfBytesRead, NULL) || + lpNumberOfBytesRead != nNumberOfBytesToRead) + { + printf("%s: Server NamedPipe ReadFile failure\n", __func__); + goto out; + } + + printf("Server ReadFile: %" PRIu32 " bytes\n", lpNumberOfBytesRead); + winpr_HexDump("pipe.test", WLOG_DEBUG, lpReadBuffer, lpNumberOfBytesRead); + lpNumberOfBytesWritten = 0; + nNumberOfBytesToWrite = PIPE_BUFFER_SIZE; + FillMemory(lpWriteBuffer, PIPE_BUFFER_SIZE, 0x45); + + if (!WriteFile(hNamedPipe, lpWriteBuffer, nNumberOfBytesToWrite, &lpNumberOfBytesWritten, + NULL) || + lpNumberOfBytesWritten != nNumberOfBytesToWrite) + { + printf("%s: Server NamedPipe WriteFile failure\n", __func__); + goto out; + } + + fSuccess = TRUE; +out: + free(lpReadBuffer); + free(lpWriteBuffer); + (void)CloseHandle(hNamedPipe); + + if (!fSuccess) + testFailed = TRUE; + + ExitThread(0); + return 0; +} + +#define TESTNUMPIPESST 16 +static DWORD WINAPI named_pipe_single_thread(LPVOID arg) +{ + HANDLE servers[TESTNUMPIPESST] = { 0 }; + HANDLE clients[TESTNUMPIPESST] = { 0 }; + DWORD dwRead = 0; + DWORD dwWritten = 0; + int numPipes = 0; + BOOL bSuccess = FALSE; + numPipes = TESTNUMPIPESST; + (void)WaitForSingleObject(ReadyEvent, INFINITE); + + for (int i = 0; i < numPipes; i++) + { + if (!(servers[i] = CreateNamedPipe(lpszPipeNameSt, PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, PIPE_BUFFER_SIZE, + PIPE_BUFFER_SIZE, 0, NULL))) + { + printf("%s: CreateNamedPipe #%d failed\n", __func__, i); + goto out; + } + } + +#ifndef _WIN32 + + for (int i = 0; i < numPipes; i++) + { + WINPR_NAMED_PIPE* p = (WINPR_NAMED_PIPE*)servers[i]; + + if (strcmp(lpszPipeNameSt, p->name) != 0) + { + printf("%s: Pipe name mismatch for pipe #%d ([%s] instead of [%s])\n", __func__, i, + p->name, lpszPipeNameSt); + goto out; + } + + if (p->clientfd != -1) + { + printf("%s: Unexpected client fd value for pipe #%d (%d instead of -1)\n", __func__, i, + p->clientfd); + goto out; + } + + if (p->serverfd < 1) + { + printf("%s: Unexpected server fd value for pipe #%d (%d is not > 0)\n", __func__, i, + p->serverfd); + goto out; + } + + if (p->ServerMode == FALSE) + { + printf("%s: Unexpected ServerMode value for pipe #%d (0 instead of 1)\n", __func__, i); + goto out; + } + } + +#endif + + for (int i = 0; i < numPipes; i++) + { + BOOL fConnected = 0; + if ((clients[i] = CreateFile(lpszPipeNameSt, GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) + { + printf("%s: CreateFile #%d failed\n", __func__, i); + goto out; + } + + /** + * Note: + * If a client connects before ConnectNamedPipe is called, the function returns zero and + * GetLastError returns ERROR_PIPE_CONNECTED. This can happen if a client connects in the + * interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. + * In this situation, there is a good connection between client and server, even though + * the function returns zero. + */ + fConnected = + ConnectNamedPipe(servers[i], NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); + + if (!fConnected) + { + printf("%s: ConnectNamedPipe #%d failed. (%" PRIu32 ")\n", __func__, i, GetLastError()); + goto out; + } + } + +#ifndef _WIN32 + + for (int i = 0; i < numPipes; i++) + { + WINPR_NAMED_PIPE* p = servers[i]; + + if (p->clientfd < 1) + { + printf("%s: Unexpected client fd value for pipe #%d (%d is not > 0)\n", __func__, i, + p->clientfd); + goto out; + } + + if (p->ServerMode) + { + printf("%s: Unexpected ServerMode value for pipe #%d (1 instead of 0)\n", __func__, i); + goto out; + } + } + + for (int i = 0; i < numPipes; i++) + { + { + char sndbuf[PIPE_BUFFER_SIZE] = { 0 }; + char rcvbuf[PIPE_BUFFER_SIZE] = { 0 }; + /* Test writing from clients to servers */ + (void)sprintf_s(sndbuf, sizeof(sndbuf), "CLIENT->SERVER ON PIPE #%05d", i); + + if (!WriteFile(clients[i], sndbuf, sizeof(sndbuf), &dwWritten, NULL) || + dwWritten != sizeof(sndbuf)) + { + printf("%s: Error writing to client end of pipe #%d\n", __func__, i); + goto out; + } + + if (!ReadFile(servers[i], rcvbuf, dwWritten, &dwRead, NULL) || dwRead != dwWritten) + { + printf("%s: Error reading on server end of pipe #%d\n", __func__, i); + goto out; + } + + if (memcmp(sndbuf, rcvbuf, sizeof(sndbuf)) != 0) + { + printf("%s: Error data read on server end of pipe #%d is corrupted\n", __func__, i); + goto out; + } + } + { + + char sndbuf[PIPE_BUFFER_SIZE] = { 0 }; + char rcvbuf[PIPE_BUFFER_SIZE] = { 0 }; + /* Test writing from servers to clients */ + + (void)sprintf_s(sndbuf, sizeof(sndbuf), "SERVER->CLIENT ON PIPE #%05d", i); + + if (!WriteFile(servers[i], sndbuf, sizeof(sndbuf), &dwWritten, NULL) || + dwWritten != sizeof(sndbuf)) + { + printf("%s: Error writing to server end of pipe #%d\n", __func__, i); + goto out; + } + + if (!ReadFile(clients[i], rcvbuf, dwWritten, &dwRead, NULL) || dwRead != dwWritten) + { + printf("%s: Error reading on client end of pipe #%d\n", __func__, i); + goto out; + } + + if (memcmp(sndbuf, rcvbuf, sizeof(sndbuf)) != 0) + { + printf("%s: Error data read on client end of pipe #%d is corrupted\n", __func__, i); + goto out; + } + } + } + +#endif + /** + * After DisconnectNamedPipe on server end + * ReadFile/WriteFile must fail on client end + */ + int i = numPipes - 1; + DisconnectNamedPipe(servers[i]); + { + char sndbuf[PIPE_BUFFER_SIZE] = { 0 }; + char rcvbuf[PIPE_BUFFER_SIZE] = { 0 }; + if (ReadFile(clients[i], rcvbuf, sizeof(rcvbuf), &dwRead, NULL)) + { + printf("%s: Error ReadFile on client should have failed after DisconnectNamedPipe on " + "server\n", + __func__); + goto out; + } + + if (WriteFile(clients[i], sndbuf, sizeof(sndbuf), &dwWritten, NULL)) + { + printf( + "%s: Error WriteFile on client end should have failed after DisconnectNamedPipe on " + "server\n", + __func__); + goto out; + } + } + (void)CloseHandle(servers[i]); + (void)CloseHandle(clients[i]); + numPipes--; + /** + * After CloseHandle (without calling DisconnectNamedPipe first) on server end + * ReadFile/WriteFile must fail on client end + */ + i = numPipes - 1; + (void)CloseHandle(servers[i]); + + { + char sndbuf[PIPE_BUFFER_SIZE] = { 0 }; + char rcvbuf[PIPE_BUFFER_SIZE] = { 0 }; + + if (ReadFile(clients[i], rcvbuf, sizeof(rcvbuf), &dwRead, NULL)) + { + printf( + "%s: Error ReadFile on client end should have failed after CloseHandle on server\n", + __func__); + goto out; + } + + if (WriteFile(clients[i], sndbuf, sizeof(sndbuf), &dwWritten, NULL)) + { + printf("%s: Error WriteFile on client end should have failed after CloseHandle on " + "server\n", + __func__); + goto out; + } + } + (void)CloseHandle(clients[i]); + numPipes--; + /** + * After CloseHandle on client end + * ReadFile/WriteFile must fail on server end + */ + i = numPipes - 1; + (void)CloseHandle(clients[i]); + + { + char sndbuf[PIPE_BUFFER_SIZE] = { 0 }; + char rcvbuf[PIPE_BUFFER_SIZE] = { 0 }; + + if (ReadFile(servers[i], rcvbuf, sizeof(rcvbuf), &dwRead, NULL)) + { + printf( + "%s: Error ReadFile on server end should have failed after CloseHandle on client\n", + __func__); + goto out; + } + + if (WriteFile(servers[i], sndbuf, sizeof(sndbuf), &dwWritten, NULL)) + { + printf("%s: Error WriteFile on server end should have failed after CloseHandle on " + "client\n", + __func__); + goto out; + } + } + + DisconnectNamedPipe(servers[i]); + (void)CloseHandle(servers[i]); + numPipes--; + + /* Close all remaining pipes */ + for (int i = 0; i < numPipes; i++) + { + DisconnectNamedPipe(servers[i]); + (void)CloseHandle(servers[i]); + (void)CloseHandle(clients[i]); + } + + bSuccess = TRUE; +out: + + if (!bSuccess) + testFailed = TRUE; + + return 0; +} + +int TestPipeCreateNamedPipe(int argc, char* argv[]) +{ + HANDLE SingleThread = NULL; + HANDLE ClientThread = NULL; + HANDLE ServerThread = NULL; + HANDLE hPipe = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + /* Verify that CreateNamedPipe returns INVALID_HANDLE_VALUE on failure */ + hPipe = CreateNamedPipeA(NULL, 0, 0, 0, 0, 0, 0, NULL); + if (hPipe != INVALID_HANDLE_VALUE) + { + printf("CreateNamedPipe unexpectedly returned %p instead of INVALID_HANDLE_VALUE (%p)\n", + hPipe, INVALID_HANDLE_VALUE); + return -1; + } + +#ifndef _WIN32 + (void)signal(SIGPIPE, SIG_IGN); +#endif + if (!(ReadyEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("CreateEvent failure: (%" PRIu32 ")\n", GetLastError()); + return -1; + } + if (!(SingleThread = CreateThread(NULL, 0, named_pipe_single_thread, NULL, 0, NULL))) + { + printf("CreateThread (SingleThread) failure: (%" PRIu32 ")\n", GetLastError()); + return -1; + } + if (!(ClientThread = CreateThread(NULL, 0, named_pipe_client_thread, NULL, 0, NULL))) + { + printf("CreateThread (ClientThread) failure: (%" PRIu32 ")\n", GetLastError()); + return -1; + } + if (!(ServerThread = CreateThread(NULL, 0, named_pipe_server_thread, NULL, 0, NULL))) + { + printf("CreateThread (ServerThread) failure: (%" PRIu32 ")\n", GetLastError()); + return -1; + } + (void)WaitForSingleObject(SingleThread, INFINITE); + (void)WaitForSingleObject(ClientThread, INFINITE); + (void)WaitForSingleObject(ServerThread, INFINITE); + (void)CloseHandle(SingleThread); + (void)CloseHandle(ClientThread); + (void)CloseHandle(ServerThread); + return testFailed; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c new file mode 100644 index 0000000000000000000000000000000000000000..1fc2fdd0cf1a7039a7fa89020969fb325d9a704a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c @@ -0,0 +1,397 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PIPE_BUFFER_SIZE 32 +#define PIPE_TIMEOUT_MS 20000 // 20 seconds + +static BYTE SERVER_MESSAGE[PIPE_BUFFER_SIZE]; +static BYTE CLIENT_MESSAGE[PIPE_BUFFER_SIZE]; + +static BOOL bClientSuccess = FALSE; +static BOOL bServerSuccess = FALSE; + +static HANDLE serverReadyEvent = NULL; + +static LPTSTR lpszPipeName = _T("\\\\.\\pipe\\winpr_test_pipe_overlapped"); + +static DWORD WINAPI named_pipe_client_thread(LPVOID arg) +{ + DWORD status = 0; + HANDLE hEvent = NULL; + HANDLE hNamedPipe = NULL; + BYTE* lpReadBuffer = NULL; + BOOL fSuccess = FALSE; + OVERLAPPED overlapped = { 0 }; + DWORD nNumberOfBytesToRead = 0; + DWORD nNumberOfBytesToWrite = 0; + DWORD NumberOfBytesTransferred = 0; + + WINPR_UNUSED(arg); + + status = WaitForSingleObject(serverReadyEvent, PIPE_TIMEOUT_MS); + if (status != WAIT_OBJECT_0) + { + printf("client: failed to wait for server ready event: %" PRIu32 "\n", status); + goto finish; + } + + /* 1: initialize overlapped structure */ + if (!(hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("client: CreateEvent failure: %" PRIu32 "\n", GetLastError()); + goto finish; + } + overlapped.hEvent = hEvent; + + /* 2: connect to server named pipe */ + + hNamedPipe = CreateFile(lpszPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, NULL); + + if (hNamedPipe == INVALID_HANDLE_VALUE) + { + printf("client: Named Pipe CreateFile failure: %" PRIu32 "\n", GetLastError()); + goto finish; + } + + /* 3: write to named pipe */ + + nNumberOfBytesToWrite = PIPE_BUFFER_SIZE; + NumberOfBytesTransferred = 0; + + fSuccess = WriteFile(hNamedPipe, CLIENT_MESSAGE, nNumberOfBytesToWrite, NULL, &overlapped); + + if (!fSuccess) + fSuccess = (GetLastError() == ERROR_IO_PENDING); + + if (!fSuccess) + { + printf("client: NamedPipe WriteFile failure (initial): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + status = WaitForSingleObject(hEvent, PIPE_TIMEOUT_MS); + if (status != WAIT_OBJECT_0) + { + printf("client: failed to wait for overlapped event (write): %" PRIu32 "\n", status); + goto finish; + } + + fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, FALSE); + if (!fSuccess) + { + printf("client: NamedPipe WriteFile failure (final): %" PRIu32 "\n", GetLastError()); + goto finish; + } + printf("client: WriteFile transferred %" PRIu32 " bytes:\n", NumberOfBytesTransferred); + + /* 4: read from named pipe */ + + if (!(lpReadBuffer = (BYTE*)calloc(1, PIPE_BUFFER_SIZE))) + { + printf("client: Error allocating read buffer\n"); + goto finish; + } + + nNumberOfBytesToRead = PIPE_BUFFER_SIZE; + NumberOfBytesTransferred = 0; + + fSuccess = ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, NULL, &overlapped); + + if (!fSuccess) + fSuccess = (GetLastError() == ERROR_IO_PENDING); + + if (!fSuccess) + { + printf("client: NamedPipe ReadFile failure (initial): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + status = WaitForMultipleObjects(1, &hEvent, FALSE, PIPE_TIMEOUT_MS); + if (status != WAIT_OBJECT_0) + { + printf("client: failed to wait for overlapped event (read): %" PRIu32 "\n", status); + goto finish; + } + + fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, TRUE); + if (!fSuccess) + { + printf("client: NamedPipe ReadFile failure (final): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + printf("client: ReadFile transferred %" PRIu32 " bytes:\n", NumberOfBytesTransferred); + winpr_HexDump("pipe.test", WLOG_DEBUG, lpReadBuffer, NumberOfBytesTransferred); + + if (NumberOfBytesTransferred != PIPE_BUFFER_SIZE || + memcmp(lpReadBuffer, SERVER_MESSAGE, PIPE_BUFFER_SIZE) != 0) + { + printf("client: received unexpected data from server\n"); + goto finish; + } + + printf("client: finished successfully\n"); + bClientSuccess = TRUE; + +finish: + free(lpReadBuffer); + if (hNamedPipe) + (void)CloseHandle(hNamedPipe); + if (hEvent) + (void)CloseHandle(hEvent); + + return 0; +} + +static DWORD WINAPI named_pipe_server_thread(LPVOID arg) +{ + DWORD status = 0; + HANDLE hEvent = NULL; + HANDLE hNamedPipe = NULL; + BYTE* lpReadBuffer = NULL; + OVERLAPPED overlapped = { 0 }; + BOOL fSuccess = FALSE; + BOOL fConnected = FALSE; + DWORD nNumberOfBytesToRead = 0; + DWORD nNumberOfBytesToWrite = 0; + DWORD NumberOfBytesTransferred = 0; + + WINPR_UNUSED(arg); + + /* 1: initialize overlapped structure */ + if (!(hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("server: CreateEvent failure: %" PRIu32 "\n", GetLastError()); + (void)SetEvent(serverReadyEvent); /* unblock client thread */ + goto finish; + } + overlapped.hEvent = hEvent; + + /* 2: create named pipe and set ready event */ + + hNamedPipe = + CreateNamedPipe(lpszPipeName, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, + PIPE_BUFFER_SIZE, PIPE_BUFFER_SIZE, 0, NULL); + + if (hNamedPipe == INVALID_HANDLE_VALUE) + { + printf("server: CreateNamedPipe failure: %" PRIu32 "\n", GetLastError()); + (void)SetEvent(serverReadyEvent); /* unblock client thread */ + goto finish; + } + + (void)SetEvent(serverReadyEvent); + + /* 3: connect named pipe */ + +#if 0 + /* This sleep will most certainly cause ERROR_PIPE_CONNECTED below */ + Sleep(2000); +#endif + + fConnected = ConnectNamedPipe(hNamedPipe, &overlapped); + status = GetLastError(); + + /** + * At this point if fConnected is FALSE, we have to check GetLastError() for: + * ERROR_PIPE_CONNECTED: + * client has already connected before we have called ConnectNamedPipe. + * this is quite common depending on the timings and indicates success + * ERROR_IO_PENDING: + * Since we're using ConnectNamedPipe asynchronously here, the function returns + * immediately and this error code simply indicates that the operation is + * still in progress. Hence we have to wait for the completion event and use + * GetOverlappedResult to query the actual result of the operation (note that + * the lpNumberOfBytesTransferred parameter is undefined/useless for a + * ConnectNamedPipe operation) + */ + + if (!fConnected) + fConnected = (status == ERROR_PIPE_CONNECTED); + + printf("server: ConnectNamedPipe status: %" PRIu32 "\n", status); + + if (!fConnected && status == ERROR_IO_PENDING) + { + DWORD dwDummy = 0; + printf("server: waiting up to %u ms for connection ...\n", PIPE_TIMEOUT_MS); + status = WaitForSingleObject(hEvent, PIPE_TIMEOUT_MS); + if (status == WAIT_OBJECT_0) + fConnected = GetOverlappedResult(hNamedPipe, &overlapped, &dwDummy, FALSE); + else + printf("server: failed to wait for overlapped event (connect): %" PRIu32 "\n", status); + } + + if (!fConnected) + { + printf("server: ConnectNamedPipe failed: %" PRIu32 "\n", status); + goto finish; + } + + printf("server: named pipe successfully connected\n"); + + /* 4: read from named pipe */ + + if (!(lpReadBuffer = (BYTE*)calloc(1, PIPE_BUFFER_SIZE))) + { + printf("server: Error allocating read buffer\n"); + goto finish; + } + + nNumberOfBytesToRead = PIPE_BUFFER_SIZE; + NumberOfBytesTransferred = 0; + + fSuccess = ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, NULL, &overlapped); + + if (!fSuccess) + fSuccess = (GetLastError() == ERROR_IO_PENDING); + + if (!fSuccess) + { + printf("server: NamedPipe ReadFile failure (initial): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + status = WaitForSingleObject(hEvent, PIPE_TIMEOUT_MS); + if (status != WAIT_OBJECT_0) + { + printf("server: failed to wait for overlapped event (read): %" PRIu32 "\n", status); + goto finish; + } + + fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, FALSE); + if (!fSuccess) + { + printf("server: NamedPipe ReadFile failure (final): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + printf("server: ReadFile transferred %" PRIu32 " bytes:\n", NumberOfBytesTransferred); + winpr_HexDump("pipe.test", WLOG_DEBUG, lpReadBuffer, NumberOfBytesTransferred); + + if (NumberOfBytesTransferred != PIPE_BUFFER_SIZE || + memcmp(lpReadBuffer, CLIENT_MESSAGE, PIPE_BUFFER_SIZE) != 0) + { + printf("server: received unexpected data from client\n"); + goto finish; + } + + /* 5: write to named pipe */ + + nNumberOfBytesToWrite = PIPE_BUFFER_SIZE; + NumberOfBytesTransferred = 0; + + fSuccess = WriteFile(hNamedPipe, SERVER_MESSAGE, nNumberOfBytesToWrite, NULL, &overlapped); + + if (!fSuccess) + fSuccess = (GetLastError() == ERROR_IO_PENDING); + + if (!fSuccess) + { + printf("server: NamedPipe WriteFile failure (initial): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + status = WaitForSingleObject(hEvent, PIPE_TIMEOUT_MS); + if (status != WAIT_OBJECT_0) + { + printf("server: failed to wait for overlapped event (write): %" PRIu32 "\n", status); + goto finish; + } + + fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, FALSE); + if (!fSuccess) + { + printf("server: NamedPipe WriteFile failure (final): %" PRIu32 "\n", GetLastError()); + goto finish; + } + + printf("server: WriteFile transferred %" PRIu32 " bytes:\n", NumberOfBytesTransferred); + // winpr_HexDump("pipe.test", WLOG_DEBUG, lpWriteBuffer, NumberOfBytesTransferred); + + bServerSuccess = TRUE; + printf("server: finished successfully\n"); + +finish: + (void)CloseHandle(hNamedPipe); + (void)CloseHandle(hEvent); + free(lpReadBuffer); + return 0; +} + +int TestPipeCreateNamedPipeOverlapped(int argc, char* argv[]) +{ + HANDLE ClientThread = NULL; + HANDLE ServerThread = NULL; + int result = -1; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + FillMemory(SERVER_MESSAGE, PIPE_BUFFER_SIZE, 0xAA); + FillMemory(CLIENT_MESSAGE, PIPE_BUFFER_SIZE, 0xBB); + + if (!(serverReadyEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("CreateEvent failed: %" PRIu32 "\n", GetLastError()); + goto out; + } + if (!(ClientThread = CreateThread(NULL, 0, named_pipe_client_thread, NULL, 0, NULL))) + { + printf("CreateThread (client) failed: %" PRIu32 "\n", GetLastError()); + goto out; + } + if (!(ServerThread = CreateThread(NULL, 0, named_pipe_server_thread, NULL, 0, NULL))) + { + printf("CreateThread (server) failed: %" PRIu32 "\n", GetLastError()); + goto out; + } + + if (WAIT_OBJECT_0 != WaitForSingleObject(ClientThread, INFINITE)) + { + printf("%s: Failed to wait for client thread: %" PRIu32 "\n", __func__, GetLastError()); + goto out; + } + if (WAIT_OBJECT_0 != WaitForSingleObject(ServerThread, INFINITE)) + { + printf("%s: Failed to wait for server thread: %" PRIu32 "\n", __func__, GetLastError()); + goto out; + } + + if (bClientSuccess && bServerSuccess) + result = 0; + +out: + + if (ClientThread) + (void)CloseHandle(ClientThread); + if (ServerThread) + (void)CloseHandle(ServerThread); + if (serverReadyEvent) + (void)CloseHandle(serverReadyEvent); + +#ifndef _WIN32 + if (result == 0) + { + printf("%s: Error, this test is currently expected not to succeed on this platform.\n", + __func__); + result = -1; + } + else + { + printf("%s: This test is currently expected to fail on this platform.\n", __func__); + result = 0; + } +#endif + + return result; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreatePipe.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreatePipe.c new file mode 100644 index 0000000000000000000000000000000000000000..0537b8aed90e5d64fde6e3b90ac8d1b0bef4813c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pipe/test/TestPipeCreatePipe.c @@ -0,0 +1,72 @@ + +#include +#include +#include +#include +#include + +#define BUFFER_SIZE 16 + +int TestPipeCreatePipe(int argc, char* argv[]) +{ + BOOL status = 0; + DWORD dwRead = 0; + DWORD dwWrite = 0; + HANDLE hReadPipe = NULL; + HANDLE hWritePipe = NULL; + BYTE readBuffer[BUFFER_SIZE] = { 0 }; + BYTE writeBuffer[BUFFER_SIZE] = { 0 }; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + status = CreatePipe(&hReadPipe, &hWritePipe, NULL, BUFFER_SIZE * 2); + + if (!status) + { + _tprintf(_T("CreatePipe failed\n")); + return -1; + } + + FillMemory(writeBuffer, sizeof(writeBuffer), 0xAA); + status = WriteFile(hWritePipe, &writeBuffer, sizeof(writeBuffer), &dwWrite, NULL); + + if (!status) + { + _tprintf(_T("WriteFile failed\n")); + return -1; + } + + if (dwWrite != sizeof(writeBuffer)) + { + _tprintf(_T("WriteFile: unexpected number of bytes written: Actual: %") _T( + PRIu32) _T(", Expected: %") _T(PRIuz) _T("\n"), + dwWrite, sizeof(writeBuffer)); + return -1; + } + + status = ReadFile(hReadPipe, &readBuffer, sizeof(readBuffer), &dwRead, NULL); + + if (!status) + { + _tprintf(_T("ReadFile failed\n")); + return -1; + } + + if (dwRead != sizeof(readBuffer)) + { + _tprintf(_T("ReadFile: unexpected number of bytes read: Actual: %") _T( + PRIu32) _T(", Expected: %") _T(PRIuz) _T("\n"), + dwWrite, sizeof(readBuffer)); + return -1; + } + + if (memcmp(readBuffer, writeBuffer, BUFFER_SIZE) != 0) + { + _tprintf(_T("ReadFile: read buffer is different from write buffer\n")); + return -1; + } + + (void)CloseHandle(hReadPipe); + (void)CloseHandle(hWritePipe); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb2dee58f510812b8d12248ea9a662baa1818c73 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/CMakeLists.txt @@ -0,0 +1,34 @@ +# WinPR: Windows Portable Runtime +# libwinpr-pool cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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( + synch.c + work.c + timer.c + io.c + cleanup_group.c + pool.c + pool.h + callback.c + callback_cleanup.c +) + +winpr_library_add_private(${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS}) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e2d7e38db35e323607a991240c8f040b2f20316e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "1") +set(MINWIN_SHORT_NAME "threadpool") +set(MINWIN_LONG_NAME "Thread Pool API") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback.c new file mode 100644 index 0000000000000000000000000000000000000000..46c1605747e2a18763a30235ec32597e3c323094 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback.c @@ -0,0 +1,54 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Callback) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +typedef BOOL(WINAPI* pCallbackMayRunLong_t)(PTP_CALLBACK_INSTANCE pci); +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static pCallbackMayRunLong_t pCallbackMayRunLong = NULL; + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + if (kernel32) + pCallbackMayRunLong = + GetProcAddressAs(kernel32, "CallbackMayRunLong", pCallbackMayRunLong_t); + return TRUE; +} +#endif + +BOOL winpr_CallbackMayRunLong(PTP_CALLBACK_INSTANCE pci) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pCallbackMayRunLong) + return pCallbackMayRunLong(pci); +#endif + /* No default implementation */ + return FALSE; +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback_cleanup.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback_cleanup.c new file mode 100644 index 0000000000000000000000000000000000000000..068a34612aa8cbae01add989508906b22ecce700 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/callback_cleanup.c @@ -0,0 +1,140 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Callback Clean-up) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "pool.h" + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static VOID(WINAPI* pSetEventWhenCallbackReturns)(PTP_CALLBACK_INSTANCE pci, HANDLE evt); +static VOID(WINAPI* pReleaseSemaphoreWhenCallbackReturns)(PTP_CALLBACK_INSTANCE pci, HANDLE sem, + DWORD crel); +static VOID(WINAPI* pReleaseMutexWhenCallbackReturns)(PTP_CALLBACK_INSTANCE pci, HANDLE mut); +static VOID(WINAPI* pLeaveCriticalSectionWhenCallbackReturns)(PTP_CALLBACK_INSTANCE pci, + PCRITICAL_SECTION pcs); +static VOID(WINAPI* pFreeLibraryWhenCallbackReturns)(PTP_CALLBACK_INSTANCE pci, HMODULE mod); +static VOID(WINAPI* pDisassociateCurrentThreadFromCallback)(PTP_CALLBACK_INSTANCE pci); + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + if (kernel32) + { + pSetEventWhenCallbackReturns = + GetProcAddressAs(kernel32, "SetEventWhenCallbackReturns"), void*); + pReleaseSemaphoreWhenCallbackReturns = + GetProcAddressAs(kernel32, "ReleaseSemaphoreWhenCallbackReturns", void*); + pReleaseMutexWhenCallbackReturns = + GetProcAddressAs(kernel32, "ReleaseMutexWhenCallbackReturns", void*); + pLeaveCriticalSectionWhenCallbackReturns = + GetProcAddressAs(kernel32, "LeaveCriticalSectionWhenCallbackReturns", void*); + pFreeLibraryWhenCallbackReturns = + GetProcAddressAs(kernel32, "FreeLibraryWhenCallbackReturns", void*); + pDisassociateCurrentThreadFromCallback = + GetProcAddressAs(kernel32, "DisassociateCurrentThreadFromCallback", void*); + } + return TRUE; +} +#endif + +VOID SetEventWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE evt) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pSetEventWhenCallbackReturns) + { + pSetEventWhenCallbackReturns(pci, evt); + return; + } +#endif + /* No default implementation */ +} + +VOID ReleaseSemaphoreWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE sem, DWORD crel) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pReleaseSemaphoreWhenCallbackReturns) + { + pReleaseSemaphoreWhenCallbackReturns(pci, sem, crel); + return; + } +#endif + /* No default implementation */ +} + +VOID ReleaseMutexWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE mut) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pReleaseMutexWhenCallbackReturns) + { + pReleaseMutexWhenCallbackReturns(pci, mut); + return; + } +#endif + /* No default implementation */ +} + +VOID LeaveCriticalSectionWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, PCRITICAL_SECTION pcs) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pLeaveCriticalSectionWhenCallbackReturns) + { + pLeaveCriticalSectionWhenCallbackReturns(pci, pcs); + } +#endif + /* No default implementation */ +} + +VOID FreeLibraryWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HMODULE mod) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pFreeLibraryWhenCallbackReturns) + { + pFreeLibraryWhenCallbackReturns(pci, mod); + return; + } +#endif + /* No default implementation */ +} + +VOID DisassociateCurrentThreadFromCallback(PTP_CALLBACK_INSTANCE pci) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pDisassociateCurrentThreadFromCallback) + { + pDisassociateCurrentThreadFromCallback(pci); + return; + } +#endif + /* No default implementation */ +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/cleanup_group.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/cleanup_group.c new file mode 100644 index 0000000000000000000000000000000000000000..50b68e20dcb6b958c165808afe5fe400ffd848db --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/cleanup_group.c @@ -0,0 +1,141 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Clean-up Group) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "pool.h" + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static PTP_CLEANUP_GROUP(WINAPI* pCreateThreadpoolCleanupGroup)(); +static VOID(WINAPI* pCloseThreadpoolCleanupGroupMembers)(PTP_CLEANUP_GROUP ptpcg, + BOOL fCancelPendingCallbacks, + PVOID pvCleanupContext); +static VOID(WINAPI* pCloseThreadpoolCleanupGroup)(PTP_CLEANUP_GROUP ptpcg); + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + + if (kernel32) + { + pCreateThreadpoolCleanupGroup = + GetProcAddressAs(kernel32, "CreateThreadpoolCleanupGroup", void*); + pCloseThreadpoolCleanupGroupMembers = + GetProcAddressAs(kernel32, "CloseThreadpoolCleanupGroupMembers", void*); + pCloseThreadpoolCleanupGroup = + GetProcAddressAs(kernel32, "CloseThreadpoolCleanupGroup", void*); + } + + return TRUE; +} +#endif + +PTP_CLEANUP_GROUP winpr_CreateThreadpoolCleanupGroup(void) +{ + PTP_CLEANUP_GROUP cleanupGroup = NULL; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pCreateThreadpoolCleanupGroup) + return pCreateThreadpoolCleanupGroup(); + + return cleanupGroup; +#else + cleanupGroup = (PTP_CLEANUP_GROUP)calloc(1, sizeof(TP_CLEANUP_GROUP)); + + if (!cleanupGroup) + return NULL; + + cleanupGroup->groups = ArrayList_New(FALSE); + + if (!cleanupGroup->groups) + { + free(cleanupGroup); + return NULL; + } + + return cleanupGroup; +#endif +} + +VOID winpr_SetThreadpoolCallbackCleanupGroup(PTP_CALLBACK_ENVIRON pcbe, PTP_CLEANUP_GROUP ptpcg, + PTP_CLEANUP_GROUP_CANCEL_CALLBACK pfng) +{ + pcbe->CleanupGroup = ptpcg; + pcbe->CleanupGroupCancelCallback = pfng; +#ifndef _WIN32 + pcbe->CleanupGroup->env = pcbe; +#endif +} + +VOID winpr_CloseThreadpoolCleanupGroupMembers(PTP_CLEANUP_GROUP ptpcg, BOOL fCancelPendingCallbacks, + PVOID pvCleanupContext) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pCloseThreadpoolCleanupGroupMembers) + { + pCloseThreadpoolCleanupGroupMembers(ptpcg, fCancelPendingCallbacks, pvCleanupContext); + return; + } + +#else + + while (ArrayList_Count(ptpcg->groups) > 0) + { + PTP_WORK work = ArrayList_GetItem(ptpcg->groups, 0); + winpr_CloseThreadpoolWork(work); + } + +#endif +} + +VOID winpr_CloseThreadpoolCleanupGroup(PTP_CLEANUP_GROUP ptpcg) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pCloseThreadpoolCleanupGroup) + { + pCloseThreadpoolCleanupGroup(ptpcg); + return; + } + +#else + + if (ptpcg && ptpcg->groups) + ArrayList_Free(ptpcg->groups); + + if (ptpcg && ptpcg->env) + ptpcg->env->CleanupGroup = NULL; + + free(ptpcg); +#endif +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/io.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/io.c new file mode 100644 index 0000000000000000000000000000000000000000..7442c37175179c6e5f616bacf1605c1828d3dfa3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/io.c @@ -0,0 +1,49 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (I/O) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#ifdef WINPR_THREAD_POOL + +PTP_IO winpr_CreateThreadpoolIo(HANDLE fl, PTP_WIN32_IO_CALLBACK pfnio, PVOID pv, + PTP_CALLBACK_ENVIRON pcbe) +{ + return NULL; +} + +VOID winpr_CloseThreadpoolIo(PTP_IO pio) +{ +} + +VOID winpr_StartThreadpoolIo(PTP_IO pio) +{ +} + +VOID winpr_CancelThreadpoolIo(PTP_IO pio) +{ +} + +VOID winpr_WaitForThreadpoolIoCallbacks(PTP_IO pio, BOOL fCancelPendingCallbacks) +{ +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.c new file mode 100644 index 0000000000000000000000000000000000000000..39bbaaac98e99bb3d599655242a8e691d77cc814 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.c @@ -0,0 +1,258 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Pool) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "pool.h" + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static PTP_POOL(WINAPI* pCreateThreadpool)(PVOID reserved); +static VOID(WINAPI* pCloseThreadpool)(PTP_POOL ptpp); +static BOOL(WINAPI* pSetThreadpoolThreadMinimum)(PTP_POOL ptpp, DWORD cthrdMic); +static VOID(WINAPI* pSetThreadpoolThreadMaximum)(PTP_POOL ptpp, DWORD cthrdMost); + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + if (kernel32) + { + pCreateThreadpool = GetProcAddressAs(kernel32, "CreateThreadpool", void*); + pCloseThreadpool = GetProcAddressAs(kernel32, "CloseThreadpool", void*); + pSetThreadpoolThreadMinimum = + GetProcAddressAs(kernel32, "SetThreadpoolThreadMinimum", void*); + pSetThreadpoolThreadMaximum = + GetProcAddressAs(kernel32, "SetThreadpoolThreadMaximum", void*); + } + return TRUE; +} +#endif + +static TP_POOL DEFAULT_POOL = { + 0, /* DWORD Minimum */ + 500, /* DWORD Maximum */ + NULL, /* wArrayList* Threads */ + NULL, /* wQueue* PendingQueue */ + NULL, /* HANDLE TerminateEvent */ + NULL, /* wCountdownEvent* WorkComplete */ +}; + +static DWORD WINAPI thread_pool_work_func(LPVOID arg) +{ + DWORD status = 0; + PTP_POOL pool = NULL; + PTP_WORK work = NULL; + HANDLE events[2]; + PTP_CALLBACK_INSTANCE callbackInstance = NULL; + + pool = (PTP_POOL)arg; + + events[0] = pool->TerminateEvent; + events[1] = Queue_Event(pool->PendingQueue); + + while (1) + { + status = WaitForMultipleObjects(2, events, FALSE, INFINITE); + + if (status == WAIT_OBJECT_0) + break; + + if (status != (WAIT_OBJECT_0 + 1)) + break; + + callbackInstance = (PTP_CALLBACK_INSTANCE)Queue_Dequeue(pool->PendingQueue); + + if (callbackInstance) + { + work = callbackInstance->Work; + work->WorkCallback(callbackInstance, work->CallbackParameter, work); + CountdownEvent_Signal(pool->WorkComplete, 1); + free(callbackInstance); + } + } + + ExitThread(0); + return 0; +} + +static void threads_close(void* thread) +{ + (void)WaitForSingleObject(thread, INFINITE); + (void)CloseHandle(thread); +} + +static BOOL InitializeThreadpool(PTP_POOL pool) +{ + BOOL rc = FALSE; + wObject* obj = NULL; + + if (pool->Threads) + return TRUE; + + if (!(pool->PendingQueue = Queue_New(TRUE, -1, -1))) + goto fail; + + if (!(pool->WorkComplete = CountdownEvent_New(0))) + goto fail; + + if (!(pool->TerminateEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail; + + if (!(pool->Threads = ArrayList_New(TRUE))) + goto fail; + + obj = ArrayList_Object(pool->Threads); + obj->fnObjectFree = threads_close; + + SYSTEM_INFO info = { 0 }; + GetSystemInfo(&info); + if (info.dwNumberOfProcessors < 1) + info.dwNumberOfProcessors = 1; + if (!SetThreadpoolThreadMinimum(pool, info.dwNumberOfProcessors)) + goto fail; + SetThreadpoolThreadMaximum(pool, info.dwNumberOfProcessors); + + rc = TRUE; + +fail: + return rc; +} + +PTP_POOL GetDefaultThreadpool(void) +{ + PTP_POOL pool = NULL; + + pool = &DEFAULT_POOL; + + if (!InitializeThreadpool(pool)) + return NULL; + + return pool; +} + +PTP_POOL winpr_CreateThreadpool(PVOID reserved) +{ + PTP_POOL pool = NULL; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pCreateThreadpool) + return pCreateThreadpool(reserved); +#else + WINPR_UNUSED(reserved); +#endif + if (!(pool = (PTP_POOL)calloc(1, sizeof(TP_POOL)))) + return NULL; + + if (!InitializeThreadpool(pool)) + { + winpr_CloseThreadpool(pool); + return NULL; + } + + return pool; +} + +VOID winpr_CloseThreadpool(PTP_POOL ptpp) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pCloseThreadpool) + { + pCloseThreadpool(ptpp); + return; + } +#endif + (void)SetEvent(ptpp->TerminateEvent); + + ArrayList_Free(ptpp->Threads); + Queue_Free(ptpp->PendingQueue); + CountdownEvent_Free(ptpp->WorkComplete); + (void)CloseHandle(ptpp->TerminateEvent); + + { + TP_POOL empty = { 0 }; + *ptpp = empty; + } + + if (ptpp != &DEFAULT_POOL) + free(ptpp); +} + +BOOL winpr_SetThreadpoolThreadMinimum(PTP_POOL ptpp, DWORD cthrdMic) +{ + BOOL rc = FALSE; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pSetThreadpoolThreadMinimum) + return pSetThreadpoolThreadMinimum(ptpp, cthrdMic); +#endif + ptpp->Minimum = cthrdMic; + + ArrayList_Lock(ptpp->Threads); + while (ArrayList_Count(ptpp->Threads) < ptpp->Minimum) + { + HANDLE thread = CreateThread(NULL, 0, thread_pool_work_func, (void*)ptpp, 0, NULL); + if (!thread) + goto fail; + + if (!ArrayList_Append(ptpp->Threads, thread)) + { + (void)CloseHandle(thread); + goto fail; + } + } + + rc = TRUE; +fail: + ArrayList_Unlock(ptpp->Threads); + + return rc; +} + +VOID winpr_SetThreadpoolThreadMaximum(PTP_POOL ptpp, DWORD cthrdMost) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pSetThreadpoolThreadMaximum) + { + pSetThreadpoolThreadMaximum(ptpp, cthrdMost); + return; + } +#endif + ptpp->Maximum = cthrdMost; + + ArrayList_Lock(ptpp->Threads); + if (ArrayList_Count(ptpp->Threads) > ptpp->Maximum) + { + (void)SetEvent(ptpp->TerminateEvent); + ArrayList_Clear(ptpp->Threads); + (void)ResetEvent(ptpp->TerminateEvent); + } + ArrayList_Unlock(ptpp->Threads); + winpr_SetThreadpoolThreadMinimum(ptpp, ptpp->Minimum); +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.h new file mode 100644 index 0000000000000000000000000000000000000000..7e8cf4cd99f255745dd47e779f32aec3b4389d9e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/pool.h @@ -0,0 +1,122 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Pool) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_POOL_PRIVATE_H + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#if (_WIN32_WINNT < _WIN32_WINNT_WIN6) || defined(__MINGW32__) +struct S_TP_CALLBACK_INSTANCE +{ + PTP_WORK Work; +}; + +struct S_TP_POOL +{ + DWORD Minimum; + DWORD Maximum; + wArrayList* Threads; + wQueue* PendingQueue; + HANDLE TerminateEvent; + wCountdownEvent* WorkComplete; +}; + +struct S_TP_WORK +{ + PVOID CallbackParameter; + PTP_WORK_CALLBACK WorkCallback; + PTP_CALLBACK_ENVIRON CallbackEnvironment; +}; + +struct S_TP_TIMER +{ + void* dummy; +}; + +struct S_TP_WAIT +{ + void* dummy; +}; + +struct S_TP_IO +{ + void* dummy; +}; + +struct S_TP_CLEANUP_GROUP +{ + void* dummy; +}; + +#endif +#else +struct S_TP_CALLBACK_INSTANCE +{ + PTP_WORK Work; +}; + +struct S_TP_POOL +{ + DWORD Minimum; + DWORD Maximum; + wArrayList* Threads; + wQueue* PendingQueue; + HANDLE TerminateEvent; + wCountdownEvent* WorkComplete; +}; + +struct S_TP_WORK +{ + PVOID CallbackParameter; + PTP_WORK_CALLBACK WorkCallback; + PTP_CALLBACK_ENVIRON CallbackEnvironment; +}; + +struct S_TP_TIMER +{ + void* dummy; +}; + +struct S_TP_WAIT +{ + void* dummy; +}; + +struct S_TP_IO +{ + void* dummy; +}; + +struct S_TP_CLEANUP_GROUP +{ + wArrayList* groups; + PTP_CALLBACK_ENVIRON env; +}; + +#endif + +PTP_POOL GetDefaultThreadpool(void); + +#endif /* WINPR_POOL_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/synch.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/synch.c new file mode 100644 index 0000000000000000000000000000000000000000..1586a0ec595b03a4d0f179e96a341b354bb0788c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/synch.c @@ -0,0 +1,44 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Synch) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#ifdef WINPR_THREAD_POOL + +PTP_WAIT winpr_CreateThreadpoolWait(PTP_WAIT_CALLBACK pfnwa, PVOID pv, PTP_CALLBACK_ENVIRON pcbe) +{ + return NULL; +} + +VOID winpr_CloseThreadpoolWait(PTP_WAIT pwa) +{ +} + +VOID winpr_SetThreadpoolWait(PTP_WAIT pwa, HANDLE h, PFILETIME pftTimeout) +{ +} + +VOID winpr_WaitForThreadpoolWaitCallbacks(PTP_WAIT pwa, BOOL fCancelPendingCallbacks) +{ +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e591e8a9f26c247087b522ebe8410402e1d6f9bc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestPool") +set(MODULE_PREFIX "TEST_POOL") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestPoolIO.c TestPoolSynch.c TestPoolThread.c TestPoolTimer.c TestPoolWork.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolIO.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolIO.c new file mode 100644 index 0000000000000000000000000000000000000000..d68586edeaee395e3ce987cbf5a72dfa4eb94ca9 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolIO.c @@ -0,0 +1,8 @@ + +#include +#include + +int TestPoolIO(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolSynch.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolSynch.c new file mode 100644 index 0000000000000000000000000000000000000000..4d6f38199b76550f55f96e8095801a03288715c1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolSynch.c @@ -0,0 +1,8 @@ + +#include +#include + +int TestPoolSynch(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolThread.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolThread.c new file mode 100644 index 0000000000000000000000000000000000000000..d006ae6f8c5bea113af669a88673f22ae4c7903c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolThread.c @@ -0,0 +1,41 @@ + +#include +#include + +/** + * Improve Scalability With New Thread Pool APIs: + * http://msdn.microsoft.com/en-us/magazine/cc16332.aspx + * + * Developing with Thread Pool Enhancements: + * http://msdn.microsoft.com/en-us/library/cc308561.aspx + * + * Introduction to the Windows Threadpool: + * http://blogs.msdn.com/b/harip/archive/2010/10/11/introduction-to-the-windows-threadpool-part-1.aspx + * http://blogs.msdn.com/b/harip/archive/2010/10/12/introduction-to-the-windows-threadpool-part-2.aspx + */ + +int TestPoolThread(int argc, char* argv[]) +{ + TP_POOL* pool = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!(pool = CreateThreadpool(NULL))) + { + printf("CreateThreadpool failed\n"); + return -1; + } + + if (!SetThreadpoolThreadMinimum(pool, 8)) /* default is 0 */ + { + printf("SetThreadpoolThreadMinimum failed\n"); + return -1; + } + + SetThreadpoolThreadMaximum(pool, 64); /* default is 500 */ + + CloseThreadpool(pool); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolTimer.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolTimer.c new file mode 100644 index 0000000000000000000000000000000000000000..c749bc73437c5d0a6562a445465753b20e3cd69a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolTimer.c @@ -0,0 +1,8 @@ + +#include +#include + +int TestPoolTimer(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolWork.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolWork.c new file mode 100644 index 0000000000000000000000000000000000000000..ec50a229ee90e19648b85a52d8be419304a7d7bb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/test/TestPoolWork.c @@ -0,0 +1,136 @@ + +#include +#include +#include +#include + +static LONG count = 0; + +static void CALLBACK test_WorkCallback(PTP_CALLBACK_INSTANCE instance, void* context, PTP_WORK work) +{ + printf("Hello %s: %03" PRId32 " (thread: 0x%08" PRIX32 ")\n", (char*)context, + InterlockedIncrement(&count), GetCurrentThreadId()); + + for (int index = 0; index < 100; index++) + { + BYTE a[1024]; + BYTE b[1024]; + BYTE c[1024] = { 0 }; + + FillMemory(a, ARRAYSIZE(a), 0xAA); + FillMemory(b, ARRAYSIZE(b), 0xBB); + + CopyMemory(c, a, ARRAYSIZE(a)); + CopyMemory(c, b, ARRAYSIZE(b)); + } +} + +static BOOL test1(void) +{ + PTP_WORK work = NULL; + printf("Global Thread Pool\n"); + work = CreateThreadpoolWork(test_WorkCallback, "world", NULL); + + if (!work) + { + printf("CreateThreadpoolWork failure\n"); + return FALSE; + } + + /** + * You can post a work object one or more times (up to MAXULONG) without waiting for prior + * callbacks to complete. The callbacks will execute in parallel. To improve efficiency, the + * thread pool may throttle the threads. + */ + + for (int index = 0; index < 10; index++) + SubmitThreadpoolWork(work); + + WaitForThreadpoolWorkCallbacks(work, FALSE); + CloseThreadpoolWork(work); + return TRUE; +} + +static BOOL test2(void) +{ + BOOL rc = FALSE; + PTP_POOL pool = NULL; + PTP_WORK work = NULL; + PTP_CLEANUP_GROUP cleanupGroup = NULL; + TP_CALLBACK_ENVIRON environment; + printf("Private Thread Pool\n"); + + if (!(pool = CreateThreadpool(NULL))) + { + printf("CreateThreadpool failure\n"); + return FALSE; + } + + if (!SetThreadpoolThreadMinimum(pool, 4)) + { + printf("SetThreadpoolThreadMinimum failure\n"); + goto fail; + } + + SetThreadpoolThreadMaximum(pool, 8); + InitializeThreadpoolEnvironment(&environment); + SetThreadpoolCallbackPool(&environment, pool); + cleanupGroup = CreateThreadpoolCleanupGroup(); + + if (!cleanupGroup) + { + printf("CreateThreadpoolCleanupGroup failure\n"); + goto fail; + } + + SetThreadpoolCallbackCleanupGroup(&environment, cleanupGroup, NULL); + work = CreateThreadpoolWork(test_WorkCallback, "world", &environment); + + if (!work) + { + printf("CreateThreadpoolWork failure\n"); + goto fail; + } + + for (int index = 0; index < 10; index++) + SubmitThreadpoolWork(work); + + WaitForThreadpoolWorkCallbacks(work, FALSE); + rc = TRUE; +fail: + + if (cleanupGroup) + { + CloseThreadpoolCleanupGroupMembers(cleanupGroup, TRUE, NULL); + CloseThreadpoolCleanupGroup(cleanupGroup); + DestroyThreadpoolEnvironment(&environment); + /** + * See Remarks at + * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682043(v=vs.85).aspx If there + * is a cleanup group associated with the work object, it is not necessary to call + * CloseThreadpoolWork ! calling the CloseThreadpoolCleanupGroupMembers function releases + * the work, wait, and timer objects associated with the cleanup group. + */ +#if 0 + CloseThreadpoolWork(work); // this would segfault, see comment above. */ +#endif + } + + CloseThreadpool(pool); + return rc; +} + +int TestPoolWork(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test1()) + return -1; + + if (!test2()) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/timer.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/timer.c new file mode 100644 index 0000000000000000000000000000000000000000..a8aa1a7853616e0fe7e8978edc69f6b5985f8b68 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/timer.c @@ -0,0 +1,50 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Timer) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#ifdef WINPR_THREAD_POOL + +PTP_TIMER winpr_CreateThreadpoolTimer(PTP_TIMER_CALLBACK pfnti, PVOID pv, PTP_CALLBACK_ENVIRON pcbe) +{ + return NULL; +} + +VOID winpr_CloseThreadpoolTimer(PTP_TIMER pti) +{ +} + +BOOL winpr_IsThreadpoolTimerSet(PTP_TIMER pti) +{ + return FALSE; +} + +VOID winpr_SetThreadpoolTimer(PTP_TIMER pti, PFILETIME pftDueTime, DWORD msPeriod, + DWORD msWindowLength) +{ +} + +VOID winpr_WaitForThreadpoolTimerCallbacks(PTP_TIMER pti, BOOL fCancelPendingCallbacks) +{ +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/work.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/work.c new file mode 100644 index 0000000000000000000000000000000000000000..0fd2e65c4961d9c00cc89e30229e0742ffda90c1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/pool/work.c @@ -0,0 +1,199 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Work) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "pool.h" +#include "../log.h" +#define TAG WINPR_TAG("pool") + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static PTP_WORK(WINAPI* pCreateThreadpoolWork)(PTP_WORK_CALLBACK pfnwk, PVOID pv, + PTP_CALLBACK_ENVIRON pcbe); +static VOID(WINAPI* pCloseThreadpoolWork)(PTP_WORK pwk); +static VOID(WINAPI* pSubmitThreadpoolWork)(PTP_WORK pwk); +static BOOL(WINAPI* pTrySubmitThreadpoolCallback)(PTP_SIMPLE_CALLBACK pfns, PVOID pv, + PTP_CALLBACK_ENVIRON pcbe); +static VOID(WINAPI* pWaitForThreadpoolWorkCallbacks)(PTP_WORK pwk, BOOL fCancelPendingCallbacks); + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + + if (kernel32) + { + pCreateThreadpoolWork = GetProcAddressAs(kernel32, "CreateThreadpoolWork", void*); + pCloseThreadpoolWork = GetProcAddressAs(kernel32, "CloseThreadpoolWork", void*); + pSubmitThreadpoolWork = GetProcAddressAs(kernel32, "SubmitThreadpoolWork", void*); + pTrySubmitThreadpoolCallback = + GetProcAddressAs(kernel32, "TrySubmitThreadpoolCallback", void*); + pWaitForThreadpoolWorkCallbacks = + GetProcAddressAs(kernel32, "WaitForThreadpoolWorkCallbacks", void*); + } + + return TRUE; +} +#endif + +static TP_CALLBACK_ENVIRON DEFAULT_CALLBACK_ENVIRONMENT = { + 1, /* Version */ + NULL, /* Pool */ + NULL, /* CleanupGroup */ + NULL, /* CleanupGroupCancelCallback */ + NULL, /* RaceDll */ + NULL, /* FinalizationCallback */ + { 0 } /* Flags */ +}; + +PTP_WORK winpr_CreateThreadpoolWork(PTP_WORK_CALLBACK pfnwk, PVOID pv, PTP_CALLBACK_ENVIRON pcbe) +{ + PTP_WORK work = NULL; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pCreateThreadpoolWork) + return pCreateThreadpoolWork(pfnwk, pv, pcbe); + +#endif + work = (PTP_WORK)calloc(1, sizeof(TP_WORK)); + + if (work) + { + if (!pcbe) + { + pcbe = &DEFAULT_CALLBACK_ENVIRONMENT; + pcbe->Pool = GetDefaultThreadpool(); + } + + work->CallbackEnvironment = pcbe; + work->WorkCallback = pfnwk; + work->CallbackParameter = pv; +#ifndef _WIN32 + + if (pcbe->CleanupGroup) + ArrayList_Append(pcbe->CleanupGroup->groups, work); + +#endif + } + + return work; +} + +VOID winpr_CloseThreadpoolWork(PTP_WORK pwk) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pCloseThreadpoolWork) + { + pCloseThreadpoolWork(pwk); + return; + } + +#else + + WINPR_ASSERT(pwk); + WINPR_ASSERT(pwk->CallbackEnvironment); + if (pwk->CallbackEnvironment->CleanupGroup) + ArrayList_Remove(pwk->CallbackEnvironment->CleanupGroup->groups, pwk); + +#endif + free(pwk); +} + +VOID winpr_SubmitThreadpoolWork(PTP_WORK pwk) +{ + PTP_POOL pool = NULL; + PTP_CALLBACK_INSTANCE callbackInstance = NULL; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pSubmitThreadpoolWork) + { + pSubmitThreadpoolWork(pwk); + return; + } + +#endif + + WINPR_ASSERT(pwk); + WINPR_ASSERT(pwk->CallbackEnvironment); + pool = pwk->CallbackEnvironment->Pool; + callbackInstance = (PTP_CALLBACK_INSTANCE)calloc(1, sizeof(TP_CALLBACK_INSTANCE)); + + if (callbackInstance) + { + callbackInstance->Work = pwk; + CountdownEvent_AddCount(pool->WorkComplete, 1); + if (!Queue_Enqueue(pool->PendingQueue, callbackInstance)) + free(callbackInstance); + } + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): Queue_Enqueue takes ownership of callbackInstance +} + +BOOL winpr_TrySubmitThreadpoolCallback(PTP_SIMPLE_CALLBACK pfns, PVOID pv, + PTP_CALLBACK_ENVIRON pcbe) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pTrySubmitThreadpoolCallback) + return pTrySubmitThreadpoolCallback(pfns, pv, pcbe); + +#endif + WLog_ERR(TAG, "TrySubmitThreadpoolCallback is not implemented"); + return FALSE; +} + +VOID winpr_WaitForThreadpoolWorkCallbacks(PTP_WORK pwk, BOOL fCancelPendingCallbacks) +{ + HANDLE event = NULL; + PTP_POOL pool = NULL; + +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + + if (pWaitForThreadpoolWorkCallbacks) + { + pWaitForThreadpoolWorkCallbacks(pwk, fCancelPendingCallbacks); + return; + } + +#endif + WINPR_ASSERT(pwk); + WINPR_ASSERT(pwk->CallbackEnvironment); + + pool = pwk->CallbackEnvironment->Pool; + WINPR_ASSERT(pool); + + event = CountdownEvent_WaitHandle(pool->WorkComplete); + + if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) + WLog_ERR(TAG, "error waiting on work completion"); +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b33e6185362d445d6e3fb25be9be4da87e8cb66 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/CMakeLists.txt @@ -0,0 +1,18 @@ +# WinPR: Windows Portable Runtime +# libwinpr-registry cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(registry_reg.c registry_reg.h registry.c) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..7c71eb0149abe80b1049dd9fb33411a302947fcd --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/ModuleOptions.cmake @@ -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 "registry") +set(MINWIN_LONG_NAME "Registry Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry.c new file mode 100644 index 0000000000000000000000000000000000000000..e04c89c4594cd784615c839f8275f3d398f7b860 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry.c @@ -0,0 +1,559 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Registry + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +/* + * Windows registry MSDN pages: + * Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724880/ + * Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724875/ + */ + +#if !defined(_WIN32) || defined(_UWP) + +#include +#include +#include + +#include +#include + +#include "registry_reg.h" + +#include "../log.h" +#define TAG WINPR_TAG("registry") + +static Reg* instance = NULL; + +static Reg* RegGetInstance(void) +{ + if (!instance) + instance = reg_open(1); + + return instance; +} + +LONG RegCloseKey(HKEY hKey) +{ + WINPR_UNUSED(hKey); + return 0; +} + +LONG RegCopyTreeW(HKEY hKeySrc, LPCWSTR lpSubKey, HKEY hKeyDest) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegCopyTreeA(HKEY hKeySrc, LPCSTR lpSubKey, HKEY hKeyDest) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, + REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, + LPDWORD lpdwDisposition) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegCreateKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, + REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, + LPDWORD lpdwDisposition) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteKeyExW(HKEY hKey, LPCWSTR lpSubKey, REGSAM samDesired, DWORD Reserved) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteKeyExA(HKEY hKey, LPCSTR lpSubKey, REGSAM samDesired, DWORD Reserved) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteTreeW(HKEY hKey, LPCWSTR lpSubKey) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteTreeA(HKEY hKey, LPCSTR lpSubKey) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteValueW(HKEY hKey, LPCWSTR lpValueName) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDeleteValueA(HKEY hKey, LPCSTR lpValueName) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegDisablePredefinedCacheEx(void) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegEnumKeyExW(HKEY hKey, DWORD dwIndex, LPWSTR lpName, LPDWORD lpcName, LPDWORD lpReserved, + LPWSTR lpClass, LPDWORD lpcClass, PFILETIME lpftLastWriteTime) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegEnumKeyExA(HKEY hKey, DWORD dwIndex, LPSTR lpName, LPDWORD lpcName, LPDWORD lpReserved, + LPSTR lpClass, LPDWORD lpcClass, PFILETIME lpftLastWriteTime) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName, + LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegEnumValueA(HKEY hKey, DWORD dwIndex, LPSTR lpValueName, LPDWORD lpcchValueName, + LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegFlushKey(HKEY hKey) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegGetKeySecurity(HKEY hKey, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, LPDWORD lpcbSecurityDescriptor) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegGetValueW(HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpValue, DWORD dwFlags, LPDWORD pdwType, + PVOID pvData, LPDWORD pcbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegGetValueA(HKEY hkey, LPCSTR lpSubKey, LPCSTR lpValue, DWORD dwFlags, LPDWORD pdwType, + PVOID pvData, LPDWORD pcbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadAppKeyW(LPCWSTR lpFile, PHKEY phkResult, REGSAM samDesired, DWORD dwOptions, + DWORD Reserved) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadAppKeyA(LPCSTR lpFile, PHKEY phkResult, REGSAM samDesired, DWORD dwOptions, + DWORD Reserved) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadKeyW(HKEY hKey, LPCWSTR lpSubKey, LPCWSTR lpFile) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadKeyA(HKEY hKey, LPCSTR lpSubKey, LPCSTR lpFile) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadMUIStringW(HKEY hKey, LPCWSTR pszValue, LPWSTR pszOutBuf, DWORD cbOutBuf, + LPDWORD pcbData, DWORD Flags, LPCWSTR pszDirectory) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegLoadMUIStringA(HKEY hKey, LPCSTR pszValue, LPSTR pszOutBuf, DWORD cbOutBuf, LPDWORD pcbData, + DWORD Flags, LPCSTR pszDirectory) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegNotifyChangeKeyValue(HKEY hKey, BOOL bWatchSubtree, DWORD dwNotifyFilter, HANDLE hEvent, + BOOL fAsynchronous) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegOpenCurrentUser(REGSAM samDesired, PHKEY phkResult) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) +{ + LONG rc = 0; + char* str = ConvertWCharToUtf8Alloc(lpSubKey, NULL); + if (!str) + return ERROR_FILE_NOT_FOUND; + + rc = RegOpenKeyExA(hKey, str, ulOptions, samDesired, phkResult); + free(str); + return rc; +} + +LONG RegOpenKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) +{ + Reg* reg = RegGetInstance(); + + if (!reg) + return -1; + + if (hKey != HKEY_LOCAL_MACHINE) + { + WLog_WARN(TAG, "Registry emulation only supports HKEY_LOCAL_MACHINE"); + return ERROR_FILE_NOT_FOUND; + } + + WINPR_ASSERT(reg->root_key); + RegKey* pKey = reg->root_key->subkeys; + + while (pKey != NULL) + { + WINPR_ASSERT(lpSubKey); + + if (pKey->subname && (_stricmp(pKey->subname, lpSubKey) == 0)) + { + *phkResult = (HKEY)pKey; + return ERROR_SUCCESS; + } + + pKey = pKey->next; + } + + *phkResult = NULL; + + return ERROR_FILE_NOT_FOUND; +} + +LONG RegOpenUserClassesRoot(HANDLE hToken, DWORD dwOptions, REGSAM samDesired, PHKEY phkResult) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +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) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +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) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +static LONG reg_read_int(const RegVal* pValue, LPBYTE lpData, LPDWORD lpcbData) +{ + const BYTE* ptr = NULL; + DWORD required = 0; + + WINPR_ASSERT(pValue); + + switch (pValue->type) + { + case REG_DWORD: + case REG_DWORD_BIG_ENDIAN: + required = sizeof(DWORD); + ptr = (const BYTE*)&pValue->data.dword; + break; + case REG_QWORD: + required = sizeof(UINT64); + ptr = (const BYTE*)&pValue->data.qword; + break; + default: + return ERROR_INTERNAL_ERROR; + } + + if (lpcbData) + { + DWORD size = *lpcbData; + *lpcbData = required; + if (lpData) + { + if (size < *lpcbData) + return ERROR_MORE_DATA; + } + } + + if (lpData != NULL) + { + DWORD size = 0; + WINPR_ASSERT(lpcbData); + + size = *lpcbData; + *lpcbData = required; + if (size < required) + return ERROR_MORE_DATA; + memcpy(lpData, ptr, required); + } + else if (lpcbData != NULL) + *lpcbData = required; + return ERROR_SUCCESS; +} + +// NOLINTBEGIN(readability-non-const-parameter) +LONG RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, + LPBYTE lpData, LPDWORD lpcbData) +// NOLINTEND(readability-non-const-parameter) +{ + LONG status = ERROR_FILE_NOT_FOUND; + RegKey* key = NULL; + RegVal* pValue = NULL; + char* valueName = NULL; + + WINPR_UNUSED(lpReserved); + + key = (RegKey*)hKey; + WINPR_ASSERT(key); + + valueName = ConvertWCharToUtf8Alloc(lpValueName, NULL); + if (!valueName) + goto end; + + pValue = key->values; + + while (pValue != NULL) + { + if (strcmp(pValue->name, valueName) == 0) + { + if (lpType) + *lpType = pValue->type; + + switch (pValue->type) + { + case REG_DWORD_BIG_ENDIAN: + case REG_QWORD: + case REG_DWORD: + status = reg_read_int(pValue, lpData, lpcbData); + goto end; + case REG_SZ: + { + const size_t length = strnlen(pValue->data.string, UINT32_MAX) * sizeof(WCHAR); + + status = ERROR_SUCCESS; + if (lpData != NULL) + { + DWORD size = 0; + union + { + WCHAR* wc; + BYTE* b; + } cnv; + WINPR_ASSERT(lpcbData); + + cnv.b = lpData; + size = *lpcbData; + *lpcbData = (DWORD)length; + if (size < length) + status = ERROR_MORE_DATA; + if (ConvertUtf8NToWChar(pValue->data.string, length, cnv.wc, length) < 0) + status = ERROR_OUTOFMEMORY; + } + else if (lpcbData) + *lpcbData = (UINT32)length; + + goto end; + } + default: + WLog_WARN(TAG, + "Registry emulation does not support value type %s [0x%08" PRIx32 "]", + reg_type_string(pValue->type), pValue->type); + break; + } + } + + pValue = pValue->next; + } + +end: + free(valueName); + return status; +} + +// NOLINTBEGIN(readability-non-const-parameter) +LONG RegQueryValueExA(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, + LPBYTE lpData, LPDWORD lpcbData) +// NOLINTEND(readability-non-const-parameter) +{ + RegKey* key = NULL; + RegVal* pValue = NULL; + + WINPR_UNUSED(lpReserved); + + key = (RegKey*)hKey; + WINPR_ASSERT(key); + + pValue = key->values; + + while (pValue != NULL) + { + if (strcmp(pValue->name, lpValueName) == 0) + { + if (lpType) + *lpType = pValue->type; + + switch (pValue->type) + { + case REG_DWORD_BIG_ENDIAN: + case REG_QWORD: + case REG_DWORD: + return reg_read_int(pValue, lpData, lpcbData); + case REG_SZ: + { + const size_t length = strnlen(pValue->data.string, UINT32_MAX); + char* pData = (char*)lpData; + + if (pData != NULL) + { + DWORD size = 0; + WINPR_ASSERT(lpcbData); + + size = *lpcbData; + *lpcbData = (DWORD)length; + if (size < length) + return ERROR_MORE_DATA; + memcpy(pData, pValue->data.string, length); + pData[length] = '\0'; + } + else if (lpcbData) + *lpcbData = (UINT32)length; + + return ERROR_SUCCESS; + } + default: + WLog_WARN(TAG, + "Registry emulation does not support value type %s [0x%08" PRIx32 "]", + reg_type_string(pValue->type), pValue->type); + break; + } + } + + pValue = pValue->next; + } + + return ERROR_FILE_NOT_FOUND; +} + +LONG RegRestoreKeyW(HKEY hKey, LPCWSTR lpFile, DWORD dwFlags) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegRestoreKeyA(HKEY hKey, LPCSTR lpFile, DWORD dwFlags) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegSaveKeyExW(HKEY hKey, LPCWSTR lpFile, LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD Flags) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegSaveKeyExA(HKEY hKey, LPCSTR lpFile, LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD Flags) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegSetKeySecurity(HKEY hKey, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, + const BYTE* lpData, DWORD cbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegSetValueExA(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, + DWORD cbData) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegUnLoadKeyW(HKEY hKey, LPCWSTR lpSubKey) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +LONG RegUnLoadKeyA(HKEY hKey, LPCSTR lpSubKey) +{ + WLog_ERR(TAG, "TODO: Implement"); + return -1; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.c new file mode 100644 index 0000000000000000000000000000000000000000..698210c06d8c080073d9bf0ddb172a9bb5f05030 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.c @@ -0,0 +1,572 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Registry (.reg file format) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "registry_reg.h" + +#include "../log.h" +#define TAG WINPR_TAG("registry") + +struct reg_data_type +{ + char* tag; + size_t length; + DWORD type; +}; + +static struct reg_data_type REG_DATA_TYPE_TABLE[] = { { "\"", 1, REG_SZ }, + { "dword:", 6, REG_DWORD }, + { "str:\"", 5, REG_SZ }, + { "str(2):\"", 8, REG_EXPAND_SZ }, + { "str(7):\"", 8, REG_MULTI_SZ }, + { "hex:", 4, REG_BINARY }, + { "hex(2):\"", 8, REG_EXPAND_SZ }, + { "hex(7):\"", 8, REG_MULTI_SZ }, + { "hex(b):\"", 8, REG_QWORD } }; + +static char* reg_data_type_string(DWORD type) +{ + switch (type) + { + case REG_NONE: + return "REG_NONE"; + case REG_SZ: + return "REG_SZ"; + case REG_EXPAND_SZ: + return "REG_EXPAND_SZ"; + case REG_BINARY: + return "REG_BINARY"; + case REG_DWORD: + return "REG_DWORD"; + case REG_DWORD_BIG_ENDIAN: + return "REG_DWORD_BIG_ENDIAN"; + case REG_LINK: + return "REG_LINK"; + case REG_MULTI_SZ: + return "REG_MULTI_SZ"; + case REG_RESOURCE_LIST: + return "REG_RESOURCE_LIST"; + case REG_FULL_RESOURCE_DESCRIPTOR: + return "REG_FULL_RESOURCE_DESCRIPTOR"; + case REG_RESOURCE_REQUIREMENTS_LIST: + return "REG_RESOURCE_REQUIREMENTS_LIST"; + case REG_QWORD: + return "REG_QWORD"; + default: + return "REG_UNKNOWN"; + } +} + +static BOOL reg_load_start(Reg* reg) +{ + char* buffer = NULL; + INT64 file_size = 0; + + WINPR_ASSERT(reg); + WINPR_ASSERT(reg->fp); + + if (_fseeki64(reg->fp, 0, SEEK_END) != 0) + return FALSE; + file_size = _ftelli64(reg->fp); + if (_fseeki64(reg->fp, 0, SEEK_SET) != 0) + return FALSE; + reg->line = NULL; + reg->next_line = NULL; + + if (file_size < 1) + return FALSE; + + buffer = (char*)realloc(reg->buffer, (size_t)file_size + 2); + + if (!buffer) + return FALSE; + reg->buffer = buffer; + + if (fread(reg->buffer, (size_t)file_size, 1, reg->fp) != 1) + return FALSE; + + reg->buffer[file_size] = '\n'; + reg->buffer[file_size + 1] = '\0'; + reg->next_line = strtok_s(reg->buffer, "\n", ®->saveptr); + return TRUE; +} + +static void reg_load_finish(Reg* reg) +{ + if (!reg) + return; + + if (reg->buffer) + { + free(reg->buffer); + reg->buffer = NULL; + } +} + +static RegVal* reg_load_value(const Reg* reg, RegKey* key) +{ + const char* p[5] = { 0 }; + size_t length = 0; + char* name = NULL; + const char* type = NULL; + const char* data = NULL; + RegVal* value = NULL; + + WINPR_ASSERT(reg); + WINPR_ASSERT(key); + WINPR_ASSERT(reg->line); + + p[0] = reg->line + 1; + p[1] = strstr(p[0], "\"="); + if (!p[1]) + return NULL; + + p[2] = p[1] + 2; + type = p[2]; + + if (p[2][0] == '"') + p[3] = p[2]; + else + p[3] = strchr(p[2], ':'); + + if (!p[3]) + return NULL; + + data = p[3] + 1; + length = (size_t)(p[1] - p[0]); + if (length < 1) + goto fail; + + name = (char*)calloc(length + 1, sizeof(char)); + + if (!name) + goto fail; + + memcpy(name, p[0], length); + value = (RegVal*)calloc(1, sizeof(RegVal)); + + if (!value) + goto fail; + + value->name = name; + value->type = REG_NONE; + + for (size_t index = 0; index < ARRAYSIZE(REG_DATA_TYPE_TABLE); index++) + { + const struct reg_data_type* current = ®_DATA_TYPE_TABLE[index]; + WINPR_ASSERT(current->tag); + WINPR_ASSERT(current->length > 0); + WINPR_ASSERT(current->type != REG_NONE); + + if (strncmp(type, current->tag, current->length) == 0) + { + value->type = current->type; + break; + } + } + + switch (value->type) + { + case REG_DWORD: + { + unsigned long val = 0; + errno = 0; + val = strtoul(data, NULL, 0); + + if ((errno != 0) || (val > UINT32_MAX)) + { + WLog_WARN(TAG, "%s::%s value %s invalid", key->name, value->name, data); + goto fail; + } + value->data.dword = (DWORD)val; + } + break; + case REG_QWORD: + { + unsigned long long val = 0; + errno = 0; + val = strtoull(data, NULL, 0); + + if ((errno != 0) || (val > UINT64_MAX)) + { + WLog_WARN(TAG, "%s::%s value %s invalid", key->name, value->name, data); + goto fail; + } + + value->data.qword = (UINT64)val; + } + break; + case REG_SZ: + { + char* start = strchr(data, '"'); + if (!start) + goto fail; + + /* Check for terminating quote, check it is the last symbol */ + const size_t len = strlen(start); + char* end = strchr(start + 1, '"'); + if (!end) + goto fail; + const intptr_t cmp = end - start + 1; + if ((cmp < 0) || (len != WINPR_ASSERTING_INT_CAST(size_t, cmp))) + goto fail; + if (start[0] == '"') + start++; + if (end[0] == '"') + end[0] = '\0'; + value->data.string = _strdup(start); + + if (!value->data.string) + goto fail; + } + break; + default: + WLog_ERR(TAG, "[%s] %s unimplemented format: %s", key->name, value->name, + reg_data_type_string(value->type)); + break; + } + + if (!key->values) + { + key->values = value; + } + else + { + RegVal* pValue = key->values; + + while (pValue->next != NULL) + { + pValue = pValue->next; + } + + pValue->next = value; + value->prev = pValue; + } + + return value; + +fail: + free(value); + free(name); + return NULL; +} + +static BOOL reg_load_has_next_line(Reg* reg) +{ + if (!reg) + return 0; + + return (reg->next_line != NULL) ? 1 : 0; +} + +static char* reg_load_get_next_line(Reg* reg) +{ + if (!reg) + return NULL; + + reg->line = reg->next_line; + reg->next_line = strtok_s(NULL, "\n", ®->saveptr); + reg->line_length = strlen(reg->line); + return reg->line; +} + +static char* reg_load_peek_next_line(Reg* reg) +{ + WINPR_ASSERT(reg); + return reg->next_line; +} + +static void reg_insert_key(Reg* reg, RegKey* key, RegKey* subkey) +{ + char* name = NULL; + char* path = NULL; + char* save = NULL; + + WINPR_ASSERT(reg); + WINPR_ASSERT(key); + WINPR_ASSERT(subkey); + WINPR_ASSERT(subkey->name); + + path = _strdup(subkey->name); + + if (!path) + return; + + name = strtok_s(path, "\\", &save); + + while (name != NULL) + { + if (strcmp(key->name, name) == 0) + { + if (save) + subkey->subname = _strdup(save); + + /* TODO: free allocated memory in error case */ + if (!subkey->subname) + { + free(path); + return; + } + } + + name = strtok_s(NULL, "\\", &save); + } + + free(path); +} + +static RegKey* reg_load_key(Reg* reg, RegKey* key) +{ + char* p[2]; + size_t length = 0; + RegKey* subkey = NULL; + + WINPR_ASSERT(reg); + WINPR_ASSERT(key); + + WINPR_ASSERT(reg->line); + p[0] = reg->line + 1; + p[1] = strrchr(p[0], ']'); + if (!p[1]) + return NULL; + + subkey = (RegKey*)calloc(1, sizeof(RegKey)); + + if (!subkey) + return NULL; + + length = (size_t)(p[1] - p[0]); + subkey->name = (char*)malloc(length + 1); + + if (!subkey->name) + { + free(subkey); + return NULL; + } + + memcpy(subkey->name, p[0], length); + subkey->name[length] = '\0'; + + while (reg_load_has_next_line(reg)) + { + char* line = reg_load_peek_next_line(reg); + + if (line[0] == '[') + break; + + reg_load_get_next_line(reg); + + if (reg->line[0] == '"') + { + reg_load_value(reg, subkey); + } + } + + reg_insert_key(reg, key, subkey); + + if (!key->subkeys) + { + key->subkeys = subkey; + } + else + { + RegKey* pKey = key->subkeys; + + while (pKey->next != NULL) + { + pKey = pKey->next; + } + + pKey->next = subkey; + subkey->prev = pKey; + } + + return subkey; +} + +static void reg_load(Reg* reg) +{ + reg_load_start(reg); + + while (reg_load_has_next_line(reg)) + { + reg_load_get_next_line(reg); + + if (reg->line[0] == '[') + { + reg_load_key(reg, reg->root_key); + } + } + + reg_load_finish(reg); +} + +static void reg_unload_value(Reg* reg, RegVal* value) +{ + WINPR_ASSERT(reg); + WINPR_ASSERT(value); + + switch (value->type) + { + case REG_SZ: + free(value->data.string); + break; + default: + break; + } + + free(value); +} + +static void reg_unload_key(Reg* reg, RegKey* key) +{ + RegVal* pValue = NULL; + + WINPR_ASSERT(reg); + WINPR_ASSERT(key); + + pValue = key->values; + + while (pValue != NULL) + { + RegVal* pValueNext = pValue->next; + reg_unload_value(reg, pValue); + pValue = pValueNext; + } + + free(key->name); + free(key); +} + +static void reg_unload(Reg* reg) +{ + WINPR_ASSERT(reg); + if (reg->root_key) + { + RegKey* pKey = reg->root_key->subkeys; + + while (pKey != NULL) + { + RegKey* pKeyNext = pKey->next; + reg_unload_key(reg, pKey); + pKey = pKeyNext; + } + + free(reg->root_key); + } +} + +Reg* reg_open(BOOL read_only) +{ + Reg* reg = (Reg*)calloc(1, sizeof(Reg)); + + if (!reg) + return NULL; + + reg->read_only = read_only; + reg->filename = winpr_GetConfigFilePath(TRUE, "HKLM.reg"); + if (!reg->filename) + goto fail; + + if (reg->read_only) + reg->fp = winpr_fopen(reg->filename, "r"); + else + { + reg->fp = winpr_fopen(reg->filename, "r+"); + + if (!reg->fp) + reg->fp = winpr_fopen(reg->filename, "w+"); + } + + if (!reg->fp) + goto fail; + + reg->root_key = (RegKey*)calloc(1, sizeof(RegKey)); + + if (!reg->root_key) + goto fail; + + reg->root_key->values = NULL; + reg->root_key->subkeys = NULL; + reg->root_key->name = "HKEY_LOCAL_MACHINE"; + reg_load(reg); + return reg; + +fail: + reg_close(reg); + return NULL; +} + +void reg_close(Reg* reg) +{ + if (reg) + { + reg_unload(reg); + if (reg->fp) + (void)fclose(reg->fp); + free(reg->filename); + free(reg); + } +} + +const char* reg_type_string(DWORD type) +{ + switch (type) + { + case REG_NONE: + return "REG_NONE"; + case REG_SZ: + return "REG_SZ"; + case REG_EXPAND_SZ: + return "REG_EXPAND_SZ"; + case REG_BINARY: + return "REG_BINARY"; + case REG_DWORD: + return "REG_DWORD"; + case REG_DWORD_BIG_ENDIAN: + return "REG_DWORD_BIG_ENDIAN"; + case REG_LINK: + return "REG_LINK"; + case REG_MULTI_SZ: + return "REG_MULTI_SZ"; + case REG_RESOURCE_LIST: + return "REG_RESOURCE_LIST"; + case REG_FULL_RESOURCE_DESCRIPTOR: + return "REG_FULL_RESOURCE_DESCRIPTOR"; + case REG_RESOURCE_REQUIREMENTS_LIST: + return "REG_RESOURCE_REQUIREMENTS_LIST"; + case REG_QWORD: + return "REG_QWORD"; + default: + return "REG_UNKNOWN"; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.h new file mode 100644 index 0000000000000000000000000000000000000000..83cc5f696d16b9bda097096c063762e4097d1907 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/registry/registry_reg.h @@ -0,0 +1,73 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Registry (.reg file format) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 REGISTRY_REG_H_ +#define REGISTRY_REG_H_ + +#include + +typedef struct s_reg Reg; +typedef struct s_reg_key RegKey; +typedef struct s_reg_val RegVal; + +struct s_reg +{ + FILE* fp; + char* line; + char* next_line; + size_t line_length; + char* buffer; + char* filename; + BOOL read_only; + RegKey* root_key; + char* saveptr; +}; + +struct s_reg_val +{ + char* name; + DWORD type; + RegVal* prev; + RegVal* next; + + union reg_data + { + DWORD dword; + UINT64 qword; + char* string; + } data; +}; + +struct s_reg_key +{ + char* name; + DWORD type; + RegKey* prev; + RegKey* next; + + char* subname; + RegVal* values; + RegKey* subkeys; +}; + +Reg* reg_open(BOOL read_only); +void reg_close(Reg* reg); + +const char* reg_type_string(DWORD type); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..05238297bdbfc1adec91c61a4bd45a8619aae551 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/CMakeLists.txt @@ -0,0 +1,26 @@ +# WinPR: Windows Portable Runtime +# libwinpr-rpc cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(rpc.c) + +winpr_system_include_directory_add(${OPENSSL_INCLUDE_DIR}) + +winpr_library_add_private(${OPENSSL_LIBRARIES}) + +if(WIN32) + winpr_library_add_public(ws2_32 rpcrt4) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..de65b390a7836b88c4848232bb58e473ebb82edc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/ModuleOptions.cmake @@ -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 "rpcrt4") +set(MINWIN_LONG_NAME "RPC NDR Engine") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/rpc.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/rpc.c new file mode 100644 index 0000000000000000000000000000000000000000..57bffef4154f563b0e8bf63aee58790e4b459fb6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/rpc/rpc.c @@ -0,0 +1,931 @@ +/** + * WinPR: Windows Portable Runtime + * Microsoft Remote Procedure Call (MSRPC) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#if !defined(_WIN32) || defined(_UWP) + +#include "../log.h" +#define TAG WINPR_TAG("rpc") + +RPC_STATUS RpcBindingCopy(RPC_BINDING_HANDLE SourceBinding, RPC_BINDING_HANDLE* DestinationBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingFree(RPC_BINDING_HANDLE* Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingSetOption(RPC_BINDING_HANDLE hBinding, unsigned long option, + ULONG_PTR optionValue) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqOption(RPC_BINDING_HANDLE hBinding, unsigned long option, + ULONG_PTR* pOptionValue) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingFromStringBindingA(RPC_CSTR StringBinding, RPC_BINDING_HANDLE* Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingFromStringBindingW(RPC_WSTR StringBinding, RPC_BINDING_HANDLE* Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcSsGetContextBinding(void* ContextHandle, RPC_BINDING_HANDLE* Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqObject(RPC_BINDING_HANDLE Binding, UUID* ObjectUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingReset(RPC_BINDING_HANDLE Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingSetObject(RPC_BINDING_HANDLE Binding, UUID* ObjectUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqDefaultProtectLevel(unsigned long AuthnSvc, unsigned long* AuthnLevel) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingToStringBindingA(RPC_BINDING_HANDLE Binding, RPC_CSTR* StringBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingToStringBindingW(RPC_BINDING_HANDLE Binding, RPC_WSTR* StringBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingVectorFree(RPC_BINDING_VECTOR** BindingVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcStringBindingComposeA(RPC_CSTR ObjUuid, RPC_CSTR Protseq, RPC_CSTR NetworkAddr, + RPC_CSTR Endpoint, RPC_CSTR Options, RPC_CSTR* StringBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcStringBindingComposeW(RPC_WSTR ObjUuid, RPC_WSTR Protseq, RPC_WSTR NetworkAddr, + RPC_WSTR Endpoint, RPC_WSTR Options, RPC_WSTR* StringBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcStringBindingParseA(RPC_CSTR StringBinding, RPC_CSTR* ObjUuid, RPC_CSTR* Protseq, + RPC_CSTR* NetworkAddr, RPC_CSTR* Endpoint, + RPC_CSTR* NetworkOptions) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcStringBindingParseW(RPC_WSTR StringBinding, RPC_WSTR* ObjUuid, RPC_WSTR* Protseq, + RPC_WSTR* NetworkAddr, RPC_WSTR* Endpoint, + RPC_WSTR* NetworkOptions) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcStringFreeA(RPC_CSTR* String) +{ + if (String) + free(*String); + + return RPC_S_OK; +} + +RPC_STATUS RpcStringFreeW(RPC_WSTR* String) +{ + if (String) + free(*String); + + return RPC_S_OK; +} + +RPC_STATUS RpcIfInqId(RPC_IF_HANDLE RpcIfHandle, RPC_IF_ID* RpcIfId) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNetworkIsProtseqValidA(RPC_CSTR Protseq) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNetworkIsProtseqValidW(RPC_WSTR Protseq) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqComTimeout(RPC_BINDING_HANDLE Binding, unsigned int* Timeout) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtSetComTimeout(RPC_BINDING_HANDLE Binding, unsigned int Timeout) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtSetCancelTimeout(long Timeout) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** ProtseqVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNetworkInqProtseqsW(RPC_PROTSEQ_VECTORW** ProtseqVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcObjectInqType(UUID* ObjUuid, UUID* TypeUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcObjectSetInqFn(RPC_OBJECT_INQ_FN* InquiryFn) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcObjectSetType(UUID* ObjUuid, UUID* TypeUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA** ProtseqVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW** ProtseqVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerInqBindings(RPC_BINDING_VECTOR** BindingVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerInqIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV** MgrEpv) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerListen(unsigned int MinimumCallThreads, unsigned int MaxCalls, + unsigned int DontWait) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerRegisterIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerRegisterIfEx(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv, + unsigned int Flags, unsigned int MaxCalls, + RPC_IF_CALLBACK_FN* IfCallback) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUnregisterIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, + unsigned int WaitForCallsToComplete) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUnregisterIfEx(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, + int RundownContextHandles) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseAllProtseqs(unsigned int MaxCalls, void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseAllProtseqsEx(unsigned int MaxCalls, void* SecurityDescriptor, + PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseAllProtseqsIf(unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseAllProtseqsIfEx(unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor, PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqExA(RPC_CSTR Protseq, unsigned int MaxCalls, void* SecurityDescriptor, + PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqExW(RPC_WSTR Protseq, unsigned int MaxCalls, void* SecurityDescriptor, + PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqEpA(RPC_CSTR Protseq, unsigned int MaxCalls, RPC_CSTR Endpoint, + void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqEpExA(RPC_CSTR Protseq, unsigned int MaxCalls, RPC_CSTR Endpoint, + void* SecurityDescriptor, PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqEpW(RPC_WSTR Protseq, unsigned int MaxCalls, RPC_WSTR Endpoint, + void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqEpExW(RPC_WSTR Protseq, unsigned int MaxCalls, RPC_WSTR Endpoint, + void* SecurityDescriptor, PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqIfA(RPC_CSTR Protseq, unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqIfExA(RPC_CSTR Protseq, unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor, PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqIfW(RPC_WSTR Protseq, unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerUseProtseqIfExW(RPC_WSTR Protseq, unsigned int MaxCalls, RPC_IF_HANDLE IfSpec, + void* SecurityDescriptor, PRPC_POLICY Policy) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +void RpcServerYield(void) +{ + WLog_ERR(TAG, "Not implemented"); +} + +RPC_STATUS RpcMgmtStatsVectorFree(RPC_STATS_VECTOR** StatsVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqStats(RPC_BINDING_HANDLE Binding, RPC_STATS_VECTOR** Statistics) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtStopServerListening(RPC_BINDING_HANDLE Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtWaitServerListen(void) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtSetServerStackSize(unsigned long ThreadStackSize) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +void RpcSsDontSerializeContext(void) +{ + WLog_ERR(TAG, "Not implemented"); +} + +RPC_STATUS RpcMgmtEnableIdleCleanup(void) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR** IfIdVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcIfIdVectorFree(RPC_IF_ID_VECTOR** IfIdVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqServerPrincNameA(RPC_BINDING_HANDLE Binding, unsigned long AuthnSvc, + RPC_CSTR* ServerPrincName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtInqServerPrincNameW(RPC_BINDING_HANDLE Binding, unsigned long AuthnSvc, + RPC_WSTR* ServerPrincName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerInqDefaultPrincNameA(unsigned long AuthnSvc, RPC_CSTR* PrincName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerInqDefaultPrincNameW(unsigned long AuthnSvc, RPC_WSTR* PrincName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcEpResolveBinding(RPC_BINDING_HANDLE Binding, RPC_IF_HANDLE IfSpec) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNsBindingInqEntryNameA(RPC_BINDING_HANDLE Binding, unsigned long EntryNameSyntax, + RPC_CSTR* EntryName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcNsBindingInqEntryNameW(RPC_BINDING_HANDLE Binding, unsigned long EntryNameSyntax, + RPC_WSTR* EntryName) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcImpersonateClient(RPC_BINDING_HANDLE BindingHandle) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcRevertToSelfEx(RPC_BINDING_HANDLE BindingHandle) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcRevertToSelf(void) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqAuthClientA(RPC_BINDING_HANDLE ClientBinding, RPC_AUTHZ_HANDLE* Privs, + RPC_CSTR* ServerPrincName, unsigned long* AuthnLevel, + unsigned long* AuthnSvc, unsigned long* AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqAuthClientW(RPC_BINDING_HANDLE ClientBinding, RPC_AUTHZ_HANDLE* Privs, + RPC_WSTR* ServerPrincName, unsigned long* AuthnLevel, + unsigned long* AuthnSvc, unsigned long* AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqAuthInfoA(RPC_BINDING_HANDLE Binding, RPC_CSTR* ServerPrincName, + unsigned long* AuthnLevel, unsigned long* AuthnSvc, + RPC_AUTH_IDENTITY_HANDLE* AuthIdentity, unsigned long* AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingInqAuthInfoW(RPC_BINDING_HANDLE Binding, RPC_WSTR* ServerPrincName, + unsigned long* AuthnLevel, unsigned long* AuthnSvc, + RPC_AUTH_IDENTITY_HANDLE* AuthIdentity, unsigned long* AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingSetAuthInfoA(RPC_BINDING_HANDLE Binding, RPC_CSTR ServerPrincName, + unsigned long AuthnLevel, unsigned long AuthnSvc, + RPC_AUTH_IDENTITY_HANDLE AuthIdentity, unsigned long AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingSetAuthInfoW(RPC_BINDING_HANDLE Binding, RPC_WSTR ServerPrincName, + unsigned long AuthnLevel, unsigned long AuthnSvc, + RPC_AUTH_IDENTITY_HANDLE AuthIdentity, unsigned long AuthzSvc) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +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) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerRegisterAuthInfoA(RPC_CSTR ServerPrincName, unsigned long AuthnSvc, + RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, void* Arg) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerRegisterAuthInfoW(RPC_WSTR ServerPrincName, unsigned long AuthnSvc, + RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, void* Arg) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcBindingServerFromClient(RPC_BINDING_HANDLE ClientBinding, + RPC_BINDING_HANDLE* ServerBinding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +void RpcRaiseException(RPC_STATUS exception) +{ + WLog_ERR(TAG, "RpcRaiseException: 0x%08luX", exception); + // NOLINTNEXTLINE(concurrency-mt-unsafe) + exit((int)exception); +} + +RPC_STATUS RpcTestCancel(void) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerTestCancel(RPC_BINDING_HANDLE BindingHandle) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcCancelThread(void* Thread) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcCancelThreadEx(void* Thread, long Timeout) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +/** + * UUID Functions + */ + +static UUID UUID_NIL = { + 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } +}; + +RPC_STATUS UuidCreate(UUID* Uuid) +{ + winpr_RAND_pseudo(Uuid, 16); + return RPC_S_OK; +} + +RPC_STATUS UuidCreateSequential(UUID* Uuid) +{ + winpr_RAND_pseudo(Uuid, 16); + return RPC_S_OK; +} + +RPC_STATUS UuidToStringA(const UUID* Uuid, RPC_CSTR* StringUuid) +{ + *StringUuid = (RPC_CSTR)malloc(36 + 1); + + if (!(*StringUuid)) + return RPC_S_OUT_OF_MEMORY; + + if (!Uuid) + Uuid = &UUID_NIL; + + /** + * Format is 32 hex digits partitioned in 5 groups: + * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + (void)sprintf_s((char*)*StringUuid, 36 + 1, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + Uuid->Data1, Uuid->Data2, Uuid->Data3, Uuid->Data4[0], Uuid->Data4[1], + Uuid->Data4[2], Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5], Uuid->Data4[6], + Uuid->Data4[7]); + return RPC_S_OK; +} + +RPC_STATUS UuidToStringW(const UUID* Uuid, RPC_WSTR* StringUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS UuidFromStringA(RPC_CSTR StringUuid, UUID* Uuid) +{ + BYTE bin[36] = { 0 }; + + if (!StringUuid) + return UuidCreateNil(Uuid); + + const size_t slen = 2 * sizeof(UUID) + 4; + if (strnlen(StringUuid, slen) != slen) + return RPC_S_INVALID_STRING_UUID; + + if ((StringUuid[8] != '-') || (StringUuid[13] != '-') || (StringUuid[18] != '-') || + (StringUuid[23] != '-')) + { + return RPC_S_INVALID_STRING_UUID; + } + + for (size_t index = 0; index < 36; index++) + { + if ((index == 8) || (index == 13) || (index == 18) || (index == 23)) + continue; + + if ((StringUuid[index] >= '0') && (StringUuid[index] <= '9')) + bin[index] = (StringUuid[index] - '0') & 0xFF; + else if ((StringUuid[index] >= 'a') && (StringUuid[index] <= 'f')) + bin[index] = (StringUuid[index] - 'a' + 10) & 0xFF; + else if ((StringUuid[index] >= 'A') && (StringUuid[index] <= 'F')) + bin[index] = (StringUuid[index] - 'A' + 10) & 0xFF; + else + return RPC_S_INVALID_STRING_UUID; + } + + Uuid->Data1 = (UINT32)((bin[0] << 28) | (bin[1] << 24) | (bin[2] << 20) | (bin[3] << 16) | + (bin[4] << 12) | (bin[5] << 8) | (bin[6] << 4) | bin[7]); + Uuid->Data2 = (UINT16)((bin[9] << 12) | (bin[10] << 8) | (bin[11] << 4) | bin[12]); + Uuid->Data3 = (UINT16)((bin[14] << 12) | (bin[15] << 8) | (bin[16] << 4) | bin[17]); + Uuid->Data4[0] = (UINT8)((bin[19] << 4) | bin[20]); + Uuid->Data4[1] = (UINT8)((bin[21] << 4) | bin[22]); + Uuid->Data4[2] = (UINT8)((bin[24] << 4) | bin[25]); + Uuid->Data4[3] = (UINT8)((bin[26] << 4) | bin[27]); + Uuid->Data4[4] = (UINT8)((bin[28] << 4) | bin[29]); + Uuid->Data4[5] = (UINT8)((bin[30] << 4) | bin[31]); + Uuid->Data4[6] = (UINT8)((bin[32] << 4) | bin[33]); + Uuid->Data4[7] = (UINT8)((bin[34] << 4) | bin[35]); + return RPC_S_OK; +} + +RPC_STATUS UuidFromStringW(RPC_WSTR StringUuid, UUID* Uuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +signed int UuidCompare(const UUID* Uuid1, const UUID* Uuid2, RPC_STATUS* Status) +{ + *Status = RPC_S_OK; + + if (!Uuid1) + Uuid1 = &UUID_NIL; + + if (!Uuid2) + Uuid2 = &UUID_NIL; + + if (Uuid1->Data1 != Uuid2->Data1) + return (Uuid1->Data1 < Uuid2->Data1) ? -1 : 1; + + if (Uuid1->Data2 != Uuid2->Data2) + return (Uuid1->Data2 < Uuid2->Data2) ? -1 : 1; + + if (Uuid1->Data3 != Uuid2->Data3) + return (Uuid1->Data3 < Uuid2->Data3) ? -1 : 1; + + for (int index = 0; index < 8; index++) + { + if (Uuid1->Data4[index] != Uuid2->Data4[index]) + return (Uuid1->Data4[index] < Uuid2->Data4[index]) ? -1 : 1; + } + + return 0; +} + +RPC_STATUS UuidCreateNil(UUID* NilUuid) +{ + CopyMemory((void*)NilUuid, (void*)&UUID_NIL, 16); + return RPC_S_OK; +} + +int UuidEqual(const UUID* Uuid1, const UUID* Uuid2, RPC_STATUS* Status) +{ + return ((UuidCompare(Uuid1, Uuid2, Status) == 0) ? TRUE : FALSE); +} + +unsigned short UuidHash(const UUID* Uuid, RPC_STATUS* Status) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +int UuidIsNil(const UUID* Uuid, RPC_STATUS* Status) +{ + return UuidEqual(Uuid, &UUID_NIL, Status); +} + +RPC_STATUS RpcEpRegisterNoReplaceA(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector, + UUID_VECTOR* UuidVector, RPC_CSTR Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcEpRegisterNoReplaceW(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector, + UUID_VECTOR* UuidVector, RPC_WSTR Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcEpRegisterA(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector, + UUID_VECTOR* UuidVector, RPC_CSTR Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcEpRegisterW(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector, + UUID_VECTOR* UuidVector, RPC_WSTR Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcEpUnregister(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector, + UUID_VECTOR* UuidVector) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS DceErrorInqTextA(RPC_STATUS RpcStatus, RPC_CSTR ErrorText) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS DceErrorInqTextW(RPC_STATUS RpcStatus, RPC_WSTR ErrorText) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE EpBinding, unsigned long InquiryType, + RPC_IF_ID* IfId, unsigned long VersOption, UUID* ObjectUuid, + RPC_EP_INQ_HANDLE* InquiryContext) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtEpEltInqDone(RPC_EP_INQ_HANDLE* InquiryContext) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtEpEltInqNextA(RPC_EP_INQ_HANDLE InquiryContext, RPC_IF_ID* IfId, + RPC_BINDING_HANDLE* Binding, UUID* ObjectUuid, RPC_CSTR* Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtEpEltInqNextW(RPC_EP_INQ_HANDLE InquiryContext, RPC_IF_ID* IfId, + RPC_BINDING_HANDLE* Binding, UUID* ObjectUuid, RPC_WSTR* Annotation) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtEpUnregister(RPC_BINDING_HANDLE EpBinding, RPC_IF_ID* IfId, + RPC_BINDING_HANDLE Binding, UUID* ObjectUuid) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcMgmtSetAuthorizationFn(RPC_MGMT_AUTHORIZATION_FN AuthorizationFn) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +RPC_STATUS RpcServerInqBindingHandle(RPC_BINDING_HANDLE* Binding) +{ + WLog_ERR(TAG, "Not implemented"); + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf48573955a82500e5d76fc795adda3f809c7517 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-security cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(security.c) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e9b5902dda80192fba0c6982758271dd4d8e1616 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "security") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "base") +set(MINWIN_LONG_NAME "Base Security Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.c new file mode 100644 index 0000000000000000000000000000000000000000..3806233b2a94fa4625d5b8d2c781ba5e78d3df46 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.c @@ -0,0 +1,226 @@ +/** + * WinPR: Windows Portable Runtime + * Base Security Functions + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include + +#include "../handle/handle.h" + +/** + * api-ms-win-security-base-l1-2-0.dll: + * + * AccessCheck + * AccessCheckAndAuditAlarmW + * AccessCheckByType + * AccessCheckByTypeAndAuditAlarmW + * AccessCheckByTypeResultList + * AccessCheckByTypeResultListAndAuditAlarmByHandleW + * AccessCheckByTypeResultListAndAuditAlarmW + * AddAccessAllowedAce + * AddAccessAllowedAceEx + * AddAccessAllowedObjectAce + * AddAccessDeniedAce + * AddAccessDeniedAceEx + * AddAccessDeniedObjectAce + * AddAce + * AddAuditAccessAce + * AddAuditAccessAceEx + * AddAuditAccessObjectAce + * AddMandatoryAce + * AddResourceAttributeAce + * AddScopedPolicyIDAce + * AdjustTokenGroups + * AdjustTokenPrivileges + * AllocateAndInitializeSid + * AllocateLocallyUniqueId + * AreAllAccessesGranted + * AreAnyAccessesGranted + * CheckTokenCapability + * CheckTokenMembership + * CheckTokenMembershipEx + * ConvertToAutoInheritPrivateObjectSecurity + * CopySid + * CreatePrivateObjectSecurity + * CreatePrivateObjectSecurityEx + * CreatePrivateObjectSecurityWithMultipleInheritance + * CreateRestrictedToken + * CreateWellKnownSid + * DeleteAce + * DestroyPrivateObjectSecurity + * DuplicateToken + * DuplicateTokenEx + * EqualDomainSid + * EqualPrefixSid + * EqualSid + * FindFirstFreeAce + * FreeSid + * GetAce + * GetAclInformation + * GetAppContainerAce + * GetCachedSigningLevel + * GetFileSecurityW + * GetKernelObjectSecurity + * GetLengthSid + * GetPrivateObjectSecurity + * GetSidIdentifierAuthority + * GetSidLengthRequired + * GetSidSubAuthority + * GetSidSubAuthorityCount + * GetTokenInformation + * GetWindowsAccountDomainSid + * ImpersonateAnonymousToken + * ImpersonateLoggedOnUser + * ImpersonateSelf + * InitializeAcl + * InitializeSid + * IsTokenRestricted + * IsValidAcl + * IsValidSid + * IsWellKnownSid + * MakeAbsoluteSD + * MakeSelfRelativeSD + * MapGenericMask + * ObjectCloseAuditAlarmW + * ObjectDeleteAuditAlarmW + * ObjectOpenAuditAlarmW + * ObjectPrivilegeAuditAlarmW + * PrivilegeCheck + * PrivilegedServiceAuditAlarmW + * QuerySecurityAccessMask + * RevertToSelf + * SetAclInformation + * SetCachedSigningLevel + * SetFileSecurityW + * SetKernelObjectSecurity + * SetPrivateObjectSecurity + * SetPrivateObjectSecurityEx + * SetSecurityAccessMask + * SetTokenInformation + */ + +#ifndef _WIN32 + +#include "security.h" + +BOOL InitializeSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision) +{ + return TRUE; +} + +DWORD GetSecurityDescriptorLength(PSECURITY_DESCRIPTOR pSecurityDescriptor) +{ + return 0; +} + +BOOL IsValidSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor) +{ + return TRUE; +} + +BOOL GetSecurityDescriptorControl(PSECURITY_DESCRIPTOR pSecurityDescriptor, + PSECURITY_DESCRIPTOR_CONTROL pControl, LPDWORD lpdwRevision) +{ + return TRUE; +} + +BOOL SetSecurityDescriptorControl(PSECURITY_DESCRIPTOR pSecurityDescriptor, + SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest, + SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet) +{ + return TRUE; +} + +BOOL GetSecurityDescriptorDacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbDaclPresent, + PACL* pDacl, LPBOOL lpbDaclDefaulted) +{ + return TRUE; +} + +BOOL SetSecurityDescriptorDacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bDaclPresent, + PACL pDacl, BOOL bDaclDefaulted) +{ + return TRUE; +} + +BOOL GetSecurityDescriptorGroup(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID* pGroup, + LPBOOL lpbGroupDefaulted) +{ + return TRUE; +} + +BOOL SetSecurityDescriptorGroup(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID pGroup, + BOOL bGroupDefaulted) +{ + return TRUE; +} + +BOOL GetSecurityDescriptorOwner(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID* pOwner, + LPBOOL lpbOwnerDefaulted) +{ + return TRUE; +} + +BOOL SetSecurityDescriptorOwner(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID pOwner, + BOOL bOwnerDefaulted) +{ + return TRUE; +} + +DWORD GetSecurityDescriptorRMControl(PSECURITY_DESCRIPTOR SecurityDescriptor, PUCHAR RMControl) +{ + return 0; +} + +DWORD SetSecurityDescriptorRMControl(PSECURITY_DESCRIPTOR SecurityDescriptor, PUCHAR RMControl) +{ + return 0; +} + +BOOL GetSecurityDescriptorSacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbSaclPresent, + PACL* pSacl, LPBOOL lpbSaclDefaulted) +{ + return TRUE; +} + +BOOL SetSecurityDescriptorSacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bSaclPresent, + PACL pSacl, BOOL bSaclDefaulted) +{ + return TRUE; +} + +#endif + +BOOL AccessTokenIsValid(HANDLE handle) +{ + WINPR_HANDLE* h = (WINPR_HANDLE*)handle; + + if (!h || (h->Type != HANDLE_TYPE_ACCESS_TOKEN)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.h new file mode 100644 index 0000000000000000000000000000000000000000..a80dfe11d9b2eaf154d09d14f5ba214ddb80a8ec --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/security.h @@ -0,0 +1,45 @@ +/** + * WinPR: Windows Portable Runtime + * Base Security Functions + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_SECURITY_PRIVATE_H + +#ifndef _WIN32 + +#include + +#include "../handle/handle.h" + +struct winpr_access_token +{ + WINPR_HANDLE common; + + LPSTR Username; + LPSTR Domain; + + DWORD UserId; + DWORD GroupId; +}; +typedef struct winpr_access_token WINPR_ACCESS_TOKEN; + +BOOL AccessTokenIsValid(HANDLE handle); + +#endif + +#endif /* WINPR_SECURITY_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9632cd04ec2f4991827737b4aacd11422a1e073 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/CMakeLists.txt @@ -0,0 +1,21 @@ +set(MODULE_NAME "TestSecurity") +set(MODULE_PREFIX "TEST_SECURITY") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestSecurityToken.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/TestSecurityToken.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/TestSecurityToken.c new file mode 100644 index 0000000000000000000000000000000000000000..0d877b67765d9aa78c6a5bdfe1699a0fa7cfc58b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/security/test/TestSecurityToken.c @@ -0,0 +1,9 @@ + +#include +#include +#include + +int TestSecurityToken(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3fa4f4e170544a23a9c9be3d5d5d91b82693ae15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/CMakeLists.txt @@ -0,0 +1,20 @@ +# WinPR: Windows Portable Runtime +# libwinpr-shell cmake build script +# +# Copyright 2015 Dell Software +# +# 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. + +if(NOT ANDROID) + winpr_module_add(shell.c) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3aed558c68e4fa00827e89234ce60de819924bec --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/ModuleOptions.cmake @@ -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 "shell") +set(MINWIN_LONG_NAME "Shell Functions") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/shell.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/shell.c new file mode 100644 index 0000000000000000000000000000000000000000..75a6d504ce060d1fa7ec8fba82317181b97bc938 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/shell/shell.c @@ -0,0 +1,147 @@ +/** + * WinPR: Windows Portable Runtime + * Shell Functions + * + * Copyright 2015 Dell Software + * + * 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 +#include +#include + +/** + * shell32.dll: + * + * GetUserProfileDirectoryA + * GetUserProfileDirectoryW + */ + +#ifndef _WIN32 + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include +#include + +#include "../handle/handle.h" + +#include "../security/security.h" + +BOOL GetUserProfileDirectoryA(HANDLE hToken, LPSTR lpProfileDir, LPDWORD lpcchSize) +{ + struct passwd pwd = { 0 }; + struct passwd* pw = NULL; + WINPR_ACCESS_TOKEN* token = (WINPR_ACCESS_TOKEN*)hToken; + + if (!AccessTokenIsValid(hToken)) + return FALSE; + + if (!lpcchSize) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + long buflen = sysconf(_SC_GETPW_R_SIZE_MAX); + if (buflen < 0) + buflen = 8196; + + const size_t s = 1ULL + (size_t)buflen; + char* buf = calloc(s, sizeof(char)); + + if (!buf) + return FALSE; + + const int status = + getpwnam_r(token->Username, &pwd, buf, WINPR_ASSERTING_INT_CAST(size_t, buflen), &pw); + + if ((status != 0) || !pw) + { + SetLastError(ERROR_INVALID_PARAMETER); + free(buf); + return FALSE; + } + + const size_t cchDirSize = strlen(pw->pw_dir) + 1; + if (cchDirSize > UINT32_MAX) + { + SetLastError(ERROR_INVALID_PARAMETER); + free(buf); + return FALSE; + } + + if (!lpProfileDir || (*lpcchSize < cchDirSize)) + { + *lpcchSize = (UINT32)cchDirSize; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + free(buf); + return FALSE; + } + + ZeroMemory(lpProfileDir, *lpcchSize); + (void)sprintf_s(lpProfileDir, *lpcchSize, "%s", pw->pw_dir); + *lpcchSize = (UINT32)cchDirSize; + free(buf); + return TRUE; +} + +BOOL GetUserProfileDirectoryW(HANDLE hToken, LPWSTR lpProfileDir, LPDWORD lpcchSize) +{ + BOOL bStatus = 0; + DWORD cchSizeA = 0; + LPSTR lpProfileDirA = NULL; + + if (!lpcchSize) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + cchSizeA = *lpcchSize; + lpProfileDirA = NULL; + + if (lpProfileDir) + { + lpProfileDirA = (LPSTR)malloc(cchSizeA); + + if (lpProfileDirA == NULL) + { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + } + + bStatus = GetUserProfileDirectoryA(hToken, lpProfileDirA, &cchSizeA); + + if (bStatus) + { + SSIZE_T size = ConvertUtf8NToWChar(lpProfileDirA, cchSizeA, lpProfileDir, *lpcchSize); + bStatus = size >= 0; + } + + if (lpProfileDirA) + { + free(lpProfileDirA); + } + + *lpcchSize = cchSizeA; + return bStatus; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c5e9af87f4def8914de9fa2e71be7b51d4d9f1b5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/CMakeLists.txt @@ -0,0 +1,50 @@ +# WinPR: Windows Portable Runtime +# libwinpr-smartcard cmake build script +# +# Copyright 2014 Marc-Andre Moreau +# +# 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_PREFIX "WINPR_SMARTCARD") + +if(PCSC_WINPR_FOUND) + winpr_definition_add(WITH_WINPR_PCSC) +endif() + +option(WITH_SMARTCARD_PCSC "Enable smartcard PCSC backend" ON) + +set(${MODULE_PREFIX}_SRCS smartcard.c smartcard.h) + +if(WITH_SMARTCARD_PCSC) + winpr_definition_add(WITH_SMARTCARD_PCSC) + list(APPEND ${MODULE_PREFIX}_SRCS smartcard_pcsc.c smartcard_pcsc.h) +endif() + +if(WITH_SMARTCARD_INSPECT) + winpr_definition_add(WITH_SMARTCARD_INSPECT) + list(APPEND ${MODULE_PREFIX}_SRCS smartcard_inspect.c smartcard_inspect.h) +endif() + +if(WIN32) + list(APPEND ${MODULE_PREFIX}_SRCS smartcard_windows.c smartcard_windows.h) +endif() + +winpr_module_add(${${MODULE_PREFIX}_SRCS}) + +if(PCSC_WINPR_FOUND) + winpr_library_add_private(${PCSC_WINPR_LIBRARY}) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..92b77d31dc03ef72ad4cf7f16e18408bce87756c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/ModuleOptions.cmake @@ -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 "smartcard") +set(MINWIN_LONG_NAME "Smart Card API") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.c new file mode 100644 index 0000000000000000000000000000000000000000..dc9b0b1839d63cc2e56098d14ee3db38d2ff33a3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.c @@ -0,0 +1,1283 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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 + +#include +#include +#include +#include +#include +#include + +#include "../log.h" + +#include "smartcard.h" + +#if defined(WITH_SMARTCARD_INSPECT) +#include "smartcard_inspect.h" +#endif + +static INIT_ONCE g_Initialized = INIT_ONCE_STATIC_INIT; +static const SCardApiFunctionTable* g_SCardApi = NULL; + +#define TAG WINPR_TAG("smartcard") + +#define xstr(s) str(s) +#define str(s) #s + +#define SCARDAPI_STUB_CALL_LONG(_name, ...) \ + InitOnceExecuteOnce(&g_Initialized, InitializeSCardApiStubs, NULL, NULL); \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + return SCARD_E_NO_SERVICE; \ + } \ + return g_SCardApi->pfn##_name(__VA_ARGS__) + +#define SCARDAPI_STUB_CALL_HANDLE(_name) \ + InitOnceExecuteOnce(&g_Initialized, InitializeSCardApiStubs, NULL, NULL); \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + return NULL; \ + } \ + return g_SCardApi->pfn##_name() + +#define SCARDAPI_STUB_CALL_VOID(_name) \ + InitOnceExecuteOnce(&g_Initialized, InitializeSCardApiStubs, NULL, NULL); \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + return; \ + } \ + g_SCardApi->pfn##_name() + +/** + * Standard Windows Smart Card API + */ + +const SCARD_IO_REQUEST g_rgSCardT0Pci = { SCARD_PROTOCOL_T0, 8 }; +const SCARD_IO_REQUEST g_rgSCardT1Pci = { SCARD_PROTOCOL_T1, 8 }; +const SCARD_IO_REQUEST g_rgSCardRawPci = { SCARD_PROTOCOL_RAW, 8 }; + +static BOOL CALLBACK InitializeSCardApiStubs(PINIT_ONCE once, PVOID param, PVOID* context) +{ +#ifdef _WIN32 + if (Windows_InitializeSCardApi() >= 0) + g_SCardApi = Windows_GetSCardApiFunctionTable(); +#else +#if defined(WITH_SMARTCARD_PCSC) + if (PCSC_InitializeSCardApi() >= 0) + g_SCardApi = PCSC_GetSCardApiFunctionTable(); +#endif +#endif + +#if defined(WITH_SMARTCARD_INSPECT) + g_SCardApi = Inspect_RegisterSCardApi(g_SCardApi); +#endif + return TRUE; +} + +WINSCARDAPI LONG WINAPI SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext) +{ + SCARDAPI_STUB_CALL_LONG(SCardEstablishContext, dwScope, pvReserved1, pvReserved2, phContext); +} + +WINSCARDAPI LONG WINAPI SCardReleaseContext(SCARDCONTEXT hContext) +{ + SCARDAPI_STUB_CALL_LONG(SCardReleaseContext, hContext); +} + +WINSCARDAPI LONG WINAPI SCardIsValidContext(SCARDCONTEXT hContext) +{ + SCARDAPI_STUB_CALL_LONG(SCardIsValidContext, hContext); +} + +WINSCARDAPI LONG WINAPI SCardListReaderGroupsA(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReaderGroupsA, hContext, mszGroups, pcchGroups); +} + +WINSCARDAPI LONG WINAPI SCardListReaderGroupsW(SCARDCONTEXT hContext, LPWSTR mszGroups, + LPDWORD pcchGroups) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReaderGroupsW, hContext, mszGroups, pcchGroups); +} + +WINSCARDAPI LONG WINAPI SCardListReadersA(SCARDCONTEXT hContext, LPCSTR mszGroups, LPSTR mszReaders, + LPDWORD pcchReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReadersA, hContext, mszGroups, mszReaders, pcchReaders); +} + +WINSCARDAPI LONG WINAPI SCardListReadersW(SCARDCONTEXT hContext, LPCWSTR mszGroups, + LPWSTR mszReaders, LPDWORD pcchReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReadersW, hContext, mszGroups, mszReaders, pcchReaders); +} + +WINSCARDAPI LONG WINAPI SCardListCardsA(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + CHAR* mszCards, LPDWORD pcchCards) +{ + SCARDAPI_STUB_CALL_LONG(SCardListCardsA, hContext, pbAtr, rgquidInterfaces, cguidInterfaceCount, + mszCards, pcchCards); +} + +WINSCARDAPI LONG WINAPI SCardListCardsW(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + WCHAR* mszCards, LPDWORD pcchCards) +{ + SCARDAPI_STUB_CALL_LONG(SCardListCardsW, hContext, pbAtr, rgquidInterfaces, cguidInterfaceCount, + mszCards, pcchCards); +} + +WINSCARDAPI LONG WINAPI SCardListInterfacesA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces) +{ + SCARDAPI_STUB_CALL_LONG(SCardListInterfacesA, hContext, szCard, pguidInterfaces, + pcguidInterfaces); +} + +WINSCARDAPI LONG WINAPI SCardListInterfacesW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces) +{ + SCARDAPI_STUB_CALL_LONG(SCardListInterfacesW, hContext, szCard, pguidInterfaces, + pcguidInterfaces); +} + +WINSCARDAPI LONG WINAPI SCardGetProviderIdA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidProviderId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetProviderIdA, hContext, szCard, pguidProviderId); +} + +WINSCARDAPI LONG WINAPI SCardGetProviderIdW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidProviderId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetProviderIdW, hContext, szCard, pguidProviderId); +} + +WINSCARDAPI LONG WINAPI SCardGetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, CHAR* szProvider, + LPDWORD pcchProvider) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetCardTypeProviderNameA, hContext, szCardName, dwProviderId, + szProvider, pcchProvider); +} + +WINSCARDAPI LONG WINAPI SCardGetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, WCHAR* szProvider, + LPDWORD pcchProvider) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetCardTypeProviderNameW, hContext, szCardName, dwProviderId, + szProvider, pcchProvider); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceReaderGroupA, hContext, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceReaderGroupW, hContext, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardForgetReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetReaderGroupA, hContext, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardForgetReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetReaderGroupW, hContext, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szDeviceName) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceReaderA, hContext, szReaderName, szDeviceName); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szDeviceName) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceReaderW, hContext, szReaderName, szDeviceName); +} + +WINSCARDAPI LONG WINAPI SCardForgetReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetReaderA, hContext, szReaderName); +} + +WINSCARDAPI LONG WINAPI SCardForgetReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetReaderW, hContext, szReaderName); +} + +WINSCARDAPI LONG WINAPI SCardAddReaderToGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardAddReaderToGroupA, hContext, szReaderName, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardAddReaderToGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardAddReaderToGroupW, hContext, szReaderName, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardRemoveReaderFromGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardRemoveReaderFromGroupA, hContext, szReaderName, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardRemoveReaderFromGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + SCARDAPI_STUB_CALL_LONG(SCardRemoveReaderFromGroupW, hContext, szReaderName, szGroupName); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceCardTypeA, hContext, szCardName, pguidPrimaryProvider, + rgguidInterfaces, dwInterfaceCount, pbAtr, pbAtrMask, cbAtrLen); +} + +WINSCARDAPI LONG WINAPI SCardIntroduceCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardIntroduceCardTypeW, hContext, szCardName, pguidPrimaryProvider, + rgguidInterfaces, dwInterfaceCount, pbAtr, pbAtrMask, cbAtrLen); +} + +WINSCARDAPI LONG WINAPI SCardSetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, LPCSTR szProvider) +{ + SCARDAPI_STUB_CALL_LONG(SCardSetCardTypeProviderNameA, hContext, szCardName, dwProviderId, + szProvider); +} + +WINSCARDAPI LONG WINAPI SCardSetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, LPCWSTR szProvider) +{ + SCARDAPI_STUB_CALL_LONG(SCardSetCardTypeProviderNameW, hContext, szCardName, dwProviderId, + szProvider); +} + +WINSCARDAPI LONG WINAPI SCardForgetCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetCardTypeA, hContext, szCardName); +} + +WINSCARDAPI LONG WINAPI SCardForgetCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName) +{ + SCARDAPI_STUB_CALL_LONG(SCardForgetCardTypeW, hContext, szCardName); +} + +WINSCARDAPI LONG WINAPI SCardFreeMemory(SCARDCONTEXT hContext, LPVOID pvMem) +{ + SCARDAPI_STUB_CALL_LONG(SCardFreeMemory, hContext, pvMem); +} + +WINSCARDAPI HANDLE WINAPI SCardAccessStartedEvent(void) +{ + SCARDAPI_STUB_CALL_HANDLE(SCardAccessStartedEvent); +} + +WINSCARDAPI void WINAPI SCardReleaseStartedEvent(void) +{ + SCARDAPI_STUB_CALL_VOID(SCardReleaseStartedEvent); +} + +WINSCARDAPI LONG WINAPI SCardLocateCardsA(SCARDCONTEXT hContext, LPCSTR mszCards, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardLocateCardsA, hContext, mszCards, rgReaderStates, cReaders); +} + +WINSCARDAPI LONG WINAPI SCardLocateCardsW(SCARDCONTEXT hContext, LPCWSTR mszCards, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardLocateCardsW, hContext, mszCards, rgReaderStates, cReaders); +} + +WINSCARDAPI LONG WINAPI SCardLocateCardsByATRA(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardLocateCardsByATRA, hContext, rgAtrMasks, cAtrs, rgReaderStates, + cReaders); +} + +WINSCARDAPI LONG WINAPI SCardLocateCardsByATRW(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardLocateCardsByATRW, hContext, rgAtrMasks, cAtrs, rgReaderStates, + cReaders); +} + +WINSCARDAPI LONG WINAPI SCardGetStatusChangeA(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetStatusChangeA, hContext, dwTimeout, rgReaderStates, cReaders); +} + +WINSCARDAPI LONG WINAPI SCardGetStatusChangeW(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetStatusChangeW, hContext, dwTimeout, rgReaderStates, cReaders); +} + +WINSCARDAPI LONG WINAPI SCardCancel(SCARDCONTEXT hContext) +{ + SCARDAPI_STUB_CALL_LONG(SCardCancel, hContext); +} + +WINSCARDAPI LONG WINAPI SCardConnectA(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + SCARDAPI_STUB_CALL_LONG(SCardConnectA, hContext, szReader, dwShareMode, dwPreferredProtocols, + phCard, pdwActiveProtocol); +} + +WINSCARDAPI LONG WINAPI SCardConnectW(SCARDCONTEXT hContext, LPCWSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + SCARDAPI_STUB_CALL_LONG(SCardConnectW, hContext, szReader, dwShareMode, dwPreferredProtocols, + phCard, pdwActiveProtocol); +} + +WINSCARDAPI LONG WINAPI SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode, + DWORD dwPreferredProtocols, DWORD dwInitialization, + LPDWORD pdwActiveProtocol) +{ + SCARDAPI_STUB_CALL_LONG(SCardReconnect, hCard, dwShareMode, dwPreferredProtocols, + dwInitialization, pdwActiveProtocol); +} + +WINSCARDAPI LONG WINAPI SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition) +{ + SCARDAPI_STUB_CALL_LONG(SCardDisconnect, hCard, dwDisposition); +} + +WINSCARDAPI LONG WINAPI SCardBeginTransaction(SCARDHANDLE hCard) +{ + SCARDAPI_STUB_CALL_LONG(SCardBeginTransaction, hCard); +} + +WINSCARDAPI LONG WINAPI SCardEndTransaction(SCARDHANDLE hCard, DWORD dwDisposition) +{ + SCARDAPI_STUB_CALL_LONG(SCardEndTransaction, hCard, dwDisposition); +} + +WINSCARDAPI LONG WINAPI SCardCancelTransaction(SCARDHANDLE hCard) +{ + SCARDAPI_STUB_CALL_LONG(SCardCancelTransaction, hCard); +} + +WINSCARDAPI LONG WINAPI SCardState(SCARDHANDLE hCard, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardState, hCard, pdwState, pdwProtocol, pbAtr, pcbAtrLen); +} + +WINSCARDAPI LONG WINAPI SCardStatusA(SCARDHANDLE hCard, LPSTR mszReaderNames, LPDWORD pcchReaderLen, + LPDWORD pdwState, LPDWORD pdwProtocol, LPBYTE pbAtr, + LPDWORD pcbAtrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardStatusA, hCard, mszReaderNames, pcchReaderLen, pdwState, + pdwProtocol, pbAtr, pcbAtrLen); +} + +WINSCARDAPI LONG WINAPI SCardStatusW(SCARDHANDLE hCard, LPWSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardStatusW, hCard, mszReaderNames, pcchReaderLen, pdwState, + pdwProtocol, pbAtr, pcbAtrLen); +} + +WINSCARDAPI LONG WINAPI SCardTransmit(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, + LPCBYTE pbSendBuffer, DWORD cbSendLength, + LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, + LPDWORD pcbRecvLength) +{ + SCARDAPI_STUB_CALL_LONG(SCardTransmit, hCard, pioSendPci, pbSendBuffer, cbSendLength, + pioRecvPci, pbRecvBuffer, pcbRecvLength); +} + +WINSCARDAPI LONG WINAPI SCardGetTransmitCount(SCARDHANDLE hCard, LPDWORD pcTransmitCount) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetTransmitCount, hCard, pcTransmitCount); +} + +WINSCARDAPI LONG WINAPI SCardControl(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID lpInBuffer, + DWORD cbInBufferSize, LPVOID lpOutBuffer, + DWORD cbOutBufferSize, LPDWORD lpBytesReturned) +{ + SCARDAPI_STUB_CALL_LONG(SCardControl, hCard, dwControlCode, lpInBuffer, cbInBufferSize, + lpOutBuffer, cbOutBufferSize, lpBytesReturned); +} + +WINSCARDAPI LONG WINAPI SCardGetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetAttrib, hCard, dwAttrId, pbAttr, pcbAttrLen); +} + +WINSCARDAPI LONG WINAPI SCardSetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr, + DWORD cbAttrLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardSetAttrib, hCard, dwAttrId, pbAttr, cbAttrLen); +} + +WINSCARDAPI LONG WINAPI SCardUIDlgSelectCardA(LPOPENCARDNAMEA_EX pDlgStruc) +{ + SCARDAPI_STUB_CALL_LONG(SCardUIDlgSelectCardA, pDlgStruc); +} + +WINSCARDAPI LONG WINAPI SCardUIDlgSelectCardW(LPOPENCARDNAMEW_EX pDlgStruc) +{ + SCARDAPI_STUB_CALL_LONG(SCardUIDlgSelectCardW, pDlgStruc); +} + +WINSCARDAPI LONG WINAPI GetOpenCardNameA(LPOPENCARDNAMEA pDlgStruc) +{ + SCARDAPI_STUB_CALL_LONG(GetOpenCardNameA, pDlgStruc); +} + +WINSCARDAPI LONG WINAPI GetOpenCardNameW(LPOPENCARDNAMEW pDlgStruc) +{ + SCARDAPI_STUB_CALL_LONG(GetOpenCardNameW, pDlgStruc); +} + +WINSCARDAPI LONG WINAPI SCardDlgExtendedError(void) +{ + SCARDAPI_STUB_CALL_LONG(SCardDlgExtendedError); +} + +WINSCARDAPI LONG WINAPI SCardReadCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardReadCacheA, hContext, CardIdentifier, FreshnessCounter, LookupName, + Data, DataLen); +} + +WINSCARDAPI LONG WINAPI SCardReadCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardReadCacheW, hContext, CardIdentifier, FreshnessCounter, LookupName, + Data, DataLen); +} + +WINSCARDAPI LONG WINAPI SCardWriteCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardWriteCacheA, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); +} + +WINSCARDAPI LONG WINAPI SCardWriteCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + SCARDAPI_STUB_CALL_LONG(SCardWriteCacheW, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); +} + +WINSCARDAPI LONG WINAPI SCardGetReaderIconA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetReaderIconA, hContext, szReaderName, pbIcon, pcbIcon); +} + +WINSCARDAPI LONG WINAPI SCardGetReaderIconW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetReaderIconW, hContext, szReaderName, pbIcon, pcbIcon); +} + +WINSCARDAPI LONG WINAPI SCardGetDeviceTypeIdA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetDeviceTypeIdA, hContext, szReaderName, pdwDeviceTypeId); +} + +WINSCARDAPI LONG WINAPI SCardGetDeviceTypeIdW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetDeviceTypeIdW, hContext, szReaderName, pdwDeviceTypeId); +} + +WINSCARDAPI LONG WINAPI SCardGetReaderDeviceInstanceIdA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetReaderDeviceInstanceIdA, hContext, szReaderName, + szDeviceInstanceId, pcchDeviceInstanceId); +} + +WINSCARDAPI LONG WINAPI SCardGetReaderDeviceInstanceIdW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPWSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId) +{ + SCARDAPI_STUB_CALL_LONG(SCardGetReaderDeviceInstanceIdW, hContext, szReaderName, + szDeviceInstanceId, pcchDeviceInstanceId); +} + +WINSCARDAPI LONG WINAPI SCardListReadersWithDeviceInstanceIdA(SCARDCONTEXT hContext, + LPCSTR szDeviceInstanceId, + LPSTR mszReaders, LPDWORD pcchReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReadersWithDeviceInstanceIdA, hContext, szDeviceInstanceId, + mszReaders, pcchReaders); +} + +WINSCARDAPI LONG WINAPI SCardListReadersWithDeviceInstanceIdW(SCARDCONTEXT hContext, + LPCWSTR szDeviceInstanceId, + LPWSTR mszReaders, + LPDWORD pcchReaders) +{ + SCARDAPI_STUB_CALL_LONG(SCardListReadersWithDeviceInstanceIdW, hContext, szDeviceInstanceId, + mszReaders, pcchReaders); +} + +WINSCARDAPI LONG WINAPI SCardAudit(SCARDCONTEXT hContext, DWORD dwEvent) +{ + SCARDAPI_STUB_CALL_LONG(SCardAudit, hContext, dwEvent); +} + +/** + * Extended API + */ + +WINSCARDAPI const char* WINAPI SCardGetErrorString(LONG errorCode) +{ + switch (errorCode) + { + case SCARD_S_SUCCESS: + return "SCARD_S_SUCCESS"; + + case SCARD_F_INTERNAL_ERROR: + return "SCARD_F_INTERNAL_ERROR"; + + case SCARD_E_CANCELLED: + return "SCARD_E_CANCELLED"; + + case SCARD_E_INVALID_HANDLE: + return "SCARD_E_INVALID_HANDLE"; + + case SCARD_E_INVALID_PARAMETER: + return "SCARD_E_INVALID_PARAMETER"; + + case SCARD_E_INVALID_TARGET: + return "SCARD_E_INVALID_TARGET"; + + case SCARD_E_NO_MEMORY: + return "SCARD_E_NO_MEMORY"; + + case SCARD_F_WAITED_TOO_LONG: + return "SCARD_F_WAITED_TOO_LONG"; + + case SCARD_E_INSUFFICIENT_BUFFER: + return "SCARD_E_INSUFFICIENT_BUFFER"; + + case SCARD_E_UNKNOWN_READER: + return "SCARD_E_UNKNOWN_READER"; + + case SCARD_E_TIMEOUT: + return "SCARD_E_TIMEOUT"; + + case SCARD_E_SHARING_VIOLATION: + return "SCARD_E_SHARING_VIOLATION"; + + case SCARD_E_NO_SMARTCARD: + return "SCARD_E_NO_SMARTCARD"; + + case SCARD_E_UNKNOWN_CARD: + return "SCARD_E_UNKNOWN_CARD"; + + case SCARD_E_CANT_DISPOSE: + return "SCARD_E_CANT_DISPOSE"; + + case SCARD_E_PROTO_MISMATCH: + return "SCARD_E_PROTO_MISMATCH"; + + case SCARD_E_NOT_READY: + return "SCARD_E_NOT_READY"; + + case SCARD_E_INVALID_VALUE: + return "SCARD_E_INVALID_VALUE"; + + case SCARD_E_SYSTEM_CANCELLED: + return "SCARD_E_SYSTEM_CANCELLED"; + + case SCARD_F_COMM_ERROR: + return "SCARD_F_COMM_ERROR"; + + case SCARD_F_UNKNOWN_ERROR: + return "SCARD_F_UNKNOWN_ERROR"; + + case SCARD_E_INVALID_ATR: + return "SCARD_E_INVALID_ATR"; + + case SCARD_E_NOT_TRANSACTED: + return "SCARD_E_NOT_TRANSACTED"; + + case SCARD_E_READER_UNAVAILABLE: + return "SCARD_E_READER_UNAVAILABLE"; + + case SCARD_P_SHUTDOWN: + return "SCARD_P_SHUTDOWN"; + + case SCARD_E_PCI_TOO_SMALL: + return "SCARD_E_PCI_TOO_SMALL"; + + case SCARD_E_READER_UNSUPPORTED: + return "SCARD_E_READER_UNSUPPORTED"; + + case SCARD_E_DUPLICATE_READER: + return "SCARD_E_DUPLICATE_READER"; + + case SCARD_E_CARD_UNSUPPORTED: + return "SCARD_E_CARD_UNSUPPORTED"; + + case SCARD_E_NO_SERVICE: + return "SCARD_E_NO_SERVICE"; + + case SCARD_E_SERVICE_STOPPED: + return "SCARD_E_SERVICE_STOPPED"; + + case SCARD_E_UNEXPECTED: + return "SCARD_E_UNEXPECTED"; + + case SCARD_E_ICC_INSTALLATION: + return "SCARD_E_ICC_INSTALLATION"; + + case SCARD_E_ICC_CREATEORDER: + return "SCARD_E_ICC_CREATEORDER"; + + case SCARD_E_UNSUPPORTED_FEATURE: + return "SCARD_E_UNSUPPORTED_FEATURE"; + + case SCARD_E_DIR_NOT_FOUND: + return "SCARD_E_DIR_NOT_FOUND"; + + case SCARD_E_FILE_NOT_FOUND: + return "SCARD_E_FILE_NOT_FOUND"; + + case SCARD_E_NO_DIR: + return "SCARD_E_NO_DIR"; + + case SCARD_E_NO_FILE: + return "SCARD_E_NO_FILE"; + + case SCARD_E_NO_ACCESS: + return "SCARD_E_NO_ACCESS"; + + case SCARD_E_WRITE_TOO_MANY: + return "SCARD_E_WRITE_TOO_MANY"; + + case SCARD_E_BAD_SEEK: + return "SCARD_E_BAD_SEEK"; + + case SCARD_E_INVALID_CHV: + return "SCARD_E_INVALID_CHV"; + + case SCARD_E_UNKNOWN_RES_MNG: + return "SCARD_E_UNKNOWN_RES_MNG"; + + case SCARD_E_NO_SUCH_CERTIFICATE: + return "SCARD_E_NO_SUCH_CERTIFICATE"; + + case SCARD_E_CERTIFICATE_UNAVAILABLE: + return "SCARD_E_CERTIFICATE_UNAVAILABLE"; + + case SCARD_E_NO_READERS_AVAILABLE: + return "SCARD_E_NO_READERS_AVAILABLE"; + + case SCARD_E_COMM_DATA_LOST: + return "SCARD_E_COMM_DATA_LOST"; + + case SCARD_E_NO_KEY_CONTAINER: + return "SCARD_E_NO_KEY_CONTAINER"; + + case SCARD_E_SERVER_TOO_BUSY: + return "SCARD_E_SERVER_TOO_BUSY"; + + case SCARD_E_PIN_CACHE_EXPIRED: + return "SCARD_E_PIN_CACHE_EXPIRED"; + + case SCARD_E_NO_PIN_CACHE: + return "SCARD_E_NO_PIN_CACHE"; + + case SCARD_E_READ_ONLY_CARD: + return "SCARD_E_READ_ONLY_CARD"; + + case SCARD_W_UNSUPPORTED_CARD: + return "SCARD_W_UNSUPPORTED_CARD"; + + case SCARD_W_UNRESPONSIVE_CARD: + return "SCARD_W_UNRESPONSIVE_CARD"; + + case SCARD_W_UNPOWERED_CARD: + return "SCARD_W_UNPOWERED_CARD"; + + case SCARD_W_RESET_CARD: + return "SCARD_W_RESET_CARD"; + + case SCARD_W_REMOVED_CARD: + return "SCARD_W_REMOVED_CARD"; + + case SCARD_W_SECURITY_VIOLATION: + return "SCARD_W_SECURITY_VIOLATION"; + + case SCARD_W_WRONG_CHV: + return "SCARD_W_WRONG_CHV"; + + case SCARD_W_CHV_BLOCKED: + return "SCARD_W_CHV_BLOCKED"; + + case SCARD_W_EOF: + return "SCARD_W_EOF"; + + case SCARD_W_CANCELLED_BY_USER: + return "SCARD_W_CANCELLED_BY_USER"; + + case SCARD_W_CARD_NOT_AUTHENTICATED: + return "SCARD_W_CARD_NOT_AUTHENTICATED"; + + case SCARD_W_CACHE_ITEM_NOT_FOUND: + return "SCARD_W_CACHE_ITEM_NOT_FOUND"; + + case SCARD_W_CACHE_ITEM_STALE: + return "SCARD_W_CACHE_ITEM_STALE"; + + case SCARD_W_CACHE_ITEM_TOO_BIG: + return "SCARD_W_CACHE_ITEM_TOO_BIG"; + + default: + return "SCARD_E_UNKNOWN"; + } +} + +WINSCARDAPI const char* WINAPI SCardGetAttributeString(DWORD dwAttrId) +{ + switch (dwAttrId) + { + case SCARD_ATTR_VENDOR_NAME: + return "SCARD_ATTR_VENDOR_NAME"; + + case SCARD_ATTR_VENDOR_IFD_TYPE: + return "SCARD_ATTR_VENDOR_IFD_TYPE"; + + case SCARD_ATTR_VENDOR_IFD_VERSION: + return "SCARD_ATTR_VENDOR_IFD_VERSION"; + + case SCARD_ATTR_VENDOR_IFD_SERIAL_NO: + return "SCARD_ATTR_VENDOR_IFD_SERIAL_NO"; + + case SCARD_ATTR_CHANNEL_ID: + return "SCARD_ATTR_CHANNEL_ID"; + + case SCARD_ATTR_PROTOCOL_TYPES: + return "SCARD_ATTR_PROTOCOL_TYPES"; + + case SCARD_ATTR_DEFAULT_CLK: + return "SCARD_ATTR_DEFAULT_CLK"; + + case SCARD_ATTR_MAX_CLK: + return "SCARD_ATTR_MAX_CLK"; + + case SCARD_ATTR_DEFAULT_DATA_RATE: + return "SCARD_ATTR_DEFAULT_DATA_RATE"; + + case SCARD_ATTR_MAX_DATA_RATE: + return "SCARD_ATTR_MAX_DATA_RATE"; + + case SCARD_ATTR_MAX_IFSD: + return "SCARD_ATTR_MAX_IFSD"; + + case SCARD_ATTR_POWER_MGMT_SUPPORT: + return "SCARD_ATTR_POWER_MGMT_SUPPORT"; + + case SCARD_ATTR_USER_TO_CARD_AUTH_DEVICE: + return "SCARD_ATTR_USER_TO_CARD_AUTH_DEVICE"; + + case SCARD_ATTR_USER_AUTH_INPUT_DEVICE: + return "SCARD_ATTR_USER_AUTH_INPUT_DEVICE"; + + case SCARD_ATTR_CHARACTERISTICS: + return "SCARD_ATTR_CHARACTERISTICS"; + + case SCARD_ATTR_CURRENT_PROTOCOL_TYPE: + return "SCARD_ATTR_CURRENT_PROTOCOL_TYPE"; + + case SCARD_ATTR_CURRENT_CLK: + return "SCARD_ATTR_CURRENT_CLK"; + + case SCARD_ATTR_CURRENT_F: + return "SCARD_ATTR_CURRENT_F"; + + case SCARD_ATTR_CURRENT_D: + return "SCARD_ATTR_CURRENT_D"; + + case SCARD_ATTR_CURRENT_N: + return "SCARD_ATTR_CURRENT_N"; + + case SCARD_ATTR_CURRENT_W: + return "SCARD_ATTR_CURRENT_W"; + + case SCARD_ATTR_CURRENT_IFSC: + return "SCARD_ATTR_CURRENT_IFSC"; + + case SCARD_ATTR_CURRENT_IFSD: + return "SCARD_ATTR_CURRENT_IFSD"; + + case SCARD_ATTR_CURRENT_BWT: + return "SCARD_ATTR_CURRENT_BWT"; + + case SCARD_ATTR_CURRENT_CWT: + return "SCARD_ATTR_CURRENT_CWT"; + + case SCARD_ATTR_CURRENT_EBC_ENCODING: + return "SCARD_ATTR_CURRENT_EBC_ENCODING"; + + case SCARD_ATTR_EXTENDED_BWT: + return "SCARD_ATTR_EXTENDED_BWT"; + + case SCARD_ATTR_ICC_PRESENCE: + return "SCARD_ATTR_ICC_PRESENCE"; + + case SCARD_ATTR_ICC_INTERFACE_STATUS: + return "SCARD_ATTR_ICC_INTERFACE_STATUS"; + + case SCARD_ATTR_CURRENT_IO_STATE: + return "SCARD_ATTR_CURRENT_IO_STATE"; + + case SCARD_ATTR_ATR_STRING: + return "SCARD_ATTR_ATR_STRING"; + + case SCARD_ATTR_ICC_TYPE_PER_ATR: + return "SCARD_ATTR_ICC_TYPE_PER_ATR"; + + case SCARD_ATTR_ESC_RESET: + return "SCARD_ATTR_ESC_RESET"; + + case SCARD_ATTR_ESC_CANCEL: + return "SCARD_ATTR_ESC_CANCEL"; + + case SCARD_ATTR_ESC_AUTHREQUEST: + return "SCARD_ATTR_ESC_AUTHREQUEST"; + + case SCARD_ATTR_MAXINPUT: + return "SCARD_ATTR_MAXINPUT"; + + case SCARD_ATTR_DEVICE_UNIT: + return "SCARD_ATTR_DEVICE_UNIT"; + + case SCARD_ATTR_DEVICE_IN_USE: + return "SCARD_ATTR_DEVICE_IN_USE"; + + case SCARD_ATTR_DEVICE_FRIENDLY_NAME_A: + return "SCARD_ATTR_DEVICE_FRIENDLY_NAME_A"; + + case SCARD_ATTR_DEVICE_SYSTEM_NAME_A: + return "SCARD_ATTR_DEVICE_SYSTEM_NAME_A"; + + case SCARD_ATTR_DEVICE_FRIENDLY_NAME_W: + return "SCARD_ATTR_DEVICE_FRIENDLY_NAME_W"; + + case SCARD_ATTR_DEVICE_SYSTEM_NAME_W: + return "SCARD_ATTR_DEVICE_SYSTEM_NAME_W"; + + case SCARD_ATTR_SUPRESS_T1_IFS_REQUEST: + return "SCARD_ATTR_SUPRESS_T1_IFS_REQUEST"; + + default: + return "SCARD_ATTR_UNKNOWN"; + } +} + +WINSCARDAPI const char* WINAPI SCardGetProtocolString(DWORD dwProtocols) +{ + if (dwProtocols == SCARD_PROTOCOL_UNDEFINED) + return "SCARD_PROTOCOL_UNDEFINED"; + + if (dwProtocols == SCARD_PROTOCOL_T0) + return "SCARD_PROTOCOL_T0"; + + if (dwProtocols == SCARD_PROTOCOL_T1) + return "SCARD_PROTOCOL_T1"; + + if (dwProtocols == SCARD_PROTOCOL_Tx) + return "SCARD_PROTOCOL_Tx"; + + if (dwProtocols == SCARD_PROTOCOL_RAW) + return "SCARD_PROTOCOL_RAW"; + + if (dwProtocols == SCARD_PROTOCOL_DEFAULT) + return "SCARD_PROTOCOL_DEFAULT"; + + if (dwProtocols == (SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_RAW)) + return "SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_RAW"; + + if (dwProtocols == (SCARD_PROTOCOL_T1 | SCARD_PROTOCOL_RAW)) + return "SCARD_PROTOCOL_T1 | SCARD_PROTOCOL_RAW"; + + if (dwProtocols == (SCARD_PROTOCOL_Tx | SCARD_PROTOCOL_RAW)) + return "SCARD_PROTOCOL_Tx | SCARD_PROTOCOL_RAW"; + + return "SCARD_PROTOCOL_UNKNOWN"; +} + +WINSCARDAPI const char* WINAPI SCardGetShareModeString(DWORD dwShareMode) +{ + switch (dwShareMode) + { + case SCARD_SHARE_EXCLUSIVE: + return "SCARD_SHARE_EXCLUSIVE"; + + case SCARD_SHARE_SHARED: + return "SCARD_SHARE_SHARED"; + + case SCARD_SHARE_DIRECT: + return "SCARD_SHARE_DIRECT"; + + default: + return "SCARD_SHARE_UNKNOWN"; + } +} + +WINSCARDAPI const char* WINAPI SCardGetDispositionString(DWORD dwDisposition) +{ + switch (dwDisposition) + { + case SCARD_LEAVE_CARD: + return "SCARD_LEAVE_CARD"; + + case SCARD_RESET_CARD: + return "SCARD_RESET_CARD"; + + case SCARD_UNPOWER_CARD: + return "SCARD_UNPOWER_CARD"; + + default: + return "SCARD_UNKNOWN_CARD"; + } +} + +WINSCARDAPI const char* WINAPI SCardGetScopeString(DWORD dwScope) +{ + switch (dwScope) + { + case SCARD_SCOPE_USER: + return "SCARD_SCOPE_USER"; + + case SCARD_SCOPE_TERMINAL: + return "SCARD_SCOPE_TERMINAL"; + + case SCARD_SCOPE_SYSTEM: + return "SCARD_SCOPE_SYSTEM"; + + default: + return "SCARD_SCOPE_UNKNOWN"; + } +} + +WINSCARDAPI const char* WINAPI SCardGetCardStateString(DWORD dwCardState) +{ + switch (dwCardState) + { + case SCARD_UNKNOWN: + return "SCARD_UNKNOWN"; + + case SCARD_ABSENT: + return "SCARD_ABSENT"; + + case SCARD_PRESENT: + return "SCARD_PRESENT"; + + case SCARD_SWALLOWED: + return "SCARD_SWALLOWED"; + + case SCARD_POWERED: + return "SCARD_POWERED"; + + case SCARD_NEGOTIABLE: + return "SCARD_NEGOTIABLE"; + + case SCARD_SPECIFIC: + return "SCARD_SPECIFIC"; + + default: + return "SCARD_UNKNOWN"; + } +} + +WINSCARDAPI char* WINAPI SCardGetReaderStateString(DWORD dwReaderState) +{ + const size_t size = 512; + char* buffer = calloc(size, sizeof(char)); + + if (!buffer) + return NULL; + + if (dwReaderState & SCARD_STATE_IGNORE) + winpr_str_append("SCARD_STATE_IGNORE", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_CHANGED) + winpr_str_append("SCARD_STATE_CHANGED", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_UNKNOWN) + winpr_str_append("SCARD_STATE_UNKNOWN", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_UNAVAILABLE) + winpr_str_append("SCARD_STATE_UNAVAILABLE", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_EMPTY) + winpr_str_append("SCARD_STATE_EMPTY", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_PRESENT) + winpr_str_append("SCARD_STATE_PRESENT", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_ATRMATCH) + winpr_str_append("SCARD_STATE_ATRMATCH", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_EXCLUSIVE) + winpr_str_append("SCARD_STATE_EXCLUSIVE", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_INUSE) + winpr_str_append("SCARD_STATE_INUSE", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_MUTE) + winpr_str_append("SCARD_STATE_MUTE", buffer, size, "|"); + + if (dwReaderState & SCARD_STATE_UNPOWERED) + winpr_str_append("SCARD_STATE_UNPOWERED", buffer, size, "|"); + + if (!buffer[0]) + winpr_str_append("SCARD_STATE_UNAWARE", buffer, size, "|"); + + return buffer; +} + +#define WINSCARD_LOAD_PROC(_name) \ + do \ + { \ + WINPR_PRAGMA_DIAG_PUSH \ + WINPR_PRAGMA_DIAG_IGNORED_PEDANTIC \ + pWinSCardApiTable->pfn##_name = GetProcAddressAs(hWinSCardLibrary, #_name, fn##_name); \ + WINPR_PRAGMA_DIAG_POP \ + } while (0) + +BOOL WinSCard_LoadApiTableFunctions(PSCardApiFunctionTable pWinSCardApiTable, + HMODULE hWinSCardLibrary) +{ + WINPR_ASSERT(pWinSCardApiTable); + WINPR_ASSERT(hWinSCardLibrary); + + WINSCARD_LOAD_PROC(SCardEstablishContext); + WINSCARD_LOAD_PROC(SCardReleaseContext); + WINSCARD_LOAD_PROC(SCardIsValidContext); + WINSCARD_LOAD_PROC(SCardListReaderGroupsA); + WINSCARD_LOAD_PROC(SCardListReaderGroupsW); + WINSCARD_LOAD_PROC(SCardListReadersA); + WINSCARD_LOAD_PROC(SCardListReadersW); + WINSCARD_LOAD_PROC(SCardListCardsA); + WINSCARD_LOAD_PROC(SCardListCardsW); + WINSCARD_LOAD_PROC(SCardListInterfacesA); + WINSCARD_LOAD_PROC(SCardListInterfacesW); + WINSCARD_LOAD_PROC(SCardGetProviderIdA); + WINSCARD_LOAD_PROC(SCardGetProviderIdW); + WINSCARD_LOAD_PROC(SCardGetCardTypeProviderNameA); + WINSCARD_LOAD_PROC(SCardGetCardTypeProviderNameW); + WINSCARD_LOAD_PROC(SCardIntroduceReaderGroupA); + WINSCARD_LOAD_PROC(SCardIntroduceReaderGroupW); + WINSCARD_LOAD_PROC(SCardForgetReaderGroupA); + WINSCARD_LOAD_PROC(SCardForgetReaderGroupW); + WINSCARD_LOAD_PROC(SCardIntroduceReaderA); + WINSCARD_LOAD_PROC(SCardIntroduceReaderW); + WINSCARD_LOAD_PROC(SCardForgetReaderA); + WINSCARD_LOAD_PROC(SCardForgetReaderW); + WINSCARD_LOAD_PROC(SCardAddReaderToGroupA); + WINSCARD_LOAD_PROC(SCardAddReaderToGroupW); + WINSCARD_LOAD_PROC(SCardRemoveReaderFromGroupA); + WINSCARD_LOAD_PROC(SCardRemoveReaderFromGroupW); + WINSCARD_LOAD_PROC(SCardIntroduceCardTypeA); + WINSCARD_LOAD_PROC(SCardIntroduceCardTypeW); + WINSCARD_LOAD_PROC(SCardSetCardTypeProviderNameA); + WINSCARD_LOAD_PROC(SCardSetCardTypeProviderNameW); + WINSCARD_LOAD_PROC(SCardForgetCardTypeA); + WINSCARD_LOAD_PROC(SCardForgetCardTypeW); + WINSCARD_LOAD_PROC(SCardFreeMemory); + WINSCARD_LOAD_PROC(SCardAccessStartedEvent); + WINSCARD_LOAD_PROC(SCardReleaseStartedEvent); + WINSCARD_LOAD_PROC(SCardLocateCardsA); + WINSCARD_LOAD_PROC(SCardLocateCardsW); + WINSCARD_LOAD_PROC(SCardLocateCardsByATRA); + WINSCARD_LOAD_PROC(SCardLocateCardsByATRW); + WINSCARD_LOAD_PROC(SCardGetStatusChangeA); + WINSCARD_LOAD_PROC(SCardGetStatusChangeW); + WINSCARD_LOAD_PROC(SCardCancel); + WINSCARD_LOAD_PROC(SCardConnectA); + WINSCARD_LOAD_PROC(SCardConnectW); + WINSCARD_LOAD_PROC(SCardReconnect); + WINSCARD_LOAD_PROC(SCardDisconnect); + WINSCARD_LOAD_PROC(SCardBeginTransaction); + WINSCARD_LOAD_PROC(SCardEndTransaction); + WINSCARD_LOAD_PROC(SCardCancelTransaction); + WINSCARD_LOAD_PROC(SCardState); + WINSCARD_LOAD_PROC(SCardStatusA); + WINSCARD_LOAD_PROC(SCardStatusW); + WINSCARD_LOAD_PROC(SCardTransmit); + WINSCARD_LOAD_PROC(SCardGetTransmitCount); + WINSCARD_LOAD_PROC(SCardControl); + WINSCARD_LOAD_PROC(SCardGetAttrib); + WINSCARD_LOAD_PROC(SCardSetAttrib); + WINSCARD_LOAD_PROC(SCardUIDlgSelectCardA); + WINSCARD_LOAD_PROC(SCardUIDlgSelectCardW); + WINSCARD_LOAD_PROC(GetOpenCardNameA); + WINSCARD_LOAD_PROC(GetOpenCardNameW); + WINSCARD_LOAD_PROC(SCardDlgExtendedError); + WINSCARD_LOAD_PROC(SCardReadCacheA); + WINSCARD_LOAD_PROC(SCardReadCacheW); + WINSCARD_LOAD_PROC(SCardWriteCacheA); + WINSCARD_LOAD_PROC(SCardWriteCacheW); + WINSCARD_LOAD_PROC(SCardGetReaderIconA); + WINSCARD_LOAD_PROC(SCardGetReaderIconW); + WINSCARD_LOAD_PROC(SCardGetDeviceTypeIdA); + WINSCARD_LOAD_PROC(SCardGetDeviceTypeIdW); + WINSCARD_LOAD_PROC(SCardGetReaderDeviceInstanceIdA); + WINSCARD_LOAD_PROC(SCardGetReaderDeviceInstanceIdW); + WINSCARD_LOAD_PROC(SCardListReadersWithDeviceInstanceIdA); + WINSCARD_LOAD_PROC(SCardListReadersWithDeviceInstanceIdW); + WINSCARD_LOAD_PROC(SCardAudit); + + return TRUE; +} + +static const SCardApiFunctionTable WinPR_SCardApiFunctionTable = { + 0, /* dwVersion */ + 0, /* dwFlags */ + + SCardEstablishContext, /* SCardEstablishContext */ + SCardReleaseContext, /* SCardReleaseContext */ + SCardIsValidContext, /* SCardIsValidContext */ + SCardListReaderGroupsA, /* SCardListReaderGroupsA */ + SCardListReaderGroupsW, /* SCardListReaderGroupsW */ + SCardListReadersA, /* SCardListReadersA */ + SCardListReadersW, /* SCardListReadersW */ + SCardListCardsA, /* SCardListCardsA */ + SCardListCardsW, /* SCardListCardsW */ + SCardListInterfacesA, /* SCardListInterfacesA */ + SCardListInterfacesW, /* SCardListInterfacesW */ + SCardGetProviderIdA, /* SCardGetProviderIdA */ + SCardGetProviderIdW, /* SCardGetProviderIdW */ + SCardGetCardTypeProviderNameA, /* SCardGetCardTypeProviderNameA */ + SCardGetCardTypeProviderNameW, /* SCardGetCardTypeProviderNameW */ + SCardIntroduceReaderGroupA, /* SCardIntroduceReaderGroupA */ + SCardIntroduceReaderGroupW, /* SCardIntroduceReaderGroupW */ + SCardForgetReaderGroupA, /* SCardForgetReaderGroupA */ + SCardForgetReaderGroupW, /* SCardForgetReaderGroupW */ + SCardIntroduceReaderA, /* SCardIntroduceReaderA */ + SCardIntroduceReaderW, /* SCardIntroduceReaderW */ + SCardForgetReaderA, /* SCardForgetReaderA */ + SCardForgetReaderW, /* SCardForgetReaderW */ + SCardAddReaderToGroupA, /* SCardAddReaderToGroupA */ + SCardAddReaderToGroupW, /* SCardAddReaderToGroupW */ + SCardRemoveReaderFromGroupA, /* SCardRemoveReaderFromGroupA */ + SCardRemoveReaderFromGroupW, /* SCardRemoveReaderFromGroupW */ + SCardIntroduceCardTypeA, /* SCardIntroduceCardTypeA */ + SCardIntroduceCardTypeW, /* SCardIntroduceCardTypeW */ + SCardSetCardTypeProviderNameA, /* SCardSetCardTypeProviderNameA */ + SCardSetCardTypeProviderNameW, /* SCardSetCardTypeProviderNameW */ + SCardForgetCardTypeA, /* SCardForgetCardTypeA */ + SCardForgetCardTypeW, /* SCardForgetCardTypeW */ + SCardFreeMemory, /* SCardFreeMemory */ + SCardAccessStartedEvent, /* SCardAccessStartedEvent */ + SCardReleaseStartedEvent, /* SCardReleaseStartedEvent */ + SCardLocateCardsA, /* SCardLocateCardsA */ + SCardLocateCardsW, /* SCardLocateCardsW */ + SCardLocateCardsByATRA, /* SCardLocateCardsByATRA */ + SCardLocateCardsByATRW, /* SCardLocateCardsByATRW */ + SCardGetStatusChangeA, /* SCardGetStatusChangeA */ + SCardGetStatusChangeW, /* SCardGetStatusChangeW */ + SCardCancel, /* SCardCancel */ + SCardConnectA, /* SCardConnectA */ + SCardConnectW, /* SCardConnectW */ + SCardReconnect, /* SCardReconnect */ + SCardDisconnect, /* SCardDisconnect */ + SCardBeginTransaction, /* SCardBeginTransaction */ + SCardEndTransaction, /* SCardEndTransaction */ + SCardCancelTransaction, /* SCardCancelTransaction */ + SCardState, /* SCardState */ + SCardStatusA, /* SCardStatusA */ + SCardStatusW, /* SCardStatusW */ + SCardTransmit, /* SCardTransmit */ + SCardGetTransmitCount, /* SCardGetTransmitCount */ + SCardControl, /* SCardControl */ + SCardGetAttrib, /* SCardGetAttrib */ + SCardSetAttrib, /* SCardSetAttrib */ + SCardUIDlgSelectCardA, /* SCardUIDlgSelectCardA */ + SCardUIDlgSelectCardW, /* SCardUIDlgSelectCardW */ + GetOpenCardNameA, /* GetOpenCardNameA */ + GetOpenCardNameW, /* GetOpenCardNameW */ + SCardDlgExtendedError, /* SCardDlgExtendedError */ + SCardReadCacheA, /* SCardReadCacheA */ + SCardReadCacheW, /* SCardReadCacheW */ + SCardWriteCacheA, /* SCardWriteCacheA */ + SCardWriteCacheW, /* SCardWriteCacheW */ + SCardGetReaderIconA, /* SCardGetReaderIconA */ + SCardGetReaderIconW, /* SCardGetReaderIconW */ + SCardGetDeviceTypeIdA, /* SCardGetDeviceTypeIdA */ + SCardGetDeviceTypeIdW, /* SCardGetDeviceTypeIdW */ + SCardGetReaderDeviceInstanceIdA, /* SCardGetReaderDeviceInstanceIdA */ + SCardGetReaderDeviceInstanceIdW, /* SCardGetReaderDeviceInstanceIdW */ + SCardListReadersWithDeviceInstanceIdA, /* SCardListReadersWithDeviceInstanceIdA */ + SCardListReadersWithDeviceInstanceIdW, /* SCardListReadersWithDeviceInstanceIdW */ + SCardAudit /* SCardAudit */ +}; + +const SCardApiFunctionTable* WinPR_GetSCardApiFunctionTable(void) +{ + return &WinPR_SCardApiFunctionTable; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.h new file mode 100644 index 0000000000000000000000000000000000000000..e9279bc6f2d12f75dd04f8c8994f60ab6d558f17 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard.h @@ -0,0 +1,31 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * + * 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_SMARTCARD_PRIVATE_H +#define WINPR_SMARTCARD_PRIVATE_H + +#include + +#ifndef _WIN32 +#include "smartcard_pcsc.h" +#else +#include "smartcard_windows.h" +#endif + +#endif /* WINPR_SMARTCARD_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.c new file mode 100644 index 0000000000000000000000000000000000000000..6b3ffff74a5fedb6709775694ac56771d457061c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.c @@ -0,0 +1,1363 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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 + +#include +#include +#include +#include +#include +#include + +#include "smartcard_inspect.h" + +#include "../log.h" +#define TAG WINPR_TAG("smartcard.inspect") + +#define xstr(s) str(s) +#define str(s) #s + +#define SCARDAPI_STUB_CALL_LONG(status, _name, ...) \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + status = SCARD_E_NO_SERVICE; \ + } \ + else \ + status = g_SCardApi->pfn##_name(__VA_ARGS__) + +#define SCARDAPI_STUB_CALL_HANDLE(status, _name, ...) \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + status = NULL; \ + } \ + else \ + status = g_SCardApi->pfn##_name(__VA_ARGS__) + +#define SCARDAPI_STUB_CALL_VOID(_name, ...) \ + if (!g_SCardApi || !g_SCardApi->pfn##_name) \ + { \ + WLog_DBG(TAG, "Missing function pointer g_SCardApi=%p->" xstr(pfn##_name) "=%p", \ + g_SCardApi, g_SCardApi ? g_SCardApi->pfn##_name : NULL); \ + } \ + else \ + g_SCardApi->pfn##_name(__VA_ARGS__) + +static const DWORD g_LogLevel = WLOG_DEBUG; +static wLog* g_Log = NULL; + +static const SCardApiFunctionTable* g_SCardApi = NULL; + +/** + * Standard Windows Smart Card API + */ + +static LONG WINAPI Inspect_SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardEstablishContext { dwScope: %s (0x%08" PRIX32 ")", + SCardGetScopeString(dwScope), dwScope); + + SCARDAPI_STUB_CALL_LONG(status, SCardEstablishContext, dwScope, pvReserved1, pvReserved2, + phContext); + + WLog_Print(g_Log, g_LogLevel, "SCardEstablishContext } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardReleaseContext(SCARDCONTEXT hContext) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardReleaseContext { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardReleaseContext, hContext); + + WLog_Print(g_Log, g_LogLevel, "SCardReleaseContext } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIsValidContext(SCARDCONTEXT hContext) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIsValidContext { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIsValidContext, hContext); + + WLog_Print(g_Log, g_LogLevel, "SCardIsValidContext } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReaderGroupsA(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListReaderGroupsA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReaderGroupsA, hContext, mszGroups, pcchGroups); + + WLog_Print(g_Log, g_LogLevel, "SCardListReaderGroupsA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReaderGroupsW(SCARDCONTEXT hContext, LPWSTR mszGroups, + LPDWORD pcchGroups) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListReaderGroupsW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReaderGroupsW, hContext, mszGroups, pcchGroups); + + WLog_Print(g_Log, g_LogLevel, "SCardListReaderGroupsW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReadersA(SCARDCONTEXT hContext, LPCSTR mszGroups, + LPSTR mszReaders, LPDWORD pcchReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListReadersA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReadersA, hContext, mszGroups, mszReaders, + pcchReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardListReadersA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReadersW(SCARDCONTEXT hContext, LPCWSTR mszGroups, + LPWSTR mszReaders, LPDWORD pcchReaders) +{ + LONG status = 0; + WLog_Print(g_Log, g_LogLevel, "SCardListReadersW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReadersW, hContext, mszGroups, mszReaders, + pcchReaders); + WLog_Print(g_Log, g_LogLevel, "SCardListReadersW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListCardsA(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + CHAR* mszCards, LPDWORD pcchCards) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListCardsA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListCardsA, hContext, pbAtr, rgquidInterfaces, + cguidInterfaceCount, mszCards, pcchCards); + + WLog_Print(g_Log, g_LogLevel, "SCardListCardsA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListCardsW(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + WCHAR* mszCards, LPDWORD pcchCards) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListCardsW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListCardsW, hContext, pbAtr, rgquidInterfaces, + cguidInterfaceCount, mszCards, pcchCards); + + WLog_Print(g_Log, g_LogLevel, "SCardListCardsW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListInterfacesA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListInterfacesA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListInterfacesA, hContext, szCard, pguidInterfaces, + pcguidInterfaces); + + WLog_Print(g_Log, g_LogLevel, "SCardListInterfacesA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListInterfacesW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidInterfaces, LPDWORD pcguidInterfaces) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListInterfacesW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListInterfacesW, hContext, szCard, pguidInterfaces, + pcguidInterfaces); + + WLog_Print(g_Log, g_LogLevel, "SCardListInterfacesW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetProviderIdA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidProviderId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetProviderIdA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetProviderIdA, hContext, szCard, pguidProviderId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetProviderIdA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetProviderIdW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidProviderId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetProviderIdW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetProviderIdW, hContext, szCard, pguidProviderId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetProviderIdW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, CHAR* szProvider, + LPDWORD pcchProvider) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetCardTypeProviderNameA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetCardTypeProviderNameA, hContext, szCardName, + dwProviderId, szProvider, pcchProvider); + + WLog_Print(g_Log, g_LogLevel, "SCardGetCardTypeProviderNameA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, WCHAR* szProvider, + LPDWORD pcchProvider) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetCardTypeProviderNameW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetCardTypeProviderNameW, hContext, szCardName, + dwProviderId, szProvider, pcchProvider); + + WLog_Print(g_Log, g_LogLevel, "SCardGetCardTypeProviderNameW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderGroupA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceReaderGroupA, hContext, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderGroupA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderGroupW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceReaderGroupW, hContext, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderGroupW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderGroupA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetReaderGroupA, hContext, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderGroupA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderGroupW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetReaderGroupW, hContext, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderGroupW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szDeviceName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceReaderA, hContext, szReaderName, szDeviceName); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szDeviceName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceReaderW, hContext, szReaderName, szDeviceName); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceReaderW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetReaderA, hContext, szReaderName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetReaderW, hContext, szReaderName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetReaderW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardAddReaderToGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardAddReaderToGroupA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardAddReaderToGroupA, hContext, szReaderName, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardAddReaderToGroupA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardAddReaderToGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardAddReaderToGroupW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardAddReaderToGroupW, hContext, szReaderName, szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardAddReaderToGroupW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardRemoveReaderFromGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardRemoveReaderFromGroupA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardRemoveReaderFromGroupA, hContext, szReaderName, + szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardRemoveReaderFromGroupA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardRemoveReaderFromGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardRemoveReaderFromGroupW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardRemoveReaderFromGroupW, hContext, szReaderName, + szGroupName); + + WLog_Print(g_Log, g_LogLevel, "SCardRemoveReaderFromGroupW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceCardTypeA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceCardTypeA, hContext, szCardName, + pguidPrimaryProvider, rgguidInterfaces, dwInterfaceCount, pbAtr, + pbAtrMask, cbAtrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceCardTypeA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardIntroduceCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceCardTypeW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardIntroduceCardTypeW, hContext, szCardName, + pguidPrimaryProvider, rgguidInterfaces, dwInterfaceCount, pbAtr, + pbAtrMask, cbAtrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardIntroduceCardTypeW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardSetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, LPCSTR szProvider) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardSetCardTypeProviderNameA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardSetCardTypeProviderNameA, hContext, szCardName, + dwProviderId, szProvider); + + WLog_Print(g_Log, g_LogLevel, "SCardSetCardTypeProviderNameA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardSetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, LPCWSTR szProvider) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardSetCardTypeProviderNameA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardSetCardTypeProviderNameW, hContext, szCardName, + dwProviderId, szProvider); + + WLog_Print(g_Log, g_LogLevel, "SCardSetCardTypeProviderNameW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetCardTypeA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetCardTypeA, hContext, szCardName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetCardTypeA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardForgetCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardForgetCardTypeW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardForgetCardTypeW, hContext, szCardName); + + WLog_Print(g_Log, g_LogLevel, "SCardForgetCardTypeW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardFreeMemory(SCARDCONTEXT hContext, LPVOID pvMem) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardFreeMemory { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardFreeMemory, hContext, pvMem); + + WLog_Print(g_Log, g_LogLevel, "SCardFreeMemory } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static HANDLE WINAPI Inspect_SCardAccessStartedEvent(void) +{ + HANDLE hEvent = NULL; + + WLog_Print(g_Log, g_LogLevel, "SCardAccessStartedEvent {"); + + SCARDAPI_STUB_CALL_HANDLE(hEvent, SCardAccessStartedEvent); + + WLog_Print(g_Log, g_LogLevel, "SCardAccessStartedEvent } hEvent: %p", hEvent); + + return hEvent; +} + +static void WINAPI Inspect_SCardReleaseStartedEvent(void) +{ + WLog_Print(g_Log, g_LogLevel, "SCardReleaseStartedEvent {"); + + SCARDAPI_STUB_CALL_VOID(SCardReleaseStartedEvent); + + WLog_Print(g_Log, g_LogLevel, "SCardReleaseStartedEvent }"); +} + +static LONG WINAPI Inspect_SCardLocateCardsA(SCARDCONTEXT hContext, LPCSTR mszCards, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardLocateCardsA, hContext, mszCards, rgReaderStates, + cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardLocateCardsW(SCARDCONTEXT hContext, LPCWSTR mszCards, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardLocateCardsW, hContext, mszCards, rgReaderStates, + cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardLocateCardsByATRA(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsByATRA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardLocateCardsByATRA, hContext, rgAtrMasks, cAtrs, + rgReaderStates, cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsByATRA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardLocateCardsByATRW(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsByATRW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardLocateCardsByATRW, hContext, rgAtrMasks, cAtrs, + rgReaderStates, cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardLocateCardsByATRW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetStatusChangeA(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetStatusChangeA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetStatusChangeA, hContext, dwTimeout, rgReaderStates, + cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardGetStatusChangeA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetStatusChangeW(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetStatusChangeW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetStatusChangeW, hContext, dwTimeout, rgReaderStates, + cReaders); + + WLog_Print(g_Log, g_LogLevel, "SCardGetStatusChangeW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardCancel(SCARDCONTEXT hContext) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardCancel { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardCancel, hContext); + + WLog_Print(g_Log, g_LogLevel, "SCardCancel } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardConnectA(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardConnectA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardConnectA, hContext, szReader, dwShareMode, + dwPreferredProtocols, phCard, pdwActiveProtocol); + + WLog_Print(g_Log, g_LogLevel, "SCardConnectA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardConnectW(SCARDCONTEXT hContext, LPCWSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardConnectW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardConnectW, hContext, szReader, dwShareMode, + dwPreferredProtocols, phCard, pdwActiveProtocol); + + WLog_Print(g_Log, g_LogLevel, "SCardConnectW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode, + DWORD dwPreferredProtocols, DWORD dwInitialization, + LPDWORD pdwActiveProtocol) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardReconnect { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardReconnect, hCard, dwShareMode, dwPreferredProtocols, + dwInitialization, pdwActiveProtocol); + + WLog_Print(g_Log, g_LogLevel, "SCardReconnect } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardDisconnect { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardDisconnect, hCard, dwDisposition); + + WLog_Print(g_Log, g_LogLevel, "SCardDisconnect } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardBeginTransaction(SCARDHANDLE hCard) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardBeginTransaction { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardBeginTransaction, hCard); + + WLog_Print(g_Log, g_LogLevel, "SCardBeginTransaction } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardEndTransaction(SCARDHANDLE hCard, DWORD dwDisposition) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardEndTransaction { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardEndTransaction, hCard, dwDisposition); + + WLog_Print(g_Log, g_LogLevel, "SCardEndTransaction } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardCancelTransaction(SCARDHANDLE hCard) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardCancelTransaction { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardCancelTransaction, hCard); + + WLog_Print(g_Log, g_LogLevel, "SCardCancelTransaction } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardState(SCARDHANDLE hCard, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardState { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardState, hCard, pdwState, pdwProtocol, pbAtr, pcbAtrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardState } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardStatusA(SCARDHANDLE hCard, LPSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, + LPDWORD pdwProtocol, LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardStatusA { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardStatusA, hCard, mszReaderNames, pcchReaderLen, pdwState, + pdwProtocol, pbAtr, pcbAtrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardStatusA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardStatusW(SCARDHANDLE hCard, LPWSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, + LPDWORD pdwProtocol, LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardStatusW { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardStatusW, hCard, mszReaderNames, pcchReaderLen, pdwState, + pdwProtocol, pbAtr, pcbAtrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardStatusW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardTransmit(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, + LPCBYTE pbSendBuffer, DWORD cbSendLength, + LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, + LPDWORD pcbRecvLength) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardTransmit { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardTransmit, hCard, pioSendPci, pbSendBuffer, cbSendLength, + pioRecvPci, pbRecvBuffer, pcbRecvLength); + + WLog_Print(g_Log, g_LogLevel, "SCardTransmit } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetTransmitCount(SCARDHANDLE hCard, LPDWORD pcTransmitCount) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetTransmitCount { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetTransmitCount, hCard, pcTransmitCount); + + WLog_Print(g_Log, g_LogLevel, "SCardGetTransmitCount } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardControl(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID lpInBuffer, + DWORD cbInBufferSize, LPVOID lpOutBuffer, + DWORD cbOutBufferSize, LPDWORD lpBytesReturned) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardControl { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardControl, hCard, dwControlCode, lpInBuffer, cbInBufferSize, + lpOutBuffer, cbOutBufferSize, lpBytesReturned); + + WLog_Print(g_Log, g_LogLevel, "SCardControl } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetAttrib { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetAttrib, hCard, dwAttrId, pbAttr, pcbAttrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardGetAttrib } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardSetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr, + DWORD cbAttrLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardSetAttrib { hCard: %p", (void*)hCard); + + SCARDAPI_STUB_CALL_LONG(status, SCardSetAttrib, hCard, dwAttrId, pbAttr, cbAttrLen); + + WLog_Print(g_Log, g_LogLevel, "SCardSetAttrib } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardUIDlgSelectCardA(LPOPENCARDNAMEA_EX pDlgStruc) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardUIDlgSelectCardA {"); + + SCARDAPI_STUB_CALL_LONG(status, SCardUIDlgSelectCardA, pDlgStruc); + + WLog_Print(g_Log, g_LogLevel, "SCardUIDlgSelectCardA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardUIDlgSelectCardW(LPOPENCARDNAMEW_EX pDlgStruc) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardUIDlgSelectCardW {"); + + SCARDAPI_STUB_CALL_LONG(status, SCardUIDlgSelectCardW, pDlgStruc); + + WLog_Print(g_Log, g_LogLevel, "SCardUIDlgSelectCardW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_GetOpenCardNameA(LPOPENCARDNAMEA pDlgStruc) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "GetOpenCardNameA {"); + + SCARDAPI_STUB_CALL_LONG(status, GetOpenCardNameA, pDlgStruc); + + WLog_Print(g_Log, g_LogLevel, "GetOpenCardNameA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_GetOpenCardNameW(LPOPENCARDNAMEW pDlgStruc) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "GetOpenCardNameW {"); + + SCARDAPI_STUB_CALL_LONG(status, GetOpenCardNameW, pDlgStruc); + + WLog_Print(g_Log, g_LogLevel, "GetOpenCardNameW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardDlgExtendedError(void) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardDlgExtendedError {"); + + SCARDAPI_STUB_CALL_LONG(status, SCardDlgExtendedError); + + WLog_Print(g_Log, g_LogLevel, "SCardDlgExtendedError } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardReadCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardReadCacheA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardReadCacheA, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); + + WLog_Print(g_Log, g_LogLevel, "SCardReadCacheA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardReadCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardReadCacheW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardReadCacheW, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); + + WLog_Print(g_Log, g_LogLevel, "SCardReadCacheW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardWriteCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardWriteCacheA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardWriteCacheA, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); + + WLog_Print(g_Log, g_LogLevel, "SCardWriteCacheA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardWriteCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardWriteCacheW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardWriteCacheW, hContext, CardIdentifier, FreshnessCounter, + LookupName, Data, DataLen); + + WLog_Print(g_Log, g_LogLevel, "SCardWriteCacheW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetReaderIconA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderIconA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetReaderIconA, hContext, szReaderName, pbIcon, pcbIcon); + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderIconA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetReaderIconW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPBYTE pbIcon, LPDWORD pcbIcon) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderIconW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetReaderIconW, hContext, szReaderName, pbIcon, pcbIcon); + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderIconW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetDeviceTypeIdA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetDeviceTypeIdA { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetDeviceTypeIdA, hContext, szReaderName, pdwDeviceTypeId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetDeviceTypeIdA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetDeviceTypeIdW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetDeviceTypeIdW { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetDeviceTypeIdW, hContext, szReaderName, pdwDeviceTypeId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetDeviceTypeIdW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetReaderDeviceInstanceIdA(SCARDCONTEXT hContext, + LPCSTR szReaderName, + LPSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderDeviceInstanceIdA { hContext: %p", + (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetReaderDeviceInstanceIdA, hContext, szReaderName, + szDeviceInstanceId, pcchDeviceInstanceId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderDeviceInstanceIdA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardGetReaderDeviceInstanceIdW(SCARDCONTEXT hContext, + LPCWSTR szReaderName, + LPWSTR szDeviceInstanceId, + LPDWORD pcchDeviceInstanceId) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderDeviceInstanceIdW { hContext: %p", + (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardGetReaderDeviceInstanceIdW, hContext, szReaderName, + szDeviceInstanceId, pcchDeviceInstanceId); + + WLog_Print(g_Log, g_LogLevel, "SCardGetReaderDeviceInstanceIdW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReadersWithDeviceInstanceIdA(SCARDCONTEXT hContext, + LPCSTR szDeviceInstanceId, + LPSTR mszReaders, + LPDWORD pcchReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListReadersWithDeviceInstanceIdA { hContext: %p", + (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReadersWithDeviceInstanceIdA, hContext, + szDeviceInstanceId, mszReaders, pcchReaders); + + WLog_Print(g_Log, g_LogLevel, + "SCardListReadersWithDeviceInstanceIdA } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardListReadersWithDeviceInstanceIdW(SCARDCONTEXT hContext, + LPCWSTR szDeviceInstanceId, + LPWSTR mszReaders, + LPDWORD pcchReaders) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardListReadersWithDeviceInstanceIdW { hContext: %p", + (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardListReadersWithDeviceInstanceIdW, hContext, + szDeviceInstanceId, mszReaders, pcchReaders); + + WLog_Print(g_Log, g_LogLevel, + "SCardListReadersWithDeviceInstanceIdW } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +static LONG WINAPI Inspect_SCardAudit(SCARDCONTEXT hContext, DWORD dwEvent) +{ + LONG status = 0; + + WLog_Print(g_Log, g_LogLevel, "SCardAudit { hContext: %p", (void*)hContext); + + SCARDAPI_STUB_CALL_LONG(status, SCardAudit, hContext, dwEvent); + + WLog_Print(g_Log, g_LogLevel, "SCardAudit } status: %s (0x%08" PRIX32 ")", + SCardGetErrorString(status), status); + + return status; +} + +/** + * Extended API + */ + +static const SCardApiFunctionTable Inspect_SCardApiFunctionTable = { + 0, /* dwVersion */ + 0, /* dwFlags */ + + Inspect_SCardEstablishContext, /* SCardEstablishContext */ + Inspect_SCardReleaseContext, /* SCardReleaseContext */ + Inspect_SCardIsValidContext, /* SCardIsValidContext */ + Inspect_SCardListReaderGroupsA, /* SCardListReaderGroupsA */ + Inspect_SCardListReaderGroupsW, /* SCardListReaderGroupsW */ + Inspect_SCardListReadersA, /* SCardListReadersA */ + Inspect_SCardListReadersW, /* SCardListReadersW */ + Inspect_SCardListCardsA, /* SCardListCardsA */ + Inspect_SCardListCardsW, /* SCardListCardsW */ + Inspect_SCardListInterfacesA, /* SCardListInterfacesA */ + Inspect_SCardListInterfacesW, /* SCardListInterfacesW */ + Inspect_SCardGetProviderIdA, /* SCardGetProviderIdA */ + Inspect_SCardGetProviderIdW, /* SCardGetProviderIdW */ + Inspect_SCardGetCardTypeProviderNameA, /* SCardGetCardTypeProviderNameA */ + Inspect_SCardGetCardTypeProviderNameW, /* SCardGetCardTypeProviderNameW */ + Inspect_SCardIntroduceReaderGroupA, /* SCardIntroduceReaderGroupA */ + Inspect_SCardIntroduceReaderGroupW, /* SCardIntroduceReaderGroupW */ + Inspect_SCardForgetReaderGroupA, /* SCardForgetReaderGroupA */ + Inspect_SCardForgetReaderGroupW, /* SCardForgetReaderGroupW */ + Inspect_SCardIntroduceReaderA, /* SCardIntroduceReaderA */ + Inspect_SCardIntroduceReaderW, /* SCardIntroduceReaderW */ + Inspect_SCardForgetReaderA, /* SCardForgetReaderA */ + Inspect_SCardForgetReaderW, /* SCardForgetReaderW */ + Inspect_SCardAddReaderToGroupA, /* SCardAddReaderToGroupA */ + Inspect_SCardAddReaderToGroupW, /* SCardAddReaderToGroupW */ + Inspect_SCardRemoveReaderFromGroupA, /* SCardRemoveReaderFromGroupA */ + Inspect_SCardRemoveReaderFromGroupW, /* SCardRemoveReaderFromGroupW */ + Inspect_SCardIntroduceCardTypeA, /* SCardIntroduceCardTypeA */ + Inspect_SCardIntroduceCardTypeW, /* SCardIntroduceCardTypeW */ + Inspect_SCardSetCardTypeProviderNameA, /* SCardSetCardTypeProviderNameA */ + Inspect_SCardSetCardTypeProviderNameW, /* SCardSetCardTypeProviderNameW */ + Inspect_SCardForgetCardTypeA, /* SCardForgetCardTypeA */ + Inspect_SCardForgetCardTypeW, /* SCardForgetCardTypeW */ + Inspect_SCardFreeMemory, /* SCardFreeMemory */ + Inspect_SCardAccessStartedEvent, /* SCardAccessStartedEvent */ + Inspect_SCardReleaseStartedEvent, /* SCardReleaseStartedEvent */ + Inspect_SCardLocateCardsA, /* SCardLocateCardsA */ + Inspect_SCardLocateCardsW, /* SCardLocateCardsW */ + Inspect_SCardLocateCardsByATRA, /* SCardLocateCardsByATRA */ + Inspect_SCardLocateCardsByATRW, /* SCardLocateCardsByATRW */ + Inspect_SCardGetStatusChangeA, /* SCardGetStatusChangeA */ + Inspect_SCardGetStatusChangeW, /* SCardGetStatusChangeW */ + Inspect_SCardCancel, /* SCardCancel */ + Inspect_SCardConnectA, /* SCardConnectA */ + Inspect_SCardConnectW, /* SCardConnectW */ + Inspect_SCardReconnect, /* SCardReconnect */ + Inspect_SCardDisconnect, /* SCardDisconnect */ + Inspect_SCardBeginTransaction, /* SCardBeginTransaction */ + Inspect_SCardEndTransaction, /* SCardEndTransaction */ + Inspect_SCardCancelTransaction, /* SCardCancelTransaction */ + Inspect_SCardState, /* SCardState */ + Inspect_SCardStatusA, /* SCardStatusA */ + Inspect_SCardStatusW, /* SCardStatusW */ + Inspect_SCardTransmit, /* SCardTransmit */ + Inspect_SCardGetTransmitCount, /* SCardGetTransmitCount */ + Inspect_SCardControl, /* SCardControl */ + Inspect_SCardGetAttrib, /* SCardGetAttrib */ + Inspect_SCardSetAttrib, /* SCardSetAttrib */ + Inspect_SCardUIDlgSelectCardA, /* SCardUIDlgSelectCardA */ + Inspect_SCardUIDlgSelectCardW, /* SCardUIDlgSelectCardW */ + Inspect_GetOpenCardNameA, /* GetOpenCardNameA */ + Inspect_GetOpenCardNameW, /* GetOpenCardNameW */ + Inspect_SCardDlgExtendedError, /* SCardDlgExtendedError */ + Inspect_SCardReadCacheA, /* SCardReadCacheA */ + Inspect_SCardReadCacheW, /* SCardReadCacheW */ + Inspect_SCardWriteCacheA, /* SCardWriteCacheA */ + Inspect_SCardWriteCacheW, /* SCardWriteCacheW */ + Inspect_SCardGetReaderIconA, /* SCardGetReaderIconA */ + Inspect_SCardGetReaderIconW, /* SCardGetReaderIconW */ + Inspect_SCardGetDeviceTypeIdA, /* SCardGetDeviceTypeIdA */ + Inspect_SCardGetDeviceTypeIdW, /* SCardGetDeviceTypeIdW */ + Inspect_SCardGetReaderDeviceInstanceIdA, /* SCardGetReaderDeviceInstanceIdA */ + Inspect_SCardGetReaderDeviceInstanceIdW, /* SCardGetReaderDeviceInstanceIdW */ + Inspect_SCardListReadersWithDeviceInstanceIdA, /* SCardListReadersWithDeviceInstanceIdA */ + Inspect_SCardListReadersWithDeviceInstanceIdW, /* SCardListReadersWithDeviceInstanceIdW */ + Inspect_SCardAudit /* SCardAudit */ +}; + +static void Inspect_InitLog(void) +{ + if (g_Log) + return; + + if (!(g_Log = WLog_Get("WinSCard"))) + return; +} + +const SCardApiFunctionTable* Inspect_RegisterSCardApi(const SCardApiFunctionTable* pSCardApi) +{ + g_SCardApi = pSCardApi; + + Inspect_InitLog(); + + return &Inspect_SCardApiFunctionTable; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.h new file mode 100644 index 0000000000000000000000000000000000000000..482dd97e05add577c1b65b259846014f2e9f19fe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_inspect.h @@ -0,0 +1,30 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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_SMARTCARD_INSPECT_PRIVATE_H +#define WINPR_SMARTCARD_INSPECT_PRIVATE_H + +#include +#include + +const SCardApiFunctionTable* Inspect_RegisterSCardApi(const SCardApiFunctionTable* pSCardApi); + +#endif /* WINPR_SMARTCARD_INSPECT_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.c new file mode 100644 index 0000000000000000000000000000000000000000..03369b2f67bb7d9bb930a33983bed1403b027e8e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.c @@ -0,0 +1,3383 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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 + +#ifndef _WIN32 + +#ifdef __APPLE__ +#include +#include +#include +#include +#include +#include +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "smartcard_pcsc.h" + +#include "../log.h" +#define TAG WINPR_TAG("smartcard") + +#define WINSCARD_LOAD_PROC_EX(module, pcsc, _fname, _name) \ + do \ + { \ + WINPR_PRAGMA_DIAG_PUSH \ + WINPR_PRAGMA_DIAG_IGNORED_PEDANTIC \ + pcsc.pfn##_fname = GetProcAddressAs(module, #_name, fnPCSC##_fname); \ + WINPR_PRAGMA_DIAG_POP \ + } while (0) + +#define WINSCARD_LOAD_PROC(module, pcsc, _name) WINSCARD_LOAD_PROC_EX(module, pcsc, _name, _name) + +/** + * PC/SC transactions: + * http://developersblog.wwpass.com/?p=180 + */ + +/** + * Smart Card Logon on Windows Vista: + * http://blogs.msdn.com/b/shivaram/archive/2007/02/26/smart-card-logon-on-windows-vista.aspx + */ + +/** + * The Smart Card Cryptographic Service Provider Cookbook: + * http://msdn.microsoft.com/en-us/library/ms953432.aspx + * + * SCARDCONTEXT + * + * The context is a communication channel with the smart card resource manager and + * all calls to the resource manager must go through this link. + * + * All functions that take a context as a parameter or a card handle as parameter, + * which is indirectly associated with a particular context, may be blocking calls. + * Examples of these are SCardGetStatusChange and SCardBeginTransaction, which takes + * a card handle as a parameter. If such a function blocks then all operations wanting + * to use the context are blocked as well. So, it is recommended that a CSP using + * monitoring establishes at least two contexts with the resource manager; one for + * monitoring (with SCardGetStatusChange) and one for other operations. + * + * If multiple cards are present, it is recommended that a separate context or pair + * of contexts be established for each card to prevent operations on one card from + * blocking operations on another. + * + * Example one + * + * The example below shows what can happen if a CSP using SCardGetStatusChange for + * monitoring does not establish two contexts with the resource manager. + * The context becomes unusable until SCardGetStatusChange unblocks. + * + * In this example, there is one process running called P1. + * P1 calls SCardEstablishContext, which returns the context hCtx. + * P1 calls SCardConnect (with the hCtx context) which returns a handle to the card, hCard. + * P1 calls SCardGetStatusChange (with the hCtx context) which blocks because + * there are no status changes to report. + * Until the thread running SCardGetStatusChange unblocks, another thread in P1 trying to + * perform an operation using the context hCtx (or the card hCard) will also be blocked. + * + * Example two + * + * The example below shows how transaction control ensures that operations meant to be + * performed without interruption can do so safely within a transaction. + * + * In this example, there are two different processes running; P1 and P2. + * P1 calls SCardEstablishContext, which returns the context hCtx1. + * P2 calls SCardEstablishContext, which returns the context hCtx2. + * P1 calls SCardConnect (with the hCtx1 context) which returns a handle to the card, hCard1. + * P2 calls SCardConnect (with the hCtx2 context) which returns a handle to the same card, hCard2. + * P1 calls SCardBeginTransaction (with the hCard 1 context). + * Until P1 calls SCardEndTransaction (with the hCard1 context), + * any operation using hCard2 will be blocked. + * Once an operation using hCard2 is blocked and until it's returning, + * any operation using hCtx2 (and hCard2) will also be blocked. + */ + +//#define DISABLE_PCSC_SCARD_AUTOALLOCATE +#include "smartcard_pcsc.h" + +#define PCSC_SCARD_PCI_T0 (&g_PCSC_rgSCardT0Pci) +#define PCSC_SCARD_PCI_T1 (&g_PCSC_rgSCardT1Pci) +#define PCSC_SCARD_PCI_RAW (&g_PCSC_rgSCardRawPci) + +typedef PCSC_LONG (*fnPCSCSCardEstablishContext)(PCSC_DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext); +typedef PCSC_LONG (*fnPCSCSCardReleaseContext)(SCARDCONTEXT hContext); +typedef PCSC_LONG (*fnPCSCSCardIsValidContext)(SCARDCONTEXT hContext); +typedef PCSC_LONG (*fnPCSCSCardConnect)(SCARDCONTEXT hContext, LPCSTR szReader, + PCSC_DWORD dwShareMode, PCSC_DWORD dwPreferredProtocols, + LPSCARDHANDLE phCard, PCSC_LPDWORD pdwActiveProtocol); +typedef PCSC_LONG (*fnPCSCSCardReconnect)(SCARDHANDLE hCard, PCSC_DWORD dwShareMode, + PCSC_DWORD dwPreferredProtocols, + PCSC_DWORD dwInitialization, + PCSC_LPDWORD pdwActiveProtocol); +typedef PCSC_LONG (*fnPCSCSCardDisconnect)(SCARDHANDLE hCard, PCSC_DWORD dwDisposition); +typedef PCSC_LONG (*fnPCSCSCardBeginTransaction)(SCARDHANDLE hCard); +typedef PCSC_LONG (*fnPCSCSCardEndTransaction)(SCARDHANDLE hCard, PCSC_DWORD dwDisposition); +typedef PCSC_LONG (*fnPCSCSCardStatus)(SCARDHANDLE hCard, LPSTR mszReaderName, + PCSC_LPDWORD pcchReaderLen, PCSC_LPDWORD pdwState, + PCSC_LPDWORD pdwProtocol, LPBYTE pbAtr, + PCSC_LPDWORD pcbAtrLen); +typedef PCSC_LONG (*fnPCSCSCardGetStatusChange)(SCARDCONTEXT hContext, PCSC_DWORD dwTimeout, + PCSC_SCARD_READERSTATE* rgReaderStates, + PCSC_DWORD cReaders); +typedef PCSC_LONG (*fnPCSCSCardControl)(SCARDHANDLE hCard, PCSC_DWORD dwControlCode, + LPCVOID pbSendBuffer, PCSC_DWORD cbSendLength, + LPVOID pbRecvBuffer, PCSC_DWORD cbRecvLength, + PCSC_LPDWORD lpBytesReturned); +typedef PCSC_LONG (*fnPCSCSCardTransmit)(SCARDHANDLE hCard, const PCSC_SCARD_IO_REQUEST* pioSendPci, + LPCBYTE pbSendBuffer, PCSC_DWORD cbSendLength, + PCSC_SCARD_IO_REQUEST* pioRecvPci, LPBYTE pbRecvBuffer, + PCSC_LPDWORD pcbRecvLength); +typedef PCSC_LONG (*fnPCSCSCardListReaderGroups)(SCARDCONTEXT hContext, LPSTR mszGroups, + PCSC_LPDWORD pcchGroups); +typedef PCSC_LONG (*fnPCSCSCardListReaders)(SCARDCONTEXT hContext, LPCSTR mszGroups, + LPSTR mszReaders, PCSC_LPDWORD pcchReaders); +typedef PCSC_LONG (*fnPCSCSCardFreeMemory)(SCARDCONTEXT hContext, LPCVOID pvMem); +typedef PCSC_LONG (*fnPCSCSCardCancel)(SCARDCONTEXT hContext); +typedef PCSC_LONG (*fnPCSCSCardGetAttrib)(SCARDHANDLE hCard, PCSC_DWORD dwAttrId, LPBYTE pbAttr, + PCSC_LPDWORD pcbAttrLen); +typedef PCSC_LONG (*fnPCSCSCardSetAttrib)(SCARDHANDLE hCard, PCSC_DWORD dwAttrId, LPCBYTE pbAttr, + PCSC_DWORD cbAttrLen); + +typedef struct +{ + fnPCSCSCardEstablishContext pfnSCardEstablishContext; + fnPCSCSCardReleaseContext pfnSCardReleaseContext; + fnPCSCSCardIsValidContext pfnSCardIsValidContext; + fnPCSCSCardConnect pfnSCardConnect; + fnPCSCSCardReconnect pfnSCardReconnect; + fnPCSCSCardDisconnect pfnSCardDisconnect; + fnPCSCSCardBeginTransaction pfnSCardBeginTransaction; + fnPCSCSCardEndTransaction pfnSCardEndTransaction; + fnPCSCSCardStatus pfnSCardStatus; + fnPCSCSCardGetStatusChange pfnSCardGetStatusChange; + fnPCSCSCardControl pfnSCardControl; + fnPCSCSCardTransmit pfnSCardTransmit; + fnPCSCSCardListReaderGroups pfnSCardListReaderGroups; + fnPCSCSCardListReaders pfnSCardListReaders; + fnPCSCSCardFreeMemory pfnSCardFreeMemory; + fnPCSCSCardCancel pfnSCardCancel; + fnPCSCSCardGetAttrib pfnSCardGetAttrib; + fnPCSCSCardSetAttrib pfnSCardSetAttrib; +} PCSCFunctionTable; + +typedef struct +{ + DWORD len; + DWORD freshness; + BYTE* data; +} PCSC_CACHE_ITEM; + +typedef struct +{ + SCARDHANDLE owner; + CRITICAL_SECTION lock; + SCARDCONTEXT hContext; + DWORD dwCardHandleCount; + BOOL isTransactionLocked; + wHashTable* cache; +} PCSC_SCARDCONTEXT; + +typedef struct +{ + BOOL shared; + SCARDCONTEXT hSharedContext; +} PCSC_SCARDHANDLE; + +static HMODULE g_PCSCModule = NULL; +static PCSCFunctionTable g_PCSC = { 0 }; + +static HANDLE g_StartedEvent = NULL; +static int g_StartedEventRefCount = 0; + +static BOOL g_SCardAutoAllocate = FALSE; +static BOOL g_PnP_Notification = TRUE; + +#ifdef __MACOSX__ +static unsigned int OSXVersion = 0; +#endif + +static wListDictionary* g_CardHandles = NULL; +static wListDictionary* g_CardContexts = NULL; +static wListDictionary* g_MemoryBlocks = NULL; + +static const char SMARTCARD_PNP_NOTIFICATION_A[] = "\\\\?PnP?\\Notification"; + +static const PCSC_SCARD_IO_REQUEST g_PCSC_rgSCardT0Pci = { SCARD_PROTOCOL_T0, + sizeof(PCSC_SCARD_IO_REQUEST) }; +static const PCSC_SCARD_IO_REQUEST g_PCSC_rgSCardT1Pci = { SCARD_PROTOCOL_T1, + sizeof(PCSC_SCARD_IO_REQUEST) }; +static const PCSC_SCARD_IO_REQUEST g_PCSC_rgSCardRawPci = { PCSC_SCARD_PROTOCOL_RAW, + sizeof(PCSC_SCARD_IO_REQUEST) }; + +static LONG WINAPI PCSC_SCardFreeMemory_Internal(SCARDCONTEXT hContext, LPVOID pvMem); +static LONG WINAPI PCSC_SCardEstablishContext_Internal(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, + LPSCARDCONTEXT phContext); +static LONG WINAPI PCSC_SCardReleaseContext_Internal(SCARDCONTEXT hContext); + +static LONG PCSC_SCard_LogError(const char* what) +{ + WLog_WARN(TAG, "Missing function pointer %s=NULL", what); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG PCSC_MapErrorCodeToWinSCard(PCSC_LONG errorCode) +{ + /** + * pcsc-lite returns SCARD_E_UNEXPECTED when it + * should return SCARD_E_UNSUPPORTED_FEATURE. + * + * Additionally, the pcsc-lite headers incorrectly + * define SCARD_E_UNSUPPORTED_FEATURE to 0x8010001F, + * when the real value should be 0x80100022. + */ + if (errorCode != SCARD_S_SUCCESS) + { + if (errorCode == SCARD_E_UNEXPECTED) + errorCode = SCARD_E_UNSUPPORTED_FEATURE; + } + + return (LONG)errorCode; +} + +static DWORD PCSC_ConvertCardStateToWinSCard(DWORD dwCardState, PCSC_LONG status) +{ + /** + * pcsc-lite's SCardStatus returns a bit-field, not an enumerated value. + * + * State WinSCard pcsc-lite + * + * SCARD_UNKNOWN 0 0x0001 + * SCARD_ABSENT 1 0x0002 + * SCARD_PRESENT 2 0x0004 + * SCARD_SWALLOWED 3 0x0008 + * SCARD_POWERED 4 0x0010 + * SCARD_NEGOTIABLE 5 0x0020 + * SCARD_SPECIFIC 6 0x0040 + * + * pcsc-lite also never sets SCARD_SPECIFIC, + * which is expected by some windows applications. + */ + if (status == SCARD_S_SUCCESS) + { + if ((dwCardState & PCSC_SCARD_NEGOTIABLE) || (dwCardState & PCSC_SCARD_SPECIFIC)) + return SCARD_SPECIFIC; + } + + if (dwCardState & PCSC_SCARD_POWERED) + return SCARD_POWERED; + + if (dwCardState & PCSC_SCARD_NEGOTIABLE) + return SCARD_NEGOTIABLE; + + if (dwCardState & PCSC_SCARD_SPECIFIC) + return SCARD_SPECIFIC; + + if (dwCardState & PCSC_SCARD_ABSENT) + return SCARD_ABSENT; + + if (dwCardState & PCSC_SCARD_PRESENT) + return SCARD_PRESENT; + + if (dwCardState & PCSC_SCARD_SWALLOWED) + return SCARD_SWALLOWED; + + if (dwCardState & PCSC_SCARD_UNKNOWN) + return SCARD_UNKNOWN; + + return SCARD_UNKNOWN; +} + +static DWORD PCSC_ConvertProtocolsToWinSCard(PCSC_DWORD dwProtocols) +{ + /** + * pcsc-lite uses a different value for SCARD_PROTOCOL_RAW, + * and also has SCARD_PROTOCOL_T15 which is not in WinSCard. + */ + if (dwProtocols & PCSC_SCARD_PROTOCOL_RAW) + { + dwProtocols &= ~PCSC_SCARD_PROTOCOL_RAW; + dwProtocols |= SCARD_PROTOCOL_RAW; + } + + if (dwProtocols & PCSC_SCARD_PROTOCOL_T15) + { + dwProtocols &= ~PCSC_SCARD_PROTOCOL_T15; + } + + return (DWORD)dwProtocols; +} + +static DWORD PCSC_ConvertProtocolsFromWinSCard(DWORD dwProtocols) +{ + /** + * pcsc-lite uses a different value for SCARD_PROTOCOL_RAW, + * and it does not define WinSCard's SCARD_PROTOCOL_DEFAULT. + */ + if (dwProtocols & SCARD_PROTOCOL_RAW) + { + dwProtocols &= ~SCARD_PROTOCOL_RAW; + dwProtocols |= PCSC_SCARD_PROTOCOL_RAW; + } + + if (dwProtocols & SCARD_PROTOCOL_DEFAULT) + { + dwProtocols &= ~SCARD_PROTOCOL_DEFAULT; + } + + if (dwProtocols == SCARD_PROTOCOL_UNDEFINED) + { + dwProtocols = SCARD_PROTOCOL_Tx; + } + + return dwProtocols; +} + +static PCSC_SCARDCONTEXT* PCSC_GetCardContextData(SCARDCONTEXT hContext) +{ + PCSC_SCARDCONTEXT* pContext = NULL; + + if (!g_CardContexts) + return NULL; + + pContext = (PCSC_SCARDCONTEXT*)ListDictionary_GetItemValue(g_CardContexts, (void*)hContext); + + if (!pContext) + return NULL; + + return pContext; +} + +static void pcsc_cache_item_free(void* ptr) +{ + PCSC_CACHE_ITEM* data = ptr; + if (data) + free(data->data); + free(data); +} + +static PCSC_SCARDCONTEXT* PCSC_EstablishCardContext(SCARDCONTEXT hContext) +{ + PCSC_SCARDCONTEXT* pContext = NULL; + pContext = (PCSC_SCARDCONTEXT*)calloc(1, sizeof(PCSC_SCARDCONTEXT)); + + if (!pContext) + return NULL; + + pContext->hContext = hContext; + + if (!InitializeCriticalSectionAndSpinCount(&(pContext->lock), 4000)) + goto error_spinlock; + + pContext->cache = HashTable_New(FALSE); + if (!pContext->cache) + goto errors; + if (!HashTable_SetupForStringData(pContext->cache, FALSE)) + goto errors; + { + wObject* obj = HashTable_ValueObject(pContext->cache); + obj->fnObjectFree = pcsc_cache_item_free; + } + + if (!g_CardContexts) + { + g_CardContexts = ListDictionary_New(TRUE); + + if (!g_CardContexts) + goto errors; + } + + if (!ListDictionary_Add(g_CardContexts, (void*)hContext, (void*)pContext)) + goto errors; + + return pContext; +errors: + HashTable_Free(pContext->cache); + DeleteCriticalSection(&(pContext->lock)); +error_spinlock: + free(pContext); + return NULL; +} + +static void PCSC_ReleaseCardContext(SCARDCONTEXT hContext) +{ + PCSC_SCARDCONTEXT* pContext = NULL; + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + { + WLog_ERR(TAG, "PCSC_ReleaseCardContext: null pContext!"); + return; + } + + DeleteCriticalSection(&(pContext->lock)); + HashTable_Free(pContext->cache); + free(pContext); + + if (!g_CardContexts) + return; + + ListDictionary_Remove(g_CardContexts, (void*)hContext); +} + +static BOOL PCSC_LockCardContext(SCARDCONTEXT hContext) +{ + PCSC_SCARDCONTEXT* pContext = NULL; + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + { + WLog_ERR(TAG, "PCSC_LockCardContext: invalid context (%p)", (void*)hContext); + return FALSE; + } + + EnterCriticalSection(&(pContext->lock)); + return TRUE; +} + +static BOOL PCSC_UnlockCardContext(SCARDCONTEXT hContext) +{ + PCSC_SCARDCONTEXT* pContext = NULL; + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + { + WLog_ERR(TAG, "PCSC_UnlockCardContext: invalid context (%p)", (void*)hContext); + return FALSE; + } + + LeaveCriticalSection(&(pContext->lock)); + return TRUE; +} + +static PCSC_SCARDHANDLE* PCSC_GetCardHandleData(SCARDHANDLE hCard) +{ + PCSC_SCARDHANDLE* pCard = NULL; + + if (!g_CardHandles) + return NULL; + + pCard = (PCSC_SCARDHANDLE*)ListDictionary_GetItemValue(g_CardHandles, (void*)hCard); + + if (!pCard) + return NULL; + + return pCard; +} + +static SCARDCONTEXT PCSC_GetCardContextFromHandle(SCARDHANDLE hCard) +{ + PCSC_SCARDHANDLE* pCard = NULL; + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return 0; + + return pCard->hSharedContext; +} + +static BOOL PCSC_WaitForCardAccess(SCARDCONTEXT hContext, SCARDHANDLE hCard, BOOL shared) +{ + BOOL status = TRUE; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + + if (!hCard) + { + /* SCardConnect */ + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + return FALSE; + + if (!pContext->owner) + return TRUE; + + /* wait for card ownership */ + return TRUE; + } + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return FALSE; + + shared = pCard->shared; + hContext = pCard->hSharedContext; + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + return FALSE; + + if (!pContext->owner) + { + /* card is not owned */ + if (!shared) + pContext->owner = hCard; + + return TRUE; + } + + if (pContext->owner == hCard) + { + /* already card owner */ + } + else + { + /* wait for card ownership */ + } + + return status; +} + +static BOOL PCSC_ReleaseCardAccess(SCARDCONTEXT hContext, SCARDHANDLE hCard) +{ + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + + if (!hCard) + { + /* release current owner */ + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + return FALSE; + + hCard = pContext->owner; + + if (!hCard) + return TRUE; + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return FALSE; + + /* release card ownership */ + pContext->owner = 0; + return TRUE; + } + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return FALSE; + + hContext = pCard->hSharedContext; + pContext = PCSC_GetCardContextData(hContext); + + if (!pContext) + return FALSE; + + if (pContext->owner == hCard) + { + /* release card ownership */ + pContext->owner = 0; + } + + return TRUE; +} + +static PCSC_SCARDHANDLE* PCSC_ConnectCardHandle(SCARDCONTEXT hSharedContext, SCARDHANDLE hCard) +{ + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + pContext = PCSC_GetCardContextData(hSharedContext); + + if (!pContext) + { + WLog_ERR(TAG, "PCSC_ConnectCardHandle: null pContext!"); + return NULL; + } + + pCard = (PCSC_SCARDHANDLE*)calloc(1, sizeof(PCSC_SCARDHANDLE)); + + if (!pCard) + return NULL; + + pCard->hSharedContext = hSharedContext; + + if (!g_CardHandles) + { + g_CardHandles = ListDictionary_New(TRUE); + + if (!g_CardHandles) + goto error; + } + + if (!ListDictionary_Add(g_CardHandles, (void*)hCard, (void*)pCard)) + goto error; + + pContext->dwCardHandleCount++; + return pCard; +error: + free(pCard); + return NULL; +} + +static void PCSC_DisconnectCardHandle(SCARDHANDLE hCard) +{ + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return; + + pContext = PCSC_GetCardContextData(pCard->hSharedContext); + free(pCard); + + if (!g_CardHandles) + return; + + ListDictionary_Remove(g_CardHandles, (void*)hCard); + + if (!pContext) + { + WLog_ERR(TAG, "PCSC_DisconnectCardHandle: null pContext!"); + return; + } + + pContext->dwCardHandleCount--; +} + +static BOOL PCSC_AddMemoryBlock(SCARDCONTEXT hContext, void* pvMem) +{ + if (!g_MemoryBlocks) + { + g_MemoryBlocks = ListDictionary_New(TRUE); + + if (!g_MemoryBlocks) + return FALSE; + } + + return ListDictionary_Add(g_MemoryBlocks, pvMem, (void*)hContext); +} + +static void* PCSC_RemoveMemoryBlock(SCARDCONTEXT hContext, void* pvMem) +{ + WINPR_UNUSED(hContext); + + if (!g_MemoryBlocks) + return NULL; + + return ListDictionary_Take(g_MemoryBlocks, pvMem); +} + +/** + * Standard Windows Smart Card API (PCSC) + */ + +static LONG WINAPI PCSC_SCardEstablishContext_Internal(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, + LPSCARDCONTEXT phContext) +{ + WINPR_UNUSED(dwScope); /* SCARD_SCOPE_SYSTEM is the only scope supported by pcsc-lite */ + PCSC_LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardEstablishContext) + return PCSC_SCard_LogError("g_PCSC.pfnSCardEstablishContext"); + + status = + g_PCSC.pfnSCardEstablishContext(SCARD_SCOPE_SYSTEM, pvReserved1, pvReserved2, phContext); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, + LPCVOID pvReserved2, LPSCARDCONTEXT phContext) +{ + LONG status = 0; + + status = PCSC_SCardEstablishContext_Internal(dwScope, pvReserved1, pvReserved2, phContext); + + if (status == SCARD_S_SUCCESS) + PCSC_EstablishCardContext(*phContext); + + return status; +} + +static LONG WINAPI PCSC_SCardReleaseContext_Internal(SCARDCONTEXT hContext) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardReleaseContext) + return PCSC_SCard_LogError("g_PCSC.pfnSCardReleaseContext"); + + if (!hContext) + { + WLog_ERR(TAG, "SCardReleaseContext: null hContext"); + return PCSC_MapErrorCodeToWinSCard(status); + } + + status = g_PCSC.pfnSCardReleaseContext(hContext); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardReleaseContext(SCARDCONTEXT hContext) +{ + LONG status = SCARD_S_SUCCESS; + + status = PCSC_SCardReleaseContext_Internal(hContext); + + if (status != SCARD_S_SUCCESS) + PCSC_ReleaseCardContext(hContext); + + return status; +} + +static LONG WINAPI PCSC_SCardIsValidContext(SCARDCONTEXT hContext) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardIsValidContext) + return PCSC_SCard_LogError("g_PCSC.pfnSCardIsValidContext"); + + status = g_PCSC.pfnSCardIsValidContext(hContext); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardListReaderGroups_Internal(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + BOOL pcchGroupsAlloc = FALSE; + PCSC_DWORD pcsc_cchGroups = 0; + + if (!pcchGroups) + return SCARD_E_INVALID_PARAMETER; + + if (!g_PCSC.pfnSCardListReaderGroups) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaderGroups"); + + if (*pcchGroups == SCARD_AUTOALLOCATE) + pcchGroupsAlloc = TRUE; + + pcsc_cchGroups = pcchGroupsAlloc ? PCSC_SCARD_AUTOALLOCATE : (PCSC_DWORD)*pcchGroups; + + if (pcchGroupsAlloc && !g_SCardAutoAllocate) + { + pcsc_cchGroups = 0; + status = g_PCSC.pfnSCardListReaderGroups(hContext, NULL, &pcsc_cchGroups); + + if (status == SCARD_S_SUCCESS) + { + LPSTR tmp = calloc(1, pcsc_cchGroups); + + if (!tmp) + return SCARD_E_NO_MEMORY; + + status = g_PCSC.pfnSCardListReaderGroups(hContext, tmp, &pcsc_cchGroups); + + if (status != SCARD_S_SUCCESS) + { + free(tmp); + tmp = NULL; + } + else + PCSC_AddMemoryBlock(hContext, tmp); + + *(LPSTR*)mszGroups = tmp; + } + } + else + { + status = g_PCSC.pfnSCardListReaderGroups(hContext, mszGroups, &pcsc_cchGroups); + } + + *pcchGroups = (DWORD)pcsc_cchGroups; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardListReaderGroupsA(SCARDCONTEXT hContext, LPSTR mszGroups, + LPDWORD pcchGroups) +{ + LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardListReaderGroups) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaderGroups"); + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + status = PCSC_SCardListReaderGroups_Internal(hContext, mszGroups, pcchGroups); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardListReaderGroupsW(SCARDCONTEXT hContext, LPWSTR mszGroups, + LPDWORD pcchGroups) +{ + LPSTR mszGroupsA = NULL; + LPSTR* pMszGroupsA = &mszGroupsA; + LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardListReaderGroups) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaderGroups"); + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + status = PCSC_SCardListReaderGroups_Internal(hContext, (LPSTR)&mszGroupsA, pcchGroups); + + if (status == SCARD_S_SUCCESS) + { + size_t size = 0; + WCHAR* str = ConvertMszUtf8NToWCharAlloc(*pMszGroupsA, *pcchGroups, &size); + if (!str) + return SCARD_E_NO_MEMORY; + *(WCHAR**)mszGroups = str; + *pcchGroups = (DWORD)size; + PCSC_AddMemoryBlock(hContext, str); + PCSC_SCardFreeMemory_Internal(hContext, *pMszGroupsA); + } + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardListReaders_Internal(SCARDCONTEXT hContext, LPCSTR mszGroups, + LPSTR mszReaders, LPDWORD pcchReaders) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + BOOL pcchReadersAlloc = FALSE; + PCSC_DWORD pcsc_cchReaders = 0; + if (!pcchReaders) + return SCARD_E_INVALID_PARAMETER; + + if (!g_PCSC.pfnSCardListReaders) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaders"); + + mszGroups = NULL; /* mszGroups is not supported by pcsc-lite */ + + if (*pcchReaders == SCARD_AUTOALLOCATE) + pcchReadersAlloc = TRUE; + + pcsc_cchReaders = pcchReadersAlloc ? PCSC_SCARD_AUTOALLOCATE : (PCSC_DWORD)*pcchReaders; + + if (pcchReadersAlloc && !g_SCardAutoAllocate) + { + pcsc_cchReaders = 0; + status = g_PCSC.pfnSCardListReaders(hContext, mszGroups, NULL, &pcsc_cchReaders); + + if (status == SCARD_S_SUCCESS) + { + char* tmp = calloc(1, pcsc_cchReaders); + + if (!tmp) + return SCARD_E_NO_MEMORY; + + status = g_PCSC.pfnSCardListReaders(hContext, mszGroups, tmp, &pcsc_cchReaders); + + if (status != SCARD_S_SUCCESS) + { + free(tmp); + tmp = NULL; + } + else + PCSC_AddMemoryBlock(hContext, tmp); + + *(char**)mszReaders = tmp; + } + } + else + { + status = g_PCSC.pfnSCardListReaders(hContext, mszGroups, mszReaders, &pcsc_cchReaders); + } + + *pcchReaders = (DWORD)pcsc_cchReaders; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardListReadersA(SCARDCONTEXT hContext, LPCSTR mszGroups, LPSTR mszReaders, + LPDWORD pcchReaders) +{ + BOOL nullCardContext = FALSE; + LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardListReaders) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaders"); + + if (!hContext) + { + status = PCSC_SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); + + if (status != SCARD_S_SUCCESS) + return status; + + nullCardContext = TRUE; + } + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + status = PCSC_SCardListReaders_Internal(hContext, mszGroups, mszReaders, pcchReaders); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + if (nullCardContext) + { + status = PCSC_SCardReleaseContext(hContext); + } + + return status; +} + +static LONG WINAPI PCSC_SCardListReadersW(SCARDCONTEXT hContext, LPCWSTR mszGroups, + LPWSTR mszReaders, LPDWORD pcchReaders) +{ + LPSTR mszGroupsA = NULL; + LPSTR mszReadersA = NULL; + LONG status = SCARD_S_SUCCESS; + BOOL nullCardContext = FALSE; + + if (!g_PCSC.pfnSCardListReaders) + return PCSC_SCard_LogError("g_PCSC.pfnSCardListReaders"); + + if (!hContext) + { + status = PCSC_SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); + + if (status != SCARD_S_SUCCESS) + return status; + + nullCardContext = TRUE; + } + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + mszGroups = NULL; /* mszGroups is not supported by pcsc-lite */ + + if (mszGroups) + { + mszGroupsA = ConvertWCharToUtf8Alloc(mszGroups, NULL); + if (!mszGroups) + return SCARD_E_NO_MEMORY; + } + + union + { + LPSTR* ppc; + LPSTR pc; + } cnv; + cnv.ppc = &mszReadersA; + + status = PCSC_SCardListReaders_Internal(hContext, mszGroupsA, cnv.pc, pcchReaders); + if (status == SCARD_S_SUCCESS) + { + size_t size = 0; + WCHAR* str = ConvertMszUtf8NToWCharAlloc(mszReadersA, *pcchReaders, &size); + PCSC_SCardFreeMemory_Internal(hContext, mszReadersA); + if (!str || (size > UINT32_MAX)) + { + free(mszGroupsA); + return SCARD_E_NO_MEMORY; + } + *(LPWSTR*)mszReaders = str; + *pcchReaders = (DWORD)size; + PCSC_AddMemoryBlock(hContext, str); + } + + free(mszGroupsA); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + if (nullCardContext) + { + status = PCSC_SCardReleaseContext(hContext); + } + + return status; +} + +typedef struct +{ + BYTE atr[64]; + size_t atrLen; + const char* cardName; +} PcscKnownAtr; + +static PcscKnownAtr knownAtrs[] = { + /* Yubico YubiKey 5 NFC (PKI) */ + { { 0x3B, 0xFD, 0x13, 0x00, 0x00, 0x81, 0x31, 0xFE, 0x15, 0x80, 0x73, 0xC0, + 0x21, 0xC0, 0x57, 0x59, 0x75, 0x62, 0x69, 0x4B, 0x65, 0x79, 0x40 }, + 23, + "NIST SP 800-73 [PIV]" }, + /* PIVKey C910 PKI Smart Card (eID) */ + { { 0x3B, 0xFC, 0x18, 0x00, 0x00, 0x81, 0x31, 0x80, 0x45, 0x90, 0x67, + 0x46, 0x4A, 0x00, 0x64, 0x16, 0x06, 0xF2, 0x72, 0x7E, 0x00, 0xE0 }, + 22, + "PIVKey Feitian (E0)" } +}; + +#ifndef ARRAY_LENGTH +#define ARRAY_LENGTH(a) (sizeof(a) / sizeof(a)[0]) +#endif + +static const char* findCardByAtr(LPCBYTE pbAtr) +{ + for (size_t i = 0; i < ARRAY_LENGTH(knownAtrs); i++) + { + if (memcmp(knownAtrs[i].atr, pbAtr, knownAtrs[i].atrLen) == 0) + return knownAtrs[i].cardName; + } + + return NULL; +} + +static LONG WINAPI PCSC_SCardListCardsA(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + CHAR* mszCards, LPDWORD pcchCards) +{ + const char* cardName = NULL; + DWORD outputLen = 1; + CHAR* output = NULL; + BOOL autoAllocate = 0; + + if (!pbAtr || rgquidInterfaces || cguidInterfaceCount) + return SCARD_E_UNSUPPORTED_FEATURE; + + if (!pcchCards) + return SCARD_E_INVALID_PARAMETER; + + autoAllocate = (*pcchCards == SCARD_AUTOALLOCATE); + + cardName = findCardByAtr(pbAtr); + if (cardName) + outputLen += strlen(cardName) + 1; + + *pcchCards = outputLen; + if (autoAllocate) + { + output = malloc(outputLen); + if (!output) + return SCARD_E_NO_MEMORY; + + *((LPSTR*)mszCards) = output; + } + else + { + if (!mszCards) + return SCARD_S_SUCCESS; + + if (*pcchCards < outputLen) + return SCARD_E_INSUFFICIENT_BUFFER; + + output = mszCards; + } + + if (cardName) + { + size_t toCopy = strlen(cardName) + 1; + memcpy(output, cardName, toCopy); + output += toCopy; + } + + *output = '\0'; + + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardListCardsW(SCARDCONTEXT hContext, LPCBYTE pbAtr, + LPCGUID rgquidInterfaces, DWORD cguidInterfaceCount, + WCHAR* mszCards, LPDWORD pcchCards) +{ + const char* cardName = NULL; + DWORD outputLen = 1; + WCHAR* output = NULL; + BOOL autoAllocate = 0; + + if (!pbAtr || rgquidInterfaces || cguidInterfaceCount) + return SCARD_E_UNSUPPORTED_FEATURE; + + if (!pcchCards) + return SCARD_E_INVALID_PARAMETER; + + autoAllocate = (*pcchCards == SCARD_AUTOALLOCATE); + + cardName = findCardByAtr(pbAtr); + if (cardName) + outputLen += strlen(cardName) + 1; + + *pcchCards = outputLen; + if (autoAllocate) + { + output = calloc(outputLen, sizeof(WCHAR)); + if (!output) + return SCARD_E_NO_MEMORY; + + *((LPWSTR*)mszCards) = output; + } + else + { + if (!mszCards) + return SCARD_S_SUCCESS; + + if (*pcchCards < outputLen) + return SCARD_E_INSUFFICIENT_BUFFER; + + output = mszCards; + } + + if (cardName) + { + size_t toCopy = strlen(cardName) + 1; + if (ConvertUtf8ToWChar(cardName, output, toCopy) < 0) + return SCARD_F_INTERNAL_ERROR; + output += toCopy; + } + + *output = 0; + + return SCARD_S_SUCCESS; +} + +static LONG WINAPI +PCSC_SCardListInterfacesA(SCARDCONTEXT hContext, LPCSTR szCard, LPGUID pguidInterfaces, + LPDWORD pcguidInterfaces /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCard); + WINPR_UNUSED(pguidInterfaces); + WINPR_UNUSED(pcguidInterfaces); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI +PCSC_SCardListInterfacesW(SCARDCONTEXT hContext, LPCWSTR szCard, LPGUID pguidInterfaces, + LPDWORD pcguidInterfaces /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCard); + WINPR_UNUSED(pguidInterfaces); + WINPR_UNUSED(pcguidInterfaces); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetProviderIdA(SCARDCONTEXT hContext, LPCSTR szCard, + LPGUID pguidProviderId) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCard); + WINPR_UNUSED(pguidProviderId); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetProviderIdW(SCARDCONTEXT hContext, LPCWSTR szCard, + LPGUID pguidProviderId) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCard); + WINPR_UNUSED(pguidProviderId); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetCardTypeProviderNameA( + SCARDCONTEXT hContext, LPCSTR szCardName, DWORD dwProviderId, + CHAR* szProvider /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchProvider /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(dwProviderId); + WINPR_UNUSED(szProvider); + WINPR_UNUSED(pcchProvider); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetCardTypeProviderNameW( + SCARDCONTEXT hContext, LPCWSTR szCardName, DWORD dwProviderId, + WCHAR* szProvider /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchProvider /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(dwProviderId); + WINPR_UNUSED(szProvider); + WINPR_UNUSED(pcchProvider); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetReaderGroupA(SCARDCONTEXT hContext, LPCSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetReaderGroupW(SCARDCONTEXT hContext, LPCWSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szDeviceName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szDeviceName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szDeviceName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szDeviceName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetReaderA(SCARDCONTEXT hContext, LPCSTR szReaderName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetReaderW(SCARDCONTEXT hContext, LPCWSTR szReaderName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardAddReaderToGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardAddReaderToGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardRemoveReaderFromGroupA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPCSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardRemoveReaderFromGroupW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPCWSTR szGroupName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szGroupName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(pguidPrimaryProvider); + WINPR_UNUSED(rgguidInterfaces); + WINPR_UNUSED(dwInterfaceCount); + WINPR_UNUSED(pbAtr); + WINPR_UNUSED(pbAtrMask); + WINPR_UNUSED(cbAtrLen); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardIntroduceCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName, + LPCGUID pguidPrimaryProvider, + LPCGUID rgguidInterfaces, DWORD dwInterfaceCount, + LPCBYTE pbAtr, LPCBYTE pbAtrMask, DWORD cbAtrLen) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(pguidPrimaryProvider); + WINPR_UNUSED(rgguidInterfaces); + WINPR_UNUSED(dwInterfaceCount); + WINPR_UNUSED(pbAtr); + WINPR_UNUSED(pbAtrMask); + WINPR_UNUSED(cbAtrLen); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardSetCardTypeProviderNameA(SCARDCONTEXT hContext, LPCSTR szCardName, + DWORD dwProviderId, LPCSTR szProvider) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(dwProviderId); + WINPR_UNUSED(szProvider); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardSetCardTypeProviderNameW(SCARDCONTEXT hContext, LPCWSTR szCardName, + DWORD dwProviderId, LPCWSTR szProvider) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + WINPR_UNUSED(dwProviderId); + WINPR_UNUSED(szProvider); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetCardTypeA(SCARDCONTEXT hContext, LPCSTR szCardName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardForgetCardTypeW(SCARDCONTEXT hContext, LPCWSTR szCardName) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szCardName); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardFreeMemory_Internal(SCARDCONTEXT hContext, LPVOID pvMem) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + + if (PCSC_RemoveMemoryBlock(hContext, pvMem)) + { + free((void*)pvMem); + status = SCARD_S_SUCCESS; + } + else + { + if (g_PCSC.pfnSCardFreeMemory) + { + status = g_PCSC.pfnSCardFreeMemory(hContext, pvMem); + } + } + + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardFreeMemory(SCARDCONTEXT hContext, LPVOID pvMem) +{ + LONG status = SCARD_S_SUCCESS; + + if (hContext) + { + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + } + + status = PCSC_SCardFreeMemory_Internal(hContext, pvMem); + + if (hContext) + { + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + } + + return status; +} + +static HANDLE WINAPI PCSC_SCardAccessStartedEvent(void) +{ + LONG status = 0; + SCARDCONTEXT hContext = 0; + + status = PCSC_SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); + + if (status != SCARD_S_SUCCESS) + return NULL; + + status = PCSC_SCardReleaseContext(hContext); + + if (status != SCARD_S_SUCCESS) + return NULL; + + if (!g_StartedEvent) + { + if (!(g_StartedEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + return NULL; + + if (!SetEvent(g_StartedEvent)) + { + (void)CloseHandle(g_StartedEvent); + return NULL; + } + } + + g_StartedEventRefCount++; + return g_StartedEvent; +} + +static void WINAPI PCSC_SCardReleaseStartedEvent(void) +{ + g_StartedEventRefCount--; + + if (g_StartedEventRefCount == 0) + { + if (g_StartedEvent) + { + (void)CloseHandle(g_StartedEvent); + g_StartedEvent = NULL; + } + } +} + +static LONG WINAPI PCSC_SCardLocateCardsA(SCARDCONTEXT hContext, LPCSTR mszCards, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(mszCards); + WINPR_UNUSED(rgReaderStates); + WINPR_UNUSED(cReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardLocateCardsW(SCARDCONTEXT hContext, LPCWSTR mszCards, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(mszCards); + WINPR_UNUSED(rgReaderStates); + WINPR_UNUSED(cReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardLocateCardsByATRA(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(rgAtrMasks); + WINPR_UNUSED(cAtrs); + WINPR_UNUSED(rgReaderStates); + WINPR_UNUSED(cReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardLocateCardsByATRW(SCARDCONTEXT hContext, LPSCARD_ATRMASK rgAtrMasks, + DWORD cAtrs, LPSCARD_READERSTATEW rgReaderStates, + DWORD cReaders) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(rgAtrMasks); + WINPR_UNUSED(cAtrs); + WINPR_UNUSED(rgReaderStates); + WINPR_UNUSED(cReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetStatusChange_Internal(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, + DWORD cReaders) +{ + INT64* map = NULL; + PCSC_DWORD cMappedReaders = 0; + PCSC_SCARD_READERSTATE* states = NULL; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_DWORD pcsc_dwTimeout = (PCSC_DWORD)dwTimeout; + PCSC_DWORD pcsc_cReaders = (PCSC_DWORD)cReaders; + + if (!g_PCSC.pfnSCardGetStatusChange) + return PCSC_SCard_LogError("g_PCSC.pfnSCardGetStatusChange"); + + if (!cReaders) + return SCARD_S_SUCCESS; + + /* pcsc-lite interprets value 0 as INFINITE, work around the problem by using value 1 */ + pcsc_dwTimeout = pcsc_dwTimeout ? pcsc_dwTimeout : 1; + /** + * Apple's SmartCard Services (not vanilla pcsc-lite) appears to have trouble with the + * "\\\\?PnP?\\Notification" reader name. I am always getting EXC_BAD_ACCESS with it. + * + * The SmartCard Services tarballs can be found here: + * http://opensource.apple.com/tarballs/SmartCardServices/ + * + * The "\\\\?PnP?\\Notification" string cannot be found anywhere in the sources, + * while this string is present in the vanilla pcsc-lite sources. + * + * To work around this apparent lack of "\\\\?PnP?\\Notification" support, + * we have to filter rgReaderStates to exclude the special PnP reader name. + */ + map = (INT64*)calloc(pcsc_cReaders, sizeof(INT64)); + + if (!map) + return SCARD_E_NO_MEMORY; + + states = (PCSC_SCARD_READERSTATE*)calloc(pcsc_cReaders, sizeof(PCSC_SCARD_READERSTATE)); + + if (!states) + { + free(map); + return SCARD_E_NO_MEMORY; + } + + PCSC_DWORD j = 0; + for (PCSC_DWORD i = 0; i < pcsc_cReaders; i++) + { + if (!g_PnP_Notification) + { + LPSCARD_READERSTATEA reader = &rgReaderStates[i]; + if (!reader->szReader) + continue; + if (0 == _stricmp(reader->szReader, SMARTCARD_PNP_NOTIFICATION_A)) + { + map[i] = -1; /* unmapped */ + continue; + } + } + + map[i] = (INT64)j; + states[j].szReader = rgReaderStates[i].szReader; + states[j].dwCurrentState = rgReaderStates[i].dwCurrentState; + states[j].pvUserData = rgReaderStates[i].pvUserData; + states[j].dwEventState = rgReaderStates[i].dwEventState; + states[j].cbAtr = rgReaderStates[i].cbAtr; + CopyMemory(&(states[j].rgbAtr), &(rgReaderStates[i].rgbAtr), PCSC_MAX_ATR_SIZE); + j++; + } + + cMappedReaders = j; + + if (cMappedReaders > 0) + { + status = g_PCSC.pfnSCardGetStatusChange(hContext, pcsc_dwTimeout, states, cMappedReaders); + } + else + { + status = SCARD_S_SUCCESS; + } + + for (PCSC_DWORD i = 0; i < pcsc_cReaders; i++) + { + if (map[i] < 0) + continue; /* unmapped */ + + PCSC_DWORD k = (PCSC_DWORD)map[i]; + rgReaderStates[i].dwCurrentState = (DWORD)states[k].dwCurrentState; + rgReaderStates[i].cbAtr = (DWORD)states[k].cbAtr; + CopyMemory(&(rgReaderStates[i].rgbAtr), &(states[k].rgbAtr), PCSC_MAX_ATR_SIZE); + rgReaderStates[i].dwEventState = (DWORD)states[k].dwEventState; + } + + free(map); + free(states); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardGetStatusChangeA(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEA rgReaderStates, DWORD cReaders) +{ + LONG status = SCARD_S_SUCCESS; + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + status = PCSC_SCardGetStatusChange_Internal(hContext, dwTimeout, rgReaderStates, cReaders); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardGetStatusChangeW(SCARDCONTEXT hContext, DWORD dwTimeout, + LPSCARD_READERSTATEW rgReaderStates, DWORD cReaders) +{ + LPSCARD_READERSTATEA states = NULL; + LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardGetStatusChange) + return PCSC_SCard_LogError("g_PCSC.pfnSCardGetStatusChange"); + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + states = (LPSCARD_READERSTATEA)calloc(cReaders, sizeof(SCARD_READERSTATEA)); + + if (!states) + { + (void)PCSC_UnlockCardContext(hContext); + return SCARD_E_NO_MEMORY; + } + + for (DWORD index = 0; index < cReaders; index++) + { + const LPSCARD_READERSTATEW curReader = &rgReaderStates[index]; + LPSCARD_READERSTATEA cur = &states[index]; + + cur->szReader = ConvertWCharToUtf8Alloc(curReader->szReader, NULL); + cur->pvUserData = curReader->pvUserData; + cur->dwCurrentState = curReader->dwCurrentState; + cur->dwEventState = curReader->dwEventState; + cur->cbAtr = curReader->cbAtr; + CopyMemory(&(cur->rgbAtr), &(curReader->rgbAtr), ARRAYSIZE(cur->rgbAtr)); + } + + status = PCSC_SCardGetStatusChange_Internal(hContext, dwTimeout, states, cReaders); + + for (DWORD index = 0; index < cReaders; index++) + { + free((void*)states[index].szReader); + rgReaderStates[index].pvUserData = states[index].pvUserData; + rgReaderStates[index].dwCurrentState = states[index].dwCurrentState; + rgReaderStates[index].dwEventState = states[index].dwEventState; + rgReaderStates[index].cbAtr = states[index].cbAtr; + CopyMemory(&(rgReaderStates[index].rgbAtr), &(states[index].rgbAtr), 36); + } + + free(states); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardCancel(SCARDCONTEXT hContext) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + + if (!g_PCSC.pfnSCardCancel) + return PCSC_SCard_LogError("g_PCSC.pfnSCardCancel"); + + status = g_PCSC.pfnSCardCancel(hContext); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardConnect_Internal(SCARDCONTEXT hContext, LPCSTR szReader, + DWORD dwShareMode, DWORD dwPreferredProtocols, + LPSCARDHANDLE phCard, LPDWORD pdwActiveProtocol) +{ + BOOL shared = 0; + const char* szReaderPCSC = NULL; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_DWORD pcsc_dwShareMode = (PCSC_DWORD)dwShareMode; + PCSC_DWORD pcsc_dwPreferredProtocols = 0; + PCSC_DWORD pcsc_dwActiveProtocol = 0; + + if (!g_PCSC.pfnSCardConnect) + return PCSC_SCard_LogError("g_PCSC.pfnSCardConnect"); + + shared = (dwShareMode == SCARD_SHARE_DIRECT) ? TRUE : FALSE; + PCSC_WaitForCardAccess(hContext, 0, shared); + szReaderPCSC = szReader; + + /** + * As stated here : + * https://pcsclite.alioth.debian.org/api/group__API.html#ga4e515829752e0a8dbc4d630696a8d6a5 + * SCARD_PROTOCOL_UNDEFINED is valid for dwPreferredProtocols (only) if dwShareMode == + * SCARD_SHARE_DIRECT and allows to send control commands to the reader (with SCardControl()) + * even if a card is not present in the reader + */ + if (pcsc_dwShareMode == SCARD_SHARE_DIRECT && dwPreferredProtocols == SCARD_PROTOCOL_UNDEFINED) + pcsc_dwPreferredProtocols = SCARD_PROTOCOL_UNDEFINED; + else + pcsc_dwPreferredProtocols = + (PCSC_DWORD)PCSC_ConvertProtocolsFromWinSCard(dwPreferredProtocols); + + status = g_PCSC.pfnSCardConnect(hContext, szReaderPCSC, pcsc_dwShareMode, + pcsc_dwPreferredProtocols, phCard, &pcsc_dwActiveProtocol); + + if (status == SCARD_S_SUCCESS) + { + pCard = PCSC_ConnectCardHandle(hContext, *phCard); + *pdwActiveProtocol = PCSC_ConvertProtocolsToWinSCard((DWORD)pcsc_dwActiveProtocol); + pCard->shared = shared; + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): ListDictionary_Add takes ownership of pCard + PCSC_WaitForCardAccess(hContext, pCard->hSharedContext, shared); + } + + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardConnectA(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + LONG status = SCARD_S_SUCCESS; + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + status = PCSC_SCardConnect_Internal(hContext, szReader, dwShareMode, dwPreferredProtocols, + phCard, pdwActiveProtocol); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardConnectW(SCARDCONTEXT hContext, LPCWSTR szReader, DWORD dwShareMode, + DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, + LPDWORD pdwActiveProtocol) +{ + LPSTR szReaderA = NULL; + LONG status = SCARD_S_SUCCESS; + + if (!PCSC_LockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + if (szReader) + { + szReaderA = ConvertWCharToUtf8Alloc(szReader, NULL); + if (!szReaderA) + return SCARD_E_INSUFFICIENT_BUFFER; + } + + status = PCSC_SCardConnect_Internal(hContext, szReaderA, dwShareMode, dwPreferredProtocols, + phCard, pdwActiveProtocol); + free(szReaderA); + + if (!PCSC_UnlockCardContext(hContext)) + return SCARD_E_INVALID_HANDLE; + + return status; +} + +static LONG WINAPI PCSC_SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode, + DWORD dwPreferredProtocols, DWORD dwInitialization, + LPDWORD pdwActiveProtocol) +{ + BOOL shared = 0; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_DWORD pcsc_dwShareMode = (PCSC_DWORD)dwShareMode; + PCSC_DWORD pcsc_dwPreferredProtocols = 0; + PCSC_DWORD pcsc_dwInitialization = (PCSC_DWORD)dwInitialization; + PCSC_DWORD pcsc_dwActiveProtocol = 0; + + if (!g_PCSC.pfnSCardReconnect) + return PCSC_SCard_LogError("g_PCSC.pfnSCardReconnect"); + + shared = (dwShareMode == SCARD_SHARE_DIRECT) ? TRUE : FALSE; + PCSC_WaitForCardAccess(0, hCard, shared); + pcsc_dwPreferredProtocols = (PCSC_DWORD)PCSC_ConvertProtocolsFromWinSCard(dwPreferredProtocols); + status = g_PCSC.pfnSCardReconnect(hCard, pcsc_dwShareMode, pcsc_dwPreferredProtocols, + pcsc_dwInitialization, &pcsc_dwActiveProtocol); + + *pdwActiveProtocol = PCSC_ConvertProtocolsToWinSCard((DWORD)pcsc_dwActiveProtocol); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_DWORD pcsc_dwDisposition = (PCSC_DWORD)dwDisposition; + + if (!g_PCSC.pfnSCardDisconnect) + return PCSC_SCard_LogError("g_PCSC.pfnSCardDisconnect"); + + status = g_PCSC.pfnSCardDisconnect(hCard, pcsc_dwDisposition); + + if (status == SCARD_S_SUCCESS) + { + PCSC_DisconnectCardHandle(hCard); + } + + PCSC_ReleaseCardAccess(0, hCard); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardBeginTransaction(SCARDHANDLE hCard) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + + if (!g_PCSC.pfnSCardBeginTransaction) + return PCSC_SCard_LogError("g_PCSC.pfnSCardBeginTransaction"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_HANDLE; + + pContext = PCSC_GetCardContextData(pCard->hSharedContext); + + if (!pContext) + return SCARD_E_INVALID_HANDLE; + + if (pContext->isTransactionLocked) + return SCARD_S_SUCCESS; /* disable nested transactions */ + + status = g_PCSC.pfnSCardBeginTransaction(hCard); + + pContext->isTransactionLocked = TRUE; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardEndTransaction(SCARDHANDLE hCard, DWORD dwDisposition) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_SCARDCONTEXT* pContext = NULL; + PCSC_DWORD pcsc_dwDisposition = (PCSC_DWORD)dwDisposition; + + if (!g_PCSC.pfnSCardEndTransaction) + return PCSC_SCard_LogError("g_PCSC.pfnSCardEndTransaction"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_HANDLE; + + pContext = PCSC_GetCardContextData(pCard->hSharedContext); + + if (!pContext) + return SCARD_E_INVALID_HANDLE; + + PCSC_ReleaseCardAccess(0, hCard); + + if (!pContext->isTransactionLocked) + return SCARD_S_SUCCESS; /* disable nested transactions */ + + status = g_PCSC.pfnSCardEndTransaction(hCard, pcsc_dwDisposition); + + pContext->isTransactionLocked = FALSE; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardCancelTransaction(SCARDHANDLE hCard) +{ + WINPR_UNUSED(hCard); + return SCARD_S_SUCCESS; +} + +/* + * PCSC returns a string but Windows SCardStatus requires the return to be a multi string. + * Therefore extra length checks and additional buffer allocation is required + */ +static LONG WINAPI PCSC_SCardStatus_Internal(SCARDHANDLE hCard, LPSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, + LPDWORD pdwProtocol, LPBYTE pbAtr, LPDWORD pcbAtrLen, + BOOL unicode) +{ + PCSC_SCARDHANDLE* pCard = NULL; + SCARDCONTEXT hContext = 0; + PCSC_LONG status = 0; + PCSC_DWORD pcsc_cchReaderLen = 0; + PCSC_DWORD pcsc_cbAtrLen = 0; + PCSC_DWORD pcsc_dwState = 0; + PCSC_DWORD pcsc_dwProtocol = 0; + BOOL allocateReader = FALSE; + BOOL allocateAtr = FALSE; + LPSTR readerNames = mszReaderNames; + LPBYTE atr = pbAtr; + LPSTR tReader = NULL; + LPBYTE tATR = NULL; + + if (!g_PCSC.pfnSCardStatus) + return PCSC_SCard_LogError("g_PCSC.pfnSCardStatus"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + hContext = PCSC_GetCardContextFromHandle(hCard); + + if (!hContext) + return SCARD_E_INVALID_VALUE; + + status = + g_PCSC.pfnSCardStatus(hCard, NULL, &pcsc_cchReaderLen, NULL, NULL, NULL, &pcsc_cbAtrLen); + + if (status != STATUS_SUCCESS) + return PCSC_MapErrorCodeToWinSCard(status); + + pcsc_cchReaderLen++; + + if (unicode) + pcsc_cchReaderLen *= 2; + + if (pcchReaderLen) + { + if (*pcchReaderLen == SCARD_AUTOALLOCATE) + allocateReader = TRUE; + else if (mszReaderNames && (*pcchReaderLen < pcsc_cchReaderLen)) + return SCARD_E_INSUFFICIENT_BUFFER; + else + pcsc_cchReaderLen = *pcchReaderLen; + } + + if (pcbAtrLen) + { + if (*pcbAtrLen == SCARD_AUTOALLOCATE) + allocateAtr = TRUE; + else if (pbAtr && (*pcbAtrLen < pcsc_cbAtrLen)) + return SCARD_E_INSUFFICIENT_BUFFER; + else + pcsc_cbAtrLen = *pcbAtrLen; + } + + if (allocateReader && pcsc_cchReaderLen > 0 && mszReaderNames) + { +#ifdef __MACOSX__ + + /** + * Workaround for SCardStatus Bug in MAC OS X Yosemite + */ + if (OSXVersion == 0x10100000) + pcsc_cchReaderLen++; + +#endif + tReader = calloc(sizeof(CHAR), pcsc_cchReaderLen + 1); + + if (!tReader) + { + status = ERROR_NOT_ENOUGH_MEMORY; + goto out_fail; + } + + readerNames = tReader; + } + + if (allocateAtr && pcsc_cbAtrLen > 0 && pbAtr) + { + tATR = calloc(1, pcsc_cbAtrLen); + + if (!tATR) + { + status = ERROR_NOT_ENOUGH_MEMORY; + goto out_fail; + } + + atr = tATR; + } + + status = g_PCSC.pfnSCardStatus(hCard, readerNames, &pcsc_cchReaderLen, &pcsc_dwState, + &pcsc_dwProtocol, atr, &pcsc_cbAtrLen); + + if (status != STATUS_SUCCESS) + goto out_fail; + + if (tATR) + { + PCSC_AddMemoryBlock(hContext, tATR); + *(BYTE**)pbAtr = tATR; + } + + if (tReader) + { + if (unicode) + { + size_t size = 0; + WCHAR* tmp = ConvertMszUtf8NToWCharAlloc(tReader, pcsc_cchReaderLen + 1, &size); + + if (tmp == NULL) + { + status = ERROR_NOT_ENOUGH_MEMORY; + goto out_fail; + } + + free(tReader); + + PCSC_AddMemoryBlock(hContext, tmp); + *(WCHAR**)mszReaderNames = tmp; + } + else + { + tReader[pcsc_cchReaderLen - 1] = '\0'; + PCSC_AddMemoryBlock(hContext, tReader); + *(char**)mszReaderNames = tReader; + } + } + + pcsc_dwState &= 0xFFFF; + + if (pdwState) + *pdwState = PCSC_ConvertCardStateToWinSCard((DWORD)pcsc_dwState, status); + + if (pdwProtocol) + *pdwProtocol = PCSC_ConvertProtocolsToWinSCard((DWORD)pcsc_dwProtocol); + + if (pcbAtrLen) + *pcbAtrLen = (DWORD)pcsc_cbAtrLen; + + if (pcchReaderLen) + { + WINPR_ASSERT(pcsc_cchReaderLen < UINT32_MAX); + *pcchReaderLen = (DWORD)pcsc_cchReaderLen + 1u; + } + + return (LONG)status; +out_fail: + free(tReader); + free(tATR); + return (LONG)status; +} + +static LONG WINAPI PCSC_SCardState(SCARDHANDLE hCard, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + DWORD cchReaderLen = 0; + SCARDCONTEXT hContext = 0; + LPSTR mszReaderNames = NULL; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + DWORD pcsc_dwState = 0; + DWORD pcsc_dwProtocol = 0; + DWORD pcsc_cbAtrLen = 0; + + if (pcbAtrLen) + pcsc_cbAtrLen = (DWORD)*pcbAtrLen; + + if (!g_PCSC.pfnSCardStatus) + return PCSC_SCard_LogError("g_PCSC.pfnSCardStatus"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + hContext = PCSC_GetCardContextFromHandle(hCard); + + if (!hContext) + return SCARD_E_INVALID_VALUE; + + cchReaderLen = SCARD_AUTOALLOCATE; + status = PCSC_SCardStatus_Internal(hCard, (LPSTR)&mszReaderNames, &cchReaderLen, &pcsc_dwState, + &pcsc_dwProtocol, pbAtr, &pcsc_cbAtrLen, FALSE); + + if (mszReaderNames) + PCSC_SCardFreeMemory_Internal(hContext, mszReaderNames); + + *pdwState = pcsc_dwState; + *pdwProtocol = PCSC_ConvertProtocolsToWinSCard(pcsc_dwProtocol); + if (pcbAtrLen) + *pcbAtrLen = pcsc_cbAtrLen; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardStatusA(SCARDHANDLE hCard, LPSTR mszReaderNames, LPDWORD pcchReaderLen, + LPDWORD pdwState, LPDWORD pdwProtocol, LPBYTE pbAtr, + LPDWORD pcbAtrLen) +{ + + return PCSC_SCardStatus_Internal(hCard, mszReaderNames, pcchReaderLen, pdwState, pdwProtocol, + pbAtr, pcbAtrLen, FALSE); +} + +static LONG WINAPI PCSC_SCardStatusW(SCARDHANDLE hCard, LPWSTR mszReaderNames, + LPDWORD pcchReaderLen, LPDWORD pdwState, LPDWORD pdwProtocol, + LPBYTE pbAtr, LPDWORD pcbAtrLen) +{ + + return PCSC_SCardStatus_Internal(hCard, (LPSTR)mszReaderNames, pcchReaderLen, pdwState, + pdwProtocol, pbAtr, pcbAtrLen, TRUE); +} + +static LONG WINAPI PCSC_SCardTransmit(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, + LPCBYTE pbSendBuffer, DWORD cbSendLength, + LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, + LPDWORD pcbRecvLength) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_DWORD cbExtraBytes = 0; + BYTE* pbExtraBytes = NULL; + BYTE* pcsc_pbExtraBytes = NULL; + PCSC_DWORD pcsc_cbSendLength = (PCSC_DWORD)cbSendLength; + PCSC_DWORD pcsc_cbRecvLength = 0; + union + { + const PCSC_SCARD_IO_REQUEST* pcs; + PCSC_SCARD_IO_REQUEST* ps; + LPSCARD_IO_REQUEST lps; + LPCSCARD_IO_REQUEST lpcs; + BYTE* pb; + } sendPci, recvPci, inRecvPci, inSendPci; + + sendPci.ps = NULL; + recvPci.ps = NULL; + inRecvPci.lps = pioRecvPci; + inSendPci.lpcs = pioSendPci; + + if (!g_PCSC.pfnSCardTransmit) + return PCSC_SCard_LogError("g_PCSC.pfnSCardTransmit"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + + if (!pcbRecvLength) + return SCARD_E_INVALID_PARAMETER; + + if (*pcbRecvLength == SCARD_AUTOALLOCATE) + return SCARD_E_INVALID_PARAMETER; + + pcsc_cbRecvLength = (PCSC_DWORD)*pcbRecvLength; + + if (!inSendPci.lpcs) + { + PCSC_DWORD dwState = 0; + PCSC_DWORD cbAtrLen = 0; + PCSC_DWORD dwProtocol = 0; + PCSC_DWORD cchReaderLen = 0; + /** + * pcsc-lite cannot have a null pioSendPci parameter, unlike WinSCard. + * Query the current protocol and use default SCARD_IO_REQUEST for it. + */ + status = g_PCSC.pfnSCardStatus(hCard, NULL, &cchReaderLen, &dwState, &dwProtocol, NULL, + &cbAtrLen); + + if (status == SCARD_S_SUCCESS) + { + if (dwProtocol == SCARD_PROTOCOL_T0) + sendPci.pcs = PCSC_SCARD_PCI_T0; + else if (dwProtocol == SCARD_PROTOCOL_T1) + sendPci.pcs = PCSC_SCARD_PCI_T1; + else if (dwProtocol == PCSC_SCARD_PROTOCOL_RAW) + sendPci.pcs = PCSC_SCARD_PCI_RAW; + } + } + else + { + cbExtraBytes = inSendPci.lpcs->cbPciLength - sizeof(SCARD_IO_REQUEST); + sendPci.ps = (PCSC_SCARD_IO_REQUEST*)malloc(sizeof(PCSC_SCARD_IO_REQUEST) + cbExtraBytes); + + if (!sendPci.ps) + return SCARD_E_NO_MEMORY; + + sendPci.ps->dwProtocol = (PCSC_DWORD)inSendPci.lpcs->dwProtocol; + sendPci.ps->cbPciLength = sizeof(PCSC_SCARD_IO_REQUEST) + cbExtraBytes; + pbExtraBytes = &(inSendPci.pb)[sizeof(SCARD_IO_REQUEST)]; + pcsc_pbExtraBytes = &(sendPci.pb)[sizeof(PCSC_SCARD_IO_REQUEST)]; + CopyMemory(pcsc_pbExtraBytes, pbExtraBytes, cbExtraBytes); + } + + if (inRecvPci.lps) + { + cbExtraBytes = inRecvPci.lps->cbPciLength - sizeof(SCARD_IO_REQUEST); + recvPci.ps = (PCSC_SCARD_IO_REQUEST*)malloc(sizeof(PCSC_SCARD_IO_REQUEST) + cbExtraBytes); + + if (!recvPci.ps) + { + if (inSendPci.lpcs) + free(sendPci.ps); + + return SCARD_E_NO_MEMORY; + } + + recvPci.ps->dwProtocol = (PCSC_DWORD)inRecvPci.lps->dwProtocol; + recvPci.ps->cbPciLength = sizeof(PCSC_SCARD_IO_REQUEST) + cbExtraBytes; + pbExtraBytes = &(inRecvPci.pb)[sizeof(SCARD_IO_REQUEST)]; + pcsc_pbExtraBytes = &(recvPci.pb)[sizeof(PCSC_SCARD_IO_REQUEST)]; + CopyMemory(pcsc_pbExtraBytes, pbExtraBytes, cbExtraBytes); + } + + status = g_PCSC.pfnSCardTransmit(hCard, sendPci.ps, pbSendBuffer, pcsc_cbSendLength, recvPci.ps, + pbRecvBuffer, &pcsc_cbRecvLength); + + *pcbRecvLength = (DWORD)pcsc_cbRecvLength; + + if (inSendPci.lpcs) + free(sendPci.ps); /* pcsc_pioSendPci is dynamically allocated only when pioSendPci is + non null */ + + if (inRecvPci.lps) + { + cbExtraBytes = inRecvPci.lps->cbPciLength - sizeof(SCARD_IO_REQUEST); + pbExtraBytes = &(inRecvPci.pb)[sizeof(SCARD_IO_REQUEST)]; + pcsc_pbExtraBytes = &(recvPci.pb)[sizeof(PCSC_SCARD_IO_REQUEST)]; + CopyMemory(pbExtraBytes, pcsc_pbExtraBytes, cbExtraBytes); /* copy extra bytes */ + free(recvPci.ps); /* pcsc_pioRecvPci is dynamically allocated only when pioRecvPci is + non null */ + } + + return PCSC_MapErrorCodeToWinSCard(status); +} + +// NOLINTNEXTLINE(readability-non-const-parameter) +static LONG WINAPI PCSC_SCardGetTransmitCount(SCARDHANDLE hCard, LPDWORD pcTransmitCount) +{ + WINPR_UNUSED(pcTransmitCount); + PCSC_SCARDHANDLE* pCard = NULL; + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardControl(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID lpInBuffer, + DWORD cbInBufferSize, LPVOID lpOutBuffer, + DWORD cbOutBufferSize, LPDWORD lpBytesReturned) +{ + DWORD IoCtlFunction = 0; + DWORD IoCtlDeviceType = 0; + BOOL getFeatureRequest = FALSE; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_DWORD pcsc_dwControlCode = 0; + PCSC_DWORD pcsc_cbInBufferSize = (PCSC_DWORD)cbInBufferSize; + PCSC_DWORD pcsc_cbOutBufferSize = (PCSC_DWORD)cbOutBufferSize; + PCSC_DWORD pcsc_BytesReturned = 0; + + if (!g_PCSC.pfnSCardControl) + return PCSC_SCard_LogError("g_PCSC.pfnSCardControl"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + /** + * PCSCv2 Part 10: + * http://www.pcscworkgroup.com/specifications/files/pcsc10_v2.02.09.pdf + * + * Smart Card Driver IOCTLs: + * http://msdn.microsoft.com/en-us/library/windows/hardware/ff548988/ + * + * Converting Windows Feature Request IOCTL code to the pcsc-lite control code: + * http://musclecard.996296.n3.nabble.com/Converting-Windows-Feature-Request-IOCTL-code-to-the-pcsc-lite-control-code-td4906.html + */ + IoCtlFunction = FUNCTION_FROM_CTL_CODE(dwControlCode); + IoCtlDeviceType = DEVICE_TYPE_FROM_CTL_CODE(dwControlCode); + + if (dwControlCode == IOCTL_SMARTCARD_GET_FEATURE_REQUEST) + getFeatureRequest = TRUE; + + if (IoCtlDeviceType == FILE_DEVICE_SMARTCARD) + dwControlCode = PCSC_SCARD_CTL_CODE(IoCtlFunction); + + pcsc_dwControlCode = (PCSC_DWORD)dwControlCode; + status = g_PCSC.pfnSCardControl(hCard, pcsc_dwControlCode, lpInBuffer, pcsc_cbInBufferSize, + lpOutBuffer, pcsc_cbOutBufferSize, &pcsc_BytesReturned); + + *lpBytesReturned = (DWORD)pcsc_BytesReturned; + + if (getFeatureRequest) + { + UINT32 count = 0; + PCSC_TLV_STRUCTURE* tlv = (PCSC_TLV_STRUCTURE*)lpOutBuffer; + + if ((*lpBytesReturned % sizeof(PCSC_TLV_STRUCTURE)) != 0) + return SCARD_E_UNEXPECTED; + + count = *lpBytesReturned / sizeof(PCSC_TLV_STRUCTURE); + + for (DWORD index = 0; index < count; index++) + { + if (tlv[index].length != 4) + return SCARD_E_UNEXPECTED; + } + } + + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardGetAttrib_Internal(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen) +{ + SCARDCONTEXT hContext = 0; + BOOL pcbAttrLenAlloc = FALSE; + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_DWORD pcsc_dwAttrId = (PCSC_DWORD)dwAttrId; + PCSC_DWORD pcsc_cbAttrLen = 0; + + if (!g_PCSC.pfnSCardGetAttrib) + return PCSC_SCard_LogError("g_PCSC.pfnSCardGetAttrib"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + hContext = PCSC_GetCardContextFromHandle(hCard); + + if (!hContext) + return SCARD_E_INVALID_HANDLE; + + if (!pcbAttrLen) + return SCARD_E_INVALID_PARAMETER; + + if (*pcbAttrLen == SCARD_AUTOALLOCATE) + { + if (!pbAttr) + return SCARD_E_INVALID_PARAMETER; + pcbAttrLenAlloc = TRUE; + } + + pcsc_cbAttrLen = pcbAttrLenAlloc ? PCSC_SCARD_AUTOALLOCATE : (PCSC_DWORD)*pcbAttrLen; + + if (pcbAttrLenAlloc && !g_SCardAutoAllocate) + { + pcsc_cbAttrLen = 0; + status = g_PCSC.pfnSCardGetAttrib(hCard, pcsc_dwAttrId, NULL, &pcsc_cbAttrLen); + + if (status == SCARD_S_SUCCESS) + { + BYTE* tmp = (BYTE*)calloc(1, pcsc_cbAttrLen); + + if (!tmp) + return SCARD_E_NO_MEMORY; + + status = g_PCSC.pfnSCardGetAttrib(hCard, pcsc_dwAttrId, tmp, &pcsc_cbAttrLen); + + if (status != SCARD_S_SUCCESS) + { + free(tmp); + tmp = NULL; + } + else + PCSC_AddMemoryBlock(hContext, tmp); + *(BYTE**)pbAttr = tmp; + } + } + else + { + status = g_PCSC.pfnSCardGetAttrib(hCard, pcsc_dwAttrId, pbAttr, &pcsc_cbAttrLen); + } + + if (status == SCARD_S_SUCCESS) + *pcbAttrLen = (DWORD)pcsc_cbAttrLen; + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardGetAttrib_FriendlyName(SCARDHANDLE hCard, DWORD dwAttrId, + LPBYTE pbAttr, LPDWORD pcbAttrLen) +{ + size_t length = 0; + char* namePCSC = NULL; + char* pbAttrA = NULL; + DWORD cbAttrLen = 0; + WCHAR* pbAttrW = NULL; + SCARDCONTEXT hContext = 0; + LONG status = SCARD_S_SUCCESS; + + hContext = PCSC_GetCardContextFromHandle(hCard); + + if (!hContext) + return SCARD_E_INVALID_HANDLE; + + if (!pcbAttrLen) + return SCARD_E_INVALID_PARAMETER; + cbAttrLen = *pcbAttrLen; + *pcbAttrLen = SCARD_AUTOALLOCATE; + status = PCSC_SCardGetAttrib_Internal(hCard, SCARD_ATTR_DEVICE_FRIENDLY_NAME_A, + (LPBYTE)&pbAttrA, pcbAttrLen); + + if (status != SCARD_S_SUCCESS) + { + *pcbAttrLen = SCARD_AUTOALLOCATE; + status = PCSC_SCardGetAttrib_Internal(hCard, SCARD_ATTR_DEVICE_FRIENDLY_NAME_W, + (LPBYTE)&pbAttrW, pcbAttrLen); + + if (status != SCARD_S_SUCCESS) + return status; + + namePCSC = ConvertMszWCharNToUtf8Alloc(pbAttrW, *pcbAttrLen, NULL); + PCSC_SCardFreeMemory_Internal(hContext, pbAttrW); + } + else + { + namePCSC = _strdup(pbAttrA); + + if (!namePCSC) + return SCARD_E_NO_MEMORY; + + PCSC_SCardFreeMemory_Internal(hContext, pbAttrA); + } + + length = strlen(namePCSC); + + if (dwAttrId == SCARD_ATTR_DEVICE_FRIENDLY_NAME_W) + { + size_t size = 0; + WCHAR* friendlyNameW = ConvertUtf8ToWCharAlloc(namePCSC, &size); + /* length here includes null terminator */ + + if (!friendlyNameW) + status = SCARD_E_NO_MEMORY; + else + { + length = size; + + if (cbAttrLen == SCARD_AUTOALLOCATE) + { + WINPR_ASSERT(length <= UINT32_MAX / sizeof(WCHAR)); + *(WCHAR**)pbAttr = friendlyNameW; + *pcbAttrLen = (UINT32)length * sizeof(WCHAR); + PCSC_AddMemoryBlock(hContext, friendlyNameW); + } + else + { + if ((length * 2) > cbAttrLen) + status = SCARD_E_INSUFFICIENT_BUFFER; + else + { + WINPR_ASSERT(length <= UINT32_MAX / sizeof(WCHAR)); + CopyMemory(pbAttr, (BYTE*)friendlyNameW, (length * sizeof(WCHAR))); + *pcbAttrLen = (UINT32)length * sizeof(WCHAR); + } + free(friendlyNameW); + } + } + free(namePCSC); + } + else + { + if (cbAttrLen == SCARD_AUTOALLOCATE) + { + *(CHAR**)pbAttr = namePCSC; + WINPR_ASSERT(length <= UINT32_MAX); + *pcbAttrLen = (UINT32)length; + PCSC_AddMemoryBlock(hContext, namePCSC); + } + else + { + if ((length + 1) > cbAttrLen) + status = SCARD_E_INSUFFICIENT_BUFFER; + else + { + CopyMemory(pbAttr, namePCSC, length + 1); + WINPR_ASSERT(length <= UINT32_MAX); + *pcbAttrLen = (UINT32)length; + } + free(namePCSC); + } + } + + return status; +} + +static LONG WINAPI PCSC_SCardGetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr, + LPDWORD pcbAttrLen) +{ + DWORD cbAttrLen = 0; + SCARDCONTEXT hContext = 0; + BOOL pcbAttrLenAlloc = FALSE; + LONG status = SCARD_S_SUCCESS; + + if (NULL == pcbAttrLen) + return SCARD_E_INVALID_PARAMETER; + + cbAttrLen = *pcbAttrLen; + + if (*pcbAttrLen == SCARD_AUTOALLOCATE) + { + if (NULL == pbAttr) + return SCARD_E_INVALID_PARAMETER; + + pcbAttrLenAlloc = TRUE; + *(BYTE**)pbAttr = NULL; + } + else + { + /** + * pcsc-lite returns SCARD_E_INSUFFICIENT_BUFFER if the given + * buffer size is larger than PCSC_MAX_BUFFER_SIZE (264) + */ + if (*pcbAttrLen > PCSC_MAX_BUFFER_SIZE) + *pcbAttrLen = PCSC_MAX_BUFFER_SIZE; + } + + hContext = PCSC_GetCardContextFromHandle(hCard); + + if (!hContext) + return SCARD_E_INVALID_HANDLE; + + if ((dwAttrId == SCARD_ATTR_DEVICE_FRIENDLY_NAME_A) || + (dwAttrId == SCARD_ATTR_DEVICE_FRIENDLY_NAME_W)) + { + status = PCSC_SCardGetAttrib_FriendlyName(hCard, dwAttrId, pbAttr, pcbAttrLen); + return status; + } + + status = PCSC_SCardGetAttrib_Internal(hCard, dwAttrId, pbAttr, pcbAttrLen); + + if (status == SCARD_S_SUCCESS) + { + if (dwAttrId == SCARD_ATTR_VENDOR_NAME) + { + if (pbAttr) + { + const char* vendorName = NULL; + + /** + * pcsc-lite adds a null terminator to the vendor name, + * while WinSCard doesn't. Strip the null terminator. + */ + + if (pcbAttrLenAlloc) + vendorName = (char*)*(BYTE**)pbAttr; + else + vendorName = (char*)pbAttr; + + if (vendorName) + { + size_t len = strnlen(vendorName, *pcbAttrLen); + WINPR_ASSERT(len <= UINT32_MAX); + *pcbAttrLen = (DWORD)len; + } + else + *pcbAttrLen = 0; + } + } + } + else + { + + if (dwAttrId == SCARD_ATTR_CURRENT_PROTOCOL_TYPE) + { + if (!pcbAttrLenAlloc) + { + PCSC_DWORD dwState = 0; + PCSC_DWORD cbAtrLen = 0; + PCSC_DWORD dwProtocol = 0; + PCSC_DWORD cchReaderLen = 0; + status = (LONG)g_PCSC.pfnSCardStatus(hCard, NULL, &cchReaderLen, &dwState, + &dwProtocol, NULL, &cbAtrLen); + + if (status == SCARD_S_SUCCESS) + { + if (cbAttrLen < sizeof(DWORD)) + return SCARD_E_INSUFFICIENT_BUFFER; + + *(DWORD*)pbAttr = PCSC_ConvertProtocolsToWinSCard(dwProtocol); + *pcbAttrLen = sizeof(DWORD); + } + } + } + else if (dwAttrId == SCARD_ATTR_CHANNEL_ID) + { + if (!pcbAttrLenAlloc) + { + UINT32 channelType = 0x20; /* USB */ + UINT32 channelNumber = 0; + + if (cbAttrLen < sizeof(DWORD)) + return SCARD_E_INSUFFICIENT_BUFFER; + + status = SCARD_S_SUCCESS; + *(DWORD*)pbAttr = (channelType << 16u) | channelNumber; + *pcbAttrLen = sizeof(DWORD); + } + } + else if (dwAttrId == SCARD_ATTR_VENDOR_IFD_TYPE) + { + } + else if (dwAttrId == SCARD_ATTR_DEFAULT_CLK) + { + } + else if (dwAttrId == SCARD_ATTR_DEFAULT_DATA_RATE) + { + } + else if (dwAttrId == SCARD_ATTR_MAX_CLK) + { + } + else if (dwAttrId == SCARD_ATTR_MAX_DATA_RATE) + { + } + else if (dwAttrId == SCARD_ATTR_MAX_IFSD) + { + } + else if (dwAttrId == SCARD_ATTR_CHARACTERISTICS) + { + } + else if (dwAttrId == SCARD_ATTR_DEVICE_SYSTEM_NAME_A) + { + } + else if (dwAttrId == SCARD_ATTR_DEVICE_UNIT) + { + } + else if (dwAttrId == SCARD_ATTR_POWER_MGMT_SUPPORT) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_CLK) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_F) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_D) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_N) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_CWT) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_BWT) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_IFSC) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_EBC_ENCODING) + { + } + else if (dwAttrId == SCARD_ATTR_CURRENT_IFSD) + { + } + else if (dwAttrId == SCARD_ATTR_ICC_TYPE_PER_ATR) + { + } + } + + return status; +} + +static LONG WINAPI PCSC_SCardSetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr, + DWORD cbAttrLen) +{ + PCSC_LONG status = SCARD_S_SUCCESS; + PCSC_SCARDHANDLE* pCard = NULL; + PCSC_DWORD pcsc_dwAttrId = (PCSC_DWORD)dwAttrId; + PCSC_DWORD pcsc_cbAttrLen = (PCSC_DWORD)cbAttrLen; + + if (!g_PCSC.pfnSCardSetAttrib) + return PCSC_SCard_LogError("g_PCSC.pfnSCardSetAttrib"); + + pCard = PCSC_GetCardHandleData(hCard); + + if (!pCard) + return SCARD_E_INVALID_VALUE; + + PCSC_WaitForCardAccess(0, hCard, pCard->shared); + status = g_PCSC.pfnSCardSetAttrib(hCard, pcsc_dwAttrId, pbAttr, pcsc_cbAttrLen); + return PCSC_MapErrorCodeToWinSCard(status); +} + +static LONG WINAPI PCSC_SCardUIDlgSelectCardA(LPOPENCARDNAMEA_EX pDlgStruc) +{ + WINPR_UNUSED(pDlgStruc); + + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardUIDlgSelectCardW(LPOPENCARDNAMEW_EX pDlgStruc) +{ + WINPR_UNUSED(pDlgStruc); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_GetOpenCardNameA(LPOPENCARDNAMEA pDlgStruc) +{ + WINPR_UNUSED(pDlgStruc); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_GetOpenCardNameW(LPOPENCARDNAMEW pDlgStruc) +{ + WINPR_UNUSED(pDlgStruc); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardDlgExtendedError(void) +{ + + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static char* card_id_and_name_a(const UUID* CardIdentifier, LPCSTR LookupName) +{ + WINPR_ASSERT(CardIdentifier); + WINPR_ASSERT(LookupName); + + size_t len = strlen(LookupName) + 34; + char* id = malloc(len); + if (!id) + return NULL; + + (void)snprintf(id, len, "%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X\\%s", + CardIdentifier->Data1, CardIdentifier->Data2, CardIdentifier->Data3, + CardIdentifier->Data4[0], CardIdentifier->Data4[1], CardIdentifier->Data4[2], + CardIdentifier->Data4[3], CardIdentifier->Data4[4], CardIdentifier->Data4[5], + CardIdentifier->Data4[6], CardIdentifier->Data4[7], LookupName); + return id; +} + +static char* card_id_and_name_w(const UUID* CardIdentifier, LPCWSTR LookupName) +{ + char* res = NULL; + char* tmp = ConvertWCharToUtf8Alloc(LookupName, NULL); + if (!tmp) + return NULL; + res = card_id_and_name_a(CardIdentifier, tmp); + free(tmp); + return res; +} + +static LONG WINAPI PCSC_SCardReadCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + PCSC_CACHE_ITEM* data = NULL; + PCSC_SCARDCONTEXT* ctx = PCSC_GetCardContextData(hContext); + if (!ctx) + return SCARD_E_INVALID_HANDLE; + + char* id = card_id_and_name_a(CardIdentifier, LookupName); + + data = HashTable_GetItemValue(ctx->cache, id); + free(id); + if (!data) + { + *DataLen = 0; + return SCARD_W_CACHE_ITEM_NOT_FOUND; + } + + if (FreshnessCounter != data->freshness) + { + *DataLen = 0; + return SCARD_W_CACHE_ITEM_STALE; + } + + if (*DataLen == SCARD_AUTOALLOCATE) + { + BYTE* mem = calloc(1, data->len); + if (!mem) + return SCARD_E_NO_MEMORY; + + if (!PCSC_AddMemoryBlock(hContext, mem)) + { + free(mem); + return SCARD_E_NO_MEMORY; + } + + memcpy(mem, data->data, data->len); + *(BYTE**)Data = mem; + } + else + memcpy(Data, data->data, data->len); + *DataLen = data->len; + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardReadCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD* DataLen) +{ + PCSC_CACHE_ITEM* data = NULL; + PCSC_SCARDCONTEXT* ctx = PCSC_GetCardContextData(hContext); + if (!ctx) + return SCARD_E_INVALID_HANDLE; + + char* id = card_id_and_name_w(CardIdentifier, LookupName); + + data = HashTable_GetItemValue(ctx->cache, id); + free(id); + + if (!data) + { + *DataLen = 0; + return SCARD_W_CACHE_ITEM_NOT_FOUND; + } + + if (FreshnessCounter != data->freshness) + { + *DataLen = 0; + return SCARD_W_CACHE_ITEM_STALE; + } + + if (*DataLen == SCARD_AUTOALLOCATE) + { + BYTE* mem = calloc(1, data->len); + if (!mem) + return SCARD_E_NO_MEMORY; + + if (!PCSC_AddMemoryBlock(hContext, mem)) + { + free(mem); + return SCARD_E_NO_MEMORY; + } + + memcpy(mem, data->data, data->len); + *(BYTE**)Data = mem; + } + else + memcpy(Data, data->data, data->len); + *DataLen = data->len; + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardWriteCacheA(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + PCSC_CACHE_ITEM* data = NULL; + PCSC_SCARDCONTEXT* ctx = PCSC_GetCardContextData(hContext); + char* id = NULL; + + if (!ctx) + return SCARD_E_FILE_NOT_FOUND; + + id = card_id_and_name_a(CardIdentifier, LookupName); + + if (!id) + return SCARD_E_NO_MEMORY; + + data = malloc(sizeof(PCSC_CACHE_ITEM)); + if (!data) + { + free(id); + return SCARD_E_NO_MEMORY; + } + data->data = calloc(DataLen, 1); + if (!data->data) + { + free(id); + free(data); + return SCARD_E_NO_MEMORY; + } + data->len = DataLen; + data->freshness = FreshnessCounter; + memcpy(data->data, Data, data->len); + + HashTable_Remove(ctx->cache, id); + const BOOL rc = HashTable_Insert(ctx->cache, id, data); + free(id); + + if (!rc) + { + pcsc_cache_item_free(data); + return SCARD_E_NO_MEMORY; + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert owns data + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardWriteCacheW(SCARDCONTEXT hContext, UUID* CardIdentifier, + DWORD FreshnessCounter, LPWSTR LookupName, PBYTE Data, + DWORD DataLen) +{ + PCSC_CACHE_ITEM* data = NULL; + PCSC_SCARDCONTEXT* ctx = PCSC_GetCardContextData(hContext); + char* id = NULL; + if (!ctx) + return SCARD_E_FILE_NOT_FOUND; + + id = card_id_and_name_w(CardIdentifier, LookupName); + + if (!id) + return SCARD_E_NO_MEMORY; + + data = malloc(sizeof(PCSC_CACHE_ITEM)); + if (!data) + { + free(id); + return SCARD_E_NO_MEMORY; + } + data->data = malloc(DataLen); + if (!data->data) + { + free(id); + free(data); + return SCARD_E_NO_MEMORY; + } + data->len = DataLen; + data->freshness = FreshnessCounter; + memcpy(data->data, Data, data->len); + + HashTable_Remove(ctx->cache, id); + const BOOL rc = HashTable_Insert(ctx->cache, id, data); + free(id); + + if (!rc) + { + pcsc_cache_item_free(data); + return SCARD_E_NO_MEMORY; + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert owns data + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardGetReaderIconA( + SCARDCONTEXT hContext, LPCSTR szReaderName, + LPBYTE pbIcon /* NOLINT(readability-non-const-parameter) */, LPDWORD pcbIcon) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(pbIcon); + WINPR_ASSERT(pcbIcon); + *pcbIcon = 0; + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetReaderIconW( + SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPBYTE pbIcon /* NOLINT(readability-non-const-parameter) */, LPDWORD pcbIcon) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(pbIcon); + WINPR_ASSERT(pcbIcon); + *pcbIcon = 0; + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetDeviceTypeIdA(SCARDCONTEXT hContext, LPCSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(pdwDeviceTypeId); + if (pdwDeviceTypeId) + *pdwDeviceTypeId = SCARD_READER_TYPE_USB; + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardGetDeviceTypeIdW(SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPDWORD pdwDeviceTypeId) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + if (pdwDeviceTypeId) + *pdwDeviceTypeId = SCARD_READER_TYPE_USB; + return SCARD_S_SUCCESS; +} + +static LONG WINAPI PCSC_SCardGetReaderDeviceInstanceIdA( + SCARDCONTEXT hContext, LPCSTR szReaderName, + LPSTR szDeviceInstanceId /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchDeviceInstanceId /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szDeviceInstanceId); + WINPR_UNUSED(pcchDeviceInstanceId); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardGetReaderDeviceInstanceIdW( + SCARDCONTEXT hContext, LPCWSTR szReaderName, + LPWSTR szDeviceInstanceId /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchDeviceInstanceId /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szReaderName); + WINPR_UNUSED(szDeviceInstanceId); + WINPR_UNUSED(pcchDeviceInstanceId); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardListReadersWithDeviceInstanceIdA( + SCARDCONTEXT hContext, LPCSTR szDeviceInstanceId, + LPSTR mszReaders /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchReaders /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szDeviceInstanceId); + WINPR_UNUSED(mszReaders); + WINPR_UNUSED(pcchReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardListReadersWithDeviceInstanceIdW( + SCARDCONTEXT hContext, LPCWSTR szDeviceInstanceId, + LPWSTR mszReaders /* NOLINT(readability-non-const-parameter) */, + LPDWORD pcchReaders /* NOLINT(readability-non-const-parameter) */) +{ + WINPR_UNUSED(hContext); + WINPR_UNUSED(szDeviceInstanceId); + WINPR_UNUSED(mszReaders); + WINPR_UNUSED(pcchReaders); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +static LONG WINAPI PCSC_SCardAudit(SCARDCONTEXT hContext, DWORD dwEvent) +{ + + WINPR_UNUSED(hContext); + WINPR_UNUSED(dwEvent); + return SCARD_E_UNSUPPORTED_FEATURE; +} + +#ifdef __MACOSX__ +unsigned int determineMacOSXVersion(void) +{ + int mib[2]; + size_t len = 0; + char* kernelVersion = NULL; + char* tok = NULL; + unsigned int version = 0; + long majorVersion = 0; + long minorVersion = 0; + long patchVersion = 0; + int count = 0; + char* context = NULL; + mib[0] = CTL_KERN; + mib[1] = KERN_OSRELEASE; + + if (sysctl(mib, 2, NULL, &len, NULL, 0) != 0) + return 0; + + kernelVersion = calloc(len, sizeof(char)); + + if (!kernelVersion) + return 0; + + if (sysctl(mib, 2, kernelVersion, &len, NULL, 0) != 0) + { + free(kernelVersion); + return 0; + } + + tok = strtok_s(kernelVersion, ".", &context); + errno = 0; + + while (tok) + { + switch (count) + { + case 0: + majorVersion = strtol(tok, NULL, 0); + + if (errno != 0) + goto fail; + + break; + + case 1: + minorVersion = strtol(tok, NULL, 0); + + if (errno != 0) + goto fail; + + break; + + case 2: + patchVersion = strtol(tok, NULL, 0); + + if (errno != 0) + goto fail; + + break; + } + + tok = strtok_s(NULL, ".", &context); + count++; + } + + /** + * Source : http://en.wikipedia.org/wiki/Darwin_(operating_system) + **/ + if (majorVersion < 5) + { + if (minorVersion < 4) + version = 0x10000000; + else + version = 0x10010000; + } + else + { + switch (majorVersion) + { + case 5: + version = 0x10010000; + break; + + case 6: + version = 0x10020000; + break; + + case 7: + version = 0x10030000; + break; + + case 8: + version = 0x10040000; + break; + + case 9: + version = 0x10050000; + break; + + case 10: + version = 0x10060000; + break; + + case 11: + version = 0x10070000; + break; + + case 12: + version = 0x10080000; + break; + + case 13: + version = 0x10090000; + break; + + default: + version = 0x10100000; + break; + } + + version |= (minorVersion << 8) | (patchVersion); + } + +fail: + free(kernelVersion); + return version; +} +#endif + +static const SCardApiFunctionTable PCSC_SCardApiFunctionTable = { + 0, /* dwVersion */ + 0, /* dwFlags */ + + PCSC_SCardEstablishContext, /* SCardEstablishContext */ + PCSC_SCardReleaseContext, /* SCardReleaseContext */ + PCSC_SCardIsValidContext, /* SCardIsValidContext */ + PCSC_SCardListReaderGroupsA, /* SCardListReaderGroupsA */ + PCSC_SCardListReaderGroupsW, /* SCardListReaderGroupsW */ + PCSC_SCardListReadersA, /* SCardListReadersA */ + PCSC_SCardListReadersW, /* SCardListReadersW */ + PCSC_SCardListCardsA, /* SCardListCardsA */ + PCSC_SCardListCardsW, /* SCardListCardsW */ + PCSC_SCardListInterfacesA, /* SCardListInterfacesA */ + PCSC_SCardListInterfacesW, /* SCardListInterfacesW */ + PCSC_SCardGetProviderIdA, /* SCardGetProviderIdA */ + PCSC_SCardGetProviderIdW, /* SCardGetProviderIdW */ + PCSC_SCardGetCardTypeProviderNameA, /* SCardGetCardTypeProviderNameA */ + PCSC_SCardGetCardTypeProviderNameW, /* SCardGetCardTypeProviderNameW */ + PCSC_SCardIntroduceReaderGroupA, /* SCardIntroduceReaderGroupA */ + PCSC_SCardIntroduceReaderGroupW, /* SCardIntroduceReaderGroupW */ + PCSC_SCardForgetReaderGroupA, /* SCardForgetReaderGroupA */ + PCSC_SCardForgetReaderGroupW, /* SCardForgetReaderGroupW */ + PCSC_SCardIntroduceReaderA, /* SCardIntroduceReaderA */ + PCSC_SCardIntroduceReaderW, /* SCardIntroduceReaderW */ + PCSC_SCardForgetReaderA, /* SCardForgetReaderA */ + PCSC_SCardForgetReaderW, /* SCardForgetReaderW */ + PCSC_SCardAddReaderToGroupA, /* SCardAddReaderToGroupA */ + PCSC_SCardAddReaderToGroupW, /* SCardAddReaderToGroupW */ + PCSC_SCardRemoveReaderFromGroupA, /* SCardRemoveReaderFromGroupA */ + PCSC_SCardRemoveReaderFromGroupW, /* SCardRemoveReaderFromGroupW */ + PCSC_SCardIntroduceCardTypeA, /* SCardIntroduceCardTypeA */ + PCSC_SCardIntroduceCardTypeW, /* SCardIntroduceCardTypeW */ + PCSC_SCardSetCardTypeProviderNameA, /* SCardSetCardTypeProviderNameA */ + PCSC_SCardSetCardTypeProviderNameW, /* SCardSetCardTypeProviderNameW */ + PCSC_SCardForgetCardTypeA, /* SCardForgetCardTypeA */ + PCSC_SCardForgetCardTypeW, /* SCardForgetCardTypeW */ + PCSC_SCardFreeMemory, /* SCardFreeMemory */ + PCSC_SCardAccessStartedEvent, /* SCardAccessStartedEvent */ + PCSC_SCardReleaseStartedEvent, /* SCardReleaseStartedEvent */ + PCSC_SCardLocateCardsA, /* SCardLocateCardsA */ + PCSC_SCardLocateCardsW, /* SCardLocateCardsW */ + PCSC_SCardLocateCardsByATRA, /* SCardLocateCardsByATRA */ + PCSC_SCardLocateCardsByATRW, /* SCardLocateCardsByATRW */ + PCSC_SCardGetStatusChangeA, /* SCardGetStatusChangeA */ + PCSC_SCardGetStatusChangeW, /* SCardGetStatusChangeW */ + PCSC_SCardCancel, /* SCardCancel */ + PCSC_SCardConnectA, /* SCardConnectA */ + PCSC_SCardConnectW, /* SCardConnectW */ + PCSC_SCardReconnect, /* SCardReconnect */ + PCSC_SCardDisconnect, /* SCardDisconnect */ + PCSC_SCardBeginTransaction, /* SCardBeginTransaction */ + PCSC_SCardEndTransaction, /* SCardEndTransaction */ + PCSC_SCardCancelTransaction, /* SCardCancelTransaction */ + PCSC_SCardState, /* SCardState */ + PCSC_SCardStatusA, /* SCardStatusA */ + PCSC_SCardStatusW, /* SCardStatusW */ + PCSC_SCardTransmit, /* SCardTransmit */ + PCSC_SCardGetTransmitCount, /* SCardGetTransmitCount */ + PCSC_SCardControl, /* SCardControl */ + PCSC_SCardGetAttrib, /* SCardGetAttrib */ + PCSC_SCardSetAttrib, /* SCardSetAttrib */ + PCSC_SCardUIDlgSelectCardA, /* SCardUIDlgSelectCardA */ + PCSC_SCardUIDlgSelectCardW, /* SCardUIDlgSelectCardW */ + PCSC_GetOpenCardNameA, /* GetOpenCardNameA */ + PCSC_GetOpenCardNameW, /* GetOpenCardNameW */ + PCSC_SCardDlgExtendedError, /* SCardDlgExtendedError */ + PCSC_SCardReadCacheA, /* SCardReadCacheA */ + PCSC_SCardReadCacheW, /* SCardReadCacheW */ + PCSC_SCardWriteCacheA, /* SCardWriteCacheA */ + PCSC_SCardWriteCacheW, /* SCardWriteCacheW */ + PCSC_SCardGetReaderIconA, /* SCardGetReaderIconA */ + PCSC_SCardGetReaderIconW, /* SCardGetReaderIconW */ + PCSC_SCardGetDeviceTypeIdA, /* SCardGetDeviceTypeIdA */ + PCSC_SCardGetDeviceTypeIdW, /* SCardGetDeviceTypeIdW */ + PCSC_SCardGetReaderDeviceInstanceIdA, /* SCardGetReaderDeviceInstanceIdA */ + PCSC_SCardGetReaderDeviceInstanceIdW, /* SCardGetReaderDeviceInstanceIdW */ + PCSC_SCardListReadersWithDeviceInstanceIdA, /* SCardListReadersWithDeviceInstanceIdA */ + PCSC_SCardListReadersWithDeviceInstanceIdW, /* SCardListReadersWithDeviceInstanceIdW */ + PCSC_SCardAudit /* SCardAudit */ +}; + +const SCardApiFunctionTable* PCSC_GetSCardApiFunctionTable(void) +{ + return &PCSC_SCardApiFunctionTable; +} + +int PCSC_InitializeSCardApi(void) +{ + /* Disable pcsc-lite's (poor) blocking so we can handle it ourselves */ + SetEnvironmentVariableA("PCSCLITE_NO_BLOCKING", "1"); +#ifdef __MACOSX__ + g_PCSCModule = LoadLibraryX("/System/Library/Frameworks/PCSC.framework/PCSC"); + OSXVersion = determineMacOSXVersion(); + + if (OSXVersion == 0) + return -1; + +#else + g_PCSCModule = LoadLibraryA("libpcsclite.so.1"); + + if (!g_PCSCModule) + g_PCSCModule = LoadLibraryA("libpcsclite.so"); + +#endif + + if (!g_PCSCModule) + return -1; + + /* symbols defined in winpr/smartcard.h, might pose an issue with the GetProcAddress macro + * below. therefore undefine them here */ +#undef SCardListReaderGroups +#undef SCardListReaders +#undef SCardListCards +#undef SCardListInterfaces +#undef SCardGetProviderId +#undef SCardGetCardTypeProviderName +#undef SCardIntroduceReaderGroup +#undef SCardForgetReaderGroup +#undef SCardIntroduceReader +#undef SCardForgetReader +#undef SCardAddReaderToGroup +#undef SCardRemoveReaderFromGroup +#undef SCardIntroduceCardType +#undef SCardSetCardTypeProviderName +#undef SCardForgetCardType +#undef SCardLocateCards +#undef SCardLocateCardsByATR +#undef SCardGetStatusChange +#undef SCardConnect +#undef SCardStatus +#undef SCardUIDlgSelectCard +#undef GetOpenCardName +#undef SCardReadCache +#undef SCardWriteCache +#undef SCardGetReaderIcon +#undef SCardGetDeviceTypeId +#undef SCardGetReaderDeviceInstanceId +#undef SCardListReadersWithDeviceInstanceId + + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardEstablishContext); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardReleaseContext); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardIsValidContext); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardConnect); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardReconnect); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardDisconnect); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardBeginTransaction); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardEndTransaction); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardStatus); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardGetStatusChange); + +#ifdef __MACOSX__ + + if (OSXVersion >= 0x10050600) + { + WINSCARD_LOAD_PROC_EX(g_PCSCModule, g_PCSC, SCardControl, SCardControl132); + } + else + { + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardControl); + } +#else + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardControl); +#endif + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardTransmit); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardListReaderGroups); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardListReaders); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardCancel); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardGetAttrib); + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardSetAttrib); + g_PCSC.pfnSCardFreeMemory = NULL; +#ifndef __APPLE__ + WINSCARD_LOAD_PROC(g_PCSCModule, g_PCSC, SCardFreeMemory); +#endif + + if (g_PCSC.pfnSCardFreeMemory) + g_SCardAutoAllocate = TRUE; + +#ifdef DISABLE_PCSC_SCARD_AUTOALLOCATE + g_PCSC.pfnSCardFreeMemory = NULL; + g_SCardAutoAllocate = FALSE; +#endif +#ifdef __APPLE__ + g_PnP_Notification = FALSE; +#endif + return 1; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.h new file mode 100644 index 0000000000000000000000000000000000000000..9ff822d12310366e35fa39c8b7093fc4a544096f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_pcsc.h @@ -0,0 +1,175 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2020 Armin Novak + * Copyright 2020 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_SMARTCARD_PCSC_PRIVATE_H +#define WINPR_SMARTCARD_PCSC_PRIVATE_H + +#ifndef _WIN32 + +#include +#include + +/** + * On Windows, DWORD and ULONG are defined to unsigned long. + * However, 64-bit Windows uses the LLP64 model which defines + * unsigned long as a 4-byte type, while most non-Windows + * systems use the LP64 model where unsigned long is 8 bytes. + * + * WinPR correctly defines DWORD and ULONG to be 4-byte types + * regardless of LLP64/LP64, but this has the side effect of + * breaking compatibility with the broken pcsc-lite types. + * + * To make matters worse, pcsc-lite correctly defines + * the data types on OS X, but not on other platforms. + */ + +#ifdef __APPLE__ + +#include + +#ifndef BYTE +typedef uint8_t PCSC_BYTE; +#endif +typedef uint8_t PCSC_UCHAR; +typedef PCSC_UCHAR* PCSC_PUCHAR; +typedef uint16_t PCSC_USHORT; + +#ifndef __COREFOUNDATION_CFPLUGINCOM__ +typedef uint32_t PCSC_ULONG; +typedef void* PCSC_LPVOID; +typedef int16_t PCSC_BOOL; +#endif + +typedef PCSC_ULONG* PCSC_PULONG; +typedef const void* PCSC_LPCVOID; +typedef uint32_t PCSC_DWORD; +typedef PCSC_DWORD* PCSC_PDWORD; +typedef uint16_t PCSC_WORD; +typedef int32_t PCSC_LONG; +typedef const char* PCSC_LPCSTR; +typedef const PCSC_BYTE* PCSC_LPCBYTE; +typedef PCSC_BYTE* PCSC_LPBYTE; +typedef PCSC_DWORD* PCSC_LPDWORD; +typedef char* PCSC_LPSTR; + +#else + +#ifndef BYTE +typedef unsigned char PCSC_BYTE; +#endif +typedef unsigned char PCSC_UCHAR; +typedef PCSC_UCHAR* PCSC_PUCHAR; +typedef unsigned short PCSC_USHORT; + +#ifndef __COREFOUNDATION_CFPLUGINCOM__ +typedef unsigned long PCSC_ULONG; +typedef void* PCSC_LPVOID; +#endif + +typedef const void* PCSC_LPCVOID; +typedef unsigned long PCSC_DWORD; +typedef PCSC_DWORD* PCSC_PDWORD; +typedef long PCSC_LONG; +typedef const char* PCSC_LPCSTR; +typedef const PCSC_BYTE* PCSC_LPCBYTE; +typedef PCSC_BYTE* PCSC_LPBYTE; +typedef PCSC_DWORD* PCSC_LPDWORD; +typedef char* PCSC_LPSTR; + +/* these types were deprecated but still used by old drivers and + * applications. So just declare and use them. */ +typedef PCSC_LPSTR PCSC_LPTSTR; +typedef PCSC_LPCSTR PCSC_LPCTSTR; + +/* types unused by pcsc-lite */ +typedef short PCSC_BOOL; +typedef unsigned short PCSC_WORD; +typedef PCSC_ULONG* PCSC_PULONG; + +#endif + +#define PCSC_SCARD_UNKNOWN 0x0001 +#define PCSC_SCARD_ABSENT 0x0002 +#define PCSC_SCARD_PRESENT 0x0004 +#define PCSC_SCARD_SWALLOWED 0x0008 +#define PCSC_SCARD_POWERED 0x0010 +#define PCSC_SCARD_NEGOTIABLE 0x0020 +#define PCSC_SCARD_SPECIFIC 0x0040 + +#define PCSC_SCARD_PROTOCOL_RAW 0x00000004u +#define PCSC_SCARD_PROTOCOL_T15 0x00000008u + +#define PCSC_MAX_BUFFER_SIZE 264 +#define PCSC_MAX_BUFFER_SIZE_EXTENDED (4 + 3 + (1 << 16) + 3 + 2) + +#define PCSC_MAX_ATR_SIZE 33 + +#define PCSC_SCARD_AUTOALLOCATE (PCSC_DWORD)(-1) + +#define PCSC_SCARD_CTL_CODE(code) (0x42000000 + (code)) +#define PCSC_CM_IOCTL_GET_FEATURE_REQUEST PCSC_SCARD_CTL_CODE(3400) + +/** + * pcsc-lite defines SCARD_READERSTATE, SCARD_IO_REQUEST as packed + * on Mac OS X only and uses default packing everywhere else. + */ + +#ifdef __APPLE__ +#pragma pack(push, 1) +#endif + +typedef struct +{ + LPCSTR szReader; + LPVOID pvUserData; + PCSC_DWORD dwCurrentState; + PCSC_DWORD dwEventState; + PCSC_DWORD cbAtr; + BYTE rgbAtr[PCSC_MAX_ATR_SIZE]; /* WinSCard: 36, PCSC: 33 */ +} PCSC_SCARD_READERSTATE; + +typedef struct +{ + PCSC_DWORD dwProtocol; + PCSC_DWORD cbPciLength; +} PCSC_SCARD_IO_REQUEST; + +#ifdef __APPLE__ +#pragma pack(pop) +#endif + +#pragma pack(push, 1) + +typedef struct +{ + BYTE tag; + BYTE length; + UINT32 value; +} PCSC_TLV_STRUCTURE; + +#pragma pack(pop) + +int PCSC_InitializeSCardApi(void); +const SCardApiFunctionTable* PCSC_GetSCardApiFunctionTable(void); + +#endif + +#endif /* WINPR_SMARTCARD_PCSC_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.c new file mode 100644 index 0000000000000000000000000000000000000000..967a2a0d0a300dee94defd39a01fb72787612137 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.c @@ -0,0 +1,126 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "smartcard_windows.h" + +static HMODULE g_WinSCardModule = NULL; + +static SCardApiFunctionTable Windows_SCardApiFunctionTable = { + 0, /* dwVersion */ + 0, /* dwFlags */ + + NULL, /* SCardEstablishContext */ + NULL, /* SCardReleaseContext */ + NULL, /* SCardIsValidContext */ + NULL, /* SCardListReaderGroupsA */ + NULL, /* SCardListReaderGroupsW */ + NULL, /* SCardListReadersA */ + NULL, /* SCardListReadersW */ + NULL, /* SCardListCardsA */ + NULL, /* SCardListCardsW */ + NULL, /* SCardListInterfacesA */ + NULL, /* SCardListInterfacesW */ + NULL, /* SCardGetProviderIdA */ + NULL, /* SCardGetProviderIdW */ + NULL, /* SCardGetCardTypeProviderNameA */ + NULL, /* SCardGetCardTypeProviderNameW */ + NULL, /* SCardIntroduceReaderGroupA */ + NULL, /* SCardIntroduceReaderGroupW */ + NULL, /* SCardForgetReaderGroupA */ + NULL, /* SCardForgetReaderGroupW */ + NULL, /* SCardIntroduceReaderA */ + NULL, /* SCardIntroduceReaderW */ + NULL, /* SCardForgetReaderA */ + NULL, /* SCardForgetReaderW */ + NULL, /* SCardAddReaderToGroupA */ + NULL, /* SCardAddReaderToGroupW */ + NULL, /* SCardRemoveReaderFromGroupA */ + NULL, /* SCardRemoveReaderFromGroupW */ + NULL, /* SCardIntroduceCardTypeA */ + NULL, /* SCardIntroduceCardTypeW */ + NULL, /* SCardSetCardTypeProviderNameA */ + NULL, /* SCardSetCardTypeProviderNameW */ + NULL, /* SCardForgetCardTypeA */ + NULL, /* SCardForgetCardTypeW */ + NULL, /* SCardFreeMemory */ + NULL, /* SCardAccessStartedEvent */ + NULL, /* SCardReleaseStartedEvent */ + NULL, /* SCardLocateCardsA */ + NULL, /* SCardLocateCardsW */ + NULL, /* SCardLocateCardsByATRA */ + NULL, /* SCardLocateCardsByATRW */ + NULL, /* SCardGetStatusChangeA */ + NULL, /* SCardGetStatusChangeW */ + NULL, /* SCardCancel */ + NULL, /* SCardConnectA */ + NULL, /* SCardConnectW */ + NULL, /* SCardReconnect */ + NULL, /* SCardDisconnect */ + NULL, /* SCardBeginTransaction */ + NULL, /* SCardEndTransaction */ + NULL, /* SCardCancelTransaction */ + NULL, /* SCardState */ + NULL, /* SCardStatusA */ + NULL, /* SCardStatusW */ + NULL, /* SCardTransmit */ + NULL, /* SCardGetTransmitCount */ + NULL, /* SCardControl */ + NULL, /* SCardGetAttrib */ + NULL, /* SCardSetAttrib */ + NULL, /* SCardUIDlgSelectCardA */ + NULL, /* SCardUIDlgSelectCardW */ + NULL, /* GetOpenCardNameA */ + NULL, /* GetOpenCardNameW */ + NULL, /* SCardDlgExtendedError */ + NULL, /* SCardReadCacheA */ + NULL, /* SCardReadCacheW */ + NULL, /* SCardWriteCacheA */ + NULL, /* SCardWriteCacheW */ + NULL, /* SCardGetReaderIconA */ + NULL, /* SCardGetReaderIconW */ + NULL, /* SCardGetDeviceTypeIdA */ + NULL, /* SCardGetDeviceTypeIdW */ + NULL, /* SCardGetReaderDeviceInstanceIdA */ + NULL, /* SCardGetReaderDeviceInstanceIdW */ + NULL, /* SCardListReadersWithDeviceInstanceIdA */ + NULL, /* SCardListReadersWithDeviceInstanceIdW */ + NULL /* SCardAudit */ +}; + +const SCardApiFunctionTable* Windows_GetSCardApiFunctionTable(void) +{ + return &Windows_SCardApiFunctionTable; +} + +int Windows_InitializeSCardApi(void) +{ + g_WinSCardModule = LoadLibraryA("WinSCard.dll"); + + if (!g_WinSCardModule) + return -1; + + WinSCard_LoadApiTableFunctions(&Windows_SCardApiFunctionTable, g_WinSCardModule); + return 1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.h new file mode 100644 index 0000000000000000000000000000000000000000..4df72b0af9827015d9b1e574b7509bcd80828dd2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/smartcard_windows.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * Smart Card API + * + * Copyright 2014 Marc-Andre Moreau + * + * 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_SMARTCARD_WINSCARD_PRIVATE_H +#define WINPR_SMARTCARD_WINSCARD_PRIVATE_H + +#include + +int Windows_InitializeSCardApi(void); +const SCardApiFunctionTable* Windows_GetSCardApiFunctionTable(void); + +#endif /* WINPR_SMARTCARD_WINSCARD_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8c590ef2a013080eb293434abb37620e3f98b10 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestSmartCard") +set(MODULE_PREFIX "TEST_SMARTCARD") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestSmartCardListReaders.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardListReaders.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardListReaders.c new file mode 100644 index 0000000000000000000000000000000000000000..637200b4ff967f4e671e427122918a93573d77a8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardListReaders.c @@ -0,0 +1,53 @@ + +#include +#include + +int TestSmartCardListReaders(int argc, char* argv[]) +{ + LONG lStatus = 0; + LPSTR pReader = NULL; + SCARDCONTEXT hSC = 0; + LPSTR mszReaders = NULL; + DWORD cchReaders = SCARD_AUTOALLOCATE; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + lStatus = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &hSC); + + if (lStatus != SCARD_S_SUCCESS) + { + printf("SCardEstablishContext failure: %s (0x%08" PRIX32 ")\n", + SCardGetErrorString(lStatus), lStatus); + return 0; + } + + lStatus = SCardListReadersA(hSC, NULL, (LPSTR)&mszReaders, &cchReaders); + + if (lStatus != SCARD_S_SUCCESS) + { + if (lStatus == SCARD_E_NO_READERS_AVAILABLE) + printf("SCARD_E_NO_READERS_AVAILABLE\n"); + else + return -1; + } + else + { + pReader = mszReaders; + + while (*pReader) + { + printf("Reader: %s\n", pReader); + pReader = pReader + strlen((CHAR*)pReader) + 1; + } + + lStatus = SCardFreeMemory(hSC, mszReaders); + + if (lStatus != SCARD_S_SUCCESS) + printf("Failed SCardFreeMemory\n"); + } + + SCardReleaseContext(hSC); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardStatus.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardStatus.c new file mode 100644 index 0000000000000000000000000000000000000000..011f0cec87d8427679c9961c99b52a43e0aea8f8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/smartcard/test/TestSmartCardStatus.c @@ -0,0 +1,160 @@ +// compile against PCSC gcc -o scardtest TestSmartCardStatus.c -DPCSC=1 -I /usr/include/PCSC +// -lpcsclite +#include +#include +#include +#if defined(__APPLE__) || defined(PCSC) +#include +#include +#elif defined(__linux__) +#include +#include +#include +#else +#include +#endif + +#if defined(PCSC) +int main(int argc, char* argv[]) +#else +int TestSmartCardStatus(int argc, char* argv[]) +#endif +{ + SCARDCONTEXT hContext; + LPSTR mszReaders; + DWORD cchReaders = 0; + DWORD err; + SCARDHANDLE hCard; + DWORD dwActiveProtocol; + char name[100]; + char* aname = NULL; + char* aatr = NULL; + DWORD len; + BYTE atr[32]; + DWORD atrlen = 32; + DWORD status = 0; + DWORD protocol = 0; + err = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); + + if (err != SCARD_S_SUCCESS) + { + printf("ScardEstablishedContext: 0x%08x\n", err); + return -1; + } + + err = SCardListReaders(hContext, "SCard$AllReaders", NULL, &cchReaders); + + if (err != 0) + { + printf("ScardListReaders: 0x%08x\n", err); + return -1; + } + + mszReaders = calloc(cchReaders, sizeof(char)); + + if (!mszReaders) + { + printf("calloc\n"); + return -1; + } + + err = SCardListReaders(hContext, "SCard$AllReaders", mszReaders, &cchReaders); + + if (err != SCARD_S_SUCCESS) + { + printf("ScardListReaders: 0x%08x\n", err); + return -1; + } + + printf("Reader: %s\n", mszReaders); + err = SCardConnect(hContext, mszReaders, SCARD_SHARE_SHARED, + SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &hCard, &dwActiveProtocol); + + if (err != SCARD_S_SUCCESS) + { + printf("ScardConnect: 0x%08x\n", err); + return -1; + } + + free(mszReaders); + + printf("# test 1 - get reader length\n"); + err = SCardStatus(hCard, NULL, &len, NULL, NULL, NULL, NULL); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("reader name length: %u\n", len); + + printf("# test 2 - get reader name value\n"); + err = SCardStatus(hCard, name, &len, NULL, NULL, NULL, NULL); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("Reader name: %s (%ld)\n", name, strlen(name)); + + printf("# test 3 - get all values - pre allocated\n"); + err = SCardStatus(hCard, name, &len, &status, &protocol, atr, &atrlen); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("Reader name: %s (%ld/len %u)\n", name, strlen(name), len); + printf("status: 0x%08X\n", status); + printf("proto: 0x%08X\n", protocol); + printf("atrlen: %u\n", atrlen); + + printf("# test 4 - get all values - auto allocate\n"); + len = atrlen = SCARD_AUTOALLOCATE; + err = SCardStatus(hCard, (LPSTR)&aname, &len, &status, &protocol, (LPBYTE)&aatr, &atrlen); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("Reader name: %s (%ld/%u)\n", aname, strlen(aname), len); + printf("status: 0x%08X\n", status); + printf("proto: 0x%08X\n", protocol); + printf("atrlen: %u\n", atrlen); + SCardFreeMemory(hContext, aname); + SCardFreeMemory(hContext, aatr); + + printf("# test 5 - get status and protocol only\n"); + err = SCardStatus(hCard, NULL, NULL, &status, &protocol, NULL, NULL); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("status: 0x%08X\n", status); + printf("proto: 0x%08X\n", protocol); + + printf("# test 6 - get atr only auto allocated\n"); + atrlen = SCARD_AUTOALLOCATE; + err = SCardStatus(hCard, NULL, NULL, NULL, NULL, (LPBYTE)&aatr, &atrlen); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("atrlen: %u\n", atrlen); + SCardFreeMemory(hContext, aatr); + + printf("# test 7 - get atr only pre allocated\n"); + atrlen = 32; + err = SCardStatus(hCard, NULL, NULL, NULL, NULL, atr, &atrlen); + if (err != SCARD_S_SUCCESS) + { + printf("SCardStatus: 0x%08x\n", err); + return -1; + } + printf("atrlen: %u\n", atrlen); + SCardDisconnect(hCard, SCARD_LEAVE_CARD); + SCardReleaseContext(hContext); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..421af05ceb40aa4e735c1e761d1a3123d8329a98 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CMakeLists.txt @@ -0,0 +1,118 @@ +# WinPR: Windows Portable Runtime +# libwinpr-sspi cmake build script +# +# Copyright 2011 Marc-Andre Moreau +# +# 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_PREFIX "WINPR_SSPI") + +set(${MODULE_PREFIX}_NTLM_SRCS + NTLM/ntlm_av_pairs.c + NTLM/ntlm_av_pairs.h + NTLM/ntlm_compute.c + NTLM/ntlm_compute.h + NTLM/ntlm_message.c + NTLM/ntlm_message.h + NTLM/ntlm.c + NTLM/ntlm.h + NTLM/ntlm_export.h +) + +set(${MODULE_PREFIX}_KERBEROS_SRCS Kerberos/kerberos.c Kerberos/kerberos.h) + +set(${MODULE_PREFIX}_NEGOTIATE_SRCS Negotiate/negotiate.c Negotiate/negotiate.h) + +set(${MODULE_PREFIX}_SCHANNEL_SRCS Schannel/schannel_openssl.c Schannel/schannel_openssl.h Schannel/schannel.c + Schannel/schannel.h +) + +set(${MODULE_PREFIX}_CREDSSP_SRCS CredSSP/credssp.c CredSSP/credssp.h) + +set(${MODULE_PREFIX}_SRCS + sspi_winpr.c + sspi_winpr.h + sspi_export.c + sspi_gss.c + sspi_gss.h + sspi.c + sspi.h +) + +set(KRB5_DEFAULT OFF) +if(NOT WIN32 AND NOT ANDROID AND NOT IOS AND NOT APPLE) + set(KRB5_DEFAULT ON) +endif() + +option(WITH_DEBUG_SCHANNEL "Compile support for SCHANNEL debug" ${DEFAULT_DEBUG_OPTION}) +if(WITH_DEBUG_SCHANNEL) + winpr_definition_add(WITH_DEBUG_SCHANNEL) +endif() + +option(WITH_KRB5 "Compile support for kerberos authentication." ${KRB5_DEFAULT}) +if(WITH_KRB5) + find_package(KRB5 REQUIRED) + + list(APPEND ${MODULE_PREFIX}_KERBEROS_SRCS Kerberos/krb5glue.h) + + winpr_system_include_directory_add(${KRB5_INCLUDEDIR}) + winpr_system_include_directory_add(${KRB5_INCLUDE_DIRS}) + winpr_library_add_private(${KRB5_LIBRARIES}) + winpr_library_add_private(${KRB5_LIBRARY}) + winpr_library_add_compile_options(${KRB5_CFLAGS}) + winpr_library_add_link_options(${KRB5_LDFLAGS}) + winpr_library_add_link_directory(${KRB5_LIBRARY_DIRS}) + + winpr_definition_add(WITH_KRB5) + + if(KRB5_FLAVOUR STREQUAL "MIT") + winpr_definition_add(WITH_KRB5_MIT) + list(APPEND ${MODULE_PREFIX}_KERBEROS_SRCS Kerberos/krb5glue_mit.c) + elseif(KRB5_FLAVOUR STREQUAL "Heimdal") + winpr_definition_add(WITH_KRB5_HEIMDAL) + list(APPEND ${MODULE_PREFIX}_KERBEROS_SRCS Kerberos/krb5glue_heimdal.c) + else() + message(WARNING "Kerberos version not detected") + endif() + + include(CMakeDependentOption) + cmake_dependent_option( + WITH_KRB5_NO_NTLM_FALLBACK "Do not fall back to NTLM if no kerberos ticket available" OFF "WITH_KRB5" OFF + ) + if(WITH_KRB5_NO_NTLM_FALLBACK) + add_compile_definitions("WITH_KRB5_NO_NTLM_FALLBACK") + endif() +endif() + +winpr_module_add( + ${${MODULE_PREFIX}_CREDSSP_SRCS} ${${MODULE_PREFIX}_NTLM_SRCS} ${${MODULE_PREFIX}_KERBEROS_SRCS} + ${${MODULE_PREFIX}_NEGOTIATE_SRCS} ${${MODULE_PREFIX}_SCHANNEL_SRCS} ${${MODULE_PREFIX}_SRCS} +) + +if(OPENSSL_FOUND) + winpr_system_include_directory_add(${OPENSSL_INCLUDE_DIR}) + winpr_library_add_private(${OPENSSL_LIBRARIES}) +endif() + +if(MBEDTLS_FOUND) + winpr_system_include_directory_add(${MBEDTLS_INCLUDE_DIR}) + winpr_library_add_private(${MBEDTLS_LIBRARIES}) +endif() + +if(WIN32) + winpr_library_add_public(ws2_32) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.c new file mode 100644 index 0000000000000000000000000000000000000000..55815552441c72f762418859fff9f920a2f3df21 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.c @@ -0,0 +1,322 @@ +/** + * WinPR: Windows Portable Runtime + * Credential Security Support Provider (CredSSP) + * + * Copyright 2010-2014 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include "credssp.h" + +#include "../sspi.h" +#include "../../log.h" + +#define TAG WINPR_TAG("sspi.CredSSP") + +static const char* CREDSSP_PACKAGE_NAME = "CredSSP"; + +static SECURITY_STATUS SEC_ENTRY credssp_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + CREDSSP_CONTEXT* context = NULL; + SSPI_CREDENTIALS* credentials = NULL; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = (CREDSSP_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + { + union + { + const void* cpv; + void* pv; + } cnv; + context = credssp_ContextNew(); + + if (!context) + return SEC_E_INSUFFICIENT_MEMORY; + + credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + { + credssp_ContextFree(context); + return SEC_E_INVALID_HANDLE; + } + + sspi_SecureHandleSetLowerPointer(phNewContext, context); + + cnv.cpv = CREDSSP_PACKAGE_NAME; + sspi_SecureHandleSetUpperPointer(phNewContext, cnv.pv); + } + + return SEC_E_OK; +} + +CREDSSP_CONTEXT* credssp_ContextNew(void) +{ + CREDSSP_CONTEXT* context = NULL; + context = (CREDSSP_CONTEXT*)calloc(1, sizeof(CREDSSP_CONTEXT)); + + if (!context) + return NULL; + + return context; +} + +void credssp_ContextFree(CREDSSP_CONTEXT* context) +{ + free(context); +} + +static SECURITY_STATUS SEC_ENTRY credssp_QueryContextAttributes(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + if (!phContext) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INSUFFICIENT_MEMORY; + + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SSPI_CREDENTIALS* credentials = NULL; + SEC_WINNT_AUTH_IDENTITY* identity = NULL; + + if (fCredentialUse == SECPKG_CRED_OUTBOUND) + { + union + { + const void* cpv; + void* pv; + } cnv; + credentials = sspi_CredentialsNew(); + + if (!credentials) + return SEC_E_INSUFFICIENT_MEMORY; + + identity = (SEC_WINNT_AUTH_IDENTITY*)pAuthData; + CopyMemory(&(credentials->identity), identity, sizeof(SEC_WINNT_AUTH_IDENTITY)); + sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials); + + cnv.cpv = CREDSSP_PACKAGE_NAME; + sspi_SecureHandleSetUpperPointer(phCredential, cnv.pv); + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + if (ulAttribute == SECPKG_CRED_ATTR_NAMES) + { + SSPI_CREDENTIALS* credentials = + (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + return SEC_E_INVALID_HANDLE; + + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_FreeCredentialsHandle(PCredHandle phCredential) +{ + SSPI_CREDENTIALS* credentials = NULL; + + if (!phCredential) + return SEC_E_INVALID_HANDLE; + + credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + return SEC_E_INVALID_HANDLE; + + sspi_CredentialsFree(credentials); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY credssp_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + ULONG* pfQOP) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY credssp_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +const SecurityFunctionTableA CREDSSP_SecurityFunctionTableA = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + credssp_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + credssp_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + credssp_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + credssp_InitializeSecurityContextA, /* InitializeSecurityContext */ + NULL, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + NULL, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + credssp_QueryContextAttributes, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + credssp_MakeSignature, /* MakeSignature */ + credssp_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + credssp_EncryptMessage, /* EncryptMessage */ + credssp_DecryptMessage, /* DecryptMessage */ + NULL, /* SetContextAttributes */ + NULL, /* SetCredentialsAttributes */ +}; + +const SecurityFunctionTableW CREDSSP_SecurityFunctionTableW = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + credssp_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + credssp_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + credssp_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + credssp_InitializeSecurityContextW, /* InitializeSecurityContext */ + NULL, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + NULL, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + credssp_QueryContextAttributes, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + credssp_MakeSignature, /* MakeSignature */ + credssp_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + credssp_EncryptMessage, /* EncryptMessage */ + credssp_DecryptMessage, /* DecryptMessage */ + NULL, /* SetContextAttributes */ + NULL, /* SetCredentialsAttributes */ +}; + +const SecPkgInfoA CREDSSP_SecPkgInfoA = { + 0x000110733, /* fCapabilities */ + 1, /* wVersion */ + 0xFFFF, /* wRPCID */ + 0x000090A8, /* cbMaxToken */ + "CREDSSP", /* Name */ + "Microsoft CredSSP Security Provider" /* Comment */ +}; + +static WCHAR CREDSSP_SecPkgInfoW_NameBuffer[128] = { 0 }; +static WCHAR CREDSSP_SecPkgInfoW_CommentBuffer[128] = { 0 }; + +const SecPkgInfoW CREDSSP_SecPkgInfoW = { + 0x000110733, /* fCapabilities */ + 1, /* wVersion */ + 0xFFFF, /* wRPCID */ + 0x000090A8, /* cbMaxToken */ + CREDSSP_SecPkgInfoW_NameBuffer, /* Name */ + CREDSSP_SecPkgInfoW_CommentBuffer /* Comment */ +}; + +BOOL CREDSSP_init(void) +{ + InitializeConstWCharFromUtf8(CREDSSP_SecPkgInfoA.Name, CREDSSP_SecPkgInfoW_NameBuffer, + ARRAYSIZE(CREDSSP_SecPkgInfoW_NameBuffer)); + InitializeConstWCharFromUtf8(CREDSSP_SecPkgInfoA.Comment, CREDSSP_SecPkgInfoW_CommentBuffer, + ARRAYSIZE(CREDSSP_SecPkgInfoW_CommentBuffer)); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.h new file mode 100644 index 0000000000000000000000000000000000000000..39c8fe991f7f024b7b53945e6c8e4f19417d4e37 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/CredSSP/credssp.h @@ -0,0 +1,42 @@ +/** + * WinPR: Windows Portable Runtime + * Credential Security Support Provider (CredSSP) + * + * Copyright 2010-2012 Marc-Andre Moreau + * + * 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_CREDSSP_PRIVATE_H +#define WINPR_SSPI_CREDSSP_PRIVATE_H + +#include + +#include "../sspi.h" + +typedef struct +{ + BOOL server; +} CREDSSP_CONTEXT; + +CREDSSP_CONTEXT* credssp_ContextNew(void); +void credssp_ContextFree(CREDSSP_CONTEXT* context); + +extern const SecPkgInfoA CREDSSP_SecPkgInfoA; +extern const SecPkgInfoW CREDSSP_SecPkgInfoW; +extern const SecurityFunctionTableA CREDSSP_SecurityFunctionTableA; +extern const SecurityFunctionTableW CREDSSP_SecurityFunctionTableW; + +BOOL CREDSSP_init(void); + +#endif /* WINPR_SSPI_CREDSSP_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.c new file mode 100644 index 0000000000000000000000000000000000000000..61e8e4e68d8d07663c930df3a9abfc6a63111496 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.c @@ -0,0 +1,2226 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * Kerberos Auth Protocol + * + * Copyright 2015 ANSSI, Author Thomas Calderon + * Copyright 2017 Dorian Ducournau + * Copyright 2022 David Fort + * Copyright 2022 Isaac Klein + * + * 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 + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kerberos.h" + +#ifdef WITH_KRB5_MIT +#include "krb5glue.h" +#include +#endif + +#ifdef WITH_KRB5_HEIMDAL +#include "krb5glue.h" +#include +#endif + +#include "../sspi.h" +#include "../../log.h" +#define TAG WINPR_TAG("sspi.Kerberos") + +#define KRB_TGT_REQ 16 +#define KRB_TGT_REP 17 + +const SecPkgInfoA KERBEROS_SecPkgInfoA = { + 0x000F3BBF, /* fCapabilities */ + 1, /* wVersion */ + 0x0010, /* wRPCID */ + 0x0000BB80, /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */ + "Kerberos", /* Name */ + "Kerberos Security Package" /* Comment */ +}; + +static WCHAR KERBEROS_SecPkgInfoW_NameBuffer[32] = { 0 }; +static WCHAR KERBEROS_SecPkgInfoW_CommentBuffer[32] = { 0 }; + +const SecPkgInfoW KERBEROS_SecPkgInfoW = { + 0x000F3BBF, /* fCapabilities */ + 1, /* wVersion */ + 0x0010, /* wRPCID */ + 0x0000BB80, /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */ + KERBEROS_SecPkgInfoW_NameBuffer, /* Name */ + KERBEROS_SecPkgInfoW_CommentBuffer /* Comment */ +}; + +#ifdef WITH_KRB5 + +enum KERBEROS_STATE +{ + KERBEROS_STATE_INITIAL, + KERBEROS_STATE_TGT_REQ, + KERBEROS_STATE_TGT_REP, + KERBEROS_STATE_AP_REQ, + KERBEROS_STATE_AP_REP, + KERBEROS_STATE_FINAL +}; + +typedef struct KRB_CREDENTIALS_st +{ + volatile LONG refCount; + krb5_context ctx; + char* kdc_url; + krb5_ccache ccache; + krb5_keytab keytab; + krb5_keytab client_keytab; + BOOL own_ccache; /**< Whether we created ccache, and must destroy it after use. */ +} KRB_CREDENTIALS; + +struct s_KRB_CONTEXT +{ + enum KERBEROS_STATE state; + KRB_CREDENTIALS* credentials; + krb5_auth_context auth_ctx; + BOOL acceptor; + uint32_t flags; + uint64_t local_seq; + uint64_t remote_seq; + struct krb5glue_keyset keyset; + BOOL u2u; + char* targetHost; +}; + +static const WinPrAsn1_OID kerberos_OID = { 9, (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; +static const WinPrAsn1_OID kerberos_u2u_OID = { 10, + (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x03" }; + +#define krb_log_exec_bool(fkt, ctx, ...) \ + kerberos_log_msg(ctx, fkt(ctx, ##__VA_ARGS__) ? KRB5KRB_ERR_GENERIC : 0, #fkt, __FILE__, \ + __func__, __LINE__) +#define krb_log_exec(fkt, ctx, ...) \ + kerberos_log_msg(ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__) +#define krb_log_exec_ptr(fkt, ctx, ...) \ + kerberos_log_msg(*ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__) +static krb5_error_code kerberos_log_msg(krb5_context ctx, krb5_error_code code, const char* what, + const char* file, const char* fkt, size_t line) +{ + switch (code) + { + case 0: + case KRB5_KT_END: + break; + default: + { + const DWORD level = WLOG_ERROR; + + wLog* log = WLog_Get(TAG); + if (WLog_IsLevelActive(log, level)) + { + const char* msg = krb5_get_error_message(ctx, code); + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, level, line, file, fkt, "%s (%s [%d])", + what, msg, code); + krb5_free_error_message(ctx, msg); + } + } + break; + } + return code; +} + +static void credentials_unref(KRB_CREDENTIALS* credentials); + +static void kerberos_ContextFree(KRB_CONTEXT* ctx, BOOL allocated) +{ + if (!ctx) + return; + + free(ctx->targetHost); + ctx->targetHost = NULL; + + if (ctx->credentials) + { + krb5_context krbctx = ctx->credentials->ctx; + if (krbctx) + { + if (ctx->auth_ctx) + krb5_auth_con_free(krbctx, ctx->auth_ctx); + + krb5glue_keys_free(krbctx, &ctx->keyset); + } + + credentials_unref(ctx->credentials); + } + + if (allocated) + free(ctx); +} + +static KRB_CONTEXT* kerberos_ContextNew(KRB_CREDENTIALS* credentials) +{ + KRB_CONTEXT* context = NULL; + + context = (KRB_CONTEXT*)calloc(1, sizeof(KRB_CONTEXT)); + if (!context) + return NULL; + + context->credentials = credentials; + InterlockedIncrement(&credentials->refCount); + return context; +} + +static krb5_error_code krb5_prompter(krb5_context context, void* data, const char* name, + const char* banner, int num_prompts, krb5_prompt prompts[]) +{ + for (int i = 0; i < num_prompts; i++) + { + krb5_prompt_type type = krb5glue_get_prompt_type(context, prompts, i); + if (type && (type == KRB5_PROMPT_TYPE_PREAUTH || type == KRB5_PROMPT_TYPE_PASSWORD) && data) + { + prompts[i].reply->data = _strdup((const char*)data); + + const size_t len = strlen((const char*)data); + if (len > UINT32_MAX) + return KRB5KRB_ERR_GENERIC; + prompts[i].reply->length = (UINT32)len; + } + } + return 0; +} + +static INLINE krb5glue_key get_key(struct krb5glue_keyset* keyset) +{ + return keyset->acceptor_key ? keyset->acceptor_key + : keyset->initiator_key ? keyset->initiator_key + : keyset->session_key; +} + +static BOOL isValidIPv4(const char* ipAddress) +{ + struct sockaddr_in sa = { 0 }; + int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr)); + return result != 0; +} + +static BOOL isValidIPv6(const char* ipAddress) +{ + struct sockaddr_in6 sa = { 0 }; + int result = inet_pton(AF_INET6, ipAddress, &(sa.sin6_addr)); + return result != 0; +} + +static BOOL isValidIP(const char* ipAddress) +{ + return isValidIPv4(ipAddress) || isValidIPv6(ipAddress); +} + +static int build_krbtgt(krb5_context ctx, krb5_data* realm, krb5_principal* ptarget) +{ + /* "krbtgt/" + realm + "@" + realm */ + size_t len = 0; + char* name = NULL; + krb5_error_code rv = KRB5_CC_NOMEM; + + (void)winpr_asprintf(&name, &len, "krbtgt/%s@%s", realm->data, realm->data); + if (!name || (len == 0)) + goto fail; + + krb5_principal target = { 0 }; + rv = krb5_parse_name(ctx, name, &target); + *ptarget = target; +fail: + free(name); + return rv; +} + +#endif /* WITH_KRB5 */ + +static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ +#ifdef WITH_KRB5 + SEC_WINPR_KERBEROS_SETTINGS* krb_settings = NULL; + KRB_CREDENTIALS* credentials = NULL; + krb5_context ctx = NULL; + krb5_ccache ccache = NULL; + krb5_keytab keytab = NULL; + krb5_principal principal = NULL; + char* domain = NULL; + char* username = NULL; + char* password = NULL; + BOOL own_ccache = FALSE; + const char* const default_ccache_type = "MEMORY"; + + if (pAuthData) + { + UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData); + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED) + krb_settings = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->kerberosSettings); + + if (!sspi_CopyAuthIdentityFieldsA((const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData, &username, + &domain, &password)) + { + WLog_ERR(TAG, "Failed to copy auth identity fields"); + goto cleanup; + } + + if (!pszPrincipal) + pszPrincipal = username; + } + + if (krb_log_exec_ptr(krb5_init_context, &ctx)) + goto cleanup; + + if (domain) + { + char* udomain = _strdup(domain); + if (!udomain) + goto cleanup; + + CharUpperA(udomain); + /* Will use domain if realm is not specified in username */ + krb5_error_code rv = krb_log_exec(krb5_set_default_realm, ctx, udomain); + free(udomain); + + if (rv) + goto cleanup; + } + + if (pszPrincipal) + { + char* cpszPrincipal = _strdup(pszPrincipal); + if (!cpszPrincipal) + goto cleanup; + + /* Find realm component if included and convert to uppercase */ + char* p = strchr(cpszPrincipal, '@'); + if (p) + CharUpperA(p); + + krb5_error_code rv = krb_log_exec(krb5_parse_name, ctx, cpszPrincipal, &principal); + free(cpszPrincipal); + + if (rv) + goto cleanup; + } + + if (krb_settings && krb_settings->cache) + { + if ((krb_log_exec(krb5_cc_set_default_name, ctx, krb_settings->cache))) + goto cleanup; + } + else + own_ccache = TRUE; + + if (principal) + { + /* Use the default cache if it's initialized with the right principal */ + if (krb5_cc_cache_match(ctx, principal, &ccache) == KRB5_CC_NOTFOUND) + { + if (own_ccache) + { + if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache)) + goto cleanup; + } + else + { + if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache)) + goto cleanup; + } + + if (krb_log_exec(krb5_cc_initialize, ctx, ccache, principal)) + goto cleanup; + } + else + own_ccache = FALSE; + } + else if (fCredentialUse & SECPKG_CRED_OUTBOUND) + { + /* Use the default cache with it's default principal */ + if (krb_log_exec(krb5_cc_default, ctx, &ccache)) + goto cleanup; + if (krb_log_exec(krb5_cc_get_principal, ctx, ccache, &principal)) + goto cleanup; + own_ccache = FALSE; + } + else + { + if (own_ccache) + { + if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache)) + goto cleanup; + } + else + { + if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache)) + goto cleanup; + } + } + + if (krb_settings && krb_settings->keytab) + { + if (krb_log_exec(krb5_kt_resolve, ctx, krb_settings->keytab, &keytab)) + goto cleanup; + } + else + { + if (fCredentialUse & SECPKG_CRED_INBOUND) + if (krb_log_exec(krb5_kt_default, ctx, &keytab)) + goto cleanup; + } + + /* Get initial credentials if required */ + if (fCredentialUse & SECPKG_CRED_OUTBOUND) + { + krb5_creds creds = { 0 }; + krb5_creds matchCreds = { 0 }; + krb5_flags matchFlags = KRB5_TC_MATCH_TIMES; + + krb5_timeofday(ctx, &matchCreds.times.endtime); + matchCreds.times.endtime += 60; + matchCreds.client = principal; + + if (krb_log_exec(build_krbtgt, ctx, &principal->realm, &matchCreds.server)) + goto cleanup; + + int rv = krb5_cc_retrieve_cred(ctx, ccache, matchFlags, &matchCreds, &creds); + krb5_free_principal(ctx, matchCreds.server); + krb5_free_cred_contents(ctx, &creds); + if (rv) + { + if (krb_log_exec(krb5glue_get_init_creds, ctx, principal, ccache, krb5_prompter, + password, krb_settings)) + goto cleanup; + } + } + + credentials = calloc(1, sizeof(KRB_CREDENTIALS)); + if (!credentials) + goto cleanup; + credentials->refCount = 1; + credentials->ctx = ctx; + credentials->ccache = ccache; + credentials->keytab = keytab; + credentials->own_ccache = own_ccache; + +cleanup: + + free(domain); + free(username); + free(password); + + if (principal) + krb5_free_principal(ctx, principal); + if (ctx) + { + if (!credentials) + { + if (ccache) + { + if (own_ccache) + krb5_cc_destroy(ctx, ccache); + else + krb5_cc_close(ctx, ccache); + } + if (keytab) + krb5_kt_close(ctx, keytab); + + krb5_free_context(ctx); + } + } + + /* If we managed to get credentials set the output */ + if (credentials) + { + sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)KERBEROS_SSP_NAME); + return SEC_E_OK; + } + + return SEC_E_NO_CREDENTIALS; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY; + char* principal = NULL; + char* package = NULL; + + if (pszPrincipal) + { + principal = ConvertWCharToUtf8Alloc(pszPrincipal, NULL); + if (!principal) + goto fail; + } + if (pszPackage) + { + package = ConvertWCharToUtf8Alloc(pszPackage, NULL); + if (!package) + goto fail; + } + + status = + kerberos_AcquireCredentialsHandleA(principal, package, fCredentialUse, pvLogonID, pAuthData, + pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); + +fail: + free(principal); + free(package); + + return status; +} + +#ifdef WITH_KRB5 +static void credentials_unref(KRB_CREDENTIALS* credentials) +{ + WINPR_ASSERT(credentials); + + if (InterlockedDecrement(&credentials->refCount)) + return; + + free(credentials->kdc_url); + + if (credentials->ccache) + { + if (credentials->own_ccache) + krb5_cc_destroy(credentials->ctx, credentials->ccache); + else + krb5_cc_close(credentials->ctx, credentials->ccache); + } + if (credentials->keytab) + krb5_kt_close(credentials->ctx, credentials->keytab); + + krb5_free_context(credentials->ctx); + free(credentials); +} +#endif + +static SECURITY_STATUS SEC_ENTRY kerberos_FreeCredentialsHandle(PCredHandle phCredential) +{ +#ifdef WITH_KRB5 + KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential); + if (!credentials) + return SEC_E_INVALID_HANDLE; + + credentials_unref(credentials); + + sspi_SecureHandleInvalidate(phCredential); + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ +#ifdef WITH_KRB5 + switch (ulAttribute) + { + case SECPKG_CRED_ATTR_NAMES: + return SEC_E_OK; + default: + WLog_ERR(TAG, "TODO: QueryCredentialsAttributesW, implement ulAttribute=%08" PRIx32, + ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; + } + +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + return kerberos_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); +} + +#ifdef WITH_KRB5 + +static BOOL kerberos_mk_tgt_token(SecBuffer* buf, int msg_type, char* sname, char* host, + const krb5_data* ticket) +{ + WinPrAsn1Encoder* enc = NULL; + WinPrAsn1_MemoryChunk data; + wStream s; + size_t len = 0; + sspi_gss_data token; + BOOL ret = FALSE; + + WINPR_ASSERT(buf); + + if (msg_type != KRB_TGT_REQ && msg_type != KRB_TGT_REP) + return FALSE; + if (msg_type == KRB_TGT_REP && !ticket) + return FALSE; + + enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER); + if (!enc) + return FALSE; + + /* KERB-TGT-REQUEST (SEQUENCE) */ + if (!WinPrAsn1EncSeqContainer(enc)) + goto cleanup; + + /* pvno [0] INTEGER */ + if (!WinPrAsn1EncContextualInteger(enc, 0, 5)) + goto cleanup; + + /* msg-type [1] INTEGER */ + if (!WinPrAsn1EncContextualInteger(enc, 1, msg_type)) + goto cleanup; + + if (msg_type == KRB_TGT_REQ && sname) + { + /* server-name [2] PrincipalName (SEQUENCE) */ + if (!WinPrAsn1EncContextualSeqContainer(enc, 2)) + goto cleanup; + + /* name-type [0] INTEGER */ + if (!WinPrAsn1EncContextualInteger(enc, 0, KRB5_NT_SRV_HST)) + goto cleanup; + + /* name-string [1] SEQUENCE OF GeneralString */ + if (!WinPrAsn1EncContextualSeqContainer(enc, 1)) + goto cleanup; + + if (!WinPrAsn1EncGeneralString(enc, sname)) + goto cleanup; + + if (host && !WinPrAsn1EncGeneralString(enc, host)) + goto cleanup; + + if (!WinPrAsn1EncEndContainer(enc) || !WinPrAsn1EncEndContainer(enc)) + goto cleanup; + } + else if (msg_type == KRB_TGT_REP) + { + /* ticket [2] Ticket */ + data.data = (BYTE*)ticket->data; + data.len = ticket->length; + if (!WinPrAsn1EncContextualRawContent(enc, 2, &data)) + goto cleanup; + } + + if (!WinPrAsn1EncEndContainer(enc)) + goto cleanup; + + if (!WinPrAsn1EncStreamSize(enc, &len) || len > buf->cbBuffer) + goto cleanup; + + Stream_StaticInit(&s, buf->pvBuffer, len); + if (!WinPrAsn1EncToStream(enc, &s)) + goto cleanup; + + token.data = buf->pvBuffer; + token.length = (UINT)len; + if (sspi_gss_wrap_token(buf, &kerberos_u2u_OID, + msg_type == KRB_TGT_REQ ? TOK_ID_TGT_REQ : TOK_ID_TGT_REP, &token)) + ret = TRUE; + +cleanup: + WinPrAsn1Encoder_Free(&enc); + return ret; +} + +static BOOL append(char* dst, size_t dstSize, const char* src) +{ + const size_t dlen = strnlen(dst, dstSize); + const size_t slen = strlen(src); + if (dlen + slen >= dstSize) + return FALSE; + if (!strncat(dst, src, slen)) + return FALSE; + return TRUE; +} + +static BOOL kerberos_rd_tgt_req_tag2(WinPrAsn1Decoder* dec, char* buf, size_t len) +{ + BOOL rc = FALSE; + WinPrAsn1Decoder seq = { 0 }; + + /* server-name [2] PrincipalName (SEQUENCE) */ + if (!WinPrAsn1DecReadSequence(dec, &seq)) + goto end; + + /* name-type [0] INTEGER */ + BOOL error = FALSE; + WinPrAsn1_INTEGER val = 0; + if (!WinPrAsn1DecReadContextualInteger(&seq, 0, &error, &val)) + goto end; + + /* name-string [1] SEQUENCE OF GeneralString */ + if (!WinPrAsn1DecReadContextualSequence(&seq, 1, &error, dec)) + goto end; + + WinPrAsn1_tag tag = 0; + BOOL first = TRUE; + while (WinPrAsn1DecPeekTag(dec, &tag)) + { + BOOL success = FALSE; + char* lstr = NULL; + if (!WinPrAsn1DecReadGeneralString(dec, &lstr)) + goto fail; + + if (!first) + { + if (!append(buf, len, "/")) + goto fail; + } + first = FALSE; + + if (!append(buf, len, lstr)) + goto fail; + + success = TRUE; + fail: + free(lstr); + if (!success) + goto end; + } + + rc = TRUE; +end: + return rc; +} + +static BOOL kerberos_rd_tgt_req_tag3(WinPrAsn1Decoder* dec, char* buf, size_t len) +{ + /* realm [3] Realm */ + BOOL rc = FALSE; + WinPrAsn1_STRING str = NULL; + if (!WinPrAsn1DecReadGeneralString(dec, &str)) + goto end; + + if (!append(buf, len, "@")) + goto end; + if (!append(buf, len, str)) + goto end; + + rc = TRUE; +end: + free(str); + return rc; +} + +static BOOL kerberos_rd_tgt_req(WinPrAsn1Decoder* dec, char** target) +{ + BOOL rc = FALSE; + + if (!target) + return FALSE; + *target = NULL; + + wStream s = WinPrAsn1DecGetStream(dec); + const size_t len = Stream_Length(&s); + if (len == 0) + return TRUE; + + WinPrAsn1Decoder dec2 = { 0 }; + WinPrAsn1_tagId tag = 0; + if (WinPrAsn1DecReadContextualTag(dec, &tag, &dec2) == 0) + return FALSE; + + char* buf = calloc(len + 1, sizeof(char)); + if (!buf) + return FALSE; + + /* We expect ASN1 context tag values 2 or 3. + * + * In case we got value 2 an (optional) context tag value 3 might follow. + */ + BOOL checkForTag3 = TRUE; + if (tag == 2) + { + rc = kerberos_rd_tgt_req_tag2(&dec2, buf, len); + if (rc) + { + const size_t res = WinPrAsn1DecReadContextualTag(dec, &tag, dec); + if (res == 0) + checkForTag3 = FALSE; + } + } + + if (checkForTag3) + { + if (tag == 3) + rc = kerberos_rd_tgt_req_tag3(&dec2, buf, len); + else + rc = FALSE; + } + + if (rc) + *target = buf; + else + free(buf); + return rc; +} + +static BOOL kerberos_rd_tgt_rep(WinPrAsn1Decoder* dec, krb5_data* ticket) +{ + if (!ticket) + return FALSE; + + /* ticket [2] Ticket */ + WinPrAsn1Decoder asnTicket = { 0 }; + WinPrAsn1_tagId tag = 0; + if (WinPrAsn1DecReadContextualTag(dec, &tag, &asnTicket) == 0) + return FALSE; + + if (tag != 2) + return FALSE; + + wStream s = WinPrAsn1DecGetStream(&asnTicket); + ticket->data = Stream_BufferAs(&s, char); + + const size_t len = Stream_Length(&s); + if (len > UINT32_MAX) + return FALSE; + ticket->length = (UINT32)len; + return TRUE; +} + +static BOOL kerberos_rd_tgt_token(const sspi_gss_data* token, char** target, krb5_data* ticket) +{ + BOOL error = 0; + WinPrAsn1_INTEGER val = 0; + + WINPR_ASSERT(token); + + if (target) + *target = NULL; + + WinPrAsn1Decoder der = { 0 }; + WinPrAsn1Decoder_InitMem(&der, WINPR_ASN1_DER, (BYTE*)token->data, token->length); + + /* KERB-TGT-REQUEST (SEQUENCE) */ + WinPrAsn1Decoder seq = { 0 }; + if (!WinPrAsn1DecReadSequence(&der, &seq)) + return FALSE; + + /* pvno [0] INTEGER */ + if (!WinPrAsn1DecReadContextualInteger(&seq, 0, &error, &val) || val != 5) + return FALSE; + + /* msg-type [1] INTEGER */ + if (!WinPrAsn1DecReadContextualInteger(&seq, 1, &error, &val)) + return FALSE; + + switch (val) + { + case KRB_TGT_REQ: + return kerberos_rd_tgt_req(&seq, target); + case KRB_TGT_REP: + return kerberos_rd_tgt_rep(&seq, ticket); + default: + break; + } + return FALSE; +} + +#endif /* WITH_KRB5 */ + +static BOOL kerberos_hash_channel_bindings(WINPR_DIGEST_CTX* md5, SEC_CHANNEL_BINDINGS* bindings) +{ + BYTE buf[4]; + + winpr_Data_Write_UINT32(buf, bindings->dwInitiatorAddrType); + if (!winpr_Digest_Update(md5, buf, 4)) + return FALSE; + + winpr_Data_Write_UINT32(buf, bindings->cbInitiatorLength); + if (!winpr_Digest_Update(md5, buf, 4)) + return FALSE; + + if (bindings->cbInitiatorLength && + !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwInitiatorOffset, + bindings->cbInitiatorLength)) + return FALSE; + + winpr_Data_Write_UINT32(buf, bindings->dwAcceptorAddrType); + if (!winpr_Digest_Update(md5, buf, 4)) + return FALSE; + + winpr_Data_Write_UINT32(buf, bindings->cbAcceptorLength); + if (!winpr_Digest_Update(md5, buf, 4)) + return FALSE; + + if (bindings->cbAcceptorLength && + !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwAcceptorOffset, + bindings->cbAcceptorLength)) + return FALSE; + + winpr_Data_Write_UINT32(buf, bindings->cbApplicationDataLength); + if (!winpr_Digest_Update(md5, buf, 4)) + return FALSE; + + if (bindings->cbApplicationDataLength && + !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwApplicationDataOffset, + bindings->cbApplicationDataLength)) + return FALSE; + + return TRUE; +} + +static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, PTimeStamp ptsExpiry) +{ +#ifdef WITH_KRB5 + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + PSecBuffer bindings_buffer = NULL; + WINPR_DIGEST_CTX* md5 = NULL; + char* target = NULL; + char* sname = NULL; + char* host = NULL; + krb5_data input_token = { 0 }; + krb5_data output_token = { 0 }; + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + WinPrAsn1_OID oid = { 0 }; + uint16_t tok_id = 0; + krb5_ap_rep_enc_part* reply = NULL; + krb5_flags ap_flags = AP_OPTS_USE_SUBKEY; + char cksum_contents[24] = { 0 }; + krb5_data cksum = { 0 }; + krb5_creds in_creds = { 0 }; + krb5_creds* creds = NULL; + BOOL isNewContext = FALSE; + KRB_CONTEXT* context = NULL; + KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential); + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = sspi_SecureHandleGetLowerPointer(phContext); + + if (!credentials) + return SEC_E_NO_CREDENTIALS; + + if (pInput) + { + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + bindings_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS); + } + if (pOutput) + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (fContextReq & ISC_REQ_MUTUAL_AUTH) + ap_flags |= AP_OPTS_MUTUAL_REQUIRED; + + if (fContextReq & ISC_REQ_USE_SESSION_KEY) + ap_flags |= AP_OPTS_USE_SESSION_KEY; + + /* Split target name into service/hostname components */ + if (pszTargetName) + { + target = _strdup(pszTargetName); + if (!target) + { + status = SEC_E_INSUFFICIENT_MEMORY; + goto cleanup; + } + host = strchr(target, '/'); + if (host) + { + *host++ = 0; + sname = target; + } + else + host = target; + if (isValidIP(host)) + { + status = SEC_E_NO_CREDENTIALS; + goto cleanup; + } + } + + if (!context) + { + context = kerberos_ContextNew(credentials); + if (!context) + { + status = SEC_E_INSUFFICIENT_MEMORY; + goto cleanup; + } + + isNewContext = TRUE; + + if (host) + context->targetHost = _strdup(host); + if (!context->targetHost) + { + status = SEC_E_INSUFFICIENT_MEMORY; + goto cleanup; + } + + if (fContextReq & ISC_REQ_USE_SESSION_KEY) + { + context->state = KERBEROS_STATE_TGT_REQ; + context->u2u = TRUE; + } + else + context->state = KERBEROS_STATE_AP_REQ; + } + else + { + if (!input_buffer || !sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token)) + goto bad_token; + if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) || + (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID))) + goto bad_token; + } + + /* SSPI flags are compatible with GSS flags except INTEG_FLAG */ + context->flags |= (fContextReq & 0x1F); + if ((fContextReq & ISC_REQ_INTEGRITY) && !(fContextReq & ISC_REQ_NO_INTEGRITY)) + context->flags |= SSPI_GSS_C_INTEG_FLAG; + + switch (context->state) + { + case KERBEROS_STATE_TGT_REQ: + + if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REQ, sname, host, NULL)) + goto cleanup; + + context->state = KERBEROS_STATE_TGT_REP; + status = SEC_I_CONTINUE_NEEDED; + break; + + case KERBEROS_STATE_TGT_REP: + + if (tok_id != TOK_ID_TGT_REP) + goto bad_token; + + if (!kerberos_rd_tgt_token(&input_token, NULL, &in_creds.second_ticket)) + goto bad_token; + + /* Continue to AP-REQ */ + /* fallthrough */ + WINPR_FALLTHROUGH + + case KERBEROS_STATE_AP_REQ: + + /* Set auth_context options */ + if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &context->auth_ctx)) + goto cleanup; + if (krb_log_exec(krb5_auth_con_setflags, credentials->ctx, context->auth_ctx, + KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY)) + goto cleanup; + if (krb_log_exec(krb5glue_auth_con_set_cksumtype, credentials->ctx, context->auth_ctx, + GSS_CHECKSUM_TYPE)) + goto cleanup; + + /* Get a service ticket */ + if (krb_log_exec(krb5_sname_to_principal, credentials->ctx, host, sname, + KRB5_NT_SRV_HST, &in_creds.server)) + goto cleanup; + + if (krb_log_exec(krb5_cc_get_principal, credentials->ctx, credentials->ccache, + &in_creds.client)) + { + status = SEC_E_WRONG_PRINCIPAL; + goto cleanup; + } + + if (krb_log_exec(krb5_get_credentials, credentials->ctx, + context->u2u ? KRB5_GC_USER_USER : 0, credentials->ccache, &in_creds, + &creds)) + { + status = SEC_E_NO_CREDENTIALS; + goto cleanup; + } + + /* Write the checksum (delegation not implemented) */ + cksum.data = cksum_contents; + cksum.length = sizeof(cksum_contents); + winpr_Data_Write_UINT32(cksum_contents, 16); + winpr_Data_Write_UINT32((cksum_contents + 20), context->flags); + + if (bindings_buffer) + { + SEC_CHANNEL_BINDINGS* bindings = bindings_buffer->pvBuffer; + + /* Sanity checks */ + if (bindings_buffer->cbBuffer < sizeof(SEC_CHANNEL_BINDINGS) || + (bindings->cbInitiatorLength + bindings->dwInitiatorOffset) > + bindings_buffer->cbBuffer || + (bindings->cbAcceptorLength + bindings->dwAcceptorOffset) > + bindings_buffer->cbBuffer || + (bindings->cbApplicationDataLength + bindings->dwApplicationDataOffset) > + bindings_buffer->cbBuffer) + { + status = SEC_E_BAD_BINDINGS; + goto cleanup; + } + + md5 = winpr_Digest_New(); + if (!md5) + goto cleanup; + + if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) + goto cleanup; + + if (!kerberos_hash_channel_bindings(md5, bindings)) + goto cleanup; + + if (!winpr_Digest_Final(md5, (BYTE*)cksum_contents + 4, 16)) + goto cleanup; + } + + /* Make the AP_REQ message */ + if (krb_log_exec(krb5_mk_req_extended, credentials->ctx, &context->auth_ctx, ap_flags, + &cksum, creds, &output_token)) + goto cleanup; + + if (!sspi_gss_wrap_token(output_buffer, + context->u2u ? &kerberos_u2u_OID : &kerberos_OID, + TOK_ID_AP_REQ, &output_token)) + goto cleanup; + + if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG) + { + if (krb_log_exec(krb5_auth_con_getlocalseqnumber, credentials->ctx, + context->auth_ctx, (INT32*)&context->local_seq)) + goto cleanup; + context->remote_seq ^= context->local_seq; + } + + if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, FALSE, + &context->keyset)) + goto cleanup; + + context->state = KERBEROS_STATE_AP_REP; + + if (context->flags & SSPI_GSS_C_MUTUAL_FLAG) + status = SEC_I_CONTINUE_NEEDED; + else + status = SEC_E_OK; + break; + + case KERBEROS_STATE_AP_REP: + + if (tok_id == TOK_ID_AP_REP) + { + if (krb_log_exec(krb5_rd_rep, credentials->ctx, context->auth_ctx, &input_token, + &reply)) + goto cleanup; + krb5_free_ap_rep_enc_part(credentials->ctx, reply); + } + else if (tok_id == TOK_ID_ERROR) + { + krb5glue_log_error(credentials->ctx, &input_token, TAG); + goto cleanup; + } + else + goto bad_token; + + if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG) + { + if (krb_log_exec(krb5_auth_con_getremoteseqnumber, credentials->ctx, + context->auth_ctx, (INT32*)&context->remote_seq)) + goto cleanup; + } + + if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, FALSE, + &context->keyset)) + goto cleanup; + + context->state = KERBEROS_STATE_FINAL; + + if (output_buffer) + output_buffer->cbBuffer = 0; + status = SEC_E_OK; + break; + + case KERBEROS_STATE_FINAL: + default: + WLog_ERR(TAG, "Kerberos in invalid state!"); + goto cleanup; + } + +cleanup: +{ + /* second_ticket is not allocated */ + krb5_data edata = { 0 }; + in_creds.second_ticket = edata; + krb5_free_cred_contents(credentials->ctx, &in_creds); +} + + krb5_free_creds(credentials->ctx, creds); + if (output_token.data) + krb5glue_free_data_contents(credentials->ctx, &output_token); + + winpr_Digest_Free(md5); + + free(target); + + if (isNewContext) + { + switch (status) + { + case SEC_E_OK: + case SEC_I_CONTINUE_NEEDED: + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME); + break; + default: + kerberos_ContextFree(context, TRUE); + break; + } + } + + return status; + +bad_token: + status = SEC_E_INVALID_TOKEN; + goto cleanup; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif /* WITH_KRB5 */ +} + +static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + char* target_name = NULL; + + if (pszTargetName) + { + target_name = ConvertWCharToUtf8Alloc(pszTargetName, NULL); + if (!target_name) + return SEC_E_INSUFFICIENT_MEMORY; + } + + status = kerberos_InitializeSecurityContextA(phCredential, phContext, target_name, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); + + if (target_name) + free(target_name); + + return status; +} + +static SECURITY_STATUS SEC_ENTRY kerberos_AcceptSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq, + ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, + PTimeStamp ptsExpity) +{ +#ifdef WITH_KRB5 + BOOL isNewContext = FALSE; + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + WinPrAsn1_OID oid = { 0 }; + uint16_t tok_id = 0; + krb5_data input_token = { 0 }; + krb5_data output_token = { 0 }; + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + krb5_flags ap_flags = 0; + krb5glue_authenticator authenticator = NULL; + char* target = NULL; + char* sname = NULL; + char* realm = NULL; + krb5_kt_cursor cur = { 0 }; + krb5_keytab_entry entry = { 0 }; + krb5_principal principal = NULL; + krb5_creds creds = { 0 }; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + KRB_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext); + KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential); + + if (pInput) + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + if (pOutput) + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!input_buffer) + return SEC_E_INVALID_TOKEN; + + if (!sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token)) + return SEC_E_INVALID_TOKEN; + + if (!context) + { + isNewContext = TRUE; + context = kerberos_ContextNew(credentials); + context->acceptor = TRUE; + + if (sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) + { + context->u2u = TRUE; + context->state = KERBEROS_STATE_TGT_REQ; + } + else if (sspi_gss_oid_compare(&oid, &kerberos_OID)) + context->state = KERBEROS_STATE_AP_REQ; + else + goto bad_token; + } + else + { + if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) || + (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID))) + goto bad_token; + } + + if (context->state == KERBEROS_STATE_TGT_REQ && tok_id == TOK_ID_TGT_REQ) + { + if (!kerberos_rd_tgt_token(&input_token, &target, NULL)) + goto bad_token; + + if (target) + { + if (*target != 0 && *target != '@') + sname = target; + realm = strchr(target, '@'); + if (realm) + realm++; + } + + if (krb_log_exec(krb5_parse_name_flags, credentials->ctx, sname ? sname : "", + KRB5_PRINCIPAL_PARSE_NO_REALM, &principal)) + goto cleanup; + + if (realm) + { + if (krb_log_exec(krb5glue_set_principal_realm, credentials->ctx, principal, realm)) + goto cleanup; + } + + if (krb_log_exec(krb5_kt_start_seq_get, credentials->ctx, credentials->keytab, &cur)) + goto cleanup; + + do + { + krb5_error_code rv = krb_log_exec(krb5_kt_next_entry, credentials->ctx, + credentials->keytab, &entry, &cur); + if (rv == KRB5_KT_END) + break; + if (rv != 0) + goto cleanup; + + if ((!sname || krb_log_exec_bool(krb5_principal_compare_any_realm, credentials->ctx, + principal, entry.principal)) && + (!realm || krb_log_exec_bool(krb5_realm_compare, credentials->ctx, principal, + entry.principal))) + break; + if (krb_log_exec(krb5glue_free_keytab_entry_contents, credentials->ctx, &entry)) + goto cleanup; + } while (1); + + if (krb_log_exec(krb5_kt_end_seq_get, credentials->ctx, credentials->keytab, &cur)) + goto cleanup; + + if (!entry.principal) + goto cleanup; + + /* Get the TGT */ + if (krb_log_exec(krb5_get_init_creds_keytab, credentials->ctx, &creds, entry.principal, + credentials->keytab, 0, NULL, NULL)) + goto cleanup; + + if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REP, NULL, NULL, &creds.ticket)) + goto cleanup; + + if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &context->auth_ctx)) + goto cleanup; + + if (krb_log_exec(krb5glue_auth_con_setuseruserkey, credentials->ctx, context->auth_ctx, + &krb5glue_creds_getkey(creds))) + goto cleanup; + + context->state = KERBEROS_STATE_AP_REQ; + } + else if (context->state == KERBEROS_STATE_AP_REQ && tok_id == TOK_ID_AP_REQ) + { + if (krb_log_exec(krb5_rd_req, credentials->ctx, &context->auth_ctx, &input_token, NULL, + credentials->keytab, &ap_flags, NULL)) + goto cleanup; + + if (krb_log_exec(krb5_auth_con_setflags, credentials->ctx, context->auth_ctx, + KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY)) + goto cleanup; + + /* Retrieve and validate the checksum */ + if (krb_log_exec(krb5_auth_con_getauthenticator, credentials->ctx, context->auth_ctx, + &authenticator)) + goto cleanup; + if (!krb5glue_authenticator_validate_chksum(authenticator, GSS_CHECKSUM_TYPE, + &context->flags)) + goto bad_token; + + if ((ap_flags & AP_OPTS_MUTUAL_REQUIRED) && (context->flags & SSPI_GSS_C_MUTUAL_FLAG)) + { + if (!output_buffer) + goto bad_token; + if (krb_log_exec(krb5_mk_rep, credentials->ctx, context->auth_ctx, &output_token)) + goto cleanup; + if (!sspi_gss_wrap_token(output_buffer, + context->u2u ? &kerberos_u2u_OID : &kerberos_OID, + TOK_ID_AP_REP, &output_token)) + goto cleanup; + } + else + { + if (output_buffer) + output_buffer->cbBuffer = 0; + } + + *pfContextAttr = (context->flags & 0x1F); + if (context->flags & SSPI_GSS_C_INTEG_FLAG) + *pfContextAttr |= ASC_RET_INTEGRITY; + + if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG) + { + if (krb_log_exec(krb5_auth_con_getlocalseqnumber, credentials->ctx, context->auth_ctx, + (INT32*)&context->local_seq)) + goto cleanup; + if (krb_log_exec(krb5_auth_con_getremoteseqnumber, credentials->ctx, context->auth_ctx, + (INT32*)&context->remote_seq)) + goto cleanup; + } + + if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, TRUE, + &context->keyset)) + goto cleanup; + + context->state = KERBEROS_STATE_FINAL; + } + else + goto bad_token; + + /* On first call allocate new context */ + if (context->state == KERBEROS_STATE_FINAL) + status = SEC_E_OK; + else + status = SEC_I_CONTINUE_NEEDED; + +cleanup: + free(target); + if (output_token.data) + krb5glue_free_data_contents(credentials->ctx, &output_token); + if (entry.principal) + krb5glue_free_keytab_entry_contents(credentials->ctx, &entry); + + if (isNewContext) + { + switch (status) + { + case SEC_E_OK: + case SEC_I_CONTINUE_NEEDED: + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME); + break; + default: + kerberos_ContextFree(context, TRUE); + break; + } + } + + return status; + +bad_token: + status = SEC_E_INVALID_TOKEN; + goto cleanup; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif /* WITH_KRB5 */ +} + +#ifdef WITH_KRB5 +static KRB_CONTEXT* get_context(PCtxtHandle phContext) +{ + if (!phContext) + return NULL; + + TCHAR* name = sspi_SecureHandleGetUpperPointer(phContext); + if (!name) + return NULL; + + if (_tcsncmp(KERBEROS_SSP_NAME, name, ARRAYSIZE(KERBEROS_SSP_NAME)) != 0) + return NULL; + return sspi_SecureHandleGetLowerPointer(phContext); +} + +static BOOL copy_krb5_data(krb5_data* data, PUCHAR* ptr, ULONG* psize) +{ + WINPR_ASSERT(data); + WINPR_ASSERT(ptr); + WINPR_ASSERT(psize); + + *ptr = (PUCHAR)malloc(data->length); + if (!*ptr) + return FALSE; + + *psize = data->length; + memcpy(*ptr, data->data, data->length); + return TRUE; +} +#endif + +static SECURITY_STATUS SEC_ENTRY kerberos_DeleteSecurityContext(PCtxtHandle phContext) +{ +#ifdef WITH_KRB5 + KRB_CONTEXT* context = get_context(phContext); + if (!context) + return SEC_E_INVALID_HANDLE; + + kerberos_ContextFree(context, TRUE); + + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +#ifdef WITH_KRB5 + +static SECURITY_STATUS krb5_error_to_SECURITY_STATUS(krb5_error_code code) +{ + switch (code) + { + case 0: + return SEC_E_OK; + default: + return SEC_E_INTERNAL_ERROR; + } +} + +static SECURITY_STATUS kerberos_ATTR_SIZES(KRB_CONTEXT* context, KRB_CREDENTIALS* credentials, + SecPkgContext_Sizes* ContextSizes) +{ + UINT header = 0; + UINT pad = 0; + UINT trailer = 0; + krb5glue_key key = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->auth_ctx); + + /* The MaxTokenSize by default is 12,000 bytes. This has been the default value + * since Windows 2000 SP2 and still remains in Windows 7 and Windows 2008 R2. + * For Windows Server 2012, the default value of the MaxTokenSize registry + * entry is 48,000 bytes.*/ + ContextSizes->cbMaxToken = KERBEROS_SecPkgInfoA.cbMaxToken; + ContextSizes->cbMaxSignature = 0; + ContextSizes->cbBlockSize = 1; + ContextSizes->cbSecurityTrailer = 0; + + key = get_key(&context->keyset); + + if (context->flags & SSPI_GSS_C_CONF_FLAG) + { + krb5_error_code rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, + KRB5_CRYPTO_TYPE_HEADER, &header); + if (rv) + return krb5_error_to_SECURITY_STATUS(rv); + + rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, KRB5_CRYPTO_TYPE_PADDING, + &pad); + if (rv) + return krb5_error_to_SECURITY_STATUS(rv); + + rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, KRB5_CRYPTO_TYPE_TRAILER, + &trailer); + if (rv) + return krb5_error_to_SECURITY_STATUS(rv); + + /* GSS header (= 16 bytes) + encrypted header = 32 bytes */ + ContextSizes->cbSecurityTrailer = header + pad + trailer + 32; + } + + if (context->flags & SSPI_GSS_C_INTEG_FLAG) + { + krb5_error_code rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, + KRB5_CRYPTO_TYPE_CHECKSUM, &ContextSizes->cbMaxSignature); + if (rv) + return krb5_error_to_SECURITY_STATUS(rv); + + ContextSizes->cbMaxSignature += 16; + } + + return SEC_E_OK; +} + +static SECURITY_STATUS kerberos_ATTR_TICKET_LOGON(KRB_CONTEXT* context, + KRB_CREDENTIALS* credentials, + KERB_TICKET_LOGON* ticketLogon) +{ + krb5_creds matchCred = { 0 }; + krb5_auth_context authContext = NULL; + krb5_flags getCredsFlags = KRB5_GC_CACHED; + BOOL firstRun = TRUE; + krb5_creds* hostCred = NULL; + SECURITY_STATUS ret = SEC_E_INSUFFICIENT_MEMORY; + int rv = krb_log_exec(krb5_sname_to_principal, credentials->ctx, context->targetHost, "HOST", + KRB5_NT_SRV_HST, &matchCred.server); + if (rv) + goto out; + + rv = krb_log_exec(krb5_cc_get_principal, credentials->ctx, credentials->ccache, + &matchCred.client); + if (rv) + goto out; + + /* try from the cache first, and then do a new request */ +again: + rv = krb_log_exec(krb5_get_credentials, credentials->ctx, getCredsFlags, credentials->ccache, + &matchCred, &hostCred); + switch (rv) + { + case 0: + break; + case KRB5_CC_NOTFOUND: + getCredsFlags = 0; + if (firstRun) + { + firstRun = FALSE; + goto again; + } + WINPR_FALLTHROUGH + default: + WLog_ERR(TAG, "krb5_get_credentials(hostCreds), rv=%d", rv); + goto out; + } + + if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &authContext)) + goto out; + + krb5_data derOut = { 0 }; + if (krb_log_exec(krb5_fwd_tgt_creds, credentials->ctx, authContext, context->targetHost, + matchCred.client, matchCred.server, credentials->ccache, 1, &derOut)) + { + ret = SEC_E_LOGON_DENIED; + goto out; + } + + ticketLogon->MessageType = KerbTicketLogon; + ticketLogon->Flags = KERB_LOGON_FLAG_REDIRECTED; + + if (!copy_krb5_data(&hostCred->ticket, &ticketLogon->ServiceTicket, + &ticketLogon->ServiceTicketLength)) + { + krb5_free_data(credentials->ctx, &derOut); + goto out; + } + + ticketLogon->TicketGrantingTicketLength = derOut.length; + ticketLogon->TicketGrantingTicket = (PUCHAR)derOut.data; + + ret = SEC_E_OK; +out: + krb5_auth_con_free(credentials->ctx, authContext); + krb5_free_creds(credentials->ctx, hostCred); + krb5_free_cred_contents(credentials->ctx, &matchCred); + return ret; +} + +#endif /* WITH_KRB5 */ + +static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + if (!phContext) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INVALID_PARAMETER; + +#ifdef WITH_KRB5 + KRB_CONTEXT* context = get_context(phContext); + if (!context) + return SEC_E_INVALID_PARAMETER; + + KRB_CREDENTIALS* credentials = context->credentials; + + switch (ulAttribute) + { + case SECPKG_ATTR_SIZES: + return kerberos_ATTR_SIZES(context, credentials, (SecPkgContext_Sizes*)pBuffer); + + case SECPKG_CRED_ATTR_TICKET_LOGON: + return kerberos_ATTR_TICKET_LOGON(context, credentials, (KERB_TICKET_LOGON*)pBuffer); + + default: + WLog_ERR(TAG, "TODO: QueryContextAttributes implement ulAttribute=0x%08" PRIx32, + ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; + } +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + return kerberos_QueryContextAttributesA(phContext, ulAttribute, pBuffer); +} + +static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesX(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer, + BOOL unicode) +{ +#ifdef WITH_KRB5 + KRB_CREDENTIALS* credentials = NULL; + + if (!phCredential) + return SEC_E_INVALID_HANDLE; + + credentials = sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INSUFFICIENT_MEMORY; + + switch (ulAttribute) + { + case SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS: + { + SecPkgCredentials_KdcProxySettingsW* kdc_settings = pBuffer; + + /* Sanity checks */ + if (cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) || + kdc_settings->Version != KDC_PROXY_SETTINGS_V1 || + kdc_settings->ProxyServerOffset < sizeof(SecPkgCredentials_KdcProxySettingsW) || + cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) + + kdc_settings->ProxyServerOffset + kdc_settings->ProxyServerLength) + return SEC_E_INVALID_TOKEN; + + if (credentials->kdc_url) + { + free(credentials->kdc_url); + credentials->kdc_url = NULL; + } + + if (kdc_settings->ProxyServerLength > 0) + { + WCHAR* proxy = (WCHAR*)((BYTE*)pBuffer + kdc_settings->ProxyServerOffset); + + credentials->kdc_url = ConvertWCharNToUtf8Alloc( + proxy, kdc_settings->ProxyServerLength / sizeof(WCHAR), NULL); + if (!credentials->kdc_url) + return SEC_E_INSUFFICIENT_MEMORY; + } + + return SEC_E_OK; + } + case SECPKG_CRED_ATTR_NAMES: + case SECPKG_ATTR_SUPPORTED_ALGS: + default: + WLog_ERR(TAG, "TODO: SetCredentialsAttributesX implement ulAttribute=0x%08" PRIx32, + ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; + } + +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, TRUE); +} + +static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, FALSE); +} + +static SECURITY_STATUS SEC_ENTRY kerberos_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, + ULONG MessageSeqNo) +{ +#ifdef WITH_KRB5 + KRB_CONTEXT* context = get_context(phContext); + PSecBuffer sig_buffer = NULL; + PSecBuffer data_buffer = NULL; + char* header = NULL; + BYTE flags = 0; + krb5glue_key key = NULL; + krb5_keyusage usage = 0; + krb5_crypto_iov encrypt_iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_PADDING, { 0 } }, + { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } }; + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (!(context->flags & SSPI_GSS_C_CONF_FLAG)) + return SEC_E_UNSUPPORTED_FUNCTION; + + KRB_CREDENTIALS* creds = context->credentials; + + sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN); + data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + + if (!sig_buffer || !data_buffer) + return SEC_E_INVALID_TOKEN; + + if (fQOP) + return SEC_E_QOP_NOT_SUPPORTED; + + flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0; + flags |= FLAG_WRAP_CONFIDENTIAL; + + key = get_key(&context->keyset); + if (!key) + return SEC_E_INTERNAL_ERROR; + + flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0; + + usage = context->acceptor ? KG_USAGE_ACCEPTOR_SEAL : KG_USAGE_INITIATOR_SEAL; + + /* Set the lengths of the data (plaintext + header) */ + encrypt_iov[1].data.length = data_buffer->cbBuffer; + encrypt_iov[2].data.length = 16; + + /* Get the lengths of the header, trailer, and padding and ensure sig_buffer is large enough */ + if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, encrypt_iov, + ARRAYSIZE(encrypt_iov))) + return SEC_E_INTERNAL_ERROR; + if (sig_buffer->cbBuffer < + encrypt_iov[0].data.length + encrypt_iov[3].data.length + encrypt_iov[4].data.length + 32) + return SEC_E_INSUFFICIENT_MEMORY; + + /* Set up the iov array in sig_buffer */ + header = sig_buffer->pvBuffer; + encrypt_iov[2].data.data = header + 16; + encrypt_iov[3].data.data = encrypt_iov[2].data.data + encrypt_iov[2].data.length; + encrypt_iov[4].data.data = encrypt_iov[3].data.data + encrypt_iov[3].data.length; + encrypt_iov[0].data.data = encrypt_iov[4].data.data + encrypt_iov[4].data.length; + encrypt_iov[1].data.data = data_buffer->pvBuffer; + + /* Write the GSS header with 0 in RRC */ + winpr_Data_Write_UINT16_BE(header, TOK_ID_WRAP); + header[2] = WINPR_ASSERTING_INT_CAST(char, flags); + header[3] = (char)0xFF; + winpr_Data_Write_UINT32(header + 4, 0); + winpr_Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo)); + + /* Copy header to be encrypted */ + CopyMemory(encrypt_iov[2].data.data, header, 16); + + /* Set the correct RRC */ + const size_t len = 16 + encrypt_iov[3].data.length + encrypt_iov[4].data.length; + winpr_Data_Write_UINT16_BE(header + 6, WINPR_ASSERTING_INT_CAST(UINT16, len)); + + if (krb_log_exec(krb5glue_encrypt_iov, creds->ctx, key, usage, encrypt_iov, + ARRAYSIZE(encrypt_iov))) + return SEC_E_INTERNAL_ERROR; + + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ +#ifdef WITH_KRB5 + KRB_CONTEXT* context = get_context(phContext); + PSecBuffer sig_buffer = NULL; + PSecBuffer data_buffer = NULL; + krb5glue_key key = NULL; + krb5_keyusage usage = 0; + uint16_t tok_id = 0; + BYTE flags = 0; + uint16_t ec = 0; + uint16_t rrc = 0; + uint64_t seq_no = 0; + krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_PADDING, { 0 } }, + { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } }; + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (!(context->flags & SSPI_GSS_C_CONF_FLAG)) + return SEC_E_UNSUPPORTED_FUNCTION; + + KRB_CREDENTIALS* creds = context->credentials; + + sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN); + data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + + if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16) + return SEC_E_INVALID_TOKEN; + + /* Read in header information */ + BYTE* header = sig_buffer->pvBuffer; + tok_id = winpr_Data_Get_UINT16_BE(header); + flags = header[2]; + ec = winpr_Data_Get_UINT16_BE(&header[4]); + rrc = winpr_Data_Get_UINT16_BE(&header[6]); + seq_no = winpr_Data_Get_UINT64_BE(&header[8]); + + /* Check that the header is valid */ + if ((tok_id != TOK_ID_WRAP) || (header[3] != 0xFF)) + return SEC_E_INVALID_TOKEN; + + if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor) + return SEC_E_INVALID_TOKEN; + + if ((context->flags & ISC_REQ_SEQUENCE_DETECT) && + (seq_no != context->remote_seq + MessageSeqNo)) + return SEC_E_OUT_OF_SEQUENCE; + + if (!(flags & FLAG_WRAP_CONFIDENTIAL)) + return SEC_E_INVALID_TOKEN; + + /* We don't expect a trailer buffer; the encrypted header must be rotated */ + if (rrc < 16) + return SEC_E_INVALID_TOKEN; + + /* Find the proper key and key usage */ + key = get_key(&context->keyset); + if (!key || ((flags & FLAG_ACCEPTOR_SUBKEY) && (context->keyset.acceptor_key != key))) + return SEC_E_INTERNAL_ERROR; + usage = context->acceptor ? KG_USAGE_INITIATOR_SEAL : KG_USAGE_ACCEPTOR_SEAL; + + /* Fill in the lengths of the iov array */ + iov[1].data.length = data_buffer->cbBuffer; + iov[2].data.length = 16; + if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov))) + return SEC_E_INTERNAL_ERROR; + + /* We don't expect a trailer buffer; everything must be in sig_buffer */ + if (rrc != 16 + iov[3].data.length + iov[4].data.length) + return SEC_E_INVALID_TOKEN; + if (sig_buffer->cbBuffer != 16 + rrc + iov[0].data.length) + return SEC_E_INVALID_TOKEN; + + /* Locate the parts of the message */ + iov[0].data.data = (char*)&header[16 + rrc + ec]; + iov[1].data.data = data_buffer->pvBuffer; + iov[2].data.data = (char*)&header[16 + ec]; + char* data2 = iov[2].data.data; + iov[3].data.data = &data2[iov[2].data.length]; + + char* data3 = iov[3].data.data; + iov[4].data.data = &data3[iov[3].data.length]; + + if (krb_log_exec(krb5glue_decrypt_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov))) + return SEC_E_INTERNAL_ERROR; + + /* Validate the encrypted header */ + winpr_Data_Write_UINT16_BE(iov[2].data.data + 4, ec); + winpr_Data_Write_UINT16_BE(iov[2].data.data + 6, rrc); + if (memcmp(iov[2].data.data, header, 16) != 0) + return SEC_E_MESSAGE_ALTERED; + + *pfQOP = 0; + + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ +#ifdef WITH_KRB5 + KRB_CONTEXT* context = get_context(phContext); + PSecBuffer sig_buffer = NULL; + PSecBuffer data_buffer = NULL; + krb5glue_key key = NULL; + krb5_keyusage usage = 0; + BYTE flags = 0; + krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } }; + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (!(context->flags & SSPI_GSS_C_INTEG_FLAG)) + return SEC_E_UNSUPPORTED_FUNCTION; + + KRB_CREDENTIALS* creds = context->credentials; + + sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN); + data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + + if (!sig_buffer || !data_buffer) + return SEC_E_INVALID_TOKEN; + + flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0; + + key = get_key(&context->keyset); + if (!key) + return SEC_E_INTERNAL_ERROR; + usage = context->acceptor ? KG_USAGE_ACCEPTOR_SIGN : KG_USAGE_INITIATOR_SIGN; + + flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0; + + /* Fill in the lengths of the iov array */ + iov[0].data.length = data_buffer->cbBuffer; + iov[1].data.length = 16; + if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov))) + return SEC_E_INTERNAL_ERROR; + + /* Ensure the buffer is big enough */ + if (sig_buffer->cbBuffer < iov[2].data.length + 16) + return SEC_E_INSUFFICIENT_MEMORY; + + /* Write the header */ + char* header = sig_buffer->pvBuffer; + winpr_Data_Write_UINT16_BE(header, TOK_ID_MIC); + header[2] = WINPR_ASSERTING_INT_CAST(char, flags); + memset(header + 3, 0xFF, 5); + winpr_Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo)); + + /* Set up the iov array */ + iov[0].data.data = data_buffer->pvBuffer; + iov[1].data.data = header; + iov[2].data.data = header + 16; + + if (krb_log_exec(krb5glue_make_checksum_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov))) + return SEC_E_INTERNAL_ERROR; + + sig_buffer->cbBuffer = iov[2].data.length + 16; + + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +static SECURITY_STATUS SEC_ENTRY kerberos_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ +#ifdef WITH_KRB5 + PSecBuffer sig_buffer = NULL; + PSecBuffer data_buffer = NULL; + krb5glue_key key = NULL; + krb5_keyusage usage = 0; + BYTE flags = 0; + uint16_t tok_id = 0; + uint64_t seq_no = 0; + krb5_boolean is_valid = 0; + krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_DATA, { 0 } }, + { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } }; + BYTE cmp_filler[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + + KRB_CONTEXT* context = get_context(phContext); + if (!context) + return SEC_E_INVALID_HANDLE; + + if (!(context->flags & SSPI_GSS_C_INTEG_FLAG)) + return SEC_E_UNSUPPORTED_FUNCTION; + + sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN); + data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + + if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16) + return SEC_E_INVALID_TOKEN; + + /* Read in header info */ + BYTE* header = sig_buffer->pvBuffer; + tok_id = winpr_Data_Get_UINT16_BE(header); + flags = header[2]; + seq_no = winpr_Data_Get_UINT64_BE((header + 8)); + + /* Validate header */ + if (tok_id != TOK_ID_MIC) + return SEC_E_INVALID_TOKEN; + + if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor || flags & FLAG_WRAP_CONFIDENTIAL) + return SEC_E_INVALID_TOKEN; + + if (memcmp(header + 3, cmp_filler, sizeof(cmp_filler)) != 0) + return SEC_E_INVALID_TOKEN; + + if (context->flags & ISC_REQ_SEQUENCE_DETECT && seq_no != context->remote_seq + MessageSeqNo) + return SEC_E_OUT_OF_SEQUENCE; + + /* Find the proper key and usage */ + key = get_key(&context->keyset); + if (!key || (flags & FLAG_ACCEPTOR_SUBKEY && context->keyset.acceptor_key != key)) + return SEC_E_INTERNAL_ERROR; + usage = context->acceptor ? KG_USAGE_INITIATOR_SIGN : KG_USAGE_ACCEPTOR_SIGN; + + /* Fill in the iov array lengths */ + KRB_CREDENTIALS* creds = context->credentials; + iov[0].data.length = data_buffer->cbBuffer; + iov[1].data.length = 16; + if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov))) + return SEC_E_INTERNAL_ERROR; + + if (sig_buffer->cbBuffer != iov[2].data.length + 16) + return SEC_E_INTERNAL_ERROR; + + /* Set up the iov array */ + iov[0].data.data = data_buffer->pvBuffer; + iov[1].data.data = (char*)header; + iov[2].data.data = (char*)&header[16]; + + if (krb_log_exec(krb5glue_verify_checksum_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov), + &is_valid)) + return SEC_E_INTERNAL_ERROR; + + if (!is_valid) + return SEC_E_MESSAGE_ALTERED; + + return SEC_E_OK; +#else + return SEC_E_UNSUPPORTED_FUNCTION; +#endif +} + +const SecurityFunctionTableA KERBEROS_SecurityFunctionTableA = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + kerberos_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + kerberos_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + kerberos_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + kerberos_InitializeSecurityContextA, /* InitializeSecurityContext */ + kerberos_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + kerberos_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + kerberos_QueryContextAttributesA, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + kerberos_MakeSignature, /* MakeSignature */ + kerberos_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + kerberos_EncryptMessage, /* EncryptMessage */ + kerberos_DecryptMessage, /* DecryptMessage */ + kerberos_SetContextAttributesA, /* SetContextAttributes */ + kerberos_SetCredentialsAttributesA, /* SetCredentialsAttributes */ +}; + +const SecurityFunctionTableW KERBEROS_SecurityFunctionTableW = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + kerberos_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + kerberos_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + kerberos_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + kerberos_InitializeSecurityContextW, /* InitializeSecurityContext */ + kerberos_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + kerberos_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + kerberos_QueryContextAttributesW, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + kerberos_MakeSignature, /* MakeSignature */ + kerberos_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + kerberos_EncryptMessage, /* EncryptMessage */ + kerberos_DecryptMessage, /* DecryptMessage */ + kerberos_SetContextAttributesW, /* SetContextAttributes */ + kerberos_SetCredentialsAttributesW, /* SetCredentialsAttributes */ +}; + +BOOL KERBEROS_init(void) +{ + InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Name, KERBEROS_SecPkgInfoW_NameBuffer, + ARRAYSIZE(KERBEROS_SecPkgInfoW_NameBuffer)); + InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Comment, KERBEROS_SecPkgInfoW_CommentBuffer, + ARRAYSIZE(KERBEROS_SecPkgInfoW_CommentBuffer)); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.h new file mode 100644 index 0000000000000000000000000000000000000000..aa4b86dffcd2d06cf35a6fd9be664c96153f70eb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/kerberos.h @@ -0,0 +1,39 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * Kerberos Auth Protocol + * + * Copyright 2015 ANSSI, Author Thomas Calderon + * Copyright 2017 Dorian Ducournau + * + * 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_KERBEROS_PRIVATE_H +#define WINPR_SSPI_KERBEROS_PRIVATE_H + +#include +#include + +#include "../sspi.h" +#include "../../log.h" + +typedef struct s_KRB_CONTEXT KRB_CONTEXT; + +extern const SecPkgInfoA KERBEROS_SecPkgInfoA; +extern const SecPkgInfoW KERBEROS_SecPkgInfoW; +extern const SecurityFunctionTableA KERBEROS_SecurityFunctionTableA; +extern const SecurityFunctionTableW KERBEROS_SecurityFunctionTableW; + +BOOL KERBEROS_init(void); + +#endif /* WINPR_SSPI_KERBEROS_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue.h new file mode 100644 index 0000000000000000000000000000000000000000..6d95982297c58dd9bc974652db19a9235e2b6ac3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue.h @@ -0,0 +1,104 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * Kerberos Auth Protocol + * + * Copyright 2022 Isaac Klein + * + * 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_KERBEROS_GLUE_PRIVATE_H +#define WINPR_SSPI_KERBEROS_GLUE_PRIVATE_H + +#include +#include + +#include + +#if defined(WITH_KRB5_MIT) +typedef krb5_key krb5glue_key; +typedef krb5_authenticator* krb5glue_authenticator; + +#define krb5glue_crypto_length(ctx, key, type, size) \ + krb5_c_crypto_length(ctx, krb5_k_key_enctype(ctx, key), type, size) +#define krb5glue_crypto_length_iov(ctx, key, iov, size) \ + krb5_c_crypto_length_iov(ctx, krb5_k_key_enctype(ctx, key), iov, size) +#define krb5glue_encrypt_iov(ctx, key, usage, iov, size) \ + krb5_k_encrypt_iov(ctx, key, usage, NULL, iov, size) +#define krb5glue_decrypt_iov(ctx, key, usage, iov, size) \ + krb5_k_decrypt_iov(ctx, key, usage, NULL, iov, size) +#define krb5glue_make_checksum_iov(ctx, key, usage, iov, size) \ + krb5_k_make_checksum_iov(ctx, 0, key, usage, iov, size) +#define krb5glue_verify_checksum_iov(ctx, key, usage, iov, size, is_valid) \ + krb5_k_verify_checksum_iov(ctx, 0, key, usage, iov, size, is_valid) +#define krb5glue_auth_con_set_cksumtype(ctx, auth_ctx, cksumtype) \ + krb5_auth_con_set_req_cksumtype(ctx, auth_ctx, cksumtype) +#define krb5glue_set_principal_realm(ctx, principal, realm) \ + krb5_set_principal_realm(ctx, principal, realm) +#define krb5glue_free_keytab_entry_contents(ctx, entry) krb5_free_keytab_entry_contents(ctx, entry) +#define krb5glue_auth_con_setuseruserkey(ctx, auth_ctx, keytab) \ + krb5_auth_con_setuseruserkey(ctx, auth_ctx, keytab) +#define krb5glue_free_data_contents(ctx, data) krb5_free_data_contents(ctx, data) +krb5_prompt_type krb5glue_get_prompt_type(krb5_context ctx, krb5_prompt prompts[], int index); + +#define krb5glue_creds_getkey(creds) creds.keyblock + +#elif defined(WITH_KRB5_HEIMDAL) +typedef krb5_crypto krb5glue_key; +typedef krb5_authenticator krb5glue_authenticator; + +krb5_error_code krb5glue_crypto_length(krb5_context ctx, krb5glue_key key, int type, + unsigned int* size); +#define krb5glue_crypto_length_iov(ctx, key, iov, size) krb5_crypto_length_iov(ctx, key, iov, size) +#define krb5glue_encrypt_iov(ctx, key, usage, iov, size) \ + krb5_encrypt_iov_ivec(ctx, key, usage, iov, size, NULL) +#define krb5glue_decrypt_iov(ctx, key, usage, iov, size) \ + krb5_decrypt_iov_ivec(ctx, key, usage, iov, size, NULL) +#define krb5glue_make_checksum_iov(ctx, key, usage, iov, size) \ + krb5_create_checksum_iov(ctx, key, usage, iov, size, NULL) +krb5_error_code krb5glue_verify_checksum_iov(krb5_context ctx, krb5glue_key key, + krb5_keyusage usage, krb5_crypto_iov* iov, + unsigned int iov_size, krb5_boolean* is_valid); +#define krb5glue_auth_con_set_cksumtype(ctx, auth_ctx, cksumtype) \ + krb5_auth_con_setcksumtype(ctx, auth_ctx, cksumtype) +#define krb5glue_set_principal_realm(ctx, principal, realm) \ + krb5_principal_set_realm(ctx, principal, realm) +#define krb5glue_free_keytab_entry_contents(ctx, entry) krb5_kt_free_entry(ctx, entry) +#define krb5glue_auth_con_setuseruserkey(ctx, auth_ctx, keytab) \ + krb5_auth_con_setuserkey(ctx, auth_ctx, keytab) +#define krb5glue_free_data_contents(ctx, data) krb5_data_free(data) +#define krb5glue_get_prompt_type(ctx, prompts, index) prompts[index].type + +#define krb5glue_creds_getkey(creds) creds.session +#else +#error "Missing implementation for KRB5 provider" +#endif + +struct krb5glue_keyset +{ + krb5glue_key session_key; + krb5glue_key initiator_key; + krb5glue_key acceptor_key; +}; + +void krb5glue_keys_free(krb5_context ctx, struct krb5glue_keyset* keyset); +krb5_error_code krb5glue_update_keyset(krb5_context ctx, krb5_auth_context auth_ctx, BOOL acceptor, + struct krb5glue_keyset* keyset); +krb5_error_code krb5glue_log_error(krb5_context ctx, krb5_data* msg, const char* tag); +BOOL krb5glue_authenticator_validate_chksum(krb5glue_authenticator authenticator, int cksumtype, + uint32_t* flags); +krb5_error_code krb5glue_get_init_creds(krb5_context ctx, krb5_principal princ, krb5_ccache ccache, + krb5_prompter_fct prompter, char* password, + SEC_WINPR_KERBEROS_SETTINGS* krb_settings); + +#endif /* WINPR_SSPI_KERBEROS_GLUE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_heimdal.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_heimdal.c new file mode 100644 index 0000000000000000000000000000000000000000..60b2c4572a0ba10ccb94b917c2314df108d1558e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_heimdal.c @@ -0,0 +1,215 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * Kerberos Auth Protocol + * + * Copyright 2022 Isaac Klein + * + * 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 WITH_KRB5_HEIMDAL +#error "This file must only be included with HEIMDAL kerberos" +#endif + +#include +#include +#include +#include "krb5glue.h" + +void krb5glue_keys_free(krb5_context ctx, struct krb5glue_keyset* keyset) +{ + if (!ctx || !keyset) + return; + if (keyset->session_key) + krb5_crypto_destroy(ctx, keyset->session_key); + if (keyset->initiator_key) + krb5_crypto_destroy(ctx, keyset->initiator_key); + if (keyset->acceptor_key) + krb5_crypto_destroy(ctx, keyset->acceptor_key); +} + +krb5_error_code krb5glue_update_keyset(krb5_context ctx, krb5_auth_context auth_ctx, BOOL acceptor, + struct krb5glue_keyset* keyset) +{ + krb5_keyblock* keyblock = NULL; + krb5_error_code rv = 0; + + WINPR_ASSERT(ctx); + WINPR_ASSERT(auth_ctx); + WINPR_ASSERT(keyset); + + krb5glue_keys_free(ctx, keyset); + + if (!(rv = krb5_auth_con_getkey(ctx, auth_ctx, &keyblock))) + { + krb5_crypto_init(ctx, keyblock, ENCTYPE_NULL, &keyset->session_key); + krb5_free_keyblock(ctx, keyblock); + keyblock = NULL; + } + + if (acceptor) + rv = krb5_auth_con_getremotesubkey(ctx, auth_ctx, &keyblock); + else + rv = krb5_auth_con_getlocalsubkey(ctx, auth_ctx, &keyblock); + + if (!rv && keyblock) + { + krb5_crypto_init(ctx, keyblock, ENCTYPE_NULL, &keyset->initiator_key); + krb5_free_keyblock(ctx, keyblock); + keyblock = NULL; + } + + if (acceptor) + rv = krb5_auth_con_getlocalsubkey(ctx, auth_ctx, &keyblock); + else + rv = krb5_auth_con_getremotesubkey(ctx, auth_ctx, &keyblock); + + if (!rv && keyblock) + { + krb5_crypto_init(ctx, keyblock, ENCTYPE_NULL, &keyset->acceptor_key); + krb5_free_keyblock(ctx, keyblock); + } + + return rv; +} + +krb5_error_code krb5glue_verify_checksum_iov(krb5_context ctx, krb5glue_key key, + krb5_keyusage usage, krb5_crypto_iov* iov, + unsigned int iov_size, krb5_boolean* is_valid) +{ + krb5_error_code rv = 0; + + WINPR_ASSERT(ctx); + WINPR_ASSERT(key); + WINPR_ASSERT(is_valid); + + rv = krb5_verify_checksum_iov(ctx, key, usage, iov, iov_size, NULL); + *is_valid = (rv == 0); + return rv; +} + +krb5_error_code krb5glue_crypto_length(krb5_context ctx, krb5glue_key key, int type, + unsigned int* size) +{ + krb5_error_code rv = 0; + size_t s = 0; + + WINPR_ASSERT(ctx); + WINPR_ASSERT(key); + WINPR_ASSERT(size); + + rv = krb5_crypto_length(ctx, key, type, &s); + *size = (UINT)s; + return rv; +} + +krb5_error_code krb5glue_log_error(krb5_context ctx, krb5_data* msg, const char* tag) +{ + krb5_error error = { 0 }; + krb5_error_code rv = 0; + + WINPR_ASSERT(ctx); + WINPR_ASSERT(msg); + WINPR_ASSERT(tag); + + if (!(rv = krb5_rd_error(ctx, msg, &error))) + { + WLog_ERR(tag, "KRB_ERROR: %" PRIx32, error.error_code); + krb5_free_error_contents(ctx, &error); + } + return rv; +} + +BOOL krb5glue_authenticator_validate_chksum(krb5glue_authenticator authenticator, int cksumtype, + uint32_t* flags) +{ + WINPR_ASSERT(flags); + + if (!authenticator || !authenticator->cksum || authenticator->cksum->cksumtype != cksumtype || + authenticator->cksum->checksum.length < 24) + return FALSE; + + const BYTE* data = authenticator->cksum->checksum.data; + Data_Read_UINT32((data + 20), (*flags)); + return TRUE; +} + +krb5_error_code krb5glue_get_init_creds(krb5_context ctx, krb5_principal princ, krb5_ccache ccache, + krb5_prompter_fct prompter, char* password, + SEC_WINPR_KERBEROS_SETTINGS* krb_settings) +{ + krb5_error_code rv = 0; + krb5_deltat start_time = 0; + krb5_get_init_creds_opt* gic_opt = NULL; + krb5_init_creds_context creds_ctx = NULL; + krb5_creds creds = { 0 }; + + WINPR_ASSERT(ctx); + + do + { + if ((rv = krb5_get_init_creds_opt_alloc(ctx, &gic_opt)) != 0) + break; + + krb5_get_init_creds_opt_set_forwardable(gic_opt, 0); + krb5_get_init_creds_opt_set_proxiable(gic_opt, 0); + + if (krb_settings) + { + if (krb_settings->startTime) + start_time = krb_settings->startTime; + if (krb_settings->lifeTime) + krb5_get_init_creds_opt_set_tkt_life(gic_opt, krb_settings->lifeTime); + if (krb_settings->renewLifeTime) + krb5_get_init_creds_opt_set_renew_life(gic_opt, krb_settings->renewLifeTime); + if (krb_settings->withPac) + krb5_get_init_creds_opt_set_pac_request(ctx, gic_opt, TRUE); + if (krb_settings->pkinitX509Anchors || krb_settings->pkinitX509Identity) + { + if ((rv = krb5_get_init_creds_opt_set_pkinit( + ctx, gic_opt, princ, krb_settings->pkinitX509Identity, + krb_settings->pkinitX509Anchors, NULL, NULL, 0, prompter, password, + password)) != 0) + break; + } + } + + if ((rv = krb5_init_creds_init(ctx, princ, prompter, password, start_time, gic_opt, + &creds_ctx)) != 0) + break; + if ((rv = krb5_init_creds_set_password(ctx, creds_ctx, password)) != 0) + break; + if (krb_settings && krb_settings->armorCache) + { + krb5_ccache armor_cc = NULL; + if ((rv = krb5_cc_resolve(ctx, krb_settings->armorCache, &armor_cc)) != 0) + break; + if ((rv = krb5_init_creds_set_fast_ccache(ctx, creds_ctx, armor_cc)) != 0) + break; + krb5_cc_close(ctx, armor_cc); + } + if ((rv = krb5_init_creds_get(ctx, creds_ctx)) != 0) + break; + if ((rv = krb5_init_creds_get_creds(ctx, creds_ctx, &creds)) != 0) + break; + if ((rv = krb5_cc_store_cred(ctx, ccache, &creds)) != 0) + break; + } while (0); + + krb5_free_cred_contents(ctx, &creds); + krb5_init_creds_free(ctx, creds_ctx); + krb5_get_init_creds_opt_free(ctx, gic_opt); + + return rv; +} + diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c new file mode 100644 index 0000000000000000000000000000000000000000..36683101700f5b3af0644448f6e9524a3f379171 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c @@ -0,0 +1,257 @@ +/** + * FreeRDP: A Remote Desktop Protocol Client + * Kerberos Auth Protocol + * + * Copyright 2022 Isaac Klein + * + * 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 WITH_KRB5_MIT +#error "This file must only be included with MIT kerberos" +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "krb5glue.h" +#include + +static char* create_temporary_file(void) +{ + BYTE buffer[32]; + char* hex = NULL; + char* path = NULL; + + winpr_RAND(buffer, sizeof(buffer)); + hex = winpr_BinToHexString(buffer, sizeof(buffer), FALSE); + path = GetKnownSubPath(KNOWN_PATH_TEMP, hex); + free(hex); + return path; +} + +void krb5glue_keys_free(krb5_context ctx, struct krb5glue_keyset* keyset) +{ + WINPR_ASSERT(ctx); + WINPR_ASSERT(keyset); + + krb5_k_free_key(ctx, keyset->session_key); + krb5_k_free_key(ctx, keyset->initiator_key); + krb5_k_free_key(ctx, keyset->acceptor_key); +} + +krb5_error_code krb5glue_update_keyset(krb5_context ctx, krb5_auth_context auth_ctx, BOOL acceptor, + struct krb5glue_keyset* keyset) +{ + WINPR_ASSERT(ctx); + WINPR_ASSERT(auth_ctx); + WINPR_ASSERT(keyset); + + krb5glue_keys_free(ctx, keyset); + krb5_auth_con_getkey_k(ctx, auth_ctx, &keyset->session_key); + if (acceptor) + { + krb5_auth_con_getsendsubkey_k(ctx, auth_ctx, &keyset->acceptor_key); + krb5_auth_con_getrecvsubkey_k(ctx, auth_ctx, &keyset->initiator_key); + } + else + { + krb5_auth_con_getsendsubkey_k(ctx, auth_ctx, &keyset->initiator_key); + krb5_auth_con_getrecvsubkey_k(ctx, auth_ctx, &keyset->acceptor_key); + } + return 0; +} + +krb5_prompt_type krb5glue_get_prompt_type(krb5_context ctx, krb5_prompt prompts[], int index) +{ + WINPR_ASSERT(ctx); + WINPR_ASSERT(prompts); + WINPR_UNUSED(prompts); + + krb5_prompt_type* types = krb5_get_prompt_types(ctx); + return types ? types[index] : 0; +} + +krb5_error_code krb5glue_log_error(krb5_context ctx, krb5_data* msg, const char* tag) +{ + krb5_error* error = NULL; + krb5_error_code rv = 0; + + WINPR_ASSERT(ctx); + WINPR_ASSERT(msg); + WINPR_ASSERT(tag); + + if (!(rv = krb5_rd_error(ctx, msg, &error))) + { + WLog_ERR(tag, "KRB_ERROR: %s", error->text.data); + krb5_free_error(ctx, error); + } + + return rv; +} + +BOOL krb5glue_authenticator_validate_chksum(krb5glue_authenticator authenticator, int cksumtype, + uint32_t* flags) +{ + WINPR_ASSERT(flags); + + if (!authenticator || !authenticator->checksum || + authenticator->checksum->checksum_type != cksumtype || authenticator->checksum->length < 24) + return FALSE; + *flags = winpr_Data_Get_UINT32((authenticator->checksum->contents + 20)); + return TRUE; +} + +krb5_error_code krb5glue_get_init_creds(krb5_context ctx, krb5_principal princ, krb5_ccache ccache, + krb5_prompter_fct prompter, char* password, + SEC_WINPR_KERBEROS_SETTINGS* krb_settings) +{ + krb5_error_code rv = 0; + krb5_deltat start_time = 0; + krb5_get_init_creds_opt* gic_opt = NULL; + krb5_init_creds_context creds_ctx = NULL; + char* tmp_profile_path = create_temporary_file(); + profile_t profile = NULL; + BOOL is_temp_ctx = FALSE; + + WINPR_ASSERT(ctx); + + rv = krb5_get_init_creds_opt_alloc(ctx, &gic_opt); + if (rv) + goto cleanup; + + krb5_get_init_creds_opt_set_forwardable(gic_opt, 0); + krb5_get_init_creds_opt_set_proxiable(gic_opt, 0); + + if (krb_settings) + { + if (krb_settings->startTime) + start_time = krb_settings->startTime; + if (krb_settings->lifeTime) + krb5_get_init_creds_opt_set_tkt_life(gic_opt, krb_settings->lifeTime); + if (krb_settings->renewLifeTime) + krb5_get_init_creds_opt_set_renew_life(gic_opt, krb_settings->renewLifeTime); + if (krb_settings->withPac) + { + rv = krb5_get_init_creds_opt_set_pac_request(ctx, gic_opt, TRUE); + if (rv) + goto cleanup; + } + if (krb_settings->armorCache) + { + rv = krb5_get_init_creds_opt_set_fast_ccache_name(ctx, gic_opt, + krb_settings->armorCache); + if (rv) + goto cleanup; + } + if (krb_settings->pkinitX509Identity) + { + rv = krb5_get_init_creds_opt_set_pa(ctx, gic_opt, "X509_user_identity", + krb_settings->pkinitX509Identity); + if (rv) + goto cleanup; + } + if (krb_settings->pkinitX509Anchors) + { + rv = krb5_get_init_creds_opt_set_pa(ctx, gic_opt, "X509_anchors", + krb_settings->pkinitX509Anchors); + if (rv) + goto cleanup; + } + if (krb_settings->kdcUrl && (strnlen(krb_settings->kdcUrl, 2) > 0)) + { + const char* names[4] = { 0 }; + char* realm = NULL; + char* kdc_url = NULL; + size_t size = 0; + + if ((rv = krb5_get_profile(ctx, &profile))) + goto cleanup; + + rv = ENOMEM; + if (winpr_asprintf(&kdc_url, &size, "https://%s/KdcProxy", krb_settings->kdcUrl) <= 0) + { + free(kdc_url); + goto cleanup; + } + + realm = calloc(princ->realm.length + 1, 1); + if (!realm) + { + free(kdc_url); + goto cleanup; + } + CopyMemory(realm, princ->realm.data, princ->realm.length); + + names[0] = "realms"; + names[1] = realm; + names[2] = "kdc"; + + profile_clear_relation(profile, names); + profile_add_relation(profile, names, kdc_url); + + /* Since we know who the KDC is, tell krb5 that its certificate is valid for pkinit */ + names[2] = "pkinit_kdc_hostname"; + profile_add_relation(profile, names, krb_settings->kdcUrl); + + free(kdc_url); + free(realm); + + long lrv = profile_flush_to_file(profile, tmp_profile_path); + if (lrv) + goto cleanup; + + profile_abandon(profile); + profile = NULL; + lrv = profile_init_path(tmp_profile_path, &profile); + if (lrv) + goto cleanup; + + rv = krb5_init_context_profile(profile, 0, &ctx); + if (rv) + goto cleanup; + is_temp_ctx = TRUE; + } + } + + if ((rv = krb5_get_init_creds_opt_set_in_ccache(ctx, gic_opt, ccache))) + goto cleanup; + + if ((rv = krb5_get_init_creds_opt_set_out_ccache(ctx, gic_opt, ccache))) + goto cleanup; + + if ((rv = + krb5_init_creds_init(ctx, princ, prompter, password, start_time, gic_opt, &creds_ctx))) + goto cleanup; + + if ((rv = krb5_init_creds_get(ctx, creds_ctx))) + goto cleanup; + +cleanup: + krb5_init_creds_free(ctx, creds_ctx); + krb5_get_init_creds_opt_free(ctx, gic_opt); + if (is_temp_ctx) + krb5_free_context(ctx); + profile_abandon(profile); + winpr_DeleteFile(tmp_profile_path); + free(tmp_profile_path); + + return rv; +} + diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d7684544e4f1669772346218c30aa649a47ab321 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/ModuleOptions.cmake @@ -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 "sspi") +set(MINWIN_LONG_NAME "Security Support Provider Interface") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.c new file mode 100644 index 0000000000000000000000000000000000000000..a5004117228695f7c26edf3ac83cc9065b5380fb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.c @@ -0,0 +1,1534 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ntlm.h" +#include "ntlm_export.h" +#include "../sspi.h" + +#include "ntlm_message.h" + +#include "../../log.h" +#define TAG WINPR_TAG("sspi.NTLM") + +#define WINPR_KEY "Software\\" WINPR_VENDOR_STRING "\\" WINPR_PRODUCT_STRING "\\WinPR\\NTLM" + +static char* NTLM_PACKAGE_NAME = "NTLM"; + +#define check_context(ctx) check_context_((ctx), __FILE__, __func__, __LINE__) +static BOOL check_context_(NTLM_CONTEXT* context, const char* file, const char* fkt, size_t line) +{ + BOOL rc = TRUE; + wLog* log = WLog_Get(TAG); + const DWORD log_level = WLOG_ERROR; + + if (!context) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context"); + + return FALSE; + } + + if (!context->RecvRc4Seal) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->RecvRc4Seal"); + rc = FALSE; + } + if (!context->SendRc4Seal) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->SendRc4Seal"); + rc = FALSE; + } + + if (!context->SendSigningKey) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->SendSigningKey"); + rc = FALSE; + } + if (!context->RecvSigningKey) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->RecvSigningKey"); + rc = FALSE; + } + if (!context->SendSealingKey) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->SendSealingKey"); + rc = FALSE; + } + if (!context->RecvSealingKey) + { + if (WLog_IsLevelActive(log, log_level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "invalid context->RecvSealingKey"); + rc = FALSE; + } + return rc; +} + +static char* get_name(COMPUTER_NAME_FORMAT type) +{ + DWORD nSize = 0; + + if (GetComputerNameExA(type, NULL, &nSize)) + return NULL; + + if (GetLastError() != ERROR_MORE_DATA) + return NULL; + + char* computerName = calloc(1, nSize); + + if (!computerName) + return NULL; + + if (!GetComputerNameExA(type, computerName, &nSize)) + { + free(computerName); + return NULL; + } + + return computerName; +} + +static int ntlm_SetContextWorkstation(NTLM_CONTEXT* context, char* Workstation) +{ + char* ws = Workstation; + CHAR* computerName = NULL; + + WINPR_ASSERT(context); + + if (!Workstation) + { + computerName = get_name(ComputerNameNetBIOS); + if (!computerName) + return -1; + ws = computerName; + } + + size_t len = 0; + context->Workstation.Buffer = ConvertUtf8ToWCharAlloc(ws, &len); + + free(computerName); + + if (!context->Workstation.Buffer || (len > UINT16_MAX / sizeof(WCHAR))) + return -1; + + context->Workstation.Length = (USHORT)(len * sizeof(WCHAR)); + return 1; +} + +static int ntlm_SetContextServicePrincipalNameW(NTLM_CONTEXT* context, LPWSTR ServicePrincipalName) +{ + WINPR_ASSERT(context); + + if (!ServicePrincipalName) + { + context->ServicePrincipalName.Buffer = NULL; + context->ServicePrincipalName.Length = 0; + return 1; + } + + context->ServicePrincipalName.Length = (USHORT)(_wcslen(ServicePrincipalName) * 2); + context->ServicePrincipalName.Buffer = (PWSTR)malloc(context->ServicePrincipalName.Length + 2); + + if (!context->ServicePrincipalName.Buffer) + return -1; + + memcpy(context->ServicePrincipalName.Buffer, ServicePrincipalName, + context->ServicePrincipalName.Length + 2); + return 1; +} + +static int ntlm_SetContextTargetName(NTLM_CONTEXT* context, char* TargetName) +{ + char* name = TargetName; + DWORD nSize = 0; + CHAR* computerName = NULL; + + WINPR_ASSERT(context); + + if (!name) + { + if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) || + GetLastError() != ERROR_MORE_DATA) + return -1; + + computerName = calloc(nSize, sizeof(CHAR)); + + if (!computerName) + return -1; + + if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize)) + { + free(computerName); + return -1; + } + + if (nSize > MAX_COMPUTERNAME_LENGTH) + computerName[MAX_COMPUTERNAME_LENGTH] = '\0'; + + name = computerName; + + if (!name) + return -1; + + CharUpperA(name); + } + + size_t len = 0; + context->TargetName.pvBuffer = ConvertUtf8ToWCharAlloc(name, &len); + + if (!context->TargetName.pvBuffer || (len > UINT16_MAX / sizeof(WCHAR))) + { + free(context->TargetName.pvBuffer); + context->TargetName.pvBuffer = NULL; + + if (!TargetName) + free(name); + + return -1; + } + + context->TargetName.cbBuffer = (USHORT)(len * sizeof(WCHAR)); + + if (!TargetName) + free(name); + + return 1; +} + +static NTLM_CONTEXT* ntlm_ContextNew(void) +{ + HKEY hKey = 0; + LONG status = 0; + DWORD dwType = 0; + DWORD dwSize = 0; + DWORD dwValue = 0; + NTLM_CONTEXT* context = (NTLM_CONTEXT*)calloc(1, sizeof(NTLM_CONTEXT)); + + if (!context) + return NULL; + + context->NTLMv2 = TRUE; + context->UseMIC = FALSE; + context->SendVersionInfo = TRUE; + context->SendSingleHostData = FALSE; + context->SendWorkstationName = TRUE; + context->NegotiateKeyExchange = TRUE; + context->UseSamFileDatabase = TRUE; + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, WINPR_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status == ERROR_SUCCESS) + { + if (RegQueryValueEx(hKey, _T("NTLMv2"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) == + ERROR_SUCCESS) + context->NTLMv2 = dwValue ? 1 : 0; + + if (RegQueryValueEx(hKey, _T("UseMIC"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) == + ERROR_SUCCESS) + context->UseMIC = dwValue ? 1 : 0; + + if (RegQueryValueEx(hKey, _T("SendVersionInfo"), NULL, &dwType, (BYTE*)&dwValue, &dwSize) == + ERROR_SUCCESS) + context->SendVersionInfo = dwValue ? 1 : 0; + + if (RegQueryValueEx(hKey, _T("SendSingleHostData"), NULL, &dwType, (BYTE*)&dwValue, + &dwSize) == ERROR_SUCCESS) + context->SendSingleHostData = dwValue ? 1 : 0; + + if (RegQueryValueEx(hKey, _T("SendWorkstationName"), NULL, &dwType, (BYTE*)&dwValue, + &dwSize) == ERROR_SUCCESS) + context->SendWorkstationName = dwValue ? 1 : 0; + + if (RegQueryValueEx(hKey, _T("WorkstationName"), NULL, &dwType, NULL, &dwSize) == + ERROR_SUCCESS) + { + char* workstation = (char*)malloc(dwSize + 1); + + if (!workstation) + { + free(context); + return NULL; + } + + status = RegQueryValueExA(hKey, "WorkstationName", NULL, &dwType, (BYTE*)workstation, + &dwSize); + if (status != ERROR_SUCCESS) + WLog_WARN(TAG, "Key ''WorkstationName' not found"); + workstation[dwSize] = '\0'; + + if (ntlm_SetContextWorkstation(context, workstation) < 0) + { + free(workstation); + free(context); + return NULL; + } + + free(workstation); + } + + RegCloseKey(hKey); + } + + /* + * Extended Protection is enabled by default in Windows 7, + * but enabling it in WinPR breaks TS Gateway at this point + */ + context->SuppressExtendedProtection = FALSE; + status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\LSA"), 0, + KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status == ERROR_SUCCESS) + { + if (RegQueryValueEx(hKey, _T("SuppressExtendedProtection"), NULL, &dwType, (BYTE*)&dwValue, + &dwSize) == ERROR_SUCCESS) + context->SuppressExtendedProtection = dwValue ? 1 : 0; + + RegCloseKey(hKey); + } + + context->NegotiateFlags = 0; + context->LmCompatibilityLevel = 3; + ntlm_change_state(context, NTLM_STATE_INITIAL); + FillMemory(context->MachineID, sizeof(context->MachineID), 0xAA); + + if (context->NTLMv2) + context->UseMIC = TRUE; + + return context; +} + +static void ntlm_ContextFree(NTLM_CONTEXT* context) +{ + if (!context) + return; + + winpr_RC4_Free(context->SendRc4Seal); + winpr_RC4_Free(context->RecvRc4Seal); + sspi_SecBufferFree(&context->NegotiateMessage); + sspi_SecBufferFree(&context->ChallengeMessage); + sspi_SecBufferFree(&context->AuthenticateMessage); + sspi_SecBufferFree(&context->ChallengeTargetInfo); + sspi_SecBufferFree(&context->TargetName); + sspi_SecBufferFree(&context->NtChallengeResponse); + sspi_SecBufferFree(&context->LmChallengeResponse); + free(context->ServicePrincipalName.Buffer); + free(context->Workstation.Buffer); + free(context); +} + +static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SEC_WINPR_NTLM_SETTINGS* settings = NULL; + + if ((fCredentialUse != SECPKG_CRED_OUTBOUND) && (fCredentialUse != SECPKG_CRED_INBOUND) && + (fCredentialUse != SECPKG_CRED_BOTH)) + { + return SEC_E_INVALID_PARAMETER; + } + + SSPI_CREDENTIALS* credentials = sspi_CredentialsNew(); + + if (!credentials) + return SEC_E_INTERNAL_ERROR; + + credentials->fCredentialUse = fCredentialUse; + credentials->pGetKeyFn = pGetKeyFn; + credentials->pvGetKeyArgument = pvGetKeyArgument; + + if (pAuthData) + { + UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData); + + sspi_CopyAuthIdentity(&(credentials->identity), + (const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData); + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED) + settings = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->ntlmSettings); + } + + if (settings) + { + if (settings->samFile) + { + credentials->ntlmSettings.samFile = _strdup(settings->samFile); + if (!credentials->ntlmSettings.samFile) + { + sspi_CredentialsFree(credentials); + return SEC_E_INSUFFICIENT_MEMORY; + } + } + credentials->ntlmSettings.hashCallback = settings->hashCallback; + credentials->ntlmSettings.hashCallbackArg = settings->hashCallbackArg; + } + + sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)NTLM_PACKAGE_NAME); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY; + SEC_WCHAR* principal = NULL; + SEC_WCHAR* package = NULL; + + if (pszPrincipal) + { + principal = ConvertUtf8ToWCharAlloc(pszPrincipal, NULL); + if (!principal) + goto fail; + } + if (pszPackage) + { + package = ConvertUtf8ToWCharAlloc(pszPackage, NULL); + if (!package) + goto fail; + } + + status = + ntlm_AcquireCredentialsHandleW(principal, package, fCredentialUse, pvLogonID, pAuthData, + pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); + +fail: + free(principal); + free(package); + + return status; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(PCredHandle phCredential) +{ + if (!phCredential) + return SEC_E_INVALID_HANDLE; + + SSPI_CREDENTIALS* credentials = + (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + return SEC_E_INVALID_HANDLE; + + sspi_CredentialsFree(credentials); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + if (ulAttribute == SECPKG_CRED_ATTR_NAMES) + { + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + return ntlm_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); +} + +/** + * @see http://msdn.microsoft.com/en-us/library/windows/desktop/aa374707 + */ +static SECURITY_STATUS SEC_ENTRY +ntlm_AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, + ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp) +{ + SECURITY_STATUS status = 0; + SSPI_CREDENTIALS* credentials = NULL; + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + { + context = ntlm_ContextNew(); + + if (!context) + return SEC_E_INSUFFICIENT_MEMORY; + + context->server = TRUE; + + if (fContextReq & ASC_REQ_CONFIDENTIALITY) + context->confidentiality = TRUE; + + credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + context->credentials = credentials; + context->SamFile = credentials->ntlmSettings.samFile; + context->HashCallback = credentials->ntlmSettings.hashCallback; + context->HashCallbackArg = credentials->ntlmSettings.hashCallbackArg; + + ntlm_SetContextTargetName(context, NULL); + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, (void*)NTLM_PACKAGE_NAME); + } + + switch (ntlm_get_state(context)) + { + case NTLM_STATE_INITIAL: + { + ntlm_change_state(context, NTLM_STATE_NEGOTIATE); + + if (!pInput) + return SEC_E_INVALID_TOKEN; + + if (pInput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + + if (!input_buffer) + return SEC_E_INVALID_TOKEN; + + if (input_buffer->cbBuffer < 1) + return SEC_E_INVALID_TOKEN; + + status = ntlm_read_NegotiateMessage(context, input_buffer); + if (status != SEC_I_CONTINUE_NEEDED) + return status; + + if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE) + { + if (!pOutput) + return SEC_E_INVALID_TOKEN; + + if (pOutput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!output_buffer->BufferType) + return SEC_E_INVALID_TOKEN; + + if (output_buffer->cbBuffer < 1) + return SEC_E_INSUFFICIENT_MEMORY; + + return ntlm_write_ChallengeMessage(context, output_buffer); + } + + return SEC_E_OUT_OF_SEQUENCE; + } + + case NTLM_STATE_AUTHENTICATE: + { + if (!pInput) + return SEC_E_INVALID_TOKEN; + + if (pInput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + + if (!input_buffer) + return SEC_E_INVALID_TOKEN; + + if (input_buffer->cbBuffer < 1) + return SEC_E_INVALID_TOKEN; + + status = ntlm_read_AuthenticateMessage(context, input_buffer); + + if (pOutput) + { + for (ULONG i = 0; i < pOutput->cBuffers; i++) + { + pOutput->pBuffers[i].cbBuffer = 0; + pOutput->pBuffers[i].BufferType = SECBUFFER_TOKEN; + } + } + + return status; + } + + default: + return SEC_E_OUT_OF_SEQUENCE; + } +} + +static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SSPI_CREDENTIALS* credentials = NULL; + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (pInput) + { + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + } + + if (!context) + { + context = ntlm_ContextNew(); + + if (!context) + return SEC_E_INSUFFICIENT_MEMORY; + + if (fContextReq & ISC_REQ_CONFIDENTIALITY) + context->confidentiality = TRUE; + + credentials = (SSPI_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + context->credentials = credentials; + + if (context->Workstation.Length < 1) + { + if (ntlm_SetContextWorkstation(context, NULL) < 0) + { + ntlm_ContextFree(context); + return SEC_E_INTERNAL_ERROR; + } + } + + if (ntlm_SetContextServicePrincipalNameW(context, pszTargetName) < 0) + { + ntlm_ContextFree(context); + return SEC_E_INTERNAL_ERROR; + } + + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, NTLM_SSP_NAME); + } + + if ((!input_buffer) || (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE)) + { + if (!pOutput) + return SEC_E_INVALID_TOKEN; + + if (pOutput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!output_buffer) + return SEC_E_INVALID_TOKEN; + + if (output_buffer->cbBuffer < 1) + return SEC_E_INVALID_TOKEN; + + if (ntlm_get_state(context) == NTLM_STATE_INITIAL) + ntlm_change_state(context, NTLM_STATE_NEGOTIATE); + + if (ntlm_get_state(context) == NTLM_STATE_NEGOTIATE) + return ntlm_write_NegotiateMessage(context, output_buffer); + + return SEC_E_OUT_OF_SEQUENCE; + } + else + { + if (!input_buffer) + return SEC_E_INVALID_TOKEN; + + if (input_buffer->cbBuffer < 1) + return SEC_E_INVALID_TOKEN; + + PSecBuffer channel_bindings = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS); + + if (channel_bindings) + { + context->Bindings.BindingsLength = channel_bindings->cbBuffer; + context->Bindings.Bindings = (SEC_CHANNEL_BINDINGS*)channel_bindings->pvBuffer; + } + + if (ntlm_get_state(context) == NTLM_STATE_CHALLENGE) + { + status = ntlm_read_ChallengeMessage(context, input_buffer); + + if (status != SEC_I_CONTINUE_NEEDED) + return status; + + if (!pOutput) + return SEC_E_INVALID_TOKEN; + + if (pOutput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!output_buffer) + return SEC_E_INVALID_TOKEN; + + if (output_buffer->cbBuffer < 1) + return SEC_E_INSUFFICIENT_MEMORY; + + if (ntlm_get_state(context) == NTLM_STATE_AUTHENTICATE) + return ntlm_write_AuthenticateMessage(context, output_buffer); + } + + return SEC_E_OUT_OF_SEQUENCE; + } + + return SEC_E_OUT_OF_SEQUENCE; +} + +/** + * @see http://msdn.microsoft.com/en-us/library/windows/desktop/aa375512%28v=vs.85%29.aspx + */ +static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SEC_WCHAR* pszTargetNameW = NULL; + + if (pszTargetName) + { + pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, NULL); + if (!pszTargetNameW) + return SEC_E_INTERNAL_ERROR; + } + + status = ntlm_InitializeSecurityContextW(phCredential, phContext, pszTargetNameW, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); + free(pszTargetNameW); + return status; +} + +/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375354 */ + +static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext) +{ + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + ntlm_ContextFree(context); + return SEC_E_OK; +} + +SECURITY_STATUS ntlm_computeProofValue(NTLM_CONTEXT* ntlm, SecBuffer* ntproof) +{ + BYTE* blob = NULL; + SecBuffer* target = NULL; + + WINPR_ASSERT(ntlm); + WINPR_ASSERT(ntproof); + + target = &ntlm->ChallengeTargetInfo; + + if (!sspi_SecBufferAlloc(ntproof, 36 + target->cbBuffer)) + return SEC_E_INSUFFICIENT_MEMORY; + + blob = (BYTE*)ntproof->pvBuffer; + CopyMemory(blob, ntlm->ServerChallenge, 8); /* Server challenge. */ + blob[8] = 1; /* Response version. */ + blob[9] = 1; /* Highest response version understood by the client. */ + /* Reserved 6B. */ + CopyMemory(&blob[16], ntlm->Timestamp, 8); /* Time. */ + CopyMemory(&blob[24], ntlm->ClientChallenge, 8); /* Client challenge. */ + /* Reserved 4B. */ + /* Server name. */ + CopyMemory(&blob[36], target->pvBuffer, target->cbBuffer); + return SEC_E_OK; +} + +SECURITY_STATUS ntlm_computeMicValue(NTLM_CONTEXT* ntlm, SecBuffer* micvalue) +{ + BYTE* blob = NULL; + ULONG msgSize = 0; + + WINPR_ASSERT(ntlm); + WINPR_ASSERT(micvalue); + + msgSize = ntlm->NegotiateMessage.cbBuffer + ntlm->ChallengeMessage.cbBuffer + + ntlm->AuthenticateMessage.cbBuffer; + + if (!sspi_SecBufferAlloc(micvalue, msgSize)) + return SEC_E_INSUFFICIENT_MEMORY; + + blob = (BYTE*)micvalue->pvBuffer; + CopyMemory(blob, ntlm->NegotiateMessage.pvBuffer, ntlm->NegotiateMessage.cbBuffer); + blob += ntlm->NegotiateMessage.cbBuffer; + CopyMemory(blob, ntlm->ChallengeMessage.pvBuffer, ntlm->ChallengeMessage.cbBuffer); + blob += ntlm->ChallengeMessage.cbBuffer; + CopyMemory(blob, ntlm->AuthenticateMessage.pvBuffer, ntlm->AuthenticateMessage.cbBuffer); + blob += ntlm->MessageIntegrityCheckOffset; + ZeroMemory(blob, 16); + return SEC_E_OK; +} + +/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa379337/ */ + +static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + if (!phContext) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INSUFFICIENT_MEMORY; + + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + if (!check_context(context)) + return SEC_E_INVALID_HANDLE; + + if (ulAttribute == SECPKG_ATTR_SIZES) + { + SecPkgContext_Sizes* ContextSizes = (SecPkgContext_Sizes*)pBuffer; + ContextSizes->cbMaxToken = 2010; + ContextSizes->cbMaxSignature = 16; /* the size of expected signature is 16 bytes */ + ContextSizes->cbBlockSize = 0; /* no padding */ + ContextSizes->cbSecurityTrailer = 16; /* no security trailer appended in NTLM + contrary to Kerberos */ + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_IDENTITY) + { + SSPI_CREDENTIALS* credentials = NULL; + const SecPkgContext_AuthIdentity empty = { 0 }; + SecPkgContext_AuthIdentity* AuthIdentity = (SecPkgContext_AuthIdentity*)pBuffer; + + WINPR_ASSERT(AuthIdentity); + *AuthIdentity = empty; + + context->UseSamFileDatabase = FALSE; + credentials = context->credentials; + + if (credentials->identity.UserLength > 0) + { + if (ConvertWCharNToUtf8(credentials->identity.User, credentials->identity.UserLength, + AuthIdentity->User, ARRAYSIZE(AuthIdentity->User)) <= 0) + return SEC_E_INTERNAL_ERROR; + } + + if (credentials->identity.DomainLength > 0) + { + if (ConvertWCharNToUtf8(credentials->identity.Domain, + credentials->identity.DomainLength, AuthIdentity->Domain, + ARRAYSIZE(AuthIdentity->Domain)) <= 0) + return SEC_E_INTERNAL_ERROR; + } + + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_NTPROOF_VALUE) + { + return ntlm_computeProofValue(context, (SecBuffer*)pBuffer); + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_RANDKEY) + { + SecBuffer* randkey = NULL; + randkey = (SecBuffer*)pBuffer; + + if (!sspi_SecBufferAlloc(randkey, 16)) + return (SEC_E_INSUFFICIENT_MEMORY); + + CopyMemory(randkey->pvBuffer, context->EncryptedRandomSessionKey, 16); + return (SEC_E_OK); + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC) + { + SecBuffer* mic = (SecBuffer*)pBuffer; + NTLM_AUTHENTICATE_MESSAGE* message = &context->AUTHENTICATE_MESSAGE; + + if (!sspi_SecBufferAlloc(mic, 16)) + return (SEC_E_INSUFFICIENT_MEMORY); + + CopyMemory(mic->pvBuffer, message->MessageIntegrityCheck, 16); + return (SEC_E_OK); + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MIC_VALUE) + { + return ntlm_computeMicValue(context, (SecBuffer*)pBuffer); + } + + WLog_ERR(TAG, "TODO: Implement ulAttribute=0x%08" PRIx32, ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer); +} + +static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + if (!phContext) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INVALID_PARAMETER; + + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + if (!context) + return SEC_E_INVALID_HANDLE; + + if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_HASH) + { + SecPkgContext_AuthNtlmHash* AuthNtlmHash = (SecPkgContext_AuthNtlmHash*)pBuffer; + + if (cbBuffer < sizeof(SecPkgContext_AuthNtlmHash)) + return SEC_E_INVALID_PARAMETER; + + if (AuthNtlmHash->Version == 1) + CopyMemory(context->NtlmHash, AuthNtlmHash->NtlmHash, 16); + else if (AuthNtlmHash->Version == 2) + CopyMemory(context->NtlmV2Hash, AuthNtlmHash->NtlmHash, 16); + + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_MESSAGE) + { + SecPkgContext_AuthNtlmMessage* AuthNtlmMessage = (SecPkgContext_AuthNtlmMessage*)pBuffer; + + if (cbBuffer < sizeof(SecPkgContext_AuthNtlmMessage)) + return SEC_E_INVALID_PARAMETER; + + if (AuthNtlmMessage->type == 1) + { + sspi_SecBufferFree(&context->NegotiateMessage); + + if (!sspi_SecBufferAlloc(&context->NegotiateMessage, AuthNtlmMessage->length)) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(context->NegotiateMessage.pvBuffer, AuthNtlmMessage->buffer, + AuthNtlmMessage->length); + } + else if (AuthNtlmMessage->type == 2) + { + sspi_SecBufferFree(&context->ChallengeMessage); + + if (!sspi_SecBufferAlloc(&context->ChallengeMessage, AuthNtlmMessage->length)) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(context->ChallengeMessage.pvBuffer, AuthNtlmMessage->buffer, + AuthNtlmMessage->length); + } + else if (AuthNtlmMessage->type == 3) + { + sspi_SecBufferFree(&context->AuthenticateMessage); + + if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, AuthNtlmMessage->length)) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(context->AuthenticateMessage.pvBuffer, AuthNtlmMessage->buffer, + AuthNtlmMessage->length); + } + + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_TIMESTAMP) + { + SecPkgContext_AuthNtlmTimestamp* AuthNtlmTimestamp = + (SecPkgContext_AuthNtlmTimestamp*)pBuffer; + + if (cbBuffer < sizeof(SecPkgContext_AuthNtlmTimestamp)) + return SEC_E_INVALID_PARAMETER; + + if (AuthNtlmTimestamp->ChallengeOrResponse) + CopyMemory(context->ChallengeTimestamp, AuthNtlmTimestamp->Timestamp, 8); + else + CopyMemory(context->Timestamp, AuthNtlmTimestamp->Timestamp, 8); + + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE) + { + SecPkgContext_AuthNtlmClientChallenge* AuthNtlmClientChallenge = + (SecPkgContext_AuthNtlmClientChallenge*)pBuffer; + + if (cbBuffer < sizeof(SecPkgContext_AuthNtlmClientChallenge)) + return SEC_E_INVALID_PARAMETER; + + CopyMemory(context->ClientChallenge, AuthNtlmClientChallenge->ClientChallenge, 8); + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE) + { + SecPkgContext_AuthNtlmServerChallenge* AuthNtlmServerChallenge = + (SecPkgContext_AuthNtlmServerChallenge*)pBuffer; + + if (cbBuffer < sizeof(SecPkgContext_AuthNtlmServerChallenge)) + return SEC_E_INVALID_PARAMETER; + + CopyMemory(context->ServerChallenge, AuthNtlmServerChallenge->ServerChallenge, 8); + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_SetContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + return ntlm_SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer); +} + +static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_SetCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + const UINT32 SeqNo = MessageSeqNo; + UINT32 value = 0; + BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + BYTE checksum[8] = { 0 }; + ULONG version = 1; + PSecBuffer data_buffer = NULL; + PSecBuffer signature_buffer = NULL; + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + if (!check_context(context)) + return SEC_E_INVALID_HANDLE; + + for (ULONG index = 0; index < pMessage->cBuffers; index++) + { + SecBuffer* cur = &pMessage->pBuffers[index]; + + if (cur->BufferType & SECBUFFER_DATA) + data_buffer = cur; + else if (cur->BufferType & SECBUFFER_TOKEN) + signature_buffer = cur; + } + + if (!data_buffer) + return SEC_E_INVALID_TOKEN; + + if (!signature_buffer) + return SEC_E_INVALID_TOKEN; + + /* Copy original data buffer */ + ULONG length = data_buffer->cbBuffer; + void* data = malloc(length); + + if (!data) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(data, data_buffer->pvBuffer, length); + /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */ + WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); + + if (hmac && + winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH)) + { + winpr_Data_Write_UINT32(&value, SeqNo); + winpr_HMAC_Update(hmac, (void*)&value, 4); + winpr_HMAC_Update(hmac, data, length); + winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH); + winpr_HMAC_Free(hmac); + } + else + { + winpr_HMAC_Free(hmac); + free(data); + return SEC_E_INSUFFICIENT_MEMORY; + } + + /* Encrypt message using with RC4, result overwrites original buffer */ + if ((data_buffer->BufferType & SECBUFFER_READONLY) == 0) + { + if (context->confidentiality) + winpr_RC4_Update(context->SendRc4Seal, length, (BYTE*)data, + (BYTE*)data_buffer->pvBuffer); + else + CopyMemory(data_buffer->pvBuffer, data, length); + } + +#ifdef WITH_DEBUG_NTLM + WLog_DBG(TAG, "Data Buffer (length = %" PRIuz ")", length); + winpr_HexDump(TAG, WLOG_DEBUG, data, length); + WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer); + winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer); +#endif + free(data); + /* RC4-encrypt first 8 bytes of digest */ + winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum); + if ((signature_buffer->BufferType & SECBUFFER_READONLY) == 0) + { + BYTE* signature = signature_buffer->pvBuffer; + /* Concatenate version, ciphertext and sequence number to build signature */ + winpr_Data_Write_UINT32(signature, version); + CopyMemory(&signature[4], (void*)checksum, 8); + winpr_Data_Write_UINT32(&signature[12], SeqNo); + } + context->SendSeqNum++; +#ifdef WITH_DEBUG_NTLM + WLog_DBG(TAG, "Signature (length = %" PRIu32 ")", signature_buffer->cbBuffer); + winpr_HexDump(TAG, WLOG_DEBUG, signature_buffer->pvBuffer, signature_buffer->cbBuffer); +#endif + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, + ULONG MessageSeqNo, PULONG pfQOP) +{ + const UINT32 SeqNo = (UINT32)MessageSeqNo; + UINT32 value = 0; + BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + BYTE checksum[8] = { 0 }; + UINT32 version = 1; + BYTE expected_signature[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + PSecBuffer data_buffer = NULL; + PSecBuffer signature_buffer = NULL; + NTLM_CONTEXT* context = (NTLM_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + if (!check_context(context)) + return SEC_E_INVALID_HANDLE; + + for (ULONG index = 0; index < pMessage->cBuffers; index++) + { + if (pMessage->pBuffers[index].BufferType == SECBUFFER_DATA) + data_buffer = &pMessage->pBuffers[index]; + else if (pMessage->pBuffers[index].BufferType == SECBUFFER_TOKEN) + signature_buffer = &pMessage->pBuffers[index]; + } + + if (!data_buffer) + return SEC_E_INVALID_TOKEN; + + if (!signature_buffer) + return SEC_E_INVALID_TOKEN; + + /* Copy original data buffer */ + const ULONG length = data_buffer->cbBuffer; + void* data = malloc(length); + + if (!data) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(data, data_buffer->pvBuffer, length); + + /* Decrypt message using with RC4, result overwrites original buffer */ + + if (context->confidentiality) + winpr_RC4_Update(context->RecvRc4Seal, length, (BYTE*)data, (BYTE*)data_buffer->pvBuffer); + else + CopyMemory(data_buffer->pvBuffer, data, length); + + /* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */ + WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); + + if (hmac && + winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH)) + { + winpr_Data_Write_UINT32(&value, SeqNo); + winpr_HMAC_Update(hmac, (void*)&value, 4); + winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer); + winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH); + winpr_HMAC_Free(hmac); + } + else + { + winpr_HMAC_Free(hmac); + free(data); + return SEC_E_INSUFFICIENT_MEMORY; + } + +#ifdef WITH_DEBUG_NTLM + WLog_DBG(TAG, "Encrypted Data Buffer (length = %" PRIuz ")", length); + winpr_HexDump(TAG, WLOG_DEBUG, data, length); + WLog_DBG(TAG, "Data Buffer (length = %" PRIu32 ")", data_buffer->cbBuffer); + winpr_HexDump(TAG, WLOG_DEBUG, data_buffer->pvBuffer, data_buffer->cbBuffer); +#endif + free(data); + /* RC4-encrypt first 8 bytes of digest */ + winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum); + /* Concatenate version, ciphertext and sequence number to build signature */ + winpr_Data_Write_UINT32(expected_signature, version); + CopyMemory(&expected_signature[4], (void*)checksum, 8); + winpr_Data_Write_UINT32(&expected_signature[12], SeqNo); + context->RecvSeqNum++; + + if (memcmp(signature_buffer->pvBuffer, expected_signature, 16) != 0) + { + /* signature verification failed! */ + WLog_ERR(TAG, "signature verification failed, something nasty is going on!"); +#ifdef WITH_DEBUG_NTLM + WLog_ERR(TAG, "Expected Signature:"); + winpr_HexDump(TAG, WLOG_ERROR, expected_signature, 16); + WLog_ERR(TAG, "Actual Signature:"); + winpr_HexDump(TAG, WLOG_ERROR, (BYTE*)signature_buffer->pvBuffer, 16); +#endif + return SEC_E_MESSAGE_ALTERED; + } + + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + PSecBuffer data_buffer = NULL; + PSecBuffer sig_buffer = NULL; + UINT32 seq_no = 0; + BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + BYTE checksum[8] = { 0 }; + + NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext); + if (!check_context(context)) + return SEC_E_INVALID_HANDLE; + + for (ULONG i = 0; i < pMessage->cBuffers; i++) + { + if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA) + data_buffer = &pMessage->pBuffers[i]; + else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN) + sig_buffer = &pMessage->pBuffers[i]; + } + + if (!data_buffer || !sig_buffer) + return SEC_E_INVALID_TOKEN; + + WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); + + if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->SendSigningKey, WINPR_MD5_DIGEST_LENGTH)) + { + winpr_HMAC_Free(hmac); + return SEC_E_INTERNAL_ERROR; + } + + winpr_Data_Write_UINT32(&seq_no, MessageSeqNo); + winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4); + winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer); + winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH); + winpr_HMAC_Free(hmac); + + winpr_RC4_Update(context->SendRc4Seal, 8, digest, checksum); + + BYTE* signature = sig_buffer->pvBuffer; + winpr_Data_Write_UINT32(signature, 1L); + CopyMemory(&signature[4], checksum, 8); + winpr_Data_Write_UINT32(&signature[12], seq_no); + sig_buffer->cbBuffer = 16; + + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP) +{ + PSecBuffer data_buffer = NULL; + PSecBuffer sig_buffer = NULL; + UINT32 seq_no = 0; + BYTE digest[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + BYTE checksum[8] = { 0 }; + BYTE signature[16] = { 0 }; + + NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext); + if (!check_context(context)) + return SEC_E_INVALID_HANDLE; + + for (ULONG i = 0; i < pMessage->cBuffers; i++) + { + if (pMessage->pBuffers[i].BufferType == SECBUFFER_DATA) + data_buffer = &pMessage->pBuffers[i]; + else if (pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN) + sig_buffer = &pMessage->pBuffers[i]; + } + + if (!data_buffer || !sig_buffer) + return SEC_E_INVALID_TOKEN; + + WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); + + if (!winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->RecvSigningKey, WINPR_MD5_DIGEST_LENGTH)) + { + winpr_HMAC_Free(hmac); + return SEC_E_INTERNAL_ERROR; + } + + winpr_Data_Write_UINT32(&seq_no, MessageSeqNo); + winpr_HMAC_Update(hmac, (BYTE*)&seq_no, 4); + winpr_HMAC_Update(hmac, data_buffer->pvBuffer, data_buffer->cbBuffer); + winpr_HMAC_Final(hmac, digest, WINPR_MD5_DIGEST_LENGTH); + winpr_HMAC_Free(hmac); + + winpr_RC4_Update(context->RecvRc4Seal, 8, digest, checksum); + + winpr_Data_Write_UINT32(signature, 1L); + CopyMemory(&signature[4], checksum, 8); + winpr_Data_Write_UINT32(&signature[12], seq_no); + + if (memcmp(sig_buffer->pvBuffer, signature, 16) != 0) + return SEC_E_MESSAGE_ALTERED; + + return SEC_E_OK; +} + +const SecurityFunctionTableA NTLM_SecurityFunctionTableA = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + ntlm_InitializeSecurityContextA, /* InitializeSecurityContext */ + ntlm_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + ntlm_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + ntlm_QueryContextAttributesA, /* QueryContextAttributes */ + ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + ntlm_RevertSecurityContext, /* RevertSecurityContext */ + ntlm_MakeSignature, /* MakeSignature */ + ntlm_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + ntlm_EncryptMessage, /* EncryptMessage */ + ntlm_DecryptMessage, /* DecryptMessage */ + ntlm_SetContextAttributesA, /* SetContextAttributes */ + ntlm_SetCredentialsAttributesA, /* SetCredentialsAttributes */ +}; + +const SecurityFunctionTableW NTLM_SecurityFunctionTableW = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + ntlm_InitializeSecurityContextW, /* InitializeSecurityContext */ + ntlm_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + ntlm_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + ntlm_QueryContextAttributesW, /* QueryContextAttributes */ + ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + ntlm_RevertSecurityContext, /* RevertSecurityContext */ + ntlm_MakeSignature, /* MakeSignature */ + ntlm_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + ntlm_EncryptMessage, /* EncryptMessage */ + ntlm_DecryptMessage, /* DecryptMessage */ + ntlm_SetContextAttributesW, /* SetContextAttributes */ + ntlm_SetCredentialsAttributesW, /* SetCredentialsAttributes */ +}; + +const SecPkgInfoA NTLM_SecPkgInfoA = { + 0x00082B37, /* fCapabilities */ + 1, /* wVersion */ + 0x000A, /* wRPCID */ + 0x00000B48, /* cbMaxToken */ + "NTLM", /* Name */ + "NTLM Security Package" /* Comment */ +}; + +static WCHAR NTLM_SecPkgInfoW_NameBuffer[32] = { 0 }; +static WCHAR NTLM_SecPkgInfoW_CommentBuffer[32] = { 0 }; + +const SecPkgInfoW NTLM_SecPkgInfoW = { + 0x00082B37, /* fCapabilities */ + 1, /* wVersion */ + 0x000A, /* wRPCID */ + 0x00000B48, /* cbMaxToken */ + NTLM_SecPkgInfoW_NameBuffer, /* Name */ + NTLM_SecPkgInfoW_CommentBuffer /* Comment */ +}; + +char* ntlm_negotiate_flags_string(char* buffer, size_t size, UINT32 flags) +{ + if (!buffer || (size == 0)) + return buffer; + + (void)_snprintf(buffer, size, "[0x%08" PRIx32 "] ", flags); + + for (int x = 0; x < 31; x++) + { + const UINT32 mask = 1 << x; + size_t len = strnlen(buffer, size); + if (flags & mask) + { + const char* str = ntlm_get_negotiate_string(mask); + const size_t flen = strlen(str); + + if ((len > 0) && (buffer[len - 1] != ' ')) + { + if (size - len < 1) + break; + winpr_str_append("|", buffer, size, NULL); + len++; + } + + if (size - len < flen) + break; + winpr_str_append(str, buffer, size, NULL); + } + } + + return buffer; +} + +const char* ntlm_message_type_string(UINT32 messageType) +{ + switch (messageType) + { + case MESSAGE_TYPE_NEGOTIATE: + return "MESSAGE_TYPE_NEGOTIATE"; + case MESSAGE_TYPE_CHALLENGE: + return "MESSAGE_TYPE_CHALLENGE"; + case MESSAGE_TYPE_AUTHENTICATE: + return "MESSAGE_TYPE_AUTHENTICATE"; + default: + return "MESSAGE_TYPE_UNKNOWN"; + } +} + +const char* ntlm_state_string(NTLM_STATE state) +{ + switch (state) + { + case NTLM_STATE_INITIAL: + return "NTLM_STATE_INITIAL"; + case NTLM_STATE_NEGOTIATE: + return "NTLM_STATE_NEGOTIATE"; + case NTLM_STATE_CHALLENGE: + return "NTLM_STATE_CHALLENGE"; + case NTLM_STATE_AUTHENTICATE: + return "NTLM_STATE_AUTHENTICATE"; + case NTLM_STATE_FINAL: + return "NTLM_STATE_FINAL"; + default: + return "NTLM_STATE_UNKNOWN"; + } +} +void ntlm_change_state(NTLM_CONTEXT* ntlm, NTLM_STATE state) +{ + WINPR_ASSERT(ntlm); + WLog_DBG(TAG, "change state from %s to %s", ntlm_state_string(ntlm->state), + ntlm_state_string(state)); + ntlm->state = state; +} + +NTLM_STATE ntlm_get_state(NTLM_CONTEXT* ntlm) +{ + WINPR_ASSERT(ntlm); + return ntlm->state; +} + +BOOL ntlm_reset_cipher_state(PSecHandle phContext) +{ + NTLM_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext); + + if (context) + { + check_context(context); + winpr_RC4_Free(context->SendRc4Seal); + winpr_RC4_Free(context->RecvRc4Seal); + context->SendRc4Seal = winpr_RC4_New(context->RecvSealingKey, 16); + context->RecvRc4Seal = winpr_RC4_New(context->SendSealingKey, 16); + + if (!context->SendRc4Seal) + { + WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal"); + return FALSE; + } + if (!context->RecvRc4Seal) + { + WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal"); + return FALSE; + } + } + + return TRUE; +} + +BOOL NTLM_init(void) +{ + InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Name, NTLM_SecPkgInfoW_NameBuffer, + ARRAYSIZE(NTLM_SecPkgInfoW_NameBuffer)); + InitializeConstWCharFromUtf8(NTLM_SecPkgInfoA.Comment, NTLM_SecPkgInfoW_CommentBuffer, + ARRAYSIZE(NTLM_SecPkgInfoW_CommentBuffer)); + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.h new file mode 100644 index 0000000000000000000000000000000000000000..4eac436c18f97cc93b8b4e98a5f53ad26f4f266e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm.h @@ -0,0 +1,301 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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_NTLM_PRIVATE_H +#define WINPR_SSPI_NTLM_PRIVATE_H + +#include +#include + +#include +#include + +#include "../sspi.h" + +#define MESSAGE_TYPE_NEGOTIATE 1 +#define MESSAGE_TYPE_CHALLENGE 2 +#define MESSAGE_TYPE_AUTHENTICATE 3 + +#define NTLMSSP_NEGOTIATE_56 0x80000000 /* W (0) */ +#define NTLMSSP_NEGOTIATE_KEY_EXCH 0x40000000 /* V (1) */ +#define NTLMSSP_NEGOTIATE_128 0x20000000 /* U (2) */ +#define NTLMSSP_RESERVED1 0x10000000 /* r1 (3) */ +#define NTLMSSP_RESERVED2 0x08000000 /* r2 (4) */ +#define NTLMSSP_RESERVED3 0x04000000 /* r3 (5) */ +#define NTLMSSP_NEGOTIATE_VERSION 0x02000000 /* T (6) */ +#define NTLMSSP_RESERVED4 0x01000000 /* r4 (7) */ +#define NTLMSSP_NEGOTIATE_TARGET_INFO 0x00800000 /* S (8) */ +#define NTLMSSP_REQUEST_NON_NT_SESSION_KEY 0x00400000 /* R (9) */ +#define NTLMSSP_RESERVED5 0x00200000 /* r5 (10) */ +#define NTLMSSP_NEGOTIATE_IDENTIFY 0x00100000 /* Q (11) */ +#define NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY 0x00080000 /* P (12) */ +#define NTLMSSP_RESERVED6 0x00040000 /* r6 (13) */ +#define NTLMSSP_TARGET_TYPE_SERVER 0x00020000 /* O (14) */ +#define NTLMSSP_TARGET_TYPE_DOMAIN 0x00010000 /* N (15) */ +#define NTLMSSP_NEGOTIATE_ALWAYS_SIGN 0x00008000 /* M (16) */ +#define NTLMSSP_RESERVED7 0x00004000 /* r7 (17) */ +#define NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED 0x00002000 /* L (18) */ +#define NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED 0x00001000 /* K (19) */ +#define NTLMSSP_NEGOTIATE_ANONYMOUS 0x00000800 /* J (20) */ +#define NTLMSSP_RESERVED8 0x00000400 /* r8 (21) */ +#define NTLMSSP_NEGOTIATE_NTLM 0x00000200 /* H (22) */ +#define NTLMSSP_RESERVED9 0x00000100 /* r9 (23) */ +#define NTLMSSP_NEGOTIATE_LM_KEY 0x00000080 /* G (24) */ +#define NTLMSSP_NEGOTIATE_DATAGRAM 0x00000040 /* F (25) */ +#define NTLMSSP_NEGOTIATE_SEAL 0x00000020 /* E (26) */ +#define NTLMSSP_NEGOTIATE_SIGN 0x00000010 /* D (27) */ +#define NTLMSSP_RESERVED10 0x00000008 /* r10 (28) */ +#define NTLMSSP_REQUEST_TARGET 0x00000004 /* C (29) */ +#define NTLMSSP_NEGOTIATE_OEM 0x00000002 /* B (30) */ +#define NTLMSSP_NEGOTIATE_UNICODE 0x00000001 /* A (31) */ + +typedef enum +{ + NTLM_STATE_INITIAL, + NTLM_STATE_NEGOTIATE, + NTLM_STATE_CHALLENGE, + NTLM_STATE_AUTHENTICATE, + NTLM_STATE_FINAL +} NTLM_STATE; + +#ifdef __MINGW32__ +typedef MSV1_0_AVID NTLM_AV_ID; + +#if __MINGW64_VERSION_MAJOR < 9 +enum +{ + MsvAvTimestamp = MsvAvFlags + 1, + MsvAvRestrictions, + MsvAvTargetName, + MsvAvChannelBindings, + MsvAvSingleHost = MsvAvRestrictions +}; + +#else +#ifndef MsvAvSingleHost +#define MsvAvSingleHost MsvAvRestrictions +#endif +#endif +#else +typedef enum +{ + MsvAvEOL, + MsvAvNbComputerName, + MsvAvNbDomainName, + MsvAvDnsComputerName, + MsvAvDnsDomainName, + MsvAvDnsTreeName, + MsvAvFlags, + MsvAvTimestamp, + MsvAvSingleHost, + MsvAvTargetName, + MsvAvChannelBindings +} NTLM_AV_ID; +#endif /* __MINGW32__ */ + +typedef struct +{ + UINT16 AvId; + UINT16 AvLen; +} NTLM_AV_PAIR; + +#define MSV_AV_FLAGS_AUTHENTICATION_CONSTRAINED 0x00000001 +#define MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK 0x00000002 +#define MSV_AV_FLAGS_TARGET_SPN_UNTRUSTED_SOURCE 0x00000004 + +#define WINDOWS_MAJOR_VERSION_5 0x05 +#define WINDOWS_MAJOR_VERSION_6 0x06 +#define WINDOWS_MINOR_VERSION_0 0x00 +#define WINDOWS_MINOR_VERSION_1 0x01 +#define WINDOWS_MINOR_VERSION_2 0x02 +#define NTLMSSP_REVISION_W2K3 0x0F + +typedef struct +{ + UINT8 ProductMajorVersion; + UINT8 ProductMinorVersion; + UINT16 ProductBuild; + BYTE Reserved[3]; + UINT8 NTLMRevisionCurrent; +} NTLM_VERSION_INFO; + +typedef struct +{ + UINT32 Size; + UINT32 Z4; + UINT32 DataPresent; + UINT32 CustomData; + BYTE MachineID[32]; +} NTLM_SINGLE_HOST_DATA; + +typedef struct +{ + BYTE Response[24]; +} NTLM_RESPONSE; + +typedef struct +{ + UINT8 RespType; + UINT8 HiRespType; + UINT16 Reserved1; + UINT32 Reserved2; + BYTE Timestamp[8]; + BYTE ClientChallenge[8]; + UINT32 Reserved3; + NTLM_AV_PAIR* AvPairs; + UINT32 cbAvPairs; +} NTLMv2_CLIENT_CHALLENGE; + +typedef struct +{ + BYTE Response[16]; + NTLMv2_CLIENT_CHALLENGE Challenge; +} NTLMv2_RESPONSE; + +typedef struct +{ + UINT16 Len; + UINT16 MaxLen; + PBYTE Buffer; + UINT32 BufferOffset; +} NTLM_MESSAGE_FIELDS; + +typedef struct +{ + BYTE Signature[8]; + UINT32 MessageType; +} NTLM_MESSAGE_HEADER; + +typedef struct +{ + NTLM_MESSAGE_HEADER header; + UINT32 NegotiateFlags; + NTLM_VERSION_INFO Version; + NTLM_MESSAGE_FIELDS DomainName; + NTLM_MESSAGE_FIELDS Workstation; +} NTLM_NEGOTIATE_MESSAGE; + +typedef struct +{ + NTLM_MESSAGE_HEADER header; + UINT32 NegotiateFlags; + BYTE ServerChallenge[8]; + BYTE Reserved[8]; + NTLM_VERSION_INFO Version; + NTLM_MESSAGE_FIELDS TargetName; + NTLM_MESSAGE_FIELDS TargetInfo; +} NTLM_CHALLENGE_MESSAGE; + +typedef struct +{ + NTLM_MESSAGE_HEADER header; + UINT32 NegotiateFlags; + NTLM_VERSION_INFO Version; + NTLM_MESSAGE_FIELDS DomainName; + NTLM_MESSAGE_FIELDS UserName; + NTLM_MESSAGE_FIELDS Workstation; + NTLM_MESSAGE_FIELDS LmChallengeResponse; + NTLM_MESSAGE_FIELDS NtChallengeResponse; + NTLM_MESSAGE_FIELDS EncryptedRandomSessionKey; + BYTE MessageIntegrityCheck[16]; +} NTLM_AUTHENTICATE_MESSAGE; + +typedef struct +{ + BOOL server; + BOOL NTLMv2; + BOOL UseMIC; + NTLM_STATE state; + int SendSeqNum; + int RecvSeqNum; + char* SamFile; + BYTE NtlmHash[16]; + BYTE NtlmV2Hash[16]; + BYTE MachineID[32]; + BOOL SendVersionInfo; + BOOL confidentiality; + WINPR_RC4_CTX* SendRc4Seal; + WINPR_RC4_CTX* RecvRc4Seal; + BYTE* SendSigningKey; + BYTE* RecvSigningKey; + BYTE* SendSealingKey; + BYTE* RecvSealingKey; + UINT32 NegotiateFlags; + BOOL UseSamFileDatabase; + int LmCompatibilityLevel; + int SuppressExtendedProtection; + BOOL SendWorkstationName; + UNICODE_STRING Workstation; + UNICODE_STRING ServicePrincipalName; + SSPI_CREDENTIALS* credentials; + BYTE* ChannelBindingToken; + BYTE ChannelBindingsHash[16]; + SecPkgContext_Bindings Bindings; + BOOL SendSingleHostData; + BOOL NegotiateKeyExchange; + NTLM_SINGLE_HOST_DATA SingleHostData; + NTLM_NEGOTIATE_MESSAGE NEGOTIATE_MESSAGE; + NTLM_CHALLENGE_MESSAGE CHALLENGE_MESSAGE; + NTLM_AUTHENTICATE_MESSAGE AUTHENTICATE_MESSAGE; + size_t MessageIntegrityCheckOffset; + SecBuffer NegotiateMessage; + SecBuffer ChallengeMessage; + SecBuffer AuthenticateMessage; + SecBuffer ChallengeTargetInfo; + SecBuffer AuthenticateTargetInfo; + SecBuffer TargetName; + SecBuffer NtChallengeResponse; + SecBuffer LmChallengeResponse; + NTLMv2_RESPONSE NTLMv2Response; + BYTE NtProofString[16]; + BYTE Timestamp[8]; + BYTE ChallengeTimestamp[8]; + BYTE ServerChallenge[8]; + BYTE ClientChallenge[8]; + BYTE SessionBaseKey[16]; + BYTE KeyExchangeKey[16]; + BYTE RandomSessionKey[16]; + BYTE ExportedSessionKey[16]; + BYTE EncryptedRandomSessionKey[16]; + BYTE ClientSigningKey[16]; + BYTE ClientSealingKey[16]; + BYTE ServerSigningKey[16]; + BYTE ServerSealingKey[16]; + psSspiNtlmHashCallback HashCallback; + void* HashCallbackArg; +} NTLM_CONTEXT; + +char* ntlm_negotiate_flags_string(char* buffer, size_t size, UINT32 flags); +const char* ntlm_message_type_string(UINT32 messageType); + +const char* ntlm_state_string(NTLM_STATE state); +void ntlm_change_state(NTLM_CONTEXT* ntlm, NTLM_STATE state); +NTLM_STATE ntlm_get_state(NTLM_CONTEXT* ntlm); +BOOL ntlm_reset_cipher_state(PSecHandle phContext); + +SECURITY_STATUS ntlm_computeProofValue(NTLM_CONTEXT* ntlm, SecBuffer* ntproof); +SECURITY_STATUS ntlm_computeMicValue(NTLM_CONTEXT* ntlm, SecBuffer* micvalue); + +#ifdef WITH_DEBUG_NLA +#define WITH_DEBUG_NTLM +#endif + +BOOL NTLM_init(void); + +#endif /* WINPR_SSPI_NTLM_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c new file mode 100644 index 0000000000000000000000000000000000000000..ef6a232a0f8313f1cef2bcd11e23b20f4d7d2b9f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c @@ -0,0 +1,778 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (AV_PAIRs) + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "ntlm.h" +#include "../sspi.h" + +#include +#include +#include +#include +#include + +#include "ntlm_compute.h" + +#include "ntlm_av_pairs.h" + +#include "../../log.h" +#define TAG WINPR_TAG("sspi.NTLM") + +static BOOL ntlm_av_pair_get_next_offset(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pOffset); + +static BOOL ntlm_av_pair_check_data(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair, size_t size) +{ + size_t offset = 0; + if (!pAvPair || cbAvPair < sizeof(NTLM_AV_PAIR) + size) + return FALSE; + if (!ntlm_av_pair_get_next_offset(pAvPair, cbAvPair, &offset)) + return FALSE; + return cbAvPair >= offset; +} + +static const char* get_av_pair_string(UINT16 pair) +{ + switch (pair) + { + case MsvAvEOL: + return "MsvAvEOL"; + case MsvAvNbComputerName: + return "MsvAvNbComputerName"; + case MsvAvNbDomainName: + return "MsvAvNbDomainName"; + case MsvAvDnsComputerName: + return "MsvAvDnsComputerName"; + case MsvAvDnsDomainName: + return "MsvAvDnsDomainName"; + case MsvAvDnsTreeName: + return "MsvAvDnsTreeName"; + case MsvAvFlags: + return "MsvAvFlags"; + case MsvAvTimestamp: + return "MsvAvTimestamp"; + case MsvAvSingleHost: + return "MsvAvSingleHost"; + case MsvAvTargetName: + return "MsvAvTargetName"; + case MsvAvChannelBindings: + return "MsvAvChannelBindings"; + default: + return "UNKNOWN"; + } +} + +static BOOL ntlm_av_pair_check(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair); +static NTLM_AV_PAIR* ntlm_av_pair_next(NTLM_AV_PAIR* pAvPairList, size_t* pcbAvPairList); + +static INLINE void ntlm_av_pair_set_id(NTLM_AV_PAIR* pAvPair, UINT16 id) +{ + WINPR_ASSERT(pAvPair); + winpr_Data_Write_UINT16(&pAvPair->AvId, id); +} + +static INLINE void ntlm_av_pair_set_len(NTLM_AV_PAIR* pAvPair, UINT16 len) +{ + WINPR_ASSERT(pAvPair); + winpr_Data_Write_UINT16(&pAvPair->AvLen, len); +} + +static BOOL ntlm_av_pair_list_init(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList) +{ + NTLM_AV_PAIR* pAvPair = pAvPairList; + + if (!pAvPair || (cbAvPairList < sizeof(NTLM_AV_PAIR))) + return FALSE; + + ntlm_av_pair_set_id(pAvPair, MsvAvEOL); + ntlm_av_pair_set_len(pAvPair, 0); + return TRUE; +} + +static INLINE BOOL ntlm_av_pair_get_id(const NTLM_AV_PAIR* pAvPair, size_t size, UINT16* pair) +{ + if (!pAvPair || !pair) + return FALSE; + + if (size < sizeof(NTLM_AV_PAIR)) + return FALSE; + + const UINT16 AvId = winpr_Data_Get_UINT16(&pAvPair->AvId); + + *pair = AvId; + return TRUE; +} + +ULONG ntlm_av_pair_list_length(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList) +{ + size_t cbAvPair = 0; + NTLM_AV_PAIR* pAvPair = NULL; + + pAvPair = ntlm_av_pair_get(pAvPairList, cbAvPairList, MsvAvEOL, &cbAvPair); + if (!pAvPair) + return 0; + + if (pAvPair < pAvPairList) + return 0; + + const size_t size = WINPR_ASSERTING_INT_CAST(size_t, ((PBYTE)pAvPair - (PBYTE)pAvPairList)) + + sizeof(NTLM_AV_PAIR); + WINPR_ASSERT(size <= UINT32_MAX); + WINPR_ASSERT(size >= 0); + return (ULONG)size; +} + +static INLINE BOOL ntlm_av_pair_get_len(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pAvLen) +{ + if (!pAvPair) + return FALSE; + + if (size < sizeof(NTLM_AV_PAIR)) + return FALSE; + + const UINT16 AvLen = winpr_Data_Get_UINT16(&pAvPair->AvLen); + + *pAvLen = AvLen; + return TRUE; +} + +#ifdef WITH_DEBUG_NTLM +void ntlm_print_av_pair_list(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList) +{ + UINT16 pair = 0; + size_t cbAvPair = cbAvPairList; + NTLM_AV_PAIR* pAvPair = pAvPairList; + + if (!ntlm_av_pair_check(pAvPair, cbAvPair)) + return; + + WLog_VRB(TAG, "AV_PAIRs ="); + + while (pAvPair && ntlm_av_pair_get_id(pAvPair, cbAvPair, &pair) && (pair != MsvAvEOL)) + { + size_t cbLen = 0; + ntlm_av_pair_get_len(pAvPair, cbAvPair, &cbLen); + + WLog_VRB(TAG, "\t%s AvId: %" PRIu16 " AvLen: %" PRIu16 "", get_av_pair_string(pair), pair); + winpr_HexDump(TAG, WLOG_TRACE, ntlm_av_pair_get_value_pointer(pAvPair), cbLen); + + pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair); + } +} +#endif + +static ULONG ntlm_av_pair_list_size(ULONG AvPairsCount, ULONG AvPairsValueLength) +{ + /* size of headers + value lengths + terminating MsvAvEOL AV_PAIR */ + return ((AvPairsCount + 1) * 4) + AvPairsValueLength; +} + +PBYTE ntlm_av_pair_get_value_pointer(NTLM_AV_PAIR* pAvPair) +{ + WINPR_ASSERT(pAvPair); + return (PBYTE)pAvPair + sizeof(NTLM_AV_PAIR); +} + +static BOOL ntlm_av_pair_get_next_offset(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pOffset) +{ + size_t avLen = 0; + if (!pOffset) + return FALSE; + + if (!ntlm_av_pair_get_len(pAvPair, size, &avLen)) + return FALSE; + *pOffset = avLen + sizeof(NTLM_AV_PAIR); + return TRUE; +} + +static BOOL ntlm_av_pair_check(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair) +{ + return ntlm_av_pair_check_data(pAvPair, cbAvPair, 0); +} + +static NTLM_AV_PAIR* ntlm_av_pair_next(NTLM_AV_PAIR* pAvPair, size_t* pcbAvPair) +{ + size_t offset = 0; + + if (!pcbAvPair) + return NULL; + if (!ntlm_av_pair_check(pAvPair, *pcbAvPair)) + return NULL; + + if (!ntlm_av_pair_get_next_offset(pAvPair, *pcbAvPair, &offset)) + return NULL; + + *pcbAvPair -= offset; + return (NTLM_AV_PAIR*)((PBYTE)pAvPair + offset); +} + +NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId, + size_t* pcbAvPairListRemaining) +{ + UINT16 id = 0; + size_t cbAvPair = cbAvPairList; + NTLM_AV_PAIR* pAvPair = pAvPairList; + + if (!ntlm_av_pair_check(pAvPair, cbAvPair)) + pAvPair = NULL; + + while (pAvPair && ntlm_av_pair_get_id(pAvPair, cbAvPair, &id)) + { + if (id == AvId) + break; + if (id == MsvAvEOL) + { + pAvPair = NULL; + break; + } + + pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair); + } + + if (!pAvPair) + cbAvPair = 0; + if (pcbAvPairListRemaining) + *pcbAvPairListRemaining = cbAvPair; + + return pAvPair; +} + +static BOOL ntlm_av_pair_add(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId, + PBYTE Value, UINT16 AvLen) +{ + size_t cbAvPair = 0; + NTLM_AV_PAIR* pAvPair = NULL; + + pAvPair = ntlm_av_pair_get(pAvPairList, cbAvPairList, MsvAvEOL, &cbAvPair); + + /* size of header + value length + terminating MsvAvEOL AV_PAIR */ + if (!pAvPair || cbAvPair < 2 * sizeof(NTLM_AV_PAIR) + AvLen) + return FALSE; + + ntlm_av_pair_set_id(pAvPair, (UINT16)AvId); + ntlm_av_pair_set_len(pAvPair, AvLen); + if (AvLen) + { + WINPR_ASSERT(Value != NULL); + CopyMemory(ntlm_av_pair_get_value_pointer(pAvPair), Value, AvLen); + } + + pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair); + return ntlm_av_pair_list_init(pAvPair, cbAvPair); +} + +static BOOL ntlm_av_pair_add_copy(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, + NTLM_AV_PAIR* pAvPair, size_t cbAvPair) +{ + UINT16 pair = 0; + size_t avLen = 0; + + if (!ntlm_av_pair_check(pAvPair, cbAvPair)) + return FALSE; + + if (!ntlm_av_pair_get_id(pAvPair, cbAvPair, &pair)) + return FALSE; + + if (!ntlm_av_pair_get_len(pAvPair, cbAvPair, &avLen)) + return FALSE; + + WINPR_ASSERT(avLen <= UINT16_MAX); + return ntlm_av_pair_add(pAvPairList, cbAvPairList, pair, + ntlm_av_pair_get_value_pointer(pAvPair), (UINT16)avLen); +} + +static char* get_name(COMPUTER_NAME_FORMAT type) +{ + DWORD nSize = 0; + + if (GetComputerNameExA(type, NULL, &nSize)) + return NULL; + + if (GetLastError() != ERROR_MORE_DATA) + return NULL; + + char* computerName = calloc(1, nSize); + + if (!computerName) + return NULL; + + if (!GetComputerNameExA(type, computerName, &nSize)) + { + free(computerName); + return NULL; + } + + return computerName; +} + +static int ntlm_get_target_computer_name(PUNICODE_STRING pName, COMPUTER_NAME_FORMAT type) +{ + int status = -1; + + WINPR_ASSERT(pName); + + char* name = get_name(ComputerNameNetBIOS); + if (!name) + return -1; + + CharUpperA(name); + + size_t len = 0; + pName->Buffer = ConvertUtf8ToWCharAlloc(name, &len); + free(name); + + if (!pName->Buffer || (len == 0) || (len > UINT16_MAX / sizeof(WCHAR))) + { + free(pName->Buffer); + pName->Buffer = NULL; + return status; + } + + pName->Length = (USHORT)((len) * sizeof(WCHAR)); + pName->MaximumLength = pName->Length; + return 1; +} + +static void ntlm_free_unicode_string(PUNICODE_STRING string) +{ + if (string) + { + if (string->Length > 0) + { + free(string->Buffer); + string->Buffer = NULL; + string->Length = 0; + string->MaximumLength = 0; + } + } +} + +/** + * From http://www.ietf.org/proceedings/72/slides/sasl-2.pdf: + * + * tls-server-end-point: + * + * The hash of the TLS server's end entity certificate as it appears, octet for octet, + * in the server's Certificate message (note that the Certificate message contains a + * certificate_list, the first element of which is the server's end entity certificate.) + * The hash function to be selected is as follows: if the certificate's signature hash + * algorithm is either MD5 or SHA-1, then use SHA-256, otherwise use the certificate's + * signature hash algorithm. + */ + +/** + * Channel Bindings sample usage: + * https://raw.github.com/mozilla/mozilla-central/master/extensions/auth/nsAuthSSPI.cpp + */ + +/* +typedef struct gss_channel_bindings_struct { + OM_uint32 initiator_addrtype; + gss_buffer_desc initiator_address; + OM_uint32 acceptor_addrtype; + gss_buffer_desc acceptor_address; + gss_buffer_desc application_data; +} *gss_channel_bindings_t; + */ + +static BOOL ntlm_md5_update_uint32_be(WINPR_DIGEST_CTX* md5, UINT32 num) +{ + BYTE be32[4]; + be32[0] = (num >> 0) & 0xFF; + be32[1] = (num >> 8) & 0xFF; + be32[2] = (num >> 16) & 0xFF; + be32[3] = (num >> 24) & 0xFF; + return winpr_Digest_Update(md5, be32, 4); +} + +static void ntlm_compute_channel_bindings(NTLM_CONTEXT* context) +{ + WINPR_DIGEST_CTX* md5 = NULL; + BYTE* ChannelBindingToken = NULL; + UINT32 ChannelBindingTokenLength = 0; + SEC_CHANNEL_BINDINGS* ChannelBindings = NULL; + + WINPR_ASSERT(context); + + ZeroMemory(context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH); + ChannelBindings = context->Bindings.Bindings; + + if (!ChannelBindings) + return; + + if (!(md5 = winpr_Digest_New())) + return; + + if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) + goto out; + + ChannelBindingTokenLength = context->Bindings.BindingsLength - sizeof(SEC_CHANNEL_BINDINGS); + ChannelBindingToken = &((BYTE*)ChannelBindings)[ChannelBindings->dwApplicationDataOffset]; + + if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwInitiatorAddrType)) + goto out; + + if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbInitiatorLength)) + goto out; + + if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwAcceptorAddrType)) + goto out; + + if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbAcceptorLength)) + goto out; + + if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbApplicationDataLength)) + goto out; + + if (!winpr_Digest_Update(md5, (void*)ChannelBindingToken, ChannelBindingTokenLength)) + goto out; + + if (!winpr_Digest_Final(md5, context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH)) + goto out; + +out: + winpr_Digest_Free(md5); +} + +static void ntlm_compute_single_host_data(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + /** + * The Single_Host_Data structure allows a client to send machine-specific information + * within an authentication exchange to services on the same machine. The client can + * produce additional information to be processed in an implementation-specific way when + * the client and server are on the same host. If the server and client platforms are + * different or if they are on different hosts, then the information MUST be ignored. + * Any fields after the MachineID field MUST be ignored on receipt. + */ + winpr_Data_Write_UINT32(&context->SingleHostData.Size, 48); + winpr_Data_Write_UINT32(&context->SingleHostData.Z4, 0); + winpr_Data_Write_UINT32(&context->SingleHostData.DataPresent, 1); + winpr_Data_Write_UINT32(&context->SingleHostData.CustomData, SECURITY_MANDATORY_MEDIUM_RID); + FillMemory(context->SingleHostData.MachineID, 32, 0xAA); +} + +BOOL ntlm_construct_challenge_target_info(NTLM_CONTEXT* context) +{ + BOOL rc = FALSE; + ULONG length = 0; + ULONG AvPairsCount = 0; + ULONG AvPairsLength = 0; + NTLM_AV_PAIR* pAvPairList = NULL; + size_t cbAvPairList = 0; + UNICODE_STRING NbDomainName = { 0 }; + UNICODE_STRING NbComputerName = { 0 }; + UNICODE_STRING DnsDomainName = { 0 }; + UNICODE_STRING DnsComputerName = { 0 }; + + WINPR_ASSERT(context); + + if (ntlm_get_target_computer_name(&NbDomainName, ComputerNameNetBIOS) < 0) + goto fail; + + NbComputerName.Buffer = NULL; + + if (ntlm_get_target_computer_name(&NbComputerName, ComputerNameNetBIOS) < 0) + goto fail; + + DnsDomainName.Buffer = NULL; + + if (ntlm_get_target_computer_name(&DnsDomainName, ComputerNameDnsDomain) < 0) + goto fail; + + DnsComputerName.Buffer = NULL; + + if (ntlm_get_target_computer_name(&DnsComputerName, ComputerNameDnsHostname) < 0) + goto fail; + + AvPairsCount = 5; + AvPairsLength = NbDomainName.Length + NbComputerName.Length + DnsDomainName.Length + + DnsComputerName.Length + 8; + length = ntlm_av_pair_list_size(AvPairsCount, AvPairsLength); + + if (!sspi_SecBufferAlloc(&context->ChallengeTargetInfo, length)) + goto fail; + + pAvPairList = (NTLM_AV_PAIR*)context->ChallengeTargetInfo.pvBuffer; + cbAvPairList = context->ChallengeTargetInfo.cbBuffer; + + if (!ntlm_av_pair_list_init(pAvPairList, cbAvPairList)) + goto fail; + + if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvNbDomainName, (PBYTE)NbDomainName.Buffer, + NbDomainName.Length)) + goto fail; + + if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvNbComputerName, + (PBYTE)NbComputerName.Buffer, NbComputerName.Length)) + goto fail; + + if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvDnsDomainName, + (PBYTE)DnsDomainName.Buffer, DnsDomainName.Length)) + goto fail; + + if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvDnsComputerName, + (PBYTE)DnsComputerName.Buffer, DnsComputerName.Length)) + goto fail; + + if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvTimestamp, context->Timestamp, + sizeof(context->Timestamp))) + goto fail; + + rc = TRUE; +fail: + ntlm_free_unicode_string(&NbDomainName); + ntlm_free_unicode_string(&NbComputerName); + ntlm_free_unicode_string(&DnsDomainName); + ntlm_free_unicode_string(&DnsComputerName); + return rc; +} + +BOOL ntlm_construct_authenticate_target_info(NTLM_CONTEXT* context) +{ + ULONG size = 0; + ULONG AvPairsCount = 0; + ULONG AvPairsValueLength = 0; + NTLM_AV_PAIR* AvTimestamp = NULL; + NTLM_AV_PAIR* AvNbDomainName = NULL; + NTLM_AV_PAIR* AvNbComputerName = NULL; + NTLM_AV_PAIR* AvDnsDomainName = NULL; + NTLM_AV_PAIR* AvDnsComputerName = NULL; + NTLM_AV_PAIR* AvDnsTreeName = NULL; + NTLM_AV_PAIR* ChallengeTargetInfo = NULL; + NTLM_AV_PAIR* AuthenticateTargetInfo = NULL; + size_t cbAvTimestamp = 0; + size_t cbAvNbDomainName = 0; + size_t cbAvNbComputerName = 0; + size_t cbAvDnsDomainName = 0; + size_t cbAvDnsComputerName = 0; + size_t cbAvDnsTreeName = 0; + size_t cbChallengeTargetInfo = 0; + size_t cbAuthenticateTargetInfo = 0; + + WINPR_ASSERT(context); + + AvPairsCount = 1; + AvPairsValueLength = 0; + ChallengeTargetInfo = (NTLM_AV_PAIR*)context->ChallengeTargetInfo.pvBuffer; + cbChallengeTargetInfo = context->ChallengeTargetInfo.cbBuffer; + AvNbDomainName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvNbDomainName, + &cbAvNbDomainName); + AvNbComputerName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, + MsvAvNbComputerName, &cbAvNbComputerName); + AvDnsDomainName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, + MsvAvDnsDomainName, &cbAvDnsDomainName); + AvDnsComputerName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, + MsvAvDnsComputerName, &cbAvDnsComputerName); + AvDnsTreeName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvDnsTreeName, + &cbAvDnsTreeName); + AvTimestamp = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvTimestamp, + &cbAvTimestamp); + + if (AvNbDomainName) + { + size_t avLen = 0; + if (!ntlm_av_pair_get_len(AvNbDomainName, cbAvNbDomainName, &avLen)) + goto fail; + AvPairsCount++; /* MsvAvNbDomainName */ + AvPairsValueLength += avLen; + } + + if (AvNbComputerName) + { + size_t avLen = 0; + if (!ntlm_av_pair_get_len(AvNbComputerName, cbAvNbComputerName, &avLen)) + goto fail; + AvPairsCount++; /* MsvAvNbComputerName */ + AvPairsValueLength += avLen; + } + + if (AvDnsDomainName) + { + size_t avLen = 0; + if (!ntlm_av_pair_get_len(AvDnsDomainName, cbAvDnsDomainName, &avLen)) + goto fail; + AvPairsCount++; /* MsvAvDnsDomainName */ + AvPairsValueLength += avLen; + } + + if (AvDnsComputerName) + { + size_t avLen = 0; + if (!ntlm_av_pair_get_len(AvDnsComputerName, cbAvDnsComputerName, &avLen)) + goto fail; + AvPairsCount++; /* MsvAvDnsComputerName */ + AvPairsValueLength += avLen; + } + + if (AvDnsTreeName) + { + size_t avLen = 0; + if (!ntlm_av_pair_get_len(AvDnsTreeName, cbAvDnsTreeName, &avLen)) + goto fail; + AvPairsCount++; /* MsvAvDnsTreeName */ + AvPairsValueLength += avLen; + } + + AvPairsCount++; /* MsvAvTimestamp */ + AvPairsValueLength += 8; + + if (context->UseMIC) + { + AvPairsCount++; /* MsvAvFlags */ + AvPairsValueLength += 4; + } + + if (context->SendSingleHostData) + { + AvPairsCount++; /* MsvAvSingleHost */ + ntlm_compute_single_host_data(context); + AvPairsValueLength += context->SingleHostData.Size; + } + + /** + * Extended Protection for Authentication: + * http://blogs.technet.com/b/srd/archive/2009/12/08/extended-protection-for-authentication.aspx + */ + + if (!context->SuppressExtendedProtection) + { + /** + * SEC_CHANNEL_BINDINGS structure + * http://msdn.microsoft.com/en-us/library/windows/desktop/dd919963/ + */ + AvPairsCount++; /* MsvAvChannelBindings */ + AvPairsValueLength += 16; + ntlm_compute_channel_bindings(context); + + if (context->ServicePrincipalName.Length > 0) + { + AvPairsCount++; /* MsvAvTargetName */ + AvPairsValueLength += context->ServicePrincipalName.Length; + } + } + + size = ntlm_av_pair_list_size(AvPairsCount, AvPairsValueLength); + + if (context->NTLMv2) + size += 8; /* unknown 8-byte padding */ + + if (!sspi_SecBufferAlloc(&context->AuthenticateTargetInfo, size)) + goto fail; + + AuthenticateTargetInfo = (NTLM_AV_PAIR*)context->AuthenticateTargetInfo.pvBuffer; + cbAuthenticateTargetInfo = context->AuthenticateTargetInfo.cbBuffer; + + if (!ntlm_av_pair_list_init(AuthenticateTargetInfo, cbAuthenticateTargetInfo)) + goto fail; + + if (AvNbDomainName) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvNbDomainName, + cbAvNbDomainName)) + goto fail; + } + + if (AvNbComputerName) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, + AvNbComputerName, cbAvNbComputerName)) + goto fail; + } + + if (AvDnsDomainName) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, + AvDnsDomainName, cbAvDnsDomainName)) + goto fail; + } + + if (AvDnsComputerName) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, + AvDnsComputerName, cbAvDnsComputerName)) + goto fail; + } + + if (AvDnsTreeName) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvDnsTreeName, + cbAvDnsTreeName)) + goto fail; + } + + if (AvTimestamp) + { + if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvTimestamp, + cbAvTimestamp)) + goto fail; + } + + if (context->UseMIC) + { + UINT32 flags = 0; + winpr_Data_Write_UINT32(&flags, MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK); + + if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvFlags, + (PBYTE)&flags, 4)) + goto fail; + } + + if (context->SendSingleHostData) + { + WINPR_ASSERT(context->SingleHostData.Size <= UINT16_MAX); + if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvSingleHost, + (PBYTE)&context->SingleHostData, + (UINT16)context->SingleHostData.Size)) + goto fail; + } + + if (!context->SuppressExtendedProtection) + { + if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, + MsvAvChannelBindings, context->ChannelBindingsHash, 16)) + goto fail; + + if (context->ServicePrincipalName.Length > 0) + { + if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvTargetName, + (PBYTE)context->ServicePrincipalName.Buffer, + context->ServicePrincipalName.Length)) + goto fail; + } + } + + if (context->NTLMv2) + { + NTLM_AV_PAIR* AvEOL = NULL; + AvEOL = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvEOL, NULL); + + if (!AvEOL) + goto fail; + + ZeroMemory(AvEOL, sizeof(NTLM_AV_PAIR)); + } + + return TRUE; +fail: + sspi_SecBufferFree(&context->AuthenticateTargetInfo); + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.h new file mode 100644 index 0000000000000000000000000000000000000000..ab9da4396094a4ae5b5b0293d0ab1ecae16eb808 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.h @@ -0,0 +1,42 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (AV_PAIRs) + * + * Copyright 2011-2012 Marc-Andre Moreau + * + * 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_NTLM_AV_PAIRS_H +#define WINPR_SSPI_NTLM_AV_PAIRS_H + +#include + +#include "ntlm.h" + +#include + +ULONG ntlm_av_pair_list_length(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList); + +#ifdef WITH_DEBUG_NTLM +void ntlm_print_av_pair_list(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList); +#endif + +PBYTE ntlm_av_pair_get_value_pointer(NTLM_AV_PAIR* pAvPair); +NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId, + size_t* pcbAvPairListRemaining); + +BOOL ntlm_construct_challenge_target_info(NTLM_CONTEXT* context); +BOOL ntlm_construct_authenticate_target_info(NTLM_CONTEXT* context); + +#endif /* WINPR_SSPI_NTLM_AV_PAIRS_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.c new file mode 100644 index 0000000000000000000000000000000000000000..0e420354bf05fba4924cac3d58bd542ae8328a91 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.c @@ -0,0 +1,938 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (Compute) + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 + +#include + +#include "ntlm.h" +#include "../sspi.h" + +#include +#include +#include +#include +#include +#include + +#include "ntlm_compute.h" + +#include "../../log.h" +#define TAG WINPR_TAG("sspi.NTLM") + +#define NTLM_CheckAndLogRequiredCapacity(tag, s, nmemb, what) \ + Stream_CheckAndLogRequiredCapacityEx(tag, WLOG_WARN, s, nmemb, 1, "%s(%s:%" PRIuz ") " what, \ + __func__, __FILE__, (size_t)__LINE__) + +static char NTLM_CLIENT_SIGN_MAGIC[] = "session key to client-to-server signing key magic constant"; +static char NTLM_SERVER_SIGN_MAGIC[] = "session key to server-to-client signing key magic constant"; +static char NTLM_CLIENT_SEAL_MAGIC[] = "session key to client-to-server sealing key magic constant"; +static char NTLM_SERVER_SEAL_MAGIC[] = "session key to server-to-client sealing key magic constant"; + +static const BYTE NTLM_NULL_BUFFER[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + +/** + * Populate VERSION structure msdn{cc236654} + * @param versionInfo A pointer to the version struct + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_get_version_info(NTLM_VERSION_INFO* versionInfo) +{ + WINPR_ASSERT(versionInfo); + +#if defined(WITH_WINPR_DEPRECATED) + OSVERSIONINFOA osVersionInfo = { 0 }; + osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); + if (!GetVersionExA(&osVersionInfo)) + return FALSE; + versionInfo->ProductMajorVersion = (UINT8)osVersionInfo.dwMajorVersion; + versionInfo->ProductMinorVersion = (UINT8)osVersionInfo.dwMinorVersion; + versionInfo->ProductBuild = (UINT16)osVersionInfo.dwBuildNumber; +#else + /* Always return fixed version number. + * + * ProductVersion is fixed since windows 10 to Major 10, Minor 0 + * ProductBuild taken from https://en.wikipedia.org/wiki/Windows_11_version_history + * with most recent (pre) release build number + */ + versionInfo->ProductMajorVersion = 10; + versionInfo->ProductMinorVersion = 0; + versionInfo->ProductBuild = 22631; +#endif + ZeroMemory(versionInfo->Reserved, sizeof(versionInfo->Reserved)); + versionInfo->NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3; + return TRUE; +} + +/** + * Read VERSION structure. msdn{cc236654} + * @param s A pointer to a stream to read + * @param versionInfo A pointer to the struct to read data to + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_read_version_info(wStream* s, NTLM_VERSION_INFO* versionInfo) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(versionInfo); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return FALSE; + + Stream_Read_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */ + Stream_Read_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */ + Stream_Read_UINT16(s, versionInfo->ProductBuild); /* ProductBuild (2 bytes) */ + Stream_Read(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */ + Stream_Read_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */ + return TRUE; +} + +/** + * Write VERSION structure. msdn{cc236654} + * @param s A pointer to the stream to write to + * @param versionInfo A pointer to the buffer to read the data from + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_write_version_info(wStream* s, const NTLM_VERSION_INFO* versionInfo) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(versionInfo); + + if (!Stream_CheckAndLogRequiredCapacityEx( + TAG, WLOG_WARN, s, 5ull + sizeof(versionInfo->Reserved), 1ull, + "%s(%s:%" PRIuz ") NTLM_VERSION_INFO", __func__, __FILE__, (size_t)__LINE__)) + return FALSE; + + Stream_Write_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */ + Stream_Write_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */ + Stream_Write_UINT16(s, versionInfo->ProductBuild); /* ProductBuild (2 bytes) */ + Stream_Write(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */ + Stream_Write_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */ + return TRUE; +} + +/** + * Print VERSION structure. msdn{cc236654} + * @param versionInfo A pointer to the struct containing the data to print + */ +#ifdef WITH_DEBUG_NTLM +void ntlm_print_version_info(const NTLM_VERSION_INFO* versionInfo) +{ + WINPR_ASSERT(versionInfo); + + WLog_VRB(TAG, "VERSION ={"); + WLog_VRB(TAG, "\tProductMajorVersion: %" PRIu8 "", versionInfo->ProductMajorVersion); + WLog_VRB(TAG, "\tProductMinorVersion: %" PRIu8 "", versionInfo->ProductMinorVersion); + WLog_VRB(TAG, "\tProductBuild: %" PRIu16 "", versionInfo->ProductBuild); + WLog_VRB(TAG, "\tReserved: 0x%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "", versionInfo->Reserved[0], + versionInfo->Reserved[1], versionInfo->Reserved[2]); + WLog_VRB(TAG, "\tNTLMRevisionCurrent: 0x%02" PRIX8 "", versionInfo->NTLMRevisionCurrent); +} +#endif + +static BOOL ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge) +{ + size_t size = 0; + WINPR_ASSERT(s); + WINPR_ASSERT(challenge); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 28)) + return FALSE; + + Stream_Read_UINT8(s, challenge->RespType); + Stream_Read_UINT8(s, challenge->HiRespType); + Stream_Read_UINT16(s, challenge->Reserved1); + Stream_Read_UINT32(s, challenge->Reserved2); + Stream_Read(s, challenge->Timestamp, 8); + Stream_Read(s, challenge->ClientChallenge, 8); + Stream_Read_UINT32(s, challenge->Reserved3); + size = Stream_Length(s) - Stream_GetPosition(s); + + if (size > UINT32_MAX) + { + WLog_ERR(TAG, "NTLMv2_CLIENT_CHALLENGE::cbAvPairs too large, got %" PRIuz "bytes", size); + return FALSE; + } + + challenge->cbAvPairs = (UINT32)size; + challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs); + + if (!challenge->AvPairs) + { + WLog_ERR(TAG, "NTLMv2_CLIENT_CHALLENGE::AvPairs failed to allocate %" PRIu32 "bytes", + challenge->cbAvPairs); + return FALSE; + } + + Stream_Read(s, challenge->AvPairs, size); + return TRUE; +} + +static BOOL ntlm_write_ntlm_v2_client_challenge(wStream* s, + const NTLMv2_CLIENT_CHALLENGE* challenge) +{ + ULONG length = 0; + + WINPR_ASSERT(s); + WINPR_ASSERT(challenge); + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, 28, "NTLMv2_CLIENT_CHALLENGE")) + return FALSE; + + Stream_Write_UINT8(s, challenge->RespType); + Stream_Write_UINT8(s, challenge->HiRespType); + Stream_Write_UINT16(s, challenge->Reserved1); + Stream_Write_UINT32(s, challenge->Reserved2); + Stream_Write(s, challenge->Timestamp, 8); + Stream_Write(s, challenge->ClientChallenge, 8); + Stream_Write_UINT32(s, challenge->Reserved3); + length = ntlm_av_pair_list_length(challenge->AvPairs, challenge->cbAvPairs); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, length)) + return FALSE; + + Stream_Write(s, challenge->AvPairs, length); + return TRUE; +} + +BOOL ntlm_read_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(response); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 16)) + return FALSE; + + Stream_Read(s, response->Response, 16); + return ntlm_read_ntlm_v2_client_challenge(s, &(response->Challenge)); +} + +BOOL ntlm_write_ntlm_v2_response(wStream* s, const NTLMv2_RESPONSE* response) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(response); + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, 16ull, "NTLMv2_RESPONSE")) + return FALSE; + + Stream_Write(s, response->Response, 16); + return ntlm_write_ntlm_v2_client_challenge(s, &(response->Challenge)); +} + +/** + * Get current time, in tenths of microseconds since midnight of January 1, 1601. + * @param[out] timestamp 64-bit little-endian timestamp + */ + +void ntlm_current_time(BYTE* timestamp) +{ + FILETIME ft = { 0 }; + + WINPR_ASSERT(timestamp); + + GetSystemTimeAsFileTime(&ft); + CopyMemory(timestamp, &(ft), sizeof(ft)); +} + +/** + * Generate timestamp for AUTHENTICATE_MESSAGE. + * + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_timestamp(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + if (memcmp(context->ChallengeTimestamp, NTLM_NULL_BUFFER, 8) != 0) + CopyMemory(context->Timestamp, context->ChallengeTimestamp, 8); + else + ntlm_current_time(context->Timestamp); +} + +static BOOL ntlm_fetch_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash) +{ + BOOL rc = FALSE; + WINPR_SAM* sam = NULL; + WINPR_SAM_ENTRY* entry = NULL; + SSPI_CREDENTIALS* credentials = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(hash); + + credentials = context->credentials; + sam = SamOpen(context->SamFile, TRUE); + + if (!sam) + goto fail; + + entry = SamLookupUserW( + sam, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * sizeof(WCHAR), + (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * sizeof(WCHAR)); + + if (!entry) + { + entry = SamLookupUserW(sam, (LPWSTR)credentials->identity.User, + credentials->identity.UserLength * sizeof(WCHAR), NULL, 0); + } + + if (!entry) + goto fail; + +#ifdef WITH_DEBUG_NTLM + WLog_VRB(TAG, "NTLM Hash:"); + winpr_HexDump(TAG, WLOG_DEBUG, entry->NtHash, 16); +#endif + NTOWFv2FromHashW(entry->NtHash, (LPWSTR)credentials->identity.User, + credentials->identity.UserLength * sizeof(WCHAR), + (LPWSTR)credentials->identity.Domain, + credentials->identity.DomainLength * sizeof(WCHAR), hash); + + rc = TRUE; + +fail: + SamFreeEntry(sam, entry); + SamClose(sam); + if (!rc) + WLog_ERR(TAG, "Error: Could not find user in SAM database"); + + return rc; +} + +static int hexchar2nibble(WCHAR wc) +{ +#if defined(__BIG_ENDIAN__) + union + { + BYTE b[2]; + WCHAR w; + } cnv; + cnv.w = wc; + const BYTE b = cnv.b[0]; + cnv.b[0] = cnv.b[1]; + cnv.b[1] = b; + wc = cnv.w; +#endif + + switch (wc) + { + case L'0': + case L'1': + case L'2': + case L'3': + case L'4': + case L'5': + case L'6': + case L'7': + case L'8': + case L'9': + return wc - L'0'; + case L'a': + case L'b': + case L'c': + case L'd': + case L'e': + case L'f': + return wc - L'a' + 10; + case L'A': + case L'B': + case L'C': + case L'D': + case L'E': + case L'F': + return wc - L'A' + 10; + default: + return -1; + } +} +static int ntlm_convert_password_hash(NTLM_CONTEXT* context, BYTE* hash, size_t hashlen) +{ + const size_t required_len = 2ull * hashlen; + + WINPR_ASSERT(context); + WINPR_ASSERT(hash); + + SSPI_CREDENTIALS* credentials = context->credentials; + /* Password contains a password hash of length (PasswordLength - + * SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) */ + const ULONG PasswordHashLength = credentials->identity.PasswordLength - + /* Macro [globalScope] */ SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; + + if (PasswordHashLength != required_len) + { + WLog_ERR(TAG, + "PasswordHash has invalid length %" PRIu32 " must be exactly %" PRIuz " bytes", + PasswordHashLength, required_len); + return -1; + } + + const WCHAR* PasswordHash = credentials->identity.Password; + for (size_t x = 0; x < hashlen; x++) + { + const int hi = hexchar2nibble(PasswordHash[2 * x]); + if (hi < 0) + { + WLog_ERR(TAG, "PasswordHash has an invalid value at position %" PRIuz, 2 * x); + return -1; + } + const int lo = hexchar2nibble(PasswordHash[2 * x + 1]); + if (lo < 0) + { + WLog_ERR(TAG, "PasswordHash has an invalid value at position %" PRIuz, 2 * x + 1); + return -1; + } + const BYTE val = (BYTE)((hi << 4) | lo); + hash[x] = val; + } + + return 1; +} + +static BOOL ntlm_compute_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash) +{ + SSPI_CREDENTIALS* credentials = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(hash); + + credentials = context->credentials; +#ifdef WITH_DEBUG_NTLM + + if (credentials) + { + WLog_VRB(TAG, "Password (length = %" PRIu32 ")", credentials->identity.PasswordLength * 2); + winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Password, + credentials->identity.PasswordLength * 2); + WLog_VRB(TAG, "Username (length = %" PRIu32 ")", credentials->identity.UserLength * 2); + winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.User, + credentials->identity.UserLength * 2); + WLog_VRB(TAG, "Domain (length = %" PRIu32 ")", credentials->identity.DomainLength * 2); + winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)credentials->identity.Domain, + credentials->identity.DomainLength * 2); + } + else + WLog_VRB(TAG, "Strange, NTLM_CONTEXT is missing valid credentials..."); + + WLog_VRB(TAG, "Workstation (length = %" PRIu16 ")", context->Workstation.Length); + winpr_HexDump(TAG, WLOG_TRACE, (BYTE*)context->Workstation.Buffer, context->Workstation.Length); + WLog_VRB(TAG, "NTOWFv2, NTLMv2 Hash"); + winpr_HexDump(TAG, WLOG_TRACE, context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH); +#endif + + if (memcmp(context->NtlmV2Hash, NTLM_NULL_BUFFER, 16) != 0) + return TRUE; + + if (!credentials) + return FALSE; + else if (memcmp(context->NtlmHash, NTLM_NULL_BUFFER, 16) != 0) + { + NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User, + credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, + credentials->identity.DomainLength * 2, hash); + } + else if (credentials->identity.PasswordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) + { + /* Special case for WinPR: password hash */ + if (ntlm_convert_password_hash(context, context->NtlmHash, sizeof(context->NtlmHash)) < 0) + return FALSE; + + NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User, + credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, + credentials->identity.DomainLength * 2, hash); + } + else if (credentials->identity.Password) + { + NTOWFv2W((LPWSTR)credentials->identity.Password, credentials->identity.PasswordLength * 2, + (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, + (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, + hash); + } + else if (context->HashCallback) + { + int ret = 0; + SecBuffer proofValue; + SecBuffer micValue; + + if (ntlm_computeProofValue(context, &proofValue) != SEC_E_OK) + return FALSE; + + if (ntlm_computeMicValue(context, &micValue) != SEC_E_OK) + { + sspi_SecBufferFree(&proofValue); + return FALSE; + } + + ret = context->HashCallback(context->HashCallbackArg, &credentials->identity, &proofValue, + context->EncryptedRandomSessionKey, + context->AUTHENTICATE_MESSAGE.MessageIntegrityCheck, &micValue, + hash); + sspi_SecBufferFree(&proofValue); + sspi_SecBufferFree(&micValue); + return ret ? TRUE : FALSE; + } + else if (context->UseSamFileDatabase) + { + return ntlm_fetch_ntlm_v2_hash(context, hash); + } + + return TRUE; +} + +SECURITY_STATUS ntlm_compute_lm_v2_response(NTLM_CONTEXT* context) +{ + BYTE* response = NULL; + BYTE value[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + + WINPR_ASSERT(context); + + if (context->LmCompatibilityLevel < 2) + { + if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24)) + return SEC_E_INSUFFICIENT_MEMORY; + + ZeroMemory(context->LmChallengeResponse.pvBuffer, 24); + return SEC_E_OK; + } + + /* Compute the NTLMv2 hash */ + + if (!ntlm_compute_ntlm_v2_hash(context, context->NtlmV2Hash)) + return SEC_E_NO_CREDENTIALS; + + /* Concatenate the server and client challenges */ + CopyMemory(value, context->ServerChallenge, 8); + CopyMemory(&value[8], context->ClientChallenge, 8); + + if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24)) + return SEC_E_INSUFFICIENT_MEMORY; + + response = (BYTE*)context->LmChallengeResponse.pvBuffer; + /* Compute the HMAC-MD5 hash of the resulting value using the NTLMv2 hash as the key */ + winpr_HMAC(WINPR_MD_MD5, (void*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, (BYTE*)value, + WINPR_MD5_DIGEST_LENGTH, response, WINPR_MD5_DIGEST_LENGTH); + /* Concatenate the resulting HMAC-MD5 hash and the client challenge, giving us the LMv2 response + * (24 bytes) */ + CopyMemory(&response[16], context->ClientChallenge, 8); + return SEC_E_OK; +} + +/** + * Compute NTLMv2 Response. + * + * NTLMv2_RESPONSE msdn{cc236653} + * NTLMv2 Authentication msdn{cc236700} + * + * @param context A pointer to the NTLM context + * @return \b TRUE for success, \b FALSE for failure + */ + +SECURITY_STATUS ntlm_compute_ntlm_v2_response(NTLM_CONTEXT* context) +{ + SecBuffer ntlm_v2_temp = { 0 }; + SecBuffer ntlm_v2_temp_chal = { 0 }; + + WINPR_ASSERT(context); + + PSecBuffer TargetInfo = &context->ChallengeTargetInfo; + SECURITY_STATUS ret = SEC_E_INSUFFICIENT_MEMORY; + + if (!sspi_SecBufferAlloc(&ntlm_v2_temp, TargetInfo->cbBuffer + 28)) + goto exit; + + ZeroMemory(ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); + BYTE* blob = (BYTE*)ntlm_v2_temp.pvBuffer; + + /* Compute the NTLMv2 hash */ + ret = SEC_E_NO_CREDENTIALS; + if (!ntlm_compute_ntlm_v2_hash(context, (BYTE*)context->NtlmV2Hash)) + goto exit; + + /* Construct temp */ + blob[0] = 1; /* RespType (1 byte) */ + blob[1] = 1; /* HighRespType (1 byte) */ + /* Reserved1 (2 bytes) */ + /* Reserved2 (4 bytes) */ + CopyMemory(&blob[8], context->Timestamp, 8); /* Timestamp (8 bytes) */ + CopyMemory(&blob[16], context->ClientChallenge, 8); /* ClientChallenge (8 bytes) */ + /* Reserved3 (4 bytes) */ + CopyMemory(&blob[28], TargetInfo->pvBuffer, TargetInfo->cbBuffer); +#ifdef WITH_DEBUG_NTLM + WLog_VRB(TAG, "NTLMv2 Response Temp Blob"); + winpr_HexDump(TAG, WLOG_TRACE, ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); +#endif + + /* Concatenate server challenge with temp */ + ret = SEC_E_INSUFFICIENT_MEMORY; + if (!sspi_SecBufferAlloc(&ntlm_v2_temp_chal, ntlm_v2_temp.cbBuffer + 8)) + goto exit; + + blob = (BYTE*)ntlm_v2_temp_chal.pvBuffer; + CopyMemory(blob, context->ServerChallenge, 8); + CopyMemory(&blob[8], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); + winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, + (BYTE*)ntlm_v2_temp_chal.pvBuffer, ntlm_v2_temp_chal.cbBuffer, + context->NtProofString, WINPR_MD5_DIGEST_LENGTH); + + /* NtChallengeResponse, Concatenate NTProofStr with temp */ + + if (!sspi_SecBufferAlloc(&context->NtChallengeResponse, ntlm_v2_temp.cbBuffer + 16)) + goto exit; + + blob = (BYTE*)context->NtChallengeResponse.pvBuffer; + CopyMemory(blob, context->NtProofString, WINPR_MD5_DIGEST_LENGTH); + CopyMemory(&blob[16], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); + /* Compute SessionBaseKey, the HMAC-MD5 hash of NTProofStr using the NTLMv2 hash as the key */ + winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, + context->NtProofString, WINPR_MD5_DIGEST_LENGTH, context->SessionBaseKey, + WINPR_MD5_DIGEST_LENGTH); + ret = SEC_E_OK; +exit: + sspi_SecBufferFree(&ntlm_v2_temp); + sspi_SecBufferFree(&ntlm_v2_temp_chal); + return ret; +} + +/** + * Encrypt the given plain text using RC4 and the given key. + * @param key RC4 key + * @param length text length + * @param plaintext plain text + * @param ciphertext cipher text + */ + +void ntlm_rc4k(BYTE* key, size_t length, BYTE* plaintext, BYTE* ciphertext) +{ + WINPR_RC4_CTX* rc4 = winpr_RC4_New(key, 16); + + if (rc4) + { + winpr_RC4_Update(rc4, length, plaintext, ciphertext); + winpr_RC4_Free(rc4); + } +} + +/** + * Generate client challenge (8-byte nonce). + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_client_challenge(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + /* ClientChallenge is used in computation of LMv2 and NTLMv2 responses */ + if (memcmp(context->ClientChallenge, NTLM_NULL_BUFFER, sizeof(context->ClientChallenge)) == 0) + winpr_RAND(context->ClientChallenge, sizeof(context->ClientChallenge)); +} + +/** + * Generate server challenge (8-byte nonce). + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_server_challenge(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + if (memcmp(context->ServerChallenge, NTLM_NULL_BUFFER, sizeof(context->ServerChallenge)) == 0) + winpr_RAND(context->ServerChallenge, sizeof(context->ServerChallenge)); +} + +/** + * Generate KeyExchangeKey (the 128-bit SessionBaseKey). msdn{cc236710} + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_key_exchange_key(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(sizeof(context->KeyExchangeKey) == sizeof(context->SessionBaseKey)); + + /* In NTLMv2, KeyExchangeKey is the 128-bit SessionBaseKey */ + CopyMemory(context->KeyExchangeKey, context->SessionBaseKey, sizeof(context->KeyExchangeKey)); +} + +/** + * Generate RandomSessionKey (16-byte nonce). + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_random_session_key(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + winpr_RAND(context->RandomSessionKey, sizeof(context->RandomSessionKey)); +} + +/** + * Generate ExportedSessionKey (the RandomSessionKey, exported) + * @param context A pointer to the NTLM context + */ + +void ntlm_generate_exported_session_key(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + CopyMemory(context->ExportedSessionKey, context->RandomSessionKey, + sizeof(context->ExportedSessionKey)); +} + +/** + * Encrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key). + * @param context A pointer to the NTLM context + */ + +void ntlm_encrypt_random_session_key(NTLM_CONTEXT* context) +{ + /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the + * KeyExchangeKey */ + WINPR_ASSERT(context); + ntlm_rc4k(context->KeyExchangeKey, 16, context->RandomSessionKey, + context->EncryptedRandomSessionKey); +} + +/** + * Decrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key). + * @param context A pointer to the NTLM context + */ + +void ntlm_decrypt_random_session_key(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the + * KeyExchangeKey */ + + /** + * if (NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) + * Set RandomSessionKey to RC4K(KeyExchangeKey, + * AUTHENTICATE_MESSAGE.EncryptedRandomSessionKey) else Set RandomSessionKey to KeyExchangeKey + */ + if (context->NegotiateKeyExchange) + { + WINPR_ASSERT(sizeof(context->EncryptedRandomSessionKey) == + sizeof(context->RandomSessionKey)); + ntlm_rc4k(context->KeyExchangeKey, sizeof(context->EncryptedRandomSessionKey), + context->EncryptedRandomSessionKey, context->RandomSessionKey); + } + else + { + WINPR_ASSERT(sizeof(context->RandomSessionKey) == sizeof(context->KeyExchangeKey)); + CopyMemory(context->RandomSessionKey, context->KeyExchangeKey, + sizeof(context->RandomSessionKey)); + } +} + +/** + * Generate signing key msdn{cc236711} + * + * @param exported_session_key ExportedSessionKey + * @param sign_magic Sign magic string + * @param signing_key Destination signing key + * + * @return \b TRUE for success, \b FALSE for failure + */ + +static BOOL ntlm_generate_signing_key(BYTE* exported_session_key, const SecBuffer* sign_magic, + BYTE* signing_key) +{ + BOOL rc = FALSE; + size_t length = 0; + BYTE* value = NULL; + + WINPR_ASSERT(exported_session_key); + WINPR_ASSERT(sign_magic); + WINPR_ASSERT(signing_key); + + length = WINPR_MD5_DIGEST_LENGTH + sign_magic->cbBuffer; + value = (BYTE*)malloc(length); + + if (!value) + goto out; + + /* Concatenate ExportedSessionKey with sign magic */ + CopyMemory(value, exported_session_key, WINPR_MD5_DIGEST_LENGTH); + CopyMemory(&value[WINPR_MD5_DIGEST_LENGTH], sign_magic->pvBuffer, sign_magic->cbBuffer); + + rc = winpr_Digest(WINPR_MD_MD5, value, length, signing_key, WINPR_MD5_DIGEST_LENGTH); + +out: + free(value); + return rc; +} + +/** + * Generate client signing key (ClientSigningKey). msdn{cc236711} + * @param context A pointer to the NTLM context + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_generate_client_signing_key(NTLM_CONTEXT* context) +{ + const SecBuffer signMagic = { sizeof(NTLM_CLIENT_SIGN_MAGIC), 0, NTLM_CLIENT_SIGN_MAGIC }; + + WINPR_ASSERT(context); + return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic, + context->ClientSigningKey); +} + +/** + * Generate server signing key (ServerSigningKey). msdn{cc236711} + * @param context A pointer to the NTLM context + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_generate_server_signing_key(NTLM_CONTEXT* context) +{ + const SecBuffer signMagic = { sizeof(NTLM_SERVER_SIGN_MAGIC), 0, NTLM_SERVER_SIGN_MAGIC }; + + WINPR_ASSERT(context); + return ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic, + context->ServerSigningKey); +} + +/** + * Generate client sealing key (ClientSealingKey). msdn{cc236712} + * @param context A pointer to the NTLM context + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_generate_client_sealing_key(NTLM_CONTEXT* context) +{ + const SecBuffer sealMagic = { sizeof(NTLM_CLIENT_SEAL_MAGIC), 0, NTLM_CLIENT_SEAL_MAGIC }; + + WINPR_ASSERT(context); + return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic, + context->ClientSealingKey); +} + +/** + * Generate server sealing key (ServerSealingKey). msdn{cc236712} + * @param context A pointer to the NTLM context + * + * @return \b TRUE for success, \b FALSE for failure + */ + +BOOL ntlm_generate_server_sealing_key(NTLM_CONTEXT* context) +{ + const SecBuffer sealMagic = { sizeof(NTLM_SERVER_SEAL_MAGIC), 0, NTLM_SERVER_SEAL_MAGIC }; + + WINPR_ASSERT(context); + return ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic, + context->ServerSealingKey); +} + +/** + * Initialize RC4 stream cipher states for sealing. + * @param context A pointer to the NTLM context + */ + +BOOL ntlm_init_rc4_seal_states(NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + if (context->server) + { + context->SendSigningKey = context->ServerSigningKey; + context->RecvSigningKey = context->ClientSigningKey; + context->SendSealingKey = context->ClientSealingKey; + context->RecvSealingKey = context->ServerSealingKey; + context->SendRc4Seal = + winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey)); + context->RecvRc4Seal = + winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey)); + } + else + { + context->SendSigningKey = context->ClientSigningKey; + context->RecvSigningKey = context->ServerSigningKey; + context->SendSealingKey = context->ServerSealingKey; + context->RecvSealingKey = context->ClientSealingKey; + context->SendRc4Seal = + winpr_RC4_New(context->ClientSealingKey, sizeof(context->ClientSealingKey)); + context->RecvRc4Seal = + winpr_RC4_New(context->ServerSealingKey, sizeof(context->ServerSealingKey)); + } + if (!context->SendRc4Seal) + { + WLog_ERR(TAG, "Failed to allocate context->SendRc4Seal"); + return FALSE; + } + if (!context->RecvRc4Seal) + { + WLog_ERR(TAG, "Failed to allocate context->RecvRc4Seal"); + return FALSE; + } + return TRUE; +} + +BOOL ntlm_compute_message_integrity_check(NTLM_CONTEXT* context, BYTE* mic, UINT32 size) +{ + BOOL rc = FALSE; + /* + * Compute the HMAC-MD5 hash of ConcatenationOf(NEGOTIATE_MESSAGE, + * CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE) using the ExportedSessionKey + */ + WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); + + WINPR_ASSERT(context); + WINPR_ASSERT(mic); + WINPR_ASSERT(size >= WINPR_MD5_DIGEST_LENGTH); + + memset(mic, 0, size); + if (!hmac) + return FALSE; + + if (winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->ExportedSessionKey, WINPR_MD5_DIGEST_LENGTH)) + { + winpr_HMAC_Update(hmac, (BYTE*)context->NegotiateMessage.pvBuffer, + context->NegotiateMessage.cbBuffer); + winpr_HMAC_Update(hmac, (BYTE*)context->ChallengeMessage.pvBuffer, + context->ChallengeMessage.cbBuffer); + + if (context->MessageIntegrityCheckOffset > 0) + { + const BYTE* auth = (BYTE*)context->AuthenticateMessage.pvBuffer; + const BYTE data[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + const size_t rest = context->MessageIntegrityCheckOffset + sizeof(data); + + WINPR_ASSERT(rest <= context->AuthenticateMessage.cbBuffer); + winpr_HMAC_Update(hmac, &auth[0], context->MessageIntegrityCheckOffset); + winpr_HMAC_Update(hmac, data, sizeof(data)); + winpr_HMAC_Update(hmac, &auth[rest], context->AuthenticateMessage.cbBuffer - rest); + } + else + { + winpr_HMAC_Update(hmac, (BYTE*)context->AuthenticateMessage.pvBuffer, + context->AuthenticateMessage.cbBuffer); + } + winpr_HMAC_Final(hmac, mic, WINPR_MD5_DIGEST_LENGTH); + rc = TRUE; + } + + winpr_HMAC_Free(hmac); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.h new file mode 100644 index 0000000000000000000000000000000000000000..74448329e9f0c5e496d6638b22a3d1f65ddeda78 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_compute.h @@ -0,0 +1,64 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (Compute) + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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_NTLM_COMPUTE_H +#define WINPR_SSPI_NTLM_COMPUTE_H + +#include "ntlm.h" + +#include "ntlm_av_pairs.h" + +BOOL ntlm_get_version_info(NTLM_VERSION_INFO* versionInfo); +BOOL ntlm_read_version_info(wStream* s, NTLM_VERSION_INFO* versionInfo); +BOOL ntlm_write_version_info(wStream* s, const NTLM_VERSION_INFO* versionInfo); + +#ifdef WITH_DEBUG_NTLM +void ntlm_print_version_info(const NTLM_VERSION_INFO* versionInfo); +#endif + +BOOL ntlm_read_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response); +BOOL ntlm_write_ntlm_v2_response(wStream* s, const NTLMv2_RESPONSE* response); + +void ntlm_output_target_name(NTLM_CONTEXT* context); +void ntlm_output_channel_bindings(NTLM_CONTEXT* context); + +void ntlm_current_time(BYTE* timestamp); +void ntlm_generate_timestamp(NTLM_CONTEXT* context); + +SECURITY_STATUS ntlm_compute_lm_v2_response(NTLM_CONTEXT* context); +SECURITY_STATUS ntlm_compute_ntlm_v2_response(NTLM_CONTEXT* context); + +void ntlm_rc4k(BYTE* key, size_t length, BYTE* plaintext, BYTE* ciphertext); +void ntlm_generate_client_challenge(NTLM_CONTEXT* context); +void ntlm_generate_server_challenge(NTLM_CONTEXT* context); +void ntlm_generate_key_exchange_key(NTLM_CONTEXT* context); +void ntlm_generate_random_session_key(NTLM_CONTEXT* context); +void ntlm_generate_exported_session_key(NTLM_CONTEXT* context); +void ntlm_encrypt_random_session_key(NTLM_CONTEXT* context); +void ntlm_decrypt_random_session_key(NTLM_CONTEXT* context); + +BOOL ntlm_generate_client_signing_key(NTLM_CONTEXT* context); +BOOL ntlm_generate_server_signing_key(NTLM_CONTEXT* context); +BOOL ntlm_generate_client_sealing_key(NTLM_CONTEXT* context); +BOOL ntlm_generate_server_sealing_key(NTLM_CONTEXT* context); +BOOL ntlm_init_rc4_seal_states(NTLM_CONTEXT* context); + +BOOL ntlm_compute_message_integrity_check(NTLM_CONTEXT* context, BYTE* mic, UINT32 size); + +#endif /* WINPR_AUTH_NTLM_COMPUTE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_export.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_export.h new file mode 100644 index 0000000000000000000000000000000000000000..5249be21ed4c375f799e7f2b11f763a952e2d8a2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_export.h @@ -0,0 +1,40 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package + * + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef WINPR_SSPI_NTLM_EXPORT_H +#define WINPR_SSPI_NTLM_EXPORT_H + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + extern const SecPkgInfoA NTLM_SecPkgInfoA; + extern const SecPkgInfoW NTLM_SecPkgInfoW; + extern const SecurityFunctionTableA NTLM_SecurityFunctionTableA; + extern const SecurityFunctionTableW NTLM_SecurityFunctionTableW; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.c new file mode 100644 index 0000000000000000000000000000000000000000..cc06cb610b2e8c97fb788c385d4eb8114020ef1b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.c @@ -0,0 +1,1413 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (Message) + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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 + +#include "ntlm.h" +#include "../sspi.h" + +#include +#include +#include +#include +#include + +#include "ntlm_compute.h" + +#include "ntlm_message.h" + +#include "../../log.h" +#define TAG WINPR_TAG("sspi.NTLM") + +#define NTLM_CheckAndLogRequiredCapacity(tag, s, nmemb, what) \ + Stream_CheckAndLogRequiredCapacityEx(tag, WLOG_WARN, s, nmemb, 1, "%s(%s:%" PRIuz ") " what, \ + __func__, __FILE__, (size_t)__LINE__) + +static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' }; + +static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields); + +const char* ntlm_get_negotiate_string(UINT32 flag) +{ + if (flag & NTLMSSP_NEGOTIATE_56) + return "NTLMSSP_NEGOTIATE_56"; + if (flag & NTLMSSP_NEGOTIATE_KEY_EXCH) + return "NTLMSSP_NEGOTIATE_KEY_EXCH"; + if (flag & NTLMSSP_NEGOTIATE_128) + return "NTLMSSP_NEGOTIATE_128"; + if (flag & NTLMSSP_RESERVED1) + return "NTLMSSP_RESERVED1"; + if (flag & NTLMSSP_RESERVED2) + return "NTLMSSP_RESERVED2"; + if (flag & NTLMSSP_RESERVED3) + return "NTLMSSP_RESERVED3"; + if (flag & NTLMSSP_NEGOTIATE_VERSION) + return "NTLMSSP_NEGOTIATE_VERSION"; + if (flag & NTLMSSP_RESERVED4) + return "NTLMSSP_RESERVED4"; + if (flag & NTLMSSP_NEGOTIATE_TARGET_INFO) + return "NTLMSSP_NEGOTIATE_TARGET_INFO"; + if (flag & NTLMSSP_REQUEST_NON_NT_SESSION_KEY) + return "NTLMSSP_REQUEST_NON_NT_SESSION_KEY"; + if (flag & NTLMSSP_RESERVED5) + return "NTLMSSP_RESERVED5"; + if (flag & NTLMSSP_NEGOTIATE_IDENTIFY) + return "NTLMSSP_NEGOTIATE_IDENTIFY"; + if (flag & NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY) + return "NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY"; + if (flag & NTLMSSP_RESERVED6) + return "NTLMSSP_RESERVED6"; + if (flag & NTLMSSP_TARGET_TYPE_SERVER) + return "NTLMSSP_TARGET_TYPE_SERVER"; + if (flag & NTLMSSP_TARGET_TYPE_DOMAIN) + return "NTLMSSP_TARGET_TYPE_DOMAIN"; + if (flag & NTLMSSP_NEGOTIATE_ALWAYS_SIGN) + return "NTLMSSP_NEGOTIATE_ALWAYS_SIGN"; + if (flag & NTLMSSP_RESERVED7) + return "NTLMSSP_RESERVED7"; + if (flag & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) + return "NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED"; + if (flag & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) + return "NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED"; + if (flag & NTLMSSP_NEGOTIATE_ANONYMOUS) + return "NTLMSSP_NEGOTIATE_ANONYMOUS"; + if (flag & NTLMSSP_RESERVED8) + return "NTLMSSP_RESERVED8"; + if (flag & NTLMSSP_NEGOTIATE_NTLM) + return "NTLMSSP_NEGOTIATE_NTLM"; + if (flag & NTLMSSP_RESERVED9) + return "NTLMSSP_RESERVED9"; + if (flag & NTLMSSP_NEGOTIATE_LM_KEY) + return "NTLMSSP_NEGOTIATE_LM_KEY"; + if (flag & NTLMSSP_NEGOTIATE_DATAGRAM) + return "NTLMSSP_NEGOTIATE_DATAGRAM"; + if (flag & NTLMSSP_NEGOTIATE_SEAL) + return "NTLMSSP_NEGOTIATE_SEAL"; + if (flag & NTLMSSP_NEGOTIATE_SIGN) + return "NTLMSSP_NEGOTIATE_SIGN"; + if (flag & NTLMSSP_RESERVED10) + return "NTLMSSP_RESERVED10"; + if (flag & NTLMSSP_REQUEST_TARGET) + return "NTLMSSP_REQUEST_TARGET"; + if (flag & NTLMSSP_NEGOTIATE_OEM) + return "NTLMSSP_NEGOTIATE_OEM"; + if (flag & NTLMSSP_NEGOTIATE_UNICODE) + return "NTLMSSP_NEGOTIATE_UNICODE"; + return "NTLMSSP_NEGOTIATE_UNKNOWN"; +} + +#if defined(WITH_DEBUG_NTLM) +static void ntlm_print_message_fields(const NTLM_MESSAGE_FIELDS* fields, const char* name) +{ + WINPR_ASSERT(fields); + WINPR_ASSERT(name); + + WLog_VRB(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name, + fields->Len, fields->MaxLen, fields->BufferOffset); + + if (fields->Len > 0) + winpr_HexDump(TAG, WLOG_TRACE, fields->Buffer, fields->Len); +} + +static void ntlm_print_negotiate_flags(UINT32 flags) +{ + WLog_VRB(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags); + + for (int i = 31; i >= 0; i--) + { + if ((flags >> i) & 1) + { + const char* str = ntlm_get_negotiate_string(1 << i); + WLog_VRB(TAG, "\t%s (%d),", str, (31 - i)); + } + } +} + +static void ntlm_print_negotiate_message(const SecBuffer* NegotiateMessage, + const NTLM_NEGOTIATE_MESSAGE* message) +{ + WINPR_ASSERT(NegotiateMessage); + WINPR_ASSERT(message); + + WLog_VRB(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", NegotiateMessage->cbBuffer); + winpr_HexDump(TAG, WLOG_TRACE, NegotiateMessage->pvBuffer, NegotiateMessage->cbBuffer); + ntlm_print_negotiate_flags(message->NegotiateFlags); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_print_version_info(&(message->Version)); +} + +static void ntlm_print_challenge_message(const SecBuffer* ChallengeMessage, + const NTLM_CHALLENGE_MESSAGE* message, + const SecBuffer* ChallengeTargetInfo) +{ + WINPR_ASSERT(ChallengeMessage); + WINPR_ASSERT(message); + + WLog_VRB(TAG, "CHALLENGE_MESSAGE (length = %" PRIu32 ")", ChallengeMessage->cbBuffer); + winpr_HexDump(TAG, WLOG_TRACE, ChallengeMessage->pvBuffer, ChallengeMessage->cbBuffer); + ntlm_print_negotiate_flags(message->NegotiateFlags); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_print_version_info(&(message->Version)); + + ntlm_print_message_fields(&(message->TargetName), "TargetName"); + ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); + + if (ChallengeTargetInfo && (ChallengeTargetInfo->cbBuffer > 0)) + { + WLog_VRB(TAG, "ChallengeTargetInfo (%" PRIu32 "):", ChallengeTargetInfo->cbBuffer); + ntlm_print_av_pair_list(ChallengeTargetInfo->pvBuffer, ChallengeTargetInfo->cbBuffer); + } +} + +static void ntlm_print_authenticate_message(const SecBuffer* AuthenticateMessage, + const NTLM_AUTHENTICATE_MESSAGE* message, UINT32 flags, + const SecBuffer* AuthenticateTargetInfo) +{ + WINPR_ASSERT(AuthenticateMessage); + WINPR_ASSERT(message); + + WLog_VRB(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")", AuthenticateMessage->cbBuffer); + winpr_HexDump(TAG, WLOG_TRACE, AuthenticateMessage->pvBuffer, AuthenticateMessage->cbBuffer); + ntlm_print_negotiate_flags(message->NegotiateFlags); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_print_version_info(&(message->Version)); + + if (AuthenticateTargetInfo && (AuthenticateTargetInfo->cbBuffer > 0)) + { + WLog_VRB(TAG, "AuthenticateTargetInfo (%" PRIu32 "):", AuthenticateTargetInfo->cbBuffer); + ntlm_print_av_pair_list(AuthenticateTargetInfo->pvBuffer, AuthenticateTargetInfo->cbBuffer); + } + + ntlm_print_message_fields(&(message->DomainName), "DomainName"); + ntlm_print_message_fields(&(message->UserName), "UserName"); + ntlm_print_message_fields(&(message->Workstation), "Workstation"); + ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); + ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); + ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); + + if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) + { + WLog_VRB(TAG, "MessageIntegrityCheck (length = 16)"); + winpr_HexDump(TAG, WLOG_TRACE, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck)); + } +} + +static void ntlm_print_authentication_complete(const NTLM_CONTEXT* context) +{ + WINPR_ASSERT(context); + + WLog_VRB(TAG, "ClientChallenge"); + winpr_HexDump(TAG, WLOG_TRACE, context->ClientChallenge, 8); + WLog_VRB(TAG, "ServerChallenge"); + winpr_HexDump(TAG, WLOG_TRACE, context->ServerChallenge, 8); + WLog_VRB(TAG, "SessionBaseKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->SessionBaseKey, 16); + WLog_VRB(TAG, "KeyExchangeKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->KeyExchangeKey, 16); + WLog_VRB(TAG, "ExportedSessionKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->ExportedSessionKey, 16); + WLog_VRB(TAG, "RandomSessionKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->RandomSessionKey, 16); + WLog_VRB(TAG, "ClientSigningKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->ClientSigningKey, 16); + WLog_VRB(TAG, "ClientSealingKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->ClientSealingKey, 16); + WLog_VRB(TAG, "ServerSigningKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->ServerSigningKey, 16); + WLog_VRB(TAG, "ServerSealingKey"); + winpr_HexDump(TAG, WLOG_TRACE, context->ServerSealingKey, 16); + WLog_VRB(TAG, "Timestamp"); + winpr_HexDump(TAG, WLOG_TRACE, context->Timestamp, 8); +} +#endif + +static BOOL ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header, UINT32 expected) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 12)) + return FALSE; + + Stream_Read(s, header->Signature, 8); + Stream_Read_UINT32(s, header->MessageType); + + if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0) + { + char Signature[sizeof(header->Signature) * 3 + 1] = { 0 }; + winpr_BinToHexStringBuffer(header->Signature, sizeof(header->Signature), Signature, + sizeof(Signature), TRUE); + + WLog_ERR(TAG, "NTLM_MESSAGE_HEADER Invalid signature, got %s, expected %s", Signature, + NTLM_SIGNATURE); + return FALSE; + } + + if (header->MessageType != expected) + { + WLog_ERR(TAG, "NTLM_MESSAGE_HEADER Invalid message type, got %s, expected %s", + ntlm_message_type_string(header->MessageType), ntlm_message_type_string(expected)); + return FALSE; + } + + return TRUE; +} + +static BOOL ntlm_write_message_header(wStream* s, const NTLM_MESSAGE_HEADER* header) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(header); + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, sizeof(NTLM_SIGNATURE) + 4ull, + "NTLM_MESSAGE_HEADER::header")) + return FALSE; + + Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); + Stream_Write_UINT32(s, header->MessageType); + + return TRUE; +} + +static BOOL ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) +{ + WINPR_ASSERT(header); + + CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); + header->MessageType = MessageType; + return TRUE; +} + +static BOOL ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(fields); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 8)) + return FALSE; + + ntlm_free_message_fields_buffer(fields); + + Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ + Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ + Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ + return TRUE; +} + +static BOOL ntlm_write_message_fields(wStream* s, const NTLM_MESSAGE_FIELDS* fields) +{ + UINT16 MaxLen = 0; + WINPR_ASSERT(s); + WINPR_ASSERT(fields); + + MaxLen = fields->MaxLen; + if (fields->MaxLen < 1) + MaxLen = fields->Len; + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, (s), 8, "NTLM_MESSAGE_FIELDS::header")) + return FALSE; + + Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */ + Stream_Write_UINT16(s, MaxLen); /* MaxLen (2 bytes) */ + Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ + return TRUE; +} + +static BOOL ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(fields); + + if (fields->Len > 0) + { + const UINT32 offset = fields->BufferOffset + fields->Len; + + if (fields->BufferOffset > UINT32_MAX - fields->Len) + { + WLog_ERR(TAG, + "NTLM_MESSAGE_FIELDS::BufferOffset %" PRIu32 + " too large, maximum allowed is %" PRIu32, + fields->BufferOffset, UINT32_MAX - fields->Len); + return FALSE; + } + + if (offset > Stream_Length(s)) + { + WLog_ERR(TAG, + "NTLM_MESSAGE_FIELDS::Buffer offset %" PRIu32 " beyond received data %" PRIuz, + offset, Stream_Length(s)); + return FALSE; + } + + fields->Buffer = (PBYTE)malloc(fields->Len); + + if (!fields->Buffer) + { + WLog_ERR(TAG, "NTLM_MESSAGE_FIELDS::Buffer allocation of %" PRIu16 "bytes failed", + fields->Len); + return FALSE; + } + + Stream_SetPosition(s, fields->BufferOffset); + Stream_Read(s, fields->Buffer, fields->Len); + } + + return TRUE; +} + +static BOOL ntlm_write_message_fields_buffer(wStream* s, const NTLM_MESSAGE_FIELDS* fields) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(fields); + + if (fields->Len > 0) + { + Stream_SetPosition(s, fields->BufferOffset); + if (!NTLM_CheckAndLogRequiredCapacity(TAG, (s), fields->Len, "NTLM_MESSAGE_FIELDS::Len")) + return FALSE; + + Stream_Write(s, fields->Buffer, fields->Len); + } + return TRUE; +} + +void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) +{ + if (fields) + { + if (fields->Buffer) + { + free(fields->Buffer); + fields->Len = 0; + fields->MaxLen = 0; + fields->Buffer = NULL; + fields->BufferOffset = 0; + } + } +} + +static BOOL ntlm_read_negotiate_flags(wStream* s, UINT32* flags, UINT32 required, const char* name) +{ + UINT32 NegotiateFlags = 0; + char buffer[1024] = { 0 }; + WINPR_ASSERT(s); + WINPR_ASSERT(flags); + WINPR_ASSERT(name); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 4)) + return FALSE; + + Stream_Read_UINT32(s, NegotiateFlags); /* NegotiateFlags (4 bytes) */ + + if ((NegotiateFlags & required) != required) + { + WLog_ERR(TAG, "%s::NegotiateFlags invalid flags 0x08%" PRIx32 ", 0x%08" PRIx32 " required", + name, NegotiateFlags, required); + return FALSE; + } + + WLog_DBG(TAG, "Read flags %s", + ntlm_negotiate_flags_string(buffer, ARRAYSIZE(buffer), NegotiateFlags)); + *flags = NegotiateFlags; + return TRUE; +} + +static BOOL ntlm_write_negotiate_flags(wStream* s, UINT32 flags, const char* name) +{ + char buffer[1024] = { 0 }; + WINPR_ASSERT(s); + WINPR_ASSERT(name); + + if (!Stream_CheckAndLogRequiredCapacityEx(TAG, WLOG_WARN, s, 4ull, 1ull, + "%s(%s:%" PRIuz ") %s::NegotiateFlags", __func__, + __FILE__, (size_t)__LINE__, name)) + return FALSE; + + WLog_DBG(TAG, "Write flags %s", ntlm_negotiate_flags_string(buffer, ARRAYSIZE(buffer), flags)); + Stream_Write_UINT32(s, flags); /* NegotiateFlags (4 bytes) */ + return TRUE; +} + +static BOOL ntlm_read_message_integrity_check(wStream* s, size_t* offset, BYTE* data, size_t size, + const char* name) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(offset); + WINPR_ASSERT(data); + WINPR_ASSERT(size == WINPR_MD5_DIGEST_LENGTH); + WINPR_ASSERT(name); + + *offset = Stream_GetPosition(s); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, size)) + return FALSE; + + Stream_Read(s, data, size); + return TRUE; +} + +static BOOL ntlm_write_message_integrity_check(wStream* s, size_t offset, const BYTE* data, + size_t size, const char* name) +{ + size_t pos = 0; + + WINPR_ASSERT(s); + WINPR_ASSERT(data); + WINPR_ASSERT(size == WINPR_MD5_DIGEST_LENGTH); + WINPR_ASSERT(name); + + pos = Stream_GetPosition(s); + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, offset, "MessageIntegrityCheck::offset")) + return FALSE; + + Stream_SetPosition(s, offset); + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, size, "MessageIntegrityCheck::size")) + return FALSE; + + Stream_Write(s, data, size); + Stream_SetPosition(s, pos); + return TRUE; +} + +SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) +{ + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + const NTLM_NEGOTIATE_MESSAGE empty = { 0 }; + NTLM_NEGOTIATE_MESSAGE* message = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(buffer); + + message = &context->NEGOTIATE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticConstInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (!ntlm_read_message_header(s, &message->header, MESSAGE_TYPE_NEGOTIATE)) + return SEC_E_INVALID_TOKEN; + + if (!ntlm_read_negotiate_flags(s, &message->NegotiateFlags, + NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_NTLM | + NTLMSSP_NEGOTIATE_UNICODE, + "NTLM_NEGOTIATE_MESSAGE")) + return SEC_E_INVALID_TOKEN; + + context->NegotiateFlags = message->NegotiateFlags; + + /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ + // if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) + { + if (!ntlm_read_message_fields(s, &(message->DomainName))) /* DomainNameFields (8 bytes) */ + return SEC_E_INVALID_TOKEN; + } + + /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ + // if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) + { + if (!ntlm_read_message_fields(s, &(message->Workstation))) /* WorkstationFields (8 bytes) */ + return SEC_E_INVALID_TOKEN; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_read_version_info(s, &(message->Version))) /* Version (8 bytes) */ + return SEC_E_INVALID_TOKEN; + } + + if (!ntlm_read_message_fields_buffer(s, &message->DomainName)) + return SEC_E_INVALID_TOKEN; + + if (!ntlm_read_message_fields_buffer(s, &message->Workstation)) + return SEC_E_INVALID_TOKEN; + + length = Stream_GetPosition(s); + WINPR_ASSERT(length <= UINT32_MAX); + buffer->cbBuffer = (ULONG)length; + + if (!sspi_SecBufferAlloc(&context->NegotiateMessage, (ULONG)length)) + return SEC_E_INTERNAL_ERROR; + + CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); + context->NegotiateMessage.BufferType = buffer->BufferType; +#if defined(WITH_DEBUG_NTLM) + ntlm_print_negotiate_message(&context->NegotiateMessage, message); +#endif + ntlm_change_state(context, NTLM_STATE_CHALLENGE); + return SEC_I_CONTINUE_NEEDED; +} + +SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, const PSecBuffer buffer) +{ + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + const NTLM_NEGOTIATE_MESSAGE empty = { 0 }; + NTLM_NEGOTIATE_MESSAGE* message = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(buffer); + + message = &context->NEGOTIATE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (!ntlm_populate_message_header(&message->header, MESSAGE_TYPE_NEGOTIATE)) + return SEC_E_INTERNAL_ERROR; + + if (context->NTLMv2) + { + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM; + } + + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; + message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; + + if (context->confidentiality) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; + + if (context->SendVersionInfo) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_get_version_info(&(message->Version)); + + context->NegotiateFlags = message->NegotiateFlags; + /* Message Header (12 bytes) */ + if (!ntlm_write_message_header(s, &message->header)) + return SEC_E_INTERNAL_ERROR; + + if (!ntlm_write_negotiate_flags(s, message->NegotiateFlags, "NTLM_NEGOTIATE_MESSAGE")) + return SEC_E_INTERNAL_ERROR; + + /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ + /* DomainNameFields (8 bytes) */ + if (!ntlm_write_message_fields(s, &(message->DomainName))) + return SEC_E_INTERNAL_ERROR; + + /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ + /* WorkstationFields (8 bytes) */ + if (!ntlm_write_message_fields(s, &(message->Workstation))) + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_write_version_info(s, &(message->Version))) + return SEC_E_INTERNAL_ERROR; + } + + length = Stream_GetPosition(s); + WINPR_ASSERT(length <= UINT32_MAX); + buffer->cbBuffer = (ULONG)length; + + if (!sspi_SecBufferAlloc(&context->NegotiateMessage, (ULONG)length)) + return SEC_E_INTERNAL_ERROR; + + CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); + context->NegotiateMessage.BufferType = buffer->BufferType; +#if defined(WITH_DEBUG_NTLM) + ntlm_print_negotiate_message(&context->NegotiateMessage, message); +#endif + ntlm_change_state(context, NTLM_STATE_CHALLENGE); + return SEC_I_CONTINUE_NEEDED; +} + +SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) +{ + SECURITY_STATUS status = SEC_E_INVALID_TOKEN; + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + size_t StartOffset = 0; + size_t PayloadOffset = 0; + NTLM_AV_PAIR* AvTimestamp = NULL; + const NTLM_CHALLENGE_MESSAGE empty = { 0 }; + NTLM_CHALLENGE_MESSAGE* message = NULL; + + if (!context || !buffer) + return SEC_E_INTERNAL_ERROR; + + ntlm_generate_client_challenge(context); + message = &context->CHALLENGE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticConstInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + StartOffset = Stream_GetPosition(s); + + if (!ntlm_read_message_header(s, &message->header, MESSAGE_TYPE_CHALLENGE)) + goto fail; + + if (!ntlm_read_message_fields(s, &(message->TargetName))) /* TargetNameFields (8 bytes) */ + goto fail; + + if (!ntlm_read_negotiate_flags(s, &message->NegotiateFlags, 0, "NTLM_CHALLENGE_MESSAGE")) + goto fail; + + context->NegotiateFlags = message->NegotiateFlags; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 16)) + goto fail; + + Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ + CopyMemory(context->ServerChallenge, message->ServerChallenge, 8); + Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ + + if (!ntlm_read_message_fields(s, &(message->TargetInfo))) /* TargetInfoFields (8 bytes) */ + goto fail; + + if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_read_version_info(s, &(message->Version))) /* Version (8 bytes) */ + goto fail; + } + + /* Payload (variable) */ + PayloadOffset = Stream_GetPosition(s); + + status = SEC_E_INTERNAL_ERROR; + if (message->TargetName.Len > 0) + { + if (!ntlm_read_message_fields_buffer(s, &(message->TargetName))) + goto fail; + } + + if (message->TargetInfo.Len > 0) + { + size_t cbAvTimestamp = 0; + + if (!ntlm_read_message_fields_buffer(s, &(message->TargetInfo))) + goto fail; + + context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer; + context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len; + AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer, + message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp); + + if (AvTimestamp) + { + PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp); + + if (!ptr) + goto fail; + + if (context->NTLMv2) + context->UseMIC = TRUE; + + CopyMemory(context->ChallengeTimestamp, ptr, 8); + } + } + + length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len; + if (length > buffer->cbBuffer) + goto fail; + + if (!sspi_SecBufferAlloc(&context->ChallengeMessage, (ULONG)length)) + goto fail; + + if (context->ChallengeMessage.pvBuffer) + CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s) + StartOffset, length); +#if defined(WITH_DEBUG_NTLM) + ntlm_print_challenge_message(&context->ChallengeMessage, message, NULL); +#endif + /* AV_PAIRs */ + + if (context->NTLMv2) + { + if (!ntlm_construct_authenticate_target_info(context)) + goto fail; + + sspi_SecBufferFree(&context->ChallengeTargetInfo); + context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer; + context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer; + } + + ntlm_generate_timestamp(context); /* Timestamp */ + + const SECURITY_STATUS rc = ntlm_compute_lm_v2_response(context); /* LmChallengeResponse */ + if (rc != SEC_E_OK) + { + status = rc; + goto fail; + } + + const SECURITY_STATUS rc2 = ntlm_compute_ntlm_v2_response(context); /* NtChallengeResponse */ + if (rc2 != SEC_E_OK) + { + status = rc2; + goto fail; + } + + ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */ + ntlm_generate_random_session_key(context); /* RandomSessionKey */ + ntlm_generate_exported_session_key(context); /* ExportedSessionKey */ + ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */ + + /* Generate signing keys */ + status = SEC_E_ENCRYPT_FAILURE; + if (!ntlm_generate_client_signing_key(context)) + goto fail; + if (!ntlm_generate_server_signing_key(context)) + goto fail; + /* Generate sealing keys */ + if (!ntlm_generate_client_sealing_key(context)) + goto fail; + if (!ntlm_generate_server_sealing_key(context)) + goto fail; + /* Initialize RC4 seal state using client sealing key */ + if (!ntlm_init_rc4_seal_states(context)) + goto fail; +#if defined(WITH_DEBUG_NTLM) + ntlm_print_authentication_complete(context); +#endif + ntlm_change_state(context, NTLM_STATE_AUTHENTICATE); + status = SEC_I_CONTINUE_NEEDED; +fail: + ntlm_free_message_fields_buffer(&(message->TargetName)); + return status; +} + +SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, const PSecBuffer buffer) +{ + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + UINT32 PayloadOffset = 0; + const NTLM_CHALLENGE_MESSAGE empty = { 0 }; + NTLM_CHALLENGE_MESSAGE* message = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(buffer); + + message = &context->CHALLENGE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + ntlm_get_version_info(&(message->Version)); /* Version */ + ntlm_generate_server_challenge(context); /* Server Challenge */ + ntlm_generate_timestamp(context); /* Timestamp */ + + if (!ntlm_construct_challenge_target_info(context)) /* TargetInfo */ + return SEC_E_INTERNAL_ERROR; + + CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */ + message->NegotiateFlags = context->NegotiateFlags; + if (!ntlm_populate_message_header(&message->header, MESSAGE_TYPE_CHALLENGE)) + return SEC_E_INTERNAL_ERROR; + + /* Message Header (12 bytes) */ + if (!ntlm_write_message_header(s, &message->header)) + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) + { + message->TargetName.Len = (UINT16)context->TargetName.cbBuffer; + message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer; + } + + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) + { + message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer; + message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer; + } + + PayloadOffset = 48; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + PayloadOffset += 8; + + message->TargetName.BufferOffset = PayloadOffset; + message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len; + /* TargetNameFields (8 bytes) */ + if (!ntlm_write_message_fields(s, &(message->TargetName))) + return SEC_E_INTERNAL_ERROR; + + if (!ntlm_write_negotiate_flags(s, message->NegotiateFlags, "NTLM_CHALLENGE_MESSAGE")) + return SEC_E_INTERNAL_ERROR; + + if (!NTLM_CheckAndLogRequiredCapacity(TAG, s, 16, "NTLM_CHALLENGE_MESSAGE::ServerChallenge")) + return SEC_E_INTERNAL_ERROR; + + Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ + Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ + + /* TargetInfoFields (8 bytes) */ + if (!ntlm_write_message_fields(s, &(message->TargetInfo))) + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_write_version_info(s, &(message->Version))) /* Version (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + } + + /* Payload (variable) */ + if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) + { + if (!ntlm_write_message_fields_buffer(s, &(message->TargetName))) + return SEC_E_INTERNAL_ERROR; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) + { + if (!ntlm_write_message_fields_buffer(s, &(message->TargetInfo))) + return SEC_E_INTERNAL_ERROR; + } + + length = Stream_GetPosition(s); + WINPR_ASSERT(length <= UINT32_MAX); + buffer->cbBuffer = (ULONG)length; + + if (!sspi_SecBufferAlloc(&context->ChallengeMessage, (ULONG)length)) + return SEC_E_INTERNAL_ERROR; + + CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length); +#if defined(WITH_DEBUG_NTLM) + ntlm_print_challenge_message(&context->ChallengeMessage, message, + &context->ChallengeTargetInfo); +#endif + ntlm_change_state(context, NTLM_STATE_AUTHENTICATE); + return SEC_I_CONTINUE_NEEDED; +} + +SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) +{ + SECURITY_STATUS status = SEC_E_INVALID_TOKEN; + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + UINT32 flags = 0; + NTLM_AV_PAIR* AvFlags = NULL; + size_t PayloadBufferOffset = 0; + const NTLM_AUTHENTICATE_MESSAGE empty = { 0 }; + NTLM_AUTHENTICATE_MESSAGE* message = NULL; + SSPI_CREDENTIALS* credentials = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(buffer); + + credentials = context->credentials; + WINPR_ASSERT(credentials); + + message = &context->AUTHENTICATE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticConstInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (!ntlm_read_message_header(s, &message->header, MESSAGE_TYPE_AUTHENTICATE)) + goto fail; + + if (!ntlm_read_message_fields( + s, &(message->LmChallengeResponse))) /* LmChallengeResponseFields (8 bytes) */ + goto fail; + + if (!ntlm_read_message_fields( + s, &(message->NtChallengeResponse))) /* NtChallengeResponseFields (8 bytes) */ + goto fail; + + if (!ntlm_read_message_fields(s, &(message->DomainName))) /* DomainNameFields (8 bytes) */ + goto fail; + + if (!ntlm_read_message_fields(s, &(message->UserName))) /* UserNameFields (8 bytes) */ + goto fail; + + if (!ntlm_read_message_fields(s, &(message->Workstation))) /* WorkstationFields (8 bytes) */ + goto fail; + + if (!ntlm_read_message_fields( + s, + &(message->EncryptedRandomSessionKey))) /* EncryptedRandomSessionKeyFields (8 bytes) */ + goto fail; + + if (!ntlm_read_negotiate_flags(s, &message->NegotiateFlags, 0, "NTLM_AUTHENTICATE_MESSAGE")) + goto fail; + + context->NegotiateKeyExchange = + (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE; + + if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) || + (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len)) + goto fail; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_read_version_info(s, &(message->Version))) /* Version (8 bytes) */ + goto fail; + } + + PayloadBufferOffset = Stream_GetPosition(s); + + status = SEC_E_INTERNAL_ERROR; + if (!ntlm_read_message_fields_buffer(s, &(message->DomainName))) /* DomainName */ + goto fail; + + if (!ntlm_read_message_fields_buffer(s, &(message->UserName))) /* UserName */ + goto fail; + + if (!ntlm_read_message_fields_buffer(s, &(message->Workstation))) /* Workstation */ + goto fail; + + if (!ntlm_read_message_fields_buffer(s, + &(message->LmChallengeResponse))) /* LmChallengeResponse */ + goto fail; + + if (!ntlm_read_message_fields_buffer(s, + &(message->NtChallengeResponse))) /* NtChallengeResponse */ + goto fail; + + if (message->NtChallengeResponse.Len > 0) + { + size_t cbAvFlags = 0; + wStream ssbuffer; + wStream* snt = Stream_StaticConstInit(&ssbuffer, message->NtChallengeResponse.Buffer, + message->NtChallengeResponse.Len); + + if (!snt) + goto fail; + + status = SEC_E_INVALID_TOKEN; + if (!ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response))) + goto fail; + status = SEC_E_INTERNAL_ERROR; + + context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer; + context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len; + sspi_SecBufferFree(&(context->ChallengeTargetInfo)); + context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs; + context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16); + CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8); + AvFlags = + ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, + context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags); + + if (AvFlags) + flags = winpr_Data_Get_UINT32(ntlm_av_pair_get_value_pointer(AvFlags)); + } + + if (!ntlm_read_message_fields_buffer( + s, &(message->EncryptedRandomSessionKey))) /* EncryptedRandomSessionKey */ + goto fail; + + if (message->EncryptedRandomSessionKey.Len > 0) + { + if (message->EncryptedRandomSessionKey.Len != 16) + goto fail; + + CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer, + 16); + } + + length = Stream_GetPosition(s); + WINPR_ASSERT(length <= UINT32_MAX); + + if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, (ULONG)length)) + goto fail; + + CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); + buffer->cbBuffer = (ULONG)length; + Stream_SetPosition(s, PayloadBufferOffset); + + if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) + { + status = SEC_E_INVALID_TOKEN; + if (!ntlm_read_message_integrity_check( + s, &context->MessageIntegrityCheckOffset, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck), "NTLM_AUTHENTICATE_MESSAGE")) + goto fail; + } + + status = SEC_E_INTERNAL_ERROR; + +#if defined(WITH_DEBUG_NTLM) + ntlm_print_authenticate_message(&context->AuthenticateMessage, message, flags, NULL); +#endif + + if (message->UserName.Len > 0) + { + credentials->identity.User = (UINT16*)malloc(message->UserName.Len); + + if (!credentials->identity.User) + goto fail; + + CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len); + credentials->identity.UserLength = message->UserName.Len / 2; + } + + if (message->DomainName.Len > 0) + { + credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len); + + if (!credentials->identity.Domain) + goto fail; + + CopyMemory(credentials->identity.Domain, message->DomainName.Buffer, + message->DomainName.Len); + credentials->identity.DomainLength = message->DomainName.Len / 2; + } + + if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_LM_KEY) + { + const SECURITY_STATUS rc = ntlm_compute_lm_v2_response(context); /* LmChallengeResponse */ + if (rc != SEC_E_OK) + return rc; + } + + const SECURITY_STATUS rc = ntlm_compute_ntlm_v2_response(context); /* NtChallengeResponse */ + if (rc != SEC_E_OK) + return rc; + + /* KeyExchangeKey */ + ntlm_generate_key_exchange_key(context); + /* EncryptedRandomSessionKey */ + ntlm_decrypt_random_session_key(context); + /* ExportedSessionKey */ + ntlm_generate_exported_session_key(context); + + if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) + { + BYTE messageIntegrityCheck[16] = { 0 }; + + ntlm_compute_message_integrity_check(context, messageIntegrityCheck, + sizeof(messageIntegrityCheck)); + CopyMemory( + &((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], + message->MessageIntegrityCheck, sizeof(message->MessageIntegrityCheck)); + + if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck)) != 0) + { + WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!"); +#ifdef WITH_DEBUG_NTLM + WLog_ERR(TAG, "Expected MIC:"); + winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck)); + WLog_ERR(TAG, "Actual MIC:"); + winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck)); +#endif + return SEC_E_MESSAGE_ALTERED; + } + } + else + { + /* no mic message was present + + https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec + the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and + Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5. + + now check the NtProofString, to detect if the entered client password matches the + expected password. + */ + +#ifdef WITH_DEBUG_NTLM + WLog_VRB(TAG, "No MIC present, using NtProofString for verification."); +#endif + + if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0) + { + WLog_ERR(TAG, "NtProofString verification failed!"); +#ifdef WITH_DEBUG_NTLM + WLog_ERR(TAG, "Expected NtProofString:"); + winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString)); + WLog_ERR(TAG, "Actual NtProofString:"); + winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response, + sizeof(context->NTLMv2Response)); +#endif + return SEC_E_LOGON_DENIED; + } + } + + /* Generate signing keys */ + if (!ntlm_generate_client_signing_key(context)) + return SEC_E_INTERNAL_ERROR; + if (!ntlm_generate_server_signing_key(context)) + return SEC_E_INTERNAL_ERROR; + /* Generate sealing keys */ + if (!ntlm_generate_client_sealing_key(context)) + return SEC_E_INTERNAL_ERROR; + if (!ntlm_generate_server_sealing_key(context)) + return SEC_E_INTERNAL_ERROR; + /* Initialize RC4 seal state */ + if (!ntlm_init_rc4_seal_states(context)) + return SEC_E_INTERNAL_ERROR; +#if defined(WITH_DEBUG_NTLM) + ntlm_print_authentication_complete(context); +#endif + ntlm_change_state(context, NTLM_STATE_FINAL); + ntlm_free_message_fields_buffer(&(message->DomainName)); + ntlm_free_message_fields_buffer(&(message->UserName)); + ntlm_free_message_fields_buffer(&(message->Workstation)); + ntlm_free_message_fields_buffer(&(message->LmChallengeResponse)); + ntlm_free_message_fields_buffer(&(message->NtChallengeResponse)); + ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey)); + return SEC_E_OK; + +fail: + return status; +} + +/** + * Send NTLMSSP AUTHENTICATE_MESSAGE. msdn{cc236643} + * + * @param context Pointer to the NTLM context + * @param buffer The buffer to write + */ + +SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, const PSecBuffer buffer) +{ + wStream sbuffer; + wStream* s = NULL; + size_t length = 0; + UINT32 PayloadBufferOffset = 0; + const NTLM_AUTHENTICATE_MESSAGE empty = { 0 }; + NTLM_AUTHENTICATE_MESSAGE* message = NULL; + SSPI_CREDENTIALS* credentials = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(buffer); + + credentials = context->credentials; + WINPR_ASSERT(credentials); + + message = &context->AUTHENTICATE_MESSAGE; + WINPR_ASSERT(message); + + *message = empty; + + s = Stream_StaticInit(&sbuffer, buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (context->NTLMv2) + { + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; + + if (context->SendVersionInfo) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; + } + + if (context->UseMIC) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; + + if (context->SendWorkstationName) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED; + + if (context->confidentiality) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; + + if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; + + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; + message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_get_version_info(&(message->Version)); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) + { + message->Workstation.Len = context->Workstation.Length; + message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer; + } + + if (credentials->identity.DomainLength > 0) + { + message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; + message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2; + message->DomainName.Buffer = (BYTE*)credentials->identity.Domain; + } + + message->UserName.Len = (UINT16)credentials->identity.UserLength * 2; + message->UserName.Buffer = (BYTE*)credentials->identity.User; + message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer; + message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer; + message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer; + message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) + { + message->EncryptedRandomSessionKey.Len = 16; + message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey; + } + + PayloadBufferOffset = 64; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + PayloadBufferOffset += 8; /* Version (8 bytes) */ + + if (context->UseMIC) + PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */ + + message->DomainName.BufferOffset = PayloadBufferOffset; + message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len; + message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len; + message->LmChallengeResponse.BufferOffset = + message->Workstation.BufferOffset + message->Workstation.Len; + message->NtChallengeResponse.BufferOffset = + message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len; + message->EncryptedRandomSessionKey.BufferOffset = + message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len; + if (!ntlm_populate_message_header(&message->header, MESSAGE_TYPE_AUTHENTICATE)) + return SEC_E_INVALID_TOKEN; + if (!ntlm_write_message_header(s, &message->header)) /* Message Header (12 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields( + s, &(message->LmChallengeResponse))) /* LmChallengeResponseFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields( + s, &(message->NtChallengeResponse))) /* NtChallengeResponseFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields(s, &(message->DomainName))) /* DomainNameFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields(s, &(message->UserName))) /* UserNameFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields(s, &(message->Workstation))) /* WorkstationFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_message_fields( + s, + &(message->EncryptedRandomSessionKey))) /* EncryptedRandomSessionKeyFields (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + if (!ntlm_write_negotiate_flags(s, message->NegotiateFlags, "NTLM_AUTHENTICATE_MESSAGE")) + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (!ntlm_write_version_info(s, &(message->Version))) /* Version (8 bytes) */ + return SEC_E_INTERNAL_ERROR; + } + + if (context->UseMIC) + { + const BYTE data[WINPR_MD5_DIGEST_LENGTH] = { 0 }; + + context->MessageIntegrityCheckOffset = Stream_GetPosition(s); + if (!ntlm_write_message_integrity_check(s, Stream_GetPosition(s), data, sizeof(data), + "NTLM_AUTHENTICATE_MESSAGE")) + return SEC_E_INTERNAL_ERROR; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) + { + if (!ntlm_write_message_fields_buffer(s, &(message->DomainName))) /* DomainName */ + return SEC_E_INTERNAL_ERROR; + } + + if (!ntlm_write_message_fields_buffer(s, &(message->UserName))) /* UserName */ + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) + { + if (!ntlm_write_message_fields_buffer(s, &(message->Workstation))) /* Workstation */ + return SEC_E_INTERNAL_ERROR; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_LM_KEY) + { + if (!ntlm_write_message_fields_buffer( + s, &(message->LmChallengeResponse))) /* LmChallengeResponse */ + return SEC_E_INTERNAL_ERROR; + } + if (!ntlm_write_message_fields_buffer( + s, &(message->NtChallengeResponse))) /* NtChallengeResponse */ + return SEC_E_INTERNAL_ERROR; + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) + { + if (!ntlm_write_message_fields_buffer( + s, &(message->EncryptedRandomSessionKey))) /* EncryptedRandomSessionKey */ + return SEC_E_INTERNAL_ERROR; + } + + length = Stream_GetPosition(s); + WINPR_ASSERT(length <= UINT32_MAX); + + if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, (ULONG)length)) + return SEC_E_INTERNAL_ERROR; + + CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); + buffer->cbBuffer = (ULONG)length; + + if (context->UseMIC) + { + /* Message Integrity Check */ + ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck)); + if (!ntlm_write_message_integrity_check( + s, context->MessageIntegrityCheckOffset, message->MessageIntegrityCheck, + sizeof(message->MessageIntegrityCheck), "NTLM_AUTHENTICATE_MESSAGE")) + return SEC_E_INTERNAL_ERROR; + } + +#if defined(WITH_DEBUG_NTLM) + ntlm_print_authenticate_message(&context->AuthenticateMessage, message, + context->UseMIC ? MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK : 0, + &context->AuthenticateTargetInfo); +#endif + ntlm_change_state(context, NTLM_STATE_FINAL); + return SEC_E_OK; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.h new file mode 100644 index 0000000000000000000000000000000000000000..58ff35dd5a6a8f52bc701a8388eab1c5a15bbd37 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/NTLM/ntlm_message.h @@ -0,0 +1,36 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Security Package (Message) + * + * Copyright 2011-2014 Marc-Andre Moreau + * + * 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_NTLM_MESSAGE_H +#define WINPR_SSPI_NTLM_MESSAGE_H + +#include "ntlm.h" + +SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer); +SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, const PSecBuffer buffer); +SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer); +SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, const PSecBuffer buffer); +SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer); +SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, const PSecBuffer buffer); + +SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context); + +const char* ntlm_get_negotiate_string(UINT32 flag); + +#endif /* WINPR_SSPI_NTLM_MESSAGE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.c new file mode 100644 index 0000000000000000000000000000000000000000..b88050770eaf928dd016eb51e4f808b507a027b0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.c @@ -0,0 +1,1686 @@ +/** + * WinPR: Windows Portable Runtime + * Negotiate Security Package + * + * Copyright 2011-2014 Marc-Andre Moreau + * Copyright 2017 Dorian Ducournau + * + * 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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "negotiate.h" + +#include "../NTLM/ntlm.h" +#include "../NTLM/ntlm_export.h" +#include "../Kerberos/kerberos.h" +#include "../sspi.h" +#include "../../log.h" +#define TAG WINPR_TAG("negotiate") + +static const char NEGO_REG_KEY[] = + "Software\\" WINPR_VENDOR_STRING "\\" WINPR_PRODUCT_STRING "\\SSPI\\Negotiate"; + +typedef struct +{ + const TCHAR* name; + const SecurityFunctionTableA* table; + const SecurityFunctionTableW* table_w; +} SecPkg; + +struct Mech_st +{ + const WinPrAsn1_OID* oid; + const SecPkg* pkg; + const UINT flags; + const BOOL preferred; +}; + +typedef struct +{ + const Mech* mech; + CredHandle cred; + BOOL valid; +} MechCred; + +const SecPkgInfoA NEGOTIATE_SecPkgInfoA = { + 0x00083BB3, /* fCapabilities */ + 1, /* wVersion */ + 0x0009, /* wRPCID */ + 0x00002FE0, /* cbMaxToken */ + "Negotiate", /* Name */ + "Microsoft Package Negotiator" /* Comment */ +}; + +static WCHAR NEGOTIATE_SecPkgInfoW_NameBuffer[32] = { 0 }; +static WCHAR NEGOTIATE_SecPkgInfoW_CommentBuffer[32] = { 0 }; + +const SecPkgInfoW NEGOTIATE_SecPkgInfoW = { + 0x00083BB3, /* fCapabilities */ + 1, /* wVersion */ + 0x0009, /* wRPCID */ + 0x00002FE0, /* cbMaxToken */ + NEGOTIATE_SecPkgInfoW_NameBuffer, /* Name */ + NEGOTIATE_SecPkgInfoW_CommentBuffer /* Comment */ +}; + +static const WinPrAsn1_OID spnego_OID = { 6, (BYTE*)"\x2b\x06\x01\x05\x05\x02" }; +static const WinPrAsn1_OID kerberos_u2u_OID = { 10, + (BYTE*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x03" }; +static const WinPrAsn1_OID kerberos_OID = { 9, (BYTE*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; +static const WinPrAsn1_OID kerberos_wrong_OID = { 9, + (BYTE*)"\x2a\x86\x48\x82\xf7\x12\x01\x02\x02" }; +static const WinPrAsn1_OID ntlm_OID = { 10, (BYTE*)"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a" }; + +static const WinPrAsn1_OID negoex_OID = { 10, (BYTE*)"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x1e" }; + +#ifdef WITH_KRB5 +static const SecPkg SecPkgTable[] = { + { KERBEROS_SSP_NAME, &KERBEROS_SecurityFunctionTableA, &KERBEROS_SecurityFunctionTableW }, + { KERBEROS_SSP_NAME, &KERBEROS_SecurityFunctionTableA, &KERBEROS_SecurityFunctionTableW }, + { NTLM_SSP_NAME, &NTLM_SecurityFunctionTableA, &NTLM_SecurityFunctionTableW } +}; + +static const Mech MechTable[] = { + { &kerberos_u2u_OID, &SecPkgTable[0], ISC_REQ_INTEGRITY | ISC_REQ_USE_SESSION_KEY, TRUE }, + { &kerberos_OID, &SecPkgTable[1], ISC_REQ_INTEGRITY, TRUE }, + { &ntlm_OID, &SecPkgTable[2], 0, FALSE }, +}; +#else +static const SecPkg SecPkgTable[] = { { NTLM_SSP_NAME, &NTLM_SecurityFunctionTableA, + &NTLM_SecurityFunctionTableW } }; + +static const Mech MechTable[] = { + { &ntlm_OID, &SecPkgTable[0], 0, FALSE }, +}; +#endif + +static const size_t MECH_COUNT = sizeof(MechTable) / sizeof(Mech); + +enum NegState +{ + NOSTATE = -1, + ACCEPT_COMPLETED, + ACCEPT_INCOMPLETE, + REJECT, + REQUEST_MIC +}; + +typedef struct +{ + enum NegState negState; + BOOL init; + WinPrAsn1_OID supportedMech; + SecBuffer mechTypes; + SecBuffer mechToken; + SecBuffer mic; +} NegToken; + +static const NegToken empty_neg_token = { NOSTATE, FALSE, { 0, NULL }, + { 0, 0, NULL }, { 0, 0, NULL }, { 0, 0, NULL } }; + +static NEGOTIATE_CONTEXT* negotiate_ContextNew(NEGOTIATE_CONTEXT* init_context) +{ + NEGOTIATE_CONTEXT* context = NULL; + + WINPR_ASSERT(init_context); + + context = calloc(1, sizeof(NEGOTIATE_CONTEXT)); + if (!context) + return NULL; + + if (init_context->spnego) + { + init_context->mechTypes.pvBuffer = malloc(init_context->mechTypes.cbBuffer); + if (!init_context->mechTypes.pvBuffer) + { + free(context); + return NULL; + } + } + + *context = *init_context; + + return context; +} + +static void negotiate_ContextFree(NEGOTIATE_CONTEXT* context) +{ + WINPR_ASSERT(context); + + if (context->mechTypes.pvBuffer) + free(context->mechTypes.pvBuffer); + free(context); +} + +static const char* negotiate_mech_name(const WinPrAsn1_OID* oid) +{ + if (sspi_gss_oid_compare(oid, &spnego_OID)) + return "SPNEGO (1.3.6.1.5.5.2)"; + else if (sspi_gss_oid_compare(oid, &kerberos_u2u_OID)) + return "Kerberos user to user (1.2.840.113554.1.2.2.3)"; + else if (sspi_gss_oid_compare(oid, &kerberos_OID)) + return "Kerberos (1.2.840.113554.1.2.2)"; + else if (sspi_gss_oid_compare(oid, &kerberos_wrong_OID)) + return "Kerberos [wrong OID] (1.2.840.48018.1.2.2)"; + else if (sspi_gss_oid_compare(oid, &ntlm_OID)) + return "NTLM (1.3.6.1.4.1.311.2.2.10)"; + else if (sspi_gss_oid_compare(oid, &negoex_OID)) + return "NegoEx (1.3.6.1.4.1.311.2.2.30)"; + else + return "Unknown mechanism"; +} + +static const Mech* negotiate_GetMechByOID(const WinPrAsn1_OID* oid) +{ + WINPR_ASSERT(oid); + + WinPrAsn1_OID testOid = *oid; + + if (sspi_gss_oid_compare(&testOid, &kerberos_wrong_OID)) + { + testOid.len = kerberos_OID.len; + testOid.data = kerberos_OID.data; + } + + for (size_t i = 0; i < MECH_COUNT; i++) + { + if (sspi_gss_oid_compare(&testOid, MechTable[i].oid)) + return &MechTable[i]; + } + return NULL; +} + +static PSecHandle negotiate_FindCredential(MechCred* creds, const Mech* mech) +{ + WINPR_ASSERT(creds); + + if (!mech) + return NULL; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + + if (cred->mech == mech) + { + if (cred->valid) + return &cred->cred; + return NULL; + } + } + + return NULL; +} + +static BOOL negotiate_get_dword(HKEY hKey, const char* subkey, DWORD* pdwValue) +{ + DWORD dwValue = 0; + DWORD dwType = 0; + DWORD dwSize = sizeof(dwValue); + LONG rc = RegQueryValueExA(hKey, subkey, NULL, &dwType, (BYTE*)&dwValue, &dwSize); + + if (rc != ERROR_SUCCESS) + return FALSE; + if (dwType != REG_DWORD) + return FALSE; + + *pdwValue = dwValue; + return TRUE; +} + +static BOOL negotiate_get_config_from_auth_package_list(void* pAuthData, BOOL* kerberos, BOOL* ntlm) +{ + char* tok_ctx = NULL; + char* tok_ptr = NULL; + char* PackageList = NULL; + + if (!sspi_CopyAuthPackageListA((const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData, &PackageList)) + return FALSE; + + tok_ptr = strtok_s(PackageList, ",", &tok_ctx); + + while (tok_ptr) + { + char* PackageName = tok_ptr; + BOOL PackageInclude = TRUE; + + if (PackageName[0] == '!') + { + PackageName = &PackageName[1]; + PackageInclude = FALSE; + } + + if (!_stricmp(PackageName, "ntlm")) + { + *ntlm = PackageInclude; + } + else if (!_stricmp(PackageName, "kerberos")) + { + *kerberos = PackageInclude; + } + else + { + WLog_WARN(TAG, "Unknown authentication package name: %s", PackageName); + } + + tok_ptr = strtok_s(NULL, ",", &tok_ctx); + } + + free(PackageList); + return TRUE; +} + +static BOOL negotiate_get_config(void* pAuthData, BOOL* kerberos, BOOL* ntlm) +{ + HKEY hKey = NULL; + LONG rc = 0; + + WINPR_ASSERT(kerberos); + WINPR_ASSERT(ntlm); + +#if !defined(WITH_KRB5_NO_NTLM_FALLBACK) + *ntlm = TRUE; +#else + *ntlm = FALSE; +#endif + *kerberos = TRUE; + + if (negotiate_get_config_from_auth_package_list(pAuthData, kerberos, ntlm)) + { + return TRUE; // use explicit authentication package list + } + + rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, NEGO_REG_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + if (rc == ERROR_SUCCESS) + { + DWORD dwValue = 0; + + if (negotiate_get_dword(hKey, "kerberos", &dwValue)) + *kerberos = (dwValue != 0) ? TRUE : FALSE; + +#if !defined(WITH_KRB5_NO_NTLM_FALLBACK) + if (negotiate_get_dword(hKey, "ntlm", &dwValue)) + *ntlm = (dwValue != 0) ? TRUE : FALSE; +#endif + + RegCloseKey(hKey); + } + + return TRUE; +} + +static BOOL negotiate_write_neg_token(PSecBuffer output_buffer, NegToken* token) +{ + WINPR_ASSERT(output_buffer); + WINPR_ASSERT(token); + + BOOL ret = FALSE; + WinPrAsn1Encoder* enc = NULL; + WinPrAsn1_MemoryChunk mechTypes = { token->mechTypes.cbBuffer, token->mechTypes.pvBuffer }; + WinPrAsn1_OctetString mechToken = { token->mechToken.cbBuffer, token->mechToken.pvBuffer }; + WinPrAsn1_OctetString mechListMic = { token->mic.cbBuffer, token->mic.pvBuffer }; + wStream s; + size_t len = 0; + + enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER); + if (!enc) + return FALSE; + + /* For NegTokenInit wrap in an initialContextToken */ + if (token->init) + { + /* InitialContextToken [APPLICATION 0] IMPLICIT SEQUENCE */ + if (!WinPrAsn1EncAppContainer(enc, 0)) + goto cleanup; + + /* thisMech MechType OID */ + if (!WinPrAsn1EncOID(enc, &spnego_OID)) + goto cleanup; + } + + /* innerContextToken [0] NegTokenInit or [1] NegTokenResp */ + if (!WinPrAsn1EncContextualSeqContainer(enc, token->init ? 0 : 1)) + goto cleanup; + + WLog_DBG(TAG, token->init ? "Writing negTokenInit..." : "Writing negTokenResp..."); + + /* mechTypes [0] MechTypeList (mechTypes already contains the SEQUENCE tag) */ + if (token->init) + { + if (!WinPrAsn1EncContextualRawContent(enc, 0, &mechTypes)) + goto cleanup; + WLog_DBG(TAG, "\tmechTypes [0] (%li bytes)", token->mechTypes.cbBuffer); + } + /* negState [0] ENUMERATED */ + else if (token->negState != NOSTATE) + { + if (!WinPrAsn1EncContextualEnumerated(enc, 0, token->negState)) + goto cleanup; + WLog_DBG(TAG, "\tnegState [0] (%d)", token->negState); + } + + /* supportedMech [1] OID */ + if (token->supportedMech.len) + { + if (!WinPrAsn1EncContextualOID(enc, 1, &token->supportedMech)) + goto cleanup; + WLog_DBG(TAG, "\tsupportedMech [1] (%s)", negotiate_mech_name(&token->supportedMech)); + } + + /* mechToken [2] OCTET STRING */ + if (token->mechToken.cbBuffer) + { + if (WinPrAsn1EncContextualOctetString(enc, 2, &mechToken) == 0) + goto cleanup; + WLog_DBG(TAG, "\tmechToken [2] (%li bytes)", token->mechToken.cbBuffer); + } + + /* mechListMIC [3] OCTET STRING */ + if (token->mic.cbBuffer) + { + if (WinPrAsn1EncContextualOctetString(enc, 3, &mechListMic) == 0) + goto cleanup; + WLog_DBG(TAG, "\tmechListMIC [3] (%li bytes)", token->mic.cbBuffer); + } + + /* NegTokenInit or NegTokenResp */ + if (!WinPrAsn1EncEndContainer(enc)) + goto cleanup; + + if (token->init) + { + /* initialContextToken */ + if (!WinPrAsn1EncEndContainer(enc)) + goto cleanup; + } + + if (!WinPrAsn1EncStreamSize(enc, &len) || len > output_buffer->cbBuffer) + goto cleanup; + + if (len > UINT32_MAX) + goto cleanup; + + Stream_StaticInit(&s, output_buffer->pvBuffer, len); + + if (WinPrAsn1EncToStream(enc, &s)) + { + output_buffer->cbBuffer = (UINT32)len; + ret = TRUE; + } + +cleanup: + WinPrAsn1Encoder_Free(&enc); + return ret; +} + +static BOOL negotiate_read_neg_token(PSecBuffer input, NegToken* token) +{ + WinPrAsn1Decoder dec; + WinPrAsn1Decoder dec2; + WinPrAsn1_OID oid; + WinPrAsn1_tagId contextual = 0; + WinPrAsn1_tag tag = 0; + size_t len = 0; + WinPrAsn1_OctetString octet_string; + BOOL err = 0; + + WINPR_ASSERT(input); + WINPR_ASSERT(token); + + WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, input->pvBuffer, input->cbBuffer); + + if (!WinPrAsn1DecPeekTag(&dec, &tag)) + return FALSE; + + if (tag == 0x60) + { + /* initialContextToken [APPLICATION 0] */ + if (!WinPrAsn1DecReadApp(&dec, &tag, &dec2) || tag != 0) + return FALSE; + dec = dec2; + + /* thisMech OID */ + if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE)) + return FALSE; + + if (!sspi_gss_oid_compare(&spnego_OID, &oid)) + return FALSE; + + /* [0] NegTokenInit */ + if (!WinPrAsn1DecReadContextualSequence(&dec, 0, &err, &dec2)) + return FALSE; + + token->init = TRUE; + } + /* [1] NegTokenResp */ + else if (!WinPrAsn1DecReadContextualSequence(&dec, 1, &err, &dec2)) + return FALSE; + dec = dec2; + + WLog_DBG(TAG, token->init ? "Reading negTokenInit..." : "Reading negTokenResp..."); + + /* Read NegTokenResp sequence members */ + do + { + if (!WinPrAsn1DecReadContextualTag(&dec, &contextual, &dec2)) + return FALSE; + + switch (contextual) + { + case 0: + if (token->init) + { + /* mechTypes [0] MechTypeList */ + wStream s = WinPrAsn1DecGetStream(&dec2); + token->mechTypes.BufferType = SECBUFFER_TOKEN; + const size_t mlen = Stream_Length(&s); + if (mlen > UINT32_MAX) + return FALSE; + token->mechTypes.cbBuffer = (UINT32)mlen; + token->mechTypes.pvBuffer = Stream_Buffer(&s); + WLog_DBG(TAG, "\tmechTypes [0] (%li bytes)", token->mechTypes.cbBuffer); + } + else + { + /* negState [0] ENUMERATED */ + WinPrAsn1_ENUMERATED rd = 0; + if (!WinPrAsn1DecReadEnumerated(&dec2, &rd)) + return FALSE; + token->negState = rd; + WLog_DBG(TAG, "\tnegState [0] (%d)", token->negState); + } + break; + case 1: + if (token->init) + { + /* reqFlags [1] ContextFlags BIT STRING (ignored) */ + if (!WinPrAsn1DecPeekTagAndLen(&dec2, &tag, &len) || (tag != ER_TAG_BIT_STRING)) + return FALSE; + WLog_DBG(TAG, "\treqFlags [1] (%li bytes)", len); + } + else + { + /* supportedMech [1] MechType */ + if (!WinPrAsn1DecReadOID(&dec2, &token->supportedMech, FALSE)) + return FALSE; + WLog_DBG(TAG, "\tsupportedMech [1] (%s)", + negotiate_mech_name(&token->supportedMech)); + } + break; + case 2: + /* mechToken [2] OCTET STRING */ + if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE)) + return FALSE; + if (octet_string.len > UINT32_MAX) + return FALSE; + token->mechToken.cbBuffer = (UINT32)octet_string.len; + token->mechToken.pvBuffer = octet_string.data; + token->mechToken.BufferType = SECBUFFER_TOKEN; + WLog_DBG(TAG, "\tmechToken [2] (%li bytes)", octet_string.len); + break; + case 3: + /* mechListMic [3] OCTET STRING */ + if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE)) + return FALSE; + if (octet_string.len > UINT32_MAX) + return FALSE; + token->mic.cbBuffer = (UINT32)octet_string.len; + token->mic.pvBuffer = octet_string.data; + token->mic.BufferType = SECBUFFER_TOKEN; + WLog_DBG(TAG, "\tmechListMIC [3] (%li bytes)", octet_string.len); + break; + default: + WLog_ERR(TAG, "unknown contextual item %d", contextual); + return FALSE; + } + } while (WinPrAsn1DecPeekTag(&dec, &tag)); + + return TRUE; +} + +static SECURITY_STATUS negotiate_mic_exchange(NEGOTIATE_CONTEXT* context, NegToken* input_token, + NegToken* output_token, PSecBuffer output_buffer) +{ + SecBuffer mic_buffers[2] = { 0 }; + SecBufferDesc mic_buffer_desc = { SECBUFFER_VERSION, 2, mic_buffers }; + SECURITY_STATUS status = 0; + + WINPR_ASSERT(context); + WINPR_ASSERT(input_token); + WINPR_ASSERT(output_token); + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + + const SecurityFunctionTableA* table = context->mech->pkg->table; + WINPR_ASSERT(table); + + mic_buffers[0] = context->mechTypes; + + /* Verify MIC if we received one */ + if (input_token->mic.cbBuffer > 0) + { + mic_buffers[1] = input_token->mic; + + status = table->VerifySignature(&context->sub_context, &mic_buffer_desc, 0, 0); + if (status != SEC_E_OK) + return status; + + output_token->negState = ACCEPT_COMPLETED; + } + + /* If peer expects a MIC then generate it */ + if (input_token->negState != ACCEPT_COMPLETED) + { + /* Store the mic token after the mech token in the output buffer */ + output_token->mic.BufferType = SECBUFFER_TOKEN; + if (output_buffer) + { + output_token->mic.cbBuffer = output_buffer->cbBuffer - output_token->mechToken.cbBuffer; + output_token->mic.pvBuffer = + (BYTE*)output_buffer->pvBuffer + output_token->mechToken.cbBuffer; + } + mic_buffers[1] = output_token->mic; + + status = table->MakeSignature(&context->sub_context, 0, &mic_buffer_desc, 0); + if (status != SEC_E_OK) + return status; + + output_token->mic = mic_buffers[1]; + } + + /* When using NTLM cipher states need to be reset after mic exchange */ + const TCHAR* name = sspi_SecureHandleGetUpperPointer(&context->sub_context); + if (!name) + return SEC_E_INTERNAL_ERROR; + + if (_tcsncmp(name, NTLM_SSP_NAME, ARRAYSIZE(NTLM_SSP_NAME)) == 0) + { + if (!ntlm_reset_cipher_state(&context->sub_context)) + return SEC_E_INTERNAL_ERROR; + } + + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + NEGOTIATE_CONTEXT* context = NULL; + NEGOTIATE_CONTEXT init_context = { 0 }; + MechCred* creds = NULL; + PCtxtHandle sub_context = NULL; + PCredHandle sub_cred = NULL; + NegToken input_token = empty_neg_token; + NegToken output_token = empty_neg_token; + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + PSecBuffer bindings_buffer = NULL; + SecBuffer mech_input_buffers[2] = { 0 }; + SecBufferDesc mech_input = { SECBUFFER_VERSION, 2, mech_input_buffers }; + SecBufferDesc mech_output = { SECBUFFER_VERSION, 1, &output_token.mechToken }; + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + SECURITY_STATUS sub_status = SEC_E_INTERNAL_ERROR; + WinPrAsn1Encoder* enc = NULL; + wStream s; + const Mech* mech = NULL; + + if (!phCredential || !SecIsValidHandle(phCredential)) + return SEC_E_NO_CREDENTIALS; + + creds = sspi_SecureHandleGetLowerPointer(phCredential); + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = sspi_SecureHandleGetLowerPointer(phContext); + + if (pInput) + { + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + bindings_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS); + } + if (pOutput) + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!context) + { + enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER); + if (!enc) + return SEC_E_INSUFFICIENT_MEMORY; + + if (!WinPrAsn1EncSeqContainer(enc)) + goto cleanup; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + const SecPkg* pkg = MechTable[i].pkg; + WINPR_ASSERT(pkg); + WINPR_ASSERT(pkg->table_w); + + if (!cred->valid) + continue; + + /* Send an optimistic token for the first valid mechanism */ + if (!init_context.mech) + { + /* Use the output buffer to store the optimistic token */ + if (!output_buffer) + goto cleanup; + + CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer)); + + if (bindings_buffer) + mech_input_buffers[0] = *bindings_buffer; + + WINPR_ASSERT(pkg->table_w->InitializeSecurityContextW); + sub_status = pkg->table_w->InitializeSecurityContextW( + &cred->cred, NULL, pszTargetName, fContextReq | cred->mech->flags, Reserved1, + TargetDataRep, &mech_input, Reserved2, &init_context.sub_context, &mech_output, + pfContextAttr, ptsExpiry); + + /* If the mechanism failed we can't use it; skip */ + if (IsSecurityStatusError(sub_status)) + { + if (SecIsValidHandle(&init_context.sub_context)) + { + WINPR_ASSERT(pkg->table_w->DeleteSecurityContext); + pkg->table_w->DeleteSecurityContext(&init_context.sub_context); + } + cred->valid = FALSE; + continue; + } + + init_context.mech = cred->mech; + } + + if (!WinPrAsn1EncOID(enc, cred->mech->oid)) + goto cleanup; + WLog_DBG(TAG, "Available mechanism: %s", negotiate_mech_name(cred->mech->oid)); + } + + /* No usable mechanisms were found */ + if (!init_context.mech) + goto cleanup; + + /* If the only available mech is NTLM use it directly otherwise use spnego */ + if (init_context.mech->oid == &ntlm_OID) + { + init_context.spnego = FALSE; + output_buffer->cbBuffer = output_token.mechToken.cbBuffer; + WLog_DBG(TAG, "Using direct NTLM"); + } + else + { + init_context.spnego = TRUE; + init_context.mechTypes.BufferType = SECBUFFER_DATA; + const size_t cb = WinPrAsn1EncEndContainer(enc); + WINPR_ASSERT(cb <= UINT32_MAX); + init_context.mechTypes.cbBuffer = (UINT32)cb; + } + + /* Allocate memory for the new context */ + context = negotiate_ContextNew(&init_context); + if (!context) + { + init_context.mech->pkg->table->DeleteSecurityContext(&init_context.sub_context); + WinPrAsn1Encoder_Free(&enc); + return SEC_E_INSUFFICIENT_MEMORY; + } + + sspi_SecureHandleSetUpperPointer(phNewContext, NEGO_SSP_NAME); + sspi_SecureHandleSetLowerPointer(phNewContext, context); + + if (!context->spnego) + { + status = sub_status; + goto cleanup; + } + + /* Write mechTypesList */ + Stream_StaticInit(&s, context->mechTypes.pvBuffer, context->mechTypes.cbBuffer); + if (!WinPrAsn1EncToStream(enc, &s)) + goto cleanup; + + output_token.mechTypes.cbBuffer = context->mechTypes.cbBuffer; + output_token.mechTypes.pvBuffer = context->mechTypes.pvBuffer; + output_token.init = TRUE; + + if (sub_status == SEC_E_OK) + context->state = NEGOTIATE_STATE_FINAL_OPTIMISTIC; + } + else + { + if (!input_buffer) + return SEC_E_INVALID_TOKEN; + + sub_context = &context->sub_context; + sub_cred = negotiate_FindCredential(creds, context->mech); + + if (!context->spnego) + { + return context->mech->pkg->table_w->InitializeSecurityContextW( + sub_cred, sub_context, pszTargetName, fContextReq | context->mech->flags, Reserved1, + TargetDataRep, pInput, Reserved2, sub_context, pOutput, pfContextAttr, ptsExpiry); + } + + if (!negotiate_read_neg_token(input_buffer, &input_token)) + return SEC_E_INVALID_TOKEN; + + /* On first response check if the server doesn't like out preferred mech */ + if (context->state < NEGOTIATE_STATE_NEGORESP && input_token.supportedMech.len && + !sspi_gss_oid_compare(&input_token.supportedMech, context->mech->oid)) + { + mech = negotiate_GetMechByOID(&input_token.supportedMech); + if (!mech) + return SEC_E_INVALID_TOKEN; + + /* Make sure the specified mech is supported and get the appropriate credential */ + sub_cred = negotiate_FindCredential(creds, mech); + if (!sub_cred) + return SEC_E_INVALID_TOKEN; + + /* Clean up the optimistic mech */ + context->mech->pkg->table_w->DeleteSecurityContext(&context->sub_context); + sub_context = NULL; + + context->mech = mech; + context->mic = TRUE; + } + + /* Check neg_state (required on first response) */ + if (context->state < NEGOTIATE_STATE_NEGORESP) + { + switch (input_token.negState) + { + case NOSTATE: + return SEC_E_INVALID_TOKEN; + case REJECT: + return SEC_E_LOGON_DENIED; + case REQUEST_MIC: + context->mic = TRUE; + /* fallthrough */ + WINPR_FALLTHROUGH + case ACCEPT_INCOMPLETE: + context->state = NEGOTIATE_STATE_NEGORESP; + break; + case ACCEPT_COMPLETED: + if (context->state == NEGOTIATE_STATE_INITIAL) + context->state = NEGOTIATE_STATE_NEGORESP; + else + context->state = NEGOTIATE_STATE_FINAL; + break; + default: + break; + } + + WLog_DBG(TAG, "Negotiated mechanism: %s", negotiate_mech_name(context->mech->oid)); + } + + if (context->state == NEGOTIATE_STATE_NEGORESP) + { + /* Store the mech token in the output buffer */ + if (!output_buffer) + goto cleanup; + CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer)); + + mech_input_buffers[0] = input_token.mechToken; + if (bindings_buffer) + mech_input_buffers[1] = *bindings_buffer; + + status = context->mech->pkg->table_w->InitializeSecurityContextW( + sub_cred, sub_context, pszTargetName, fContextReq | context->mech->flags, Reserved1, + TargetDataRep, input_token.mechToken.cbBuffer ? &mech_input : NULL, Reserved2, + &context->sub_context, &mech_output, pfContextAttr, ptsExpiry); + + if (IsSecurityStatusError(status)) + return status; + } + + if (status == SEC_E_OK) + { + if (output_token.mechToken.cbBuffer > 0) + context->state = NEGOTIATE_STATE_MIC; + else + context->state = NEGOTIATE_STATE_FINAL; + } + + /* Check if the acceptor sent its final token without a mic */ + if (context->state == NEGOTIATE_STATE_FINAL && input_token.mic.cbBuffer == 0) + { + if (context->mic || input_token.negState != ACCEPT_COMPLETED) + return SEC_E_INVALID_TOKEN; + + if (output_buffer) + output_buffer->cbBuffer = 0; + return SEC_E_OK; + } + + if ((context->state == NEGOTIATE_STATE_MIC && context->mic) || + context->state == NEGOTIATE_STATE_FINAL) + { + status = negotiate_mic_exchange(context, &input_token, &output_token, output_buffer); + if (status != SEC_E_OK) + return status; + } + } + + if (input_token.negState == ACCEPT_COMPLETED) + { + if (output_buffer) + output_buffer->cbBuffer = 0; + return SEC_E_OK; + } + + if (output_token.negState == ACCEPT_COMPLETED) + status = SEC_E_OK; + else + status = SEC_I_CONTINUE_NEEDED; + + if (!negotiate_write_neg_token(output_buffer, &output_token)) + status = SEC_E_INTERNAL_ERROR; + +cleanup: + WinPrAsn1Encoder_Free(&enc); + return status; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SEC_WCHAR* pszTargetNameW = NULL; + + if (pszTargetName) + { + pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, NULL); + if (!pszTargetNameW) + return SEC_E_INTERNAL_ERROR; + } + + status = negotiate_InitializeSecurityContextW( + phCredential, phContext, pszTargetNameW, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + free(pszTargetNameW); + return status; +} + +static const Mech* guessMech(PSecBuffer input_buffer, BOOL* spNego, WinPrAsn1_OID* oid) +{ + WinPrAsn1Decoder decoder; + WinPrAsn1Decoder appDecoder; + WinPrAsn1_tagId tag = 0; + const char ssp[] = "NTLMSSP"; + + *spNego = FALSE; + + /* Check for NTLM token */ + if (input_buffer->cbBuffer >= 8 && strncmp(input_buffer->pvBuffer, ssp, sizeof(ssp)) == 0) + { + *oid = ntlm_OID; + return negotiate_GetMechByOID(&ntlm_OID); + } + + /* Read initialContextToken or raw Kerberos token */ + WinPrAsn1Decoder_InitMem(&decoder, WINPR_ASN1_DER, input_buffer->pvBuffer, + input_buffer->cbBuffer); + + if (!WinPrAsn1DecReadApp(&decoder, &tag, &appDecoder) || tag != 0) + return NULL; + + if (!WinPrAsn1DecReadOID(&appDecoder, oid, FALSE)) + return NULL; + + if (sspi_gss_oid_compare(oid, &spnego_OID)) + { + *spNego = TRUE; + return NULL; + } + + return negotiate_GetMechByOID(oid); +} + +static SECURITY_STATUS SEC_ENTRY negotiate_AcceptSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq, + ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsTimeStamp) +{ + NEGOTIATE_CONTEXT* context = NULL; + NEGOTIATE_CONTEXT init_context = { 0 }; + MechCred* creds = NULL; + PCredHandle sub_cred = NULL; + NegToken input_token = empty_neg_token; + NegToken output_token = empty_neg_token; + PSecBuffer input_buffer = NULL; + PSecBuffer output_buffer = NULL; + SecBufferDesc mech_input = { SECBUFFER_VERSION, 1, &input_token.mechToken }; + SecBufferDesc mech_output = { SECBUFFER_VERSION, 1, &output_token.mechToken }; + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + WinPrAsn1Decoder dec; + WinPrAsn1Decoder dec2; + WinPrAsn1_tagId tag = 0; + WinPrAsn1_OID oid = { 0 }; + const Mech* first_mech = NULL; + + if (!phCredential || !SecIsValidHandle(phCredential)) + return SEC_E_NO_CREDENTIALS; + + creds = sspi_SecureHandleGetLowerPointer(phCredential); + + if (!pInput) + return SEC_E_INVALID_TOKEN; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = sspi_SecureHandleGetLowerPointer(phContext); + + input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + if (pOutput) + output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!context) + { + init_context.mech = guessMech(input_buffer, &init_context.spnego, &oid); + if (!init_context.mech && !init_context.spnego) + return SEC_E_INVALID_TOKEN; + + WLog_DBG(TAG, "Mechanism: %s", negotiate_mech_name(&oid)); + + if (init_context.spnego) + { + /* Process spnego token */ + if (!negotiate_read_neg_token(input_buffer, &input_token)) + return SEC_E_INVALID_TOKEN; + + /* First token must be negoTokenInit and must contain a mechList */ + if (!input_token.init || input_token.mechTypes.cbBuffer == 0) + return SEC_E_INVALID_TOKEN; + + init_context.mechTypes.BufferType = SECBUFFER_DATA; + init_context.mechTypes.cbBuffer = input_token.mechTypes.cbBuffer; + + /* Prepare to read mechList */ + WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, input_token.mechTypes.pvBuffer, + input_token.mechTypes.cbBuffer); + + if (!WinPrAsn1DecReadSequence(&dec, &dec2)) + return SEC_E_INVALID_TOKEN; + dec = dec2; + + /* If an optimistic token was provided pass it into the first mech */ + if (input_token.mechToken.cbBuffer) + { + if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE)) + return SEC_E_INVALID_TOKEN; + + init_context.mech = negotiate_GetMechByOID(&oid); + + if (init_context.mech) + { + if (output_buffer) + output_token.mechToken = *output_buffer; + WLog_DBG(TAG, "Requested mechanism: %s", + negotiate_mech_name(init_context.mech->oid)); + } + } + } + + if (init_context.mech) + { + sub_cred = negotiate_FindCredential(creds, init_context.mech); + + status = init_context.mech->pkg->table->AcceptSecurityContext( + sub_cred, NULL, init_context.spnego ? &mech_input : pInput, fContextReq, + TargetDataRep, &init_context.sub_context, + init_context.spnego ? &mech_output : pOutput, pfContextAttr, ptsTimeStamp); + } + + if (IsSecurityStatusError(status)) + { + if (!init_context.spnego) + return status; + + init_context.mic = TRUE; + first_mech = init_context.mech; + init_context.mech = NULL; + output_token.mechToken.cbBuffer = 0; + } + + while (!init_context.mech && WinPrAsn1DecPeekTag(&dec, &tag)) + { + /* Read each mechanism */ + if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE)) + return SEC_E_INVALID_TOKEN; + + init_context.mech = negotiate_GetMechByOID(&oid); + WLog_DBG(TAG, "Requested mechanism: %s", negotiate_mech_name(&oid)); + + /* Microsoft may send two versions of the kerberos OID */ + if (init_context.mech == first_mech) + init_context.mech = NULL; + + if (init_context.mech && !negotiate_FindCredential(creds, init_context.mech)) + init_context.mech = NULL; + } + + if (!init_context.mech) + return SEC_E_INTERNAL_ERROR; + + context = negotiate_ContextNew(&init_context); + if (!context) + { + if (!IsSecurityStatusError(status)) + init_context.mech->pkg->table->DeleteSecurityContext(&init_context.sub_context); + return SEC_E_INSUFFICIENT_MEMORY; + } + + sspi_SecureHandleSetUpperPointer(phNewContext, NEGO_SSP_NAME); + sspi_SecureHandleSetLowerPointer(phNewContext, context); + + if (!init_context.spnego) + return status; + + CopyMemory(init_context.mechTypes.pvBuffer, input_token.mechTypes.pvBuffer, + input_token.mechTypes.cbBuffer); + + if (!context->mech->preferred) + { + output_token.negState = REQUEST_MIC; + context->mic = TRUE; + } + else + { + output_token.negState = ACCEPT_INCOMPLETE; + } + + if (status == SEC_E_OK) + context->state = NEGOTIATE_STATE_FINAL; + else + context->state = NEGOTIATE_STATE_NEGORESP; + + output_token.supportedMech = oid; + WLog_DBG(TAG, "Accepted mechanism: %s", negotiate_mech_name(&output_token.supportedMech)); + } + else + { + sub_cred = negotiate_FindCredential(creds, context->mech); + if (!sub_cred) + return SEC_E_NO_CREDENTIALS; + + if (!context->spnego) + { + return context->mech->pkg->table->AcceptSecurityContext( + sub_cred, &context->sub_context, pInput, fContextReq, TargetDataRep, + &context->sub_context, pOutput, pfContextAttr, ptsTimeStamp); + } + + if (!negotiate_read_neg_token(input_buffer, &input_token)) + return SEC_E_INVALID_TOKEN; + + /* Process the mechanism token */ + if (input_token.mechToken.cbBuffer > 0) + { + if (context->state != NEGOTIATE_STATE_NEGORESP) + return SEC_E_INVALID_TOKEN; + + /* Use the output buffer to store the optimistic token */ + if (output_buffer) + CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer)); + + status = context->mech->pkg->table->AcceptSecurityContext( + sub_cred, &context->sub_context, &mech_input, fContextReq | context->mech->flags, + TargetDataRep, &context->sub_context, &mech_output, pfContextAttr, ptsTimeStamp); + + if (IsSecurityStatusError(status)) + return status; + + if (status == SEC_E_OK) + context->state = NEGOTIATE_STATE_FINAL; + } + else if (context->state == NEGOTIATE_STATE_NEGORESP) + return SEC_E_INVALID_TOKEN; + } + + if (context->state == NEGOTIATE_STATE_FINAL) + { + /* Check if initiator sent the last mech token without a mic and a mic was required */ + if (context->mic && output_token.mechToken.cbBuffer == 0 && input_token.mic.cbBuffer == 0) + return SEC_E_INVALID_TOKEN; + + if (context->mic || input_token.mic.cbBuffer > 0) + { + status = negotiate_mic_exchange(context, &input_token, &output_token, output_buffer); + if (status != SEC_E_OK) + return status; + } + else + output_token.negState = ACCEPT_COMPLETED; + } + + if (input_token.negState == ACCEPT_COMPLETED) + { + if (output_buffer) + output_buffer->cbBuffer = 0; + return SEC_E_OK; + } + + if (output_token.negState == ACCEPT_COMPLETED) + status = SEC_E_OK; + else + status = SEC_I_CONTINUE_NEEDED; + + if (!negotiate_write_neg_token(output_buffer, &output_token)) + return SEC_E_INTERNAL_ERROR; + + return status; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_CompleteAuthToken(PCtxtHandle phContext, + PSecBufferDesc pToken) +{ + NEGOTIATE_CONTEXT* context = NULL; + SECURITY_STATUS status = SEC_E_OK; + context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->CompleteAuthToken) + status = context->mech->pkg->table->CompleteAuthToken(&context->sub_context, pToken); + + return status; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_DeleteSecurityContext(PCtxtHandle phContext) +{ + NEGOTIATE_CONTEXT* context = NULL; + SECURITY_STATUS status = SEC_E_OK; + context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + const SecPkg* pkg = NULL; + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + pkg = context->mech->pkg; + + if (pkg->table->DeleteSecurityContext) + status = pkg->table->DeleteSecurityContext(&context->sub_context); + + negotiate_ContextFree(context); + return status; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_ImpersonateSecurityContext(PCtxtHandle phContext) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_RevertSecurityContext(PCtxtHandle phContext) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_QueryContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table_w); + if (context->mech->pkg->table_w->QueryContextAttributesW) + return context->mech->pkg->table_w->QueryContextAttributesW(&context->sub_context, + ulAttribute, pBuffer); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_QueryContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->QueryContextAttributesA) + return context->mech->pkg->table->QueryContextAttributesA(&context->sub_context, + ulAttribute, pBuffer); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_SetContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table_w); + if (context->mech->pkg->table_w->SetContextAttributesW) + return context->mech->pkg->table_w->SetContextAttributesW(&context->sub_context, + ulAttribute, pBuffer, cbBuffer); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_SetContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->SetContextAttributesA) + return context->mech->pkg->table->SetContextAttributesA(&context->sub_context, ulAttribute, + pBuffer, cbBuffer); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_SetCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + MechCred* creds = NULL; + BOOL success = FALSE; + SECURITY_STATUS secStatus = 0; + + creds = sspi_SecureHandleGetLowerPointer(phCredential); + + if (!creds) + return SEC_E_INVALID_HANDLE; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + + WINPR_ASSERT(cred->mech); + WINPR_ASSERT(cred->mech->pkg); + WINPR_ASSERT(cred->mech->pkg->table); + WINPR_ASSERT(cred->mech->pkg->table_w->SetCredentialsAttributesW); + secStatus = cred->mech->pkg->table_w->SetCredentialsAttributesW(&cred->cred, ulAttribute, + pBuffer, cbBuffer); + + if (secStatus == SEC_E_OK) + { + success = TRUE; + } + } + + // return success if at least one submodule accepts the credential attribute + return (success ? SEC_E_OK : SEC_E_UNSUPPORTED_FUNCTION); +} + +static SECURITY_STATUS SEC_ENTRY negotiate_SetCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + MechCred* creds = NULL; + BOOL success = FALSE; + SECURITY_STATUS secStatus = 0; + + creds = sspi_SecureHandleGetLowerPointer(phCredential); + + if (!creds) + return SEC_E_INVALID_HANDLE; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + + if (!cred->valid) + continue; + + WINPR_ASSERT(cred->mech); + WINPR_ASSERT(cred->mech->pkg); + WINPR_ASSERT(cred->mech->pkg->table); + WINPR_ASSERT(cred->mech->pkg->table->SetCredentialsAttributesA); + secStatus = cred->mech->pkg->table->SetCredentialsAttributesA(&cred->cred, ulAttribute, + pBuffer, cbBuffer); + + if (secStatus == SEC_E_OK) + { + success = TRUE; + } + } + + // return success if at least one submodule accepts the credential attribute + return (success ? SEC_E_OK : SEC_E_UNSUPPORTED_FUNCTION); +} + +static SECURITY_STATUS SEC_ENTRY negotiate_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + BOOL kerberos = 0; + BOOL ntlm = 0; + + if (!negotiate_get_config(pAuthData, &kerberos, &ntlm)) + return SEC_E_INTERNAL_ERROR; + + MechCred* creds = calloc(MECH_COUNT, sizeof(MechCred)); + + if (!creds) + return SEC_E_INTERNAL_ERROR; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + const SecPkg* pkg = MechTable[i].pkg; + cred->mech = &MechTable[i]; + + if (!kerberos && _tcsncmp(pkg->name, KERBEROS_SSP_NAME, ARRAYSIZE(KERBEROS_SSP_NAME)) == 0) + continue; + if (!ntlm && _tcsncmp(SecPkgTable[i].name, NTLM_SSP_NAME, ARRAYSIZE(NTLM_SSP_NAME)) == 0) + continue; + + WINPR_ASSERT(pkg->table_w); + WINPR_ASSERT(pkg->table_w->AcquireCredentialsHandleW); + if (pkg->table_w->AcquireCredentialsHandleW( + pszPrincipal, pszPackage, fCredentialUse, pvLogonID, pAuthData, pGetKeyFn, + pvGetKeyArgument, &cred->cred, ptsExpiry) != SEC_E_OK) + continue; + + cred->valid = TRUE; + } + + sspi_SecureHandleSetLowerPointer(phCredential, (void*)creds); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)NEGO_SSP_NAME); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + BOOL kerberos = 0; + BOOL ntlm = 0; + + if (!negotiate_get_config(pAuthData, &kerberos, &ntlm)) + return SEC_E_INTERNAL_ERROR; + + MechCred* creds = calloc(MECH_COUNT, sizeof(MechCred)); + + if (!creds) + return SEC_E_INTERNAL_ERROR; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + const SecPkg* pkg = MechTable[i].pkg; + MechCred* cred = &creds[i]; + + cred->mech = &MechTable[i]; + + if (!kerberos && _tcsncmp(pkg->name, KERBEROS_SSP_NAME, ARRAYSIZE(KERBEROS_SSP_NAME)) == 0) + continue; + if (!ntlm && _tcsncmp(SecPkgTable[i].name, NTLM_SSP_NAME, ARRAYSIZE(NTLM_SSP_NAME)) == 0) + continue; + + WINPR_ASSERT(pkg->table); + WINPR_ASSERT(pkg->table->AcquireCredentialsHandleA); + if (pkg->table->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, + pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, + &cred->cred, ptsExpiry) != SEC_E_OK) + continue; + + cred->valid = TRUE; + } + + sspi_SecureHandleSetLowerPointer(phCredential, (void*)creds); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)NEGO_SSP_NAME); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + WLog_ERR(TAG, "TODO: Implement"); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_FreeCredentialsHandle(PCredHandle phCredential) +{ + MechCred* creds = NULL; + + creds = sspi_SecureHandleGetLowerPointer(phCredential); + if (!creds) + return SEC_E_INVALID_HANDLE; + + for (size_t i = 0; i < MECH_COUNT; i++) + { + MechCred* cred = &creds[i]; + + WINPR_ASSERT(cred->mech); + WINPR_ASSERT(cred->mech->pkg); + WINPR_ASSERT(cred->mech->pkg->table); + WINPR_ASSERT(cred->mech->pkg->table->FreeCredentialsHandle); + cred->mech->pkg->table->FreeCredentialsHandle(&cred->cred); + } + free(creds); + + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, + ULONG MessageSeqNo) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (context->mic) + MessageSeqNo++; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->EncryptMessage) + return context->mech->pkg->table->EncryptMessage(&context->sub_context, fQOP, pMessage, + MessageSeqNo); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (context->mic) + MessageSeqNo++; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->DecryptMessage) + return context->mech->pkg->table->DecryptMessage(&context->sub_context, pMessage, + MessageSeqNo, pfQOP); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, + ULONG MessageSeqNo) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (context->mic) + MessageSeqNo++; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->MakeSignature) + return context->mech->pkg->table->MakeSignature(&context->sub_context, fQOP, pMessage, + MessageSeqNo); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY negotiate_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ + NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + if (context->mic) + MessageSeqNo++; + + WINPR_ASSERT(context->mech); + WINPR_ASSERT(context->mech->pkg); + WINPR_ASSERT(context->mech->pkg->table); + if (context->mech->pkg->table->VerifySignature) + return context->mech->pkg->table->VerifySignature(&context->sub_context, pMessage, + MessageSeqNo, pfQOP); + + return SEC_E_UNSUPPORTED_FUNCTION; +} + +const SecurityFunctionTableA NEGOTIATE_SecurityFunctionTableA = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + negotiate_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + negotiate_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + negotiate_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + negotiate_InitializeSecurityContextA, /* InitializeSecurityContext */ + negotiate_AcceptSecurityContext, /* AcceptSecurityContext */ + negotiate_CompleteAuthToken, /* CompleteAuthToken */ + negotiate_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + negotiate_QueryContextAttributesA, /* QueryContextAttributes */ + negotiate_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + negotiate_RevertSecurityContext, /* RevertSecurityContext */ + negotiate_MakeSignature, /* MakeSignature */ + negotiate_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + negotiate_EncryptMessage, /* EncryptMessage */ + negotiate_DecryptMessage, /* DecryptMessage */ + negotiate_SetContextAttributesA, /* SetContextAttributes */ + negotiate_SetCredentialsAttributesA, /* SetCredentialsAttributes */ +}; + +const SecurityFunctionTableW NEGOTIATE_SecurityFunctionTableW = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + negotiate_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + negotiate_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + negotiate_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + negotiate_InitializeSecurityContextW, /* InitializeSecurityContext */ + negotiate_AcceptSecurityContext, /* AcceptSecurityContext */ + negotiate_CompleteAuthToken, /* CompleteAuthToken */ + negotiate_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + negotiate_QueryContextAttributesW, /* QueryContextAttributes */ + negotiate_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + negotiate_RevertSecurityContext, /* RevertSecurityContext */ + negotiate_MakeSignature, /* MakeSignature */ + negotiate_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + negotiate_EncryptMessage, /* EncryptMessage */ + negotiate_DecryptMessage, /* DecryptMessage */ + negotiate_SetContextAttributesW, /* SetContextAttributes */ + negotiate_SetCredentialsAttributesW, /* SetCredentialsAttributes */ +}; + +BOOL NEGOTIATE_init(void) +{ + InitializeConstWCharFromUtf8(NEGOTIATE_SecPkgInfoA.Name, NEGOTIATE_SecPkgInfoW_NameBuffer, + ARRAYSIZE(NEGOTIATE_SecPkgInfoW_NameBuffer)); + InitializeConstWCharFromUtf8(NEGOTIATE_SecPkgInfoA.Comment, NEGOTIATE_SecPkgInfoW_CommentBuffer, + ARRAYSIZE(NEGOTIATE_SecPkgInfoW_CommentBuffer)); + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.h new file mode 100644 index 0000000000000000000000000000000000000000..767e30a2897d1379706ca086b00140a4f6dae904 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Negotiate/negotiate.h @@ -0,0 +1,57 @@ +/** + * WinPR: Windows Portable Runtime + * Negotiate Security Package + * + * Copyright 2011-2012 Jiten Pathy + * + * 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_NEGOTIATE_PRIVATE_H +#define WINPR_SSPI_NEGOTIATE_PRIVATE_H + +#include + +#include "../sspi.h" + +#define NTLM_OID "1.3.6.1.4.1.311.2.2.10" + +typedef enum +{ + NEGOTIATE_STATE_INITIAL, + NEGOTIATE_STATE_FINAL_OPTIMISTIC, + NEGOTIATE_STATE_NEGORESP, + NEGOTIATE_STATE_MIC, + NEGOTIATE_STATE_FINAL, +} NEGOTIATE_STATE; + +typedef struct Mech_st Mech; + +typedef struct +{ + NEGOTIATE_STATE state; + CtxtHandle sub_context; + SecBuffer mechTypes; + const Mech* mech; + BOOL mic; + BOOL spnego; +} NEGOTIATE_CONTEXT; + +extern const SecPkgInfoA NEGOTIATE_SecPkgInfoA; +extern const SecPkgInfoW NEGOTIATE_SecPkgInfoW; +extern const SecurityFunctionTableA NEGOTIATE_SecurityFunctionTableA; +extern const SecurityFunctionTableW NEGOTIATE_SecurityFunctionTableW; + +BOOL NEGOTIATE_init(void); + +#endif /* WINPR_SSPI_NEGOTIATE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.c new file mode 100644 index 0000000000000000000000000000000000000000..45fba37f962032f439101c0e84878872bebe3985 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.c @@ -0,0 +1,467 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include "schannel.h" + +#include "../sspi.h" +#include "../../log.h" + +static char* SCHANNEL_PACKAGE_NAME = "Schannel"; + +#define TAG WINPR_TAG("sspi.Schannel") + +SCHANNEL_CONTEXT* schannel_ContextNew(void) +{ + SCHANNEL_CONTEXT* context = NULL; + context = (SCHANNEL_CONTEXT*)calloc(1, sizeof(SCHANNEL_CONTEXT)); + + if (!context) + return NULL; + + context->openssl = schannel_openssl_new(); + + if (!context->openssl) + { + free(context); + return NULL; + } + + return context; +} + +void schannel_ContextFree(SCHANNEL_CONTEXT* context) +{ + if (!context) + return; + + schannel_openssl_free(context->openssl); + free(context); +} + +static SCHANNEL_CREDENTIALS* schannel_CredentialsNew(void) +{ + SCHANNEL_CREDENTIALS* credentials = NULL; + credentials = (SCHANNEL_CREDENTIALS*)calloc(1, sizeof(SCHANNEL_CREDENTIALS)); + return credentials; +} + +static void schannel_CredentialsFree(SCHANNEL_CREDENTIALS* credentials) +{ + free(credentials); +} + +static ALG_ID schannel_SupportedAlgs[] = { CALG_AES_128, + CALG_AES_256, + CALG_RC4, + CALG_DES, + CALG_3DES, + CALG_MD5, + CALG_SHA1, + CALG_SHA_256, + CALG_SHA_384, + CALG_SHA_512, + CALG_RSA_SIGN, + CALG_DH_EPHEM, + (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RESERVED7 | + 6), /* what is this? */ + CALG_DSS_SIGN, + CALG_ECDSA }; + +static SECURITY_STATUS SEC_ENTRY schannel_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + if (ulAttribute == SECPKG_ATTR_SUPPORTED_ALGS) + { + PSecPkgCred_SupportedAlgs SupportedAlgs = (PSecPkgCred_SupportedAlgs)pBuffer; + SupportedAlgs->cSupportedAlgs = sizeof(schannel_SupportedAlgs) / sizeof(ALG_ID); + SupportedAlgs->palgSupportedAlgs = (ALG_ID*)schannel_SupportedAlgs; + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_CIPHER_STRENGTHS) + { + PSecPkgCred_CipherStrengths CipherStrengths = (PSecPkgCred_CipherStrengths)pBuffer; + CipherStrengths->dwMinimumCipherStrength = 40; + CipherStrengths->dwMaximumCipherStrength = 256; + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_SUPPORTED_PROTOCOLS) + { + PSecPkgCred_SupportedProtocols SupportedProtocols = (PSecPkgCred_SupportedProtocols)pBuffer; + /* Observed SupportedProtocols: 0x208A0 */ + SupportedProtocols->grbitProtocol = (SP_PROT_CLIENTS | SP_PROT_SERVERS); + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY schannel_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, + void* pBuffer) +{ + return schannel_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); +} + +static SECURITY_STATUS SEC_ENTRY schannel_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SCHANNEL_CREDENTIALS* credentials = NULL; + + if (fCredentialUse == SECPKG_CRED_OUTBOUND) + { + SCHANNEL_CRED* cred = NULL; + credentials = schannel_CredentialsNew(); + credentials->fCredentialUse = fCredentialUse; + cred = (SCHANNEL_CRED*)pAuthData; + + if (cred) + { + CopyMemory(&credentials->cred, cred, sizeof(SCHANNEL_CRED)); + } + + sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)SCHANNEL_PACKAGE_NAME); + return SEC_E_OK; + } + else if (fCredentialUse == SECPKG_CRED_INBOUND) + { + credentials = schannel_CredentialsNew(); + credentials->fCredentialUse = fCredentialUse; + sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials); + sspi_SecureHandleSetUpperPointer(phCredential, (void*)SCHANNEL_PACKAGE_NAME); + return SEC_E_OK; + } + + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY schannel_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SEC_WCHAR* pszPrincipalW = NULL; + SEC_WCHAR* pszPackageW = NULL; + if (pszPrincipal) + pszPrincipalW = ConvertUtf8ToWCharAlloc(pszPrincipal, NULL); + if (pszPackage) + pszPackageW = ConvertUtf8ToWCharAlloc(pszPackage, NULL); + + status = schannel_AcquireCredentialsHandleW(pszPrincipalW, pszPackageW, fCredentialUse, + pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, + phCredential, ptsExpiry); + free(pszPrincipalW); + free(pszPackageW); + return status; +} + +static SECURITY_STATUS SEC_ENTRY schannel_FreeCredentialsHandle(PCredHandle phCredential) +{ + SCHANNEL_CREDENTIALS* credentials = NULL; + + if (!phCredential) + return SEC_E_INVALID_HANDLE; + + credentials = (SCHANNEL_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + + if (!credentials) + return SEC_E_INVALID_HANDLE; + + schannel_CredentialsFree(credentials); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY schannel_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SCHANNEL_CONTEXT* context = NULL; + SCHANNEL_CREDENTIALS* credentials = NULL; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + { + context = schannel_ContextNew(); + + if (!context) + return SEC_E_INSUFFICIENT_MEMORY; + + credentials = (SCHANNEL_CREDENTIALS*)sspi_SecureHandleGetLowerPointer(phCredential); + context->server = FALSE; + CopyMemory(&context->cred, &credentials->cred, sizeof(SCHANNEL_CRED)); + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, (void*)SCHANNEL_PACKAGE_NAME); + schannel_openssl_client_init(context->openssl); + } + + status = schannel_openssl_client_process_tokens(context->openssl, pInput, pOutput); + return status; +} + +static SECURITY_STATUS SEC_ENTRY schannel_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + SEC_WCHAR* pszTargetNameW = NULL; + + if (pszTargetName != NULL) + { + pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, NULL); + if (!pszTargetNameW) + return SEC_E_INSUFFICIENT_MEMORY; + } + + status = schannel_InitializeSecurityContextW( + phCredential, phContext, pszTargetNameW, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + free(pszTargetNameW); + return status; +} + +static SECURITY_STATUS SEC_ENTRY schannel_AcceptSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq, + ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsTimeStamp) +{ + SECURITY_STATUS status = 0; + SCHANNEL_CONTEXT* context = NULL; + + /* behave like windows SSPIs that don't want empty context */ + if (phContext && !phContext->dwLower && !phContext->dwUpper) + return SEC_E_INVALID_HANDLE; + + context = (SCHANNEL_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + { + context = schannel_ContextNew(); + + if (!context) + return SEC_E_INSUFFICIENT_MEMORY; + + context->server = TRUE; + sspi_SecureHandleSetLowerPointer(phNewContext, context); + sspi_SecureHandleSetUpperPointer(phNewContext, (void*)SCHANNEL_PACKAGE_NAME); + schannel_openssl_server_init(context->openssl); + } + + status = schannel_openssl_server_process_tokens(context->openssl, pInput, pOutput); + return status; +} + +static SECURITY_STATUS SEC_ENTRY schannel_DeleteSecurityContext(PCtxtHandle phContext) +{ + SCHANNEL_CONTEXT* context = NULL; + context = (SCHANNEL_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + schannel_ContextFree(context); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY schannel_QueryContextAttributes(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + if (!phContext) + return SEC_E_INVALID_HANDLE; + + if (!pBuffer) + return SEC_E_INSUFFICIENT_MEMORY; + + if (ulAttribute == SECPKG_ATTR_SIZES) + { + SecPkgContext_Sizes* Sizes = (SecPkgContext_Sizes*)pBuffer; + Sizes->cbMaxToken = 0x6000; + Sizes->cbMaxSignature = 16; + Sizes->cbBlockSize = 0; + Sizes->cbSecurityTrailer = 16; + return SEC_E_OK; + } + else if (ulAttribute == SECPKG_ATTR_STREAM_SIZES) + { + SecPkgContext_StreamSizes* StreamSizes = (SecPkgContext_StreamSizes*)pBuffer; + StreamSizes->cbHeader = 5; + StreamSizes->cbTrailer = 36; + StreamSizes->cbMaximumMessage = 0x4000; + StreamSizes->cBuffers = 4; + StreamSizes->cbBlockSize = 16; + return SEC_E_OK; + } + + WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute); + return SEC_E_UNSUPPORTED_FUNCTION; +} + +static SECURITY_STATUS SEC_ENTRY schannel_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY schannel_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY schannel_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, + ULONG MessageSeqNo) +{ + SECURITY_STATUS status = 0; + SCHANNEL_CONTEXT* context = NULL; + context = (SCHANNEL_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + status = schannel_openssl_encrypt_message(context->openssl, pMessage); + return status; +} + +static SECURITY_STATUS SEC_ENTRY schannel_DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, + ULONG MessageSeqNo, ULONG* pfQOP) +{ + SECURITY_STATUS status = 0; + SCHANNEL_CONTEXT* context = NULL; + context = (SCHANNEL_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext); + + if (!context) + return SEC_E_INVALID_HANDLE; + + status = schannel_openssl_decrypt_message(context->openssl, pMessage); + return status; +} + +const SecurityFunctionTableA SCHANNEL_SecurityFunctionTableA = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + schannel_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + schannel_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + schannel_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + schannel_InitializeSecurityContextA, /* InitializeSecurityContext */ + schannel_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + schannel_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + schannel_QueryContextAttributes, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + schannel_MakeSignature, /* MakeSignature */ + schannel_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + schannel_EncryptMessage, /* EncryptMessage */ + schannel_DecryptMessage, /* DecryptMessage */ + NULL, /* SetContextAttributes */ + NULL, /* SetCredentialsAttributes */ +}; + +const SecurityFunctionTableW SCHANNEL_SecurityFunctionTableW = { + 3, /* dwVersion */ + NULL, /* EnumerateSecurityPackages */ + schannel_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + schannel_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + schannel_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + schannel_InitializeSecurityContextW, /* InitializeSecurityContext */ + schannel_AcceptSecurityContext, /* AcceptSecurityContext */ + NULL, /* CompleteAuthToken */ + schannel_DeleteSecurityContext, /* DeleteSecurityContext */ + NULL, /* ApplyControlToken */ + schannel_QueryContextAttributes, /* QueryContextAttributes */ + NULL, /* ImpersonateSecurityContext */ + NULL, /* RevertSecurityContext */ + schannel_MakeSignature, /* MakeSignature */ + schannel_VerifySignature, /* VerifySignature */ + NULL, /* FreeContextBuffer */ + NULL, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + NULL, /* ExportSecurityContext */ + NULL, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + NULL, /* QuerySecurityContextToken */ + schannel_EncryptMessage, /* EncryptMessage */ + schannel_DecryptMessage, /* DecryptMessage */ + NULL, /* SetContextAttributes */ + NULL, /* SetCredentialsAttributes */ +}; + +const SecPkgInfoA SCHANNEL_SecPkgInfoA = { + 0x000107B3, /* fCapabilities */ + 1, /* wVersion */ + 0x000E, /* wRPCID */ + SCHANNEL_CB_MAX_TOKEN, /* cbMaxToken */ + "Schannel", /* Name */ + "Schannel Security Package" /* Comment */ +}; + +static WCHAR SCHANNEL_SecPkgInfoW_NameBuffer[32] = { 0 }; +static WCHAR SCHANNEL_SecPkgInfoW_CommentBuffer[32] = { 0 }; + +const SecPkgInfoW SCHANNEL_SecPkgInfoW = { + 0x000107B3, /* fCapabilities */ + 1, /* wVersion */ + 0x000E, /* wRPCID */ + SCHANNEL_CB_MAX_TOKEN, /* cbMaxToken */ + SCHANNEL_SecPkgInfoW_NameBuffer, /* Name */ + SCHANNEL_SecPkgInfoW_CommentBuffer /* Comment */ +}; + +BOOL SCHANNEL_init(void) +{ + InitializeConstWCharFromUtf8(SCHANNEL_SecPkgInfoA.Name, SCHANNEL_SecPkgInfoW_NameBuffer, + ARRAYSIZE(SCHANNEL_SecPkgInfoW_NameBuffer)); + InitializeConstWCharFromUtf8(SCHANNEL_SecPkgInfoA.Comment, SCHANNEL_SecPkgInfoW_CommentBuffer, + ARRAYSIZE(SCHANNEL_SecPkgInfoW_CommentBuffer)); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.h new file mode 100644 index 0000000000000000000000000000000000000000..e4d170a1f61b543fd37bd034167bef04d1c3777f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel.h @@ -0,0 +1,53 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_SSPI_SCHANNEL_PRIVATE_H + +#include +#include + +#include "../sspi.h" + +#include "schannel_openssl.h" + +typedef struct +{ + SCHANNEL_CRED cred; + ULONG fCredentialUse; +} SCHANNEL_CREDENTIALS; + +typedef struct +{ + BOOL server; + SCHANNEL_CRED cred; + SCHANNEL_OPENSSL* openssl; +} SCHANNEL_CONTEXT; + +SCHANNEL_CONTEXT* schannel_ContextNew(void); +void schannel_ContextFree(SCHANNEL_CONTEXT* context); + +extern const SecPkgInfoA SCHANNEL_SecPkgInfoA; +extern const SecPkgInfoW SCHANNEL_SecPkgInfoW; +extern const SecurityFunctionTableA SCHANNEL_SecurityFunctionTableA; +extern const SecurityFunctionTableW SCHANNEL_SecurityFunctionTableW; + +BOOL SCHANNEL_init(void); + +#endif /* WINPR_SSPI_SCHANNEL_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.c new file mode 100644 index 0000000000000000000000000000000000000000..16c442138d3954c5cda8953b5c728de8171140cc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.c @@ -0,0 +1,657 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package (OpenSSL) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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 + +#include "schannel_openssl.h" + +#ifdef WITH_OPENSSL + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define LIMIT_INTMAX(a) ((a) > INT32_MAX) ? INT32_MAX : (int)(a) + +struct S_SCHANNEL_OPENSSL +{ + SSL* ssl; + SSL_CTX* ctx; + BOOL connected; + BIO* bioRead; + BIO* bioWrite; + BYTE* ReadBuffer; + BYTE* WriteBuffer; +}; + +#include "../../log.h" +#define TAG WINPR_TAG("sspi.schannel") + +static char* openssl_get_ssl_error_string(int ssl_error) +{ + switch (ssl_error) + { + case SSL_ERROR_ZERO_RETURN: + return "SSL_ERROR_ZERO_RETURN"; + + case SSL_ERROR_WANT_READ: + return "SSL_ERROR_WANT_READ"; + + case SSL_ERROR_WANT_WRITE: + return "SSL_ERROR_WANT_WRITE"; + + case SSL_ERROR_SYSCALL: + return "SSL_ERROR_SYSCALL"; + + case SSL_ERROR_SSL: + return "SSL_ERROR_SSL"; + default: + break; + } + + return "SSL_ERROR_UNKNOWN"; +} + +static void schannel_context_cleanup(SCHANNEL_OPENSSL* context) +{ + WINPR_ASSERT(context); + + free(context->ReadBuffer); + context->ReadBuffer = NULL; + + if (context->bioWrite) + BIO_free_all(context->bioWrite); + context->bioWrite = NULL; + + if (context->bioRead) + BIO_free_all(context->bioRead); + context->bioRead = NULL; + + if (context->ssl) + SSL_free(context->ssl); + context->ssl = NULL; + + if (context->ctx) + SSL_CTX_free(context->ctx); + context->ctx = NULL; +} + +static const SSL_METHOD* get_method(BOOL server) +{ + if (server) + { +#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) + return SSLv23_server_method(); +#else + return TLS_server_method(); +#endif + } + else + { +#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) + return SSLv23_client_method(); +#else + return TLS_client_method(); +#endif + } +} +int schannel_openssl_client_init(SCHANNEL_OPENSSL* context) +{ + int status = 0; + long options = 0; + context->ctx = SSL_CTX_new(get_method(FALSE)); + + if (!context->ctx) + { + WLog_ERR(TAG, "SSL_CTX_new failed"); + return -1; + } + + /** + * SSL_OP_NO_COMPRESSION: + * + * The Microsoft RDP server does not advertise support + * for TLS compression, but alternative servers may support it. + * This was observed between early versions of the FreeRDP server + * and the FreeRDP client, and caused major performance issues, + * which is why we're disabling it. + */ +#ifdef SSL_OP_NO_COMPRESSION + options |= SSL_OP_NO_COMPRESSION; +#endif + /** + * SSL_OP_TLS_BLOCK_PADDING_BUG: + * + * The Microsoft RDP server does *not* support TLS padding. + * It absolutely needs to be disabled otherwise it won't work. + */ + options |= SSL_OP_TLS_BLOCK_PADDING_BUG; + /** + * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: + * + * Just like TLS padding, the Microsoft RDP server does not + * support empty fragments. This needs to be disabled. + */ + options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + SSL_CTX_set_options(context->ctx, WINPR_ASSERTING_INT_CAST(uint64_t, options)); + context->ssl = SSL_new(context->ctx); + + if (!context->ssl) + { + WLog_ERR(TAG, "SSL_new failed"); + goto fail; + } + + context->bioRead = BIO_new(BIO_s_mem()); + + if (!context->bioRead) + { + WLog_ERR(TAG, "BIO_new failed"); + goto fail; + } + + status = BIO_set_write_buf_size(context->bioRead, SCHANNEL_CB_MAX_TOKEN); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_set_write_buf_size on bioRead failed"); + goto fail; + } + + context->bioWrite = BIO_new(BIO_s_mem()); + + if (!context->bioWrite) + { + WLog_ERR(TAG, "BIO_new failed"); + goto fail; + } + + status = BIO_set_write_buf_size(context->bioWrite, SCHANNEL_CB_MAX_TOKEN); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_set_write_buf_size on bioWrite failed"); + goto fail; + } + + status = BIO_make_bio_pair(context->bioRead, context->bioWrite); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_make_bio_pair failed"); + goto fail; + } + + SSL_set_bio(context->ssl, context->bioRead, context->bioWrite); + context->ReadBuffer = (BYTE*)malloc(SCHANNEL_CB_MAX_TOKEN); + + if (!context->ReadBuffer) + { + WLog_ERR(TAG, "Failed to allocate ReadBuffer"); + goto fail; + } + + context->WriteBuffer = (BYTE*)malloc(SCHANNEL_CB_MAX_TOKEN); + + if (!context->WriteBuffer) + { + WLog_ERR(TAG, "Failed to allocate ReadBuffer"); + goto fail; + } + + return 0; +fail: + schannel_context_cleanup(context); + return -1; +} + +int schannel_openssl_server_init(SCHANNEL_OPENSSL* context) +{ + int status = 0; + unsigned long options = 0; + + context->ctx = SSL_CTX_new(get_method(TRUE)); + + if (!context->ctx) + { + WLog_ERR(TAG, "SSL_CTX_new failed"); + return -1; + } + + /* + * SSL_OP_NO_SSLv2: + * + * We only want SSLv3 and TLSv1, so disable SSLv2. + * SSLv3 is used by, eg. Microsoft RDC for Mac OS X. + */ + options |= SSL_OP_NO_SSLv2; + /** + * SSL_OP_NO_COMPRESSION: + * + * The Microsoft RDP server does not advertise support + * for TLS compression, but alternative servers may support it. + * This was observed between early versions of the FreeRDP server + * and the FreeRDP client, and caused major performance issues, + * which is why we're disabling it. + */ +#ifdef SSL_OP_NO_COMPRESSION + options |= SSL_OP_NO_COMPRESSION; +#endif + /** + * SSL_OP_TLS_BLOCK_PADDING_BUG: + * + * The Microsoft RDP server does *not* support TLS padding. + * It absolutely needs to be disabled otherwise it won't work. + */ + options |= SSL_OP_TLS_BLOCK_PADDING_BUG; + /** + * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: + * + * Just like TLS padding, the Microsoft RDP server does not + * support empty fragments. This needs to be disabled. + */ + options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + SSL_CTX_set_options(context->ctx, options); + +#if defined(WITH_DEBUG_SCHANNEL) + if (SSL_CTX_use_RSAPrivateKey_file(context->ctx, "/tmp/localhost.key", SSL_FILETYPE_PEM) <= 0) + { + WLog_ERR(TAG, "SSL_CTX_use_RSAPrivateKey_file failed"); + goto fail; + } +#endif + + context->ssl = SSL_new(context->ctx); + + if (!context->ssl) + { + WLog_ERR(TAG, "SSL_new failed"); + goto fail; + } + + if (SSL_use_certificate_file(context->ssl, "/tmp/localhost.crt", SSL_FILETYPE_PEM) <= 0) + { + WLog_ERR(TAG, "SSL_use_certificate_file failed"); + goto fail; + } + + context->bioRead = BIO_new(BIO_s_mem()); + + if (!context->bioRead) + { + WLog_ERR(TAG, "BIO_new failed"); + goto fail; + } + + status = BIO_set_write_buf_size(context->bioRead, SCHANNEL_CB_MAX_TOKEN); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_set_write_buf_size failed for bioRead"); + goto fail; + } + + context->bioWrite = BIO_new(BIO_s_mem()); + + if (!context->bioWrite) + { + WLog_ERR(TAG, "BIO_new failed"); + goto fail; + } + + status = BIO_set_write_buf_size(context->bioWrite, SCHANNEL_CB_MAX_TOKEN); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_set_write_buf_size failed for bioWrite"); + goto fail; + } + + status = BIO_make_bio_pair(context->bioRead, context->bioWrite); + + if (status != 1) + { + WLog_ERR(TAG, "BIO_make_bio_pair failed"); + goto fail; + } + + SSL_set_bio(context->ssl, context->bioRead, context->bioWrite); + context->ReadBuffer = (BYTE*)malloc(SCHANNEL_CB_MAX_TOKEN); + + if (!context->ReadBuffer) + { + WLog_ERR(TAG, "Failed to allocate memory for ReadBuffer"); + goto fail; + } + + context->WriteBuffer = (BYTE*)malloc(SCHANNEL_CB_MAX_TOKEN); + + if (!context->WriteBuffer) + { + WLog_ERR(TAG, "Failed to allocate memory for WriteBuffer"); + goto fail; + } + + return 0; +fail: + schannel_context_cleanup(context); + return -1; +} + +SECURITY_STATUS schannel_openssl_client_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput) +{ + int status = 0; + int ssl_error = 0; + PSecBuffer pBuffer = NULL; + + if (!context->connected) + { + if (pInput) + { + if (pInput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + pBuffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + + if (!pBuffer) + return SEC_E_INVALID_TOKEN; + + ERR_clear_error(); + status = + BIO_write(context->bioRead, pBuffer->pvBuffer, LIMIT_INTMAX(pBuffer->cbBuffer)); + if (status < 0) + return SEC_E_INVALID_TOKEN; + } + + status = SSL_connect(context->ssl); + + if (status < 0) + { + ssl_error = SSL_get_error(context->ssl, status); + WLog_ERR(TAG, "SSL_connect error: %s", openssl_get_ssl_error_string(ssl_error)); + } + + if (status == 1) + context->connected = TRUE; + + ERR_clear_error(); + status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); + + if (pOutput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + pBuffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!pBuffer) + return SEC_E_INVALID_TOKEN; + + if (status > 0) + { + if (pBuffer->cbBuffer < WINPR_ASSERTING_INT_CAST(uint32_t, status)) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(pBuffer->pvBuffer, context->ReadBuffer, + WINPR_ASSERTING_INT_CAST(uint32_t, status)); + pBuffer->cbBuffer = WINPR_ASSERTING_INT_CAST(uint32_t, status); + return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; + } + else + { + pBuffer->cbBuffer = 0; + return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; + } + } + + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_server_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput) +{ + int status = 0; + int ssl_error = 0; + PSecBuffer pBuffer = NULL; + + if (!context->connected) + { + if (pInput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + pBuffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); + + if (!pBuffer) + return SEC_E_INVALID_TOKEN; + + ERR_clear_error(); + status = BIO_write(context->bioRead, pBuffer->pvBuffer, LIMIT_INTMAX(pBuffer->cbBuffer)); + if (status >= 0) + status = SSL_accept(context->ssl); + + if (status < 0) + { + ssl_error = SSL_get_error(context->ssl, status); + WLog_ERR(TAG, "SSL_accept error: %s", openssl_get_ssl_error_string(ssl_error)); + return SEC_E_INVALID_TOKEN; + } + + if (status == 1) + context->connected = TRUE; + + ERR_clear_error(); + status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); + if (status < 0) + { + ssl_error = SSL_get_error(context->ssl, status); + WLog_ERR(TAG, "BIO_read: %s", openssl_get_ssl_error_string(ssl_error)); + return SEC_E_INVALID_TOKEN; + } + + if (pOutput->cBuffers < 1) + return SEC_E_INVALID_TOKEN; + + pBuffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); + + if (!pBuffer) + return SEC_E_INVALID_TOKEN; + + if (status > 0) + { + if (pBuffer->cbBuffer < WINPR_ASSERTING_INT_CAST(uint32_t, status)) + return SEC_E_INSUFFICIENT_MEMORY; + + CopyMemory(pBuffer->pvBuffer, context->ReadBuffer, + WINPR_ASSERTING_INT_CAST(uint32_t, status)); + pBuffer->cbBuffer = WINPR_ASSERTING_INT_CAST(uint32_t, status); + return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; + } + else + { + pBuffer->cbBuffer = 0; + return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; + } + } + + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_encrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) +{ + int status = 0; + int ssl_error = 0; + PSecBuffer pStreamBodyBuffer = NULL; + PSecBuffer pStreamHeaderBuffer = NULL; + PSecBuffer pStreamTrailerBuffer = NULL; + pStreamHeaderBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_STREAM_HEADER); + pStreamBodyBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + pStreamTrailerBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_STREAM_TRAILER); + + if ((!pStreamHeaderBuffer) || (!pStreamBodyBuffer) || (!pStreamTrailerBuffer)) + return SEC_E_INVALID_TOKEN; + + status = SSL_write(context->ssl, pStreamBodyBuffer->pvBuffer, + LIMIT_INTMAX(pStreamBodyBuffer->cbBuffer)); + + if (status < 0) + { + ssl_error = SSL_get_error(context->ssl, status); + WLog_ERR(TAG, "SSL_write: %s", openssl_get_ssl_error_string(ssl_error)); + } + + ERR_clear_error(); + status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); + + if (status > 0) + { + size_t ustatus = (size_t)status; + size_t length = 0; + size_t offset = 0; + + length = + (pStreamHeaderBuffer->cbBuffer > ustatus) ? ustatus : pStreamHeaderBuffer->cbBuffer; + CopyMemory(pStreamHeaderBuffer->pvBuffer, &context->ReadBuffer[offset], length); + ustatus -= length; + offset += length; + length = (pStreamBodyBuffer->cbBuffer > ustatus) ? ustatus : pStreamBodyBuffer->cbBuffer; + CopyMemory(pStreamBodyBuffer->pvBuffer, &context->ReadBuffer[offset], length); + ustatus -= length; + offset += length; + length = + (pStreamTrailerBuffer->cbBuffer > ustatus) ? ustatus : pStreamTrailerBuffer->cbBuffer; + CopyMemory(pStreamTrailerBuffer->pvBuffer, &context->ReadBuffer[offset], length); + } + + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_decrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) +{ + int status = 0; + int length = 0; + BYTE* buffer = NULL; + int ssl_error = 0; + PSecBuffer pBuffer = NULL; + pBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); + + if (!pBuffer) + return SEC_E_INVALID_TOKEN; + + ERR_clear_error(); + status = BIO_write(context->bioRead, pBuffer->pvBuffer, LIMIT_INTMAX(pBuffer->cbBuffer)); + if (status > 0) + status = SSL_read(context->ssl, pBuffer->pvBuffer, LIMIT_INTMAX(pBuffer->cbBuffer)); + + if (status < 0) + { + ssl_error = SSL_get_error(context->ssl, status); + WLog_ERR(TAG, "SSL_read: %s", openssl_get_ssl_error_string(ssl_error)); + } + + length = status; + buffer = pBuffer->pvBuffer; + pMessage->pBuffers[0].BufferType = SECBUFFER_STREAM_HEADER; + pMessage->pBuffers[0].cbBuffer = 5; + pMessage->pBuffers[1].BufferType = SECBUFFER_DATA; + pMessage->pBuffers[1].pvBuffer = buffer; + pMessage->pBuffers[1].cbBuffer = WINPR_ASSERTING_INT_CAST(uint32_t, length); + pMessage->pBuffers[2].BufferType = SECBUFFER_STREAM_TRAILER; + pMessage->pBuffers[2].cbBuffer = 36; + pMessage->pBuffers[3].BufferType = SECBUFFER_EMPTY; + pMessage->pBuffers[3].cbBuffer = 0; + return SEC_E_OK; +} + +SCHANNEL_OPENSSL* schannel_openssl_new(void) +{ + SCHANNEL_OPENSSL* context = NULL; + context = (SCHANNEL_OPENSSL*)calloc(1, sizeof(SCHANNEL_OPENSSL)); + + if (context != NULL) + { + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + context->connected = FALSE; + } + + return context; +} + +void schannel_openssl_free(SCHANNEL_OPENSSL* context) +{ + if (context) + { + free(context->ReadBuffer); + free(context->WriteBuffer); + free(context); + } +} + +#else + +int schannel_openssl_client_init(SCHANNEL_OPENSSL* context) +{ + return 0; +} + +int schannel_openssl_server_init(SCHANNEL_OPENSSL* context) +{ + return 0; +} + +SECURITY_STATUS schannel_openssl_client_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput) +{ + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_server_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput) +{ + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_encrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) +{ + return SEC_E_OK; +} + +SECURITY_STATUS schannel_openssl_decrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) +{ + return SEC_E_OK; +} + +SCHANNEL_OPENSSL* schannel_openssl_new(void) +{ + return NULL; +} + +void schannel_openssl_free(SCHANNEL_OPENSSL* context) +{ +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.h new file mode 100644 index 0000000000000000000000000000000000000000..31993e9adf2d2486ce1b7561157811f39d2ffd0c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/Schannel/schannel_openssl.h @@ -0,0 +1,52 @@ +/** + * WinPR: Windows Portable Runtime + * Schannel Security Package (OpenSSL) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_OPENSSL_H +#define WINPR_SSPI_SCHANNEL_OPENSSL_H + +#include + +#include "../sspi.h" + +/* OpenSSL includes windows.h */ +#include + +typedef struct S_SCHANNEL_OPENSSL SCHANNEL_OPENSSL; + +int schannel_openssl_client_init(SCHANNEL_OPENSSL* context); +int schannel_openssl_server_init(SCHANNEL_OPENSSL* context); + +SECURITY_STATUS schannel_openssl_client_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput); +SECURITY_STATUS schannel_openssl_server_process_tokens(SCHANNEL_OPENSSL* context, + PSecBufferDesc pInput, + PSecBufferDesc pOutput); + +SECURITY_STATUS schannel_openssl_encrypt_message(SCHANNEL_OPENSSL* context, + PSecBufferDesc pMessage); +SECURITY_STATUS schannel_openssl_decrypt_message(SCHANNEL_OPENSSL* context, + PSecBufferDesc pMessage); + +void schannel_openssl_free(SCHANNEL_OPENSSL* context); + +WINPR_ATTR_MALLOC(schannel_openssl_free, 1) +SCHANNEL_OPENSSL* schannel_openssl_new(void); + +#endif /* WINPR_SSPI_SCHANNEL_OPENSSL_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.c new file mode 100644 index 0000000000000000000000000000000000000000..a26cbc0c3064408ccd73dde3114a02fe6ec7ac12 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.c @@ -0,0 +1,1144 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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 +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO +WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO + +#define _NO_KSECDD_IMPORT_ 1 // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +WINPR_PRAGMA_DIAG_POP + +#include + +#include +#include +#include +#include +#include + +#include "sspi.h" + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_MISSING_PROTOTYPES + +static wLog* g_Log = NULL; + +static INIT_ONCE g_Initialized = INIT_ONCE_STATIC_INIT; +#if defined(WITH_NATIVE_SSPI) +static HMODULE g_SspiModule = NULL; +static SecurityFunctionTableW windows_SecurityFunctionTableW = { 0 }; +static SecurityFunctionTableA windows_SecurityFunctionTableA = { 0 }; +#endif + +static SecurityFunctionTableW* g_SspiW = NULL; +static SecurityFunctionTableA* g_SspiA = NULL; + +#if defined(WITH_NATIVE_SSPI) +static BOOL ShouldUseNativeSspi(void); +static BOOL InitializeSspiModule_Native(void); +#endif + +#if defined(WITH_NATIVE_SSPI) +BOOL ShouldUseNativeSspi(void) +{ + BOOL status = FALSE; +#ifdef _WIN32 + LPCSTR sspi = "WINPR_NATIVE_SSPI"; + DWORD nSize; + char* env = NULL; + nSize = GetEnvironmentVariableA(sspi, NULL, 0); + + if (!nSize) + return TRUE; + + env = (LPSTR)malloc(nSize); + + if (!env) + return TRUE; + + if (GetEnvironmentVariableA(sspi, env, nSize) != nSize - 1) + { + free(env); + return TRUE; + } + + if (strcmp(env, "0") == 0) + status = FALSE; + else + status = TRUE; + + free(env); +#endif + return status; +} +#endif + +#if defined(WITH_NATIVE_SSPI) +BOOL InitializeSspiModule_Native(void) +{ + SecurityFunctionTableW* pSspiW = NULL; + SecurityFunctionTableA* pSspiA = NULL; + INIT_SECURITY_INTERFACE_W pInitSecurityInterfaceW; + INIT_SECURITY_INTERFACE_A pInitSecurityInterfaceA; + g_SspiModule = LoadLibraryA("secur32.dll"); + + if (!g_SspiModule) + g_SspiModule = LoadLibraryA("sspicli.dll"); + + if (!g_SspiModule) + return FALSE; + + pInitSecurityInterfaceW = + GetProcAddressAs(g_SspiModule, "InitSecurityInterfaceW", INIT_SECURITY_INTERFACE_W); + pInitSecurityInterfaceA = + GetProcAddressAs(g_SspiModule, "InitSecurityInterfaceA", INIT_SECURITY_INTERFACE_A); + + if (pInitSecurityInterfaceW) + { + pSspiW = pInitSecurityInterfaceW(); + + if (pSspiW) + { + g_SspiW = &windows_SecurityFunctionTableW; + CopyMemory(g_SspiW, pSspiW, + FIELD_OFFSET(SecurityFunctionTableW, SetContextAttributesW)); + + g_SspiW->dwVersion = SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_3; + + g_SspiW->SetContextAttributesW = GetProcAddressAs(g_SspiModule, "SetContextAttributesW", + SET_CONTEXT_ATTRIBUTES_FN_W); + + g_SspiW->SetCredentialsAttributesW = GetProcAddressAs( + g_SspiModule, "SetCredentialsAttributesW", SET_CREDENTIALS_ATTRIBUTES_FN_W); + } + } + + if (pInitSecurityInterfaceA) + { + pSspiA = pInitSecurityInterfaceA(); + + if (pSspiA) + { + g_SspiA = &windows_SecurityFunctionTableA; + CopyMemory(g_SspiA, pSspiA, + FIELD_OFFSET(SecurityFunctionTableA, SetContextAttributesA)); + + g_SspiA->dwVersion = SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_3; + + g_SspiA->SetContextAttributesA = GetProcAddressAs(g_SspiModule, "SetContextAttributesA", + SET_CONTEXT_ATTRIBUTES_FN_W); + + g_SspiA->SetCredentialsAttributesA = GetProcAddressAs( + g_SspiModule, "SetCredentialsAttributesA", SET_CREDENTIALS_ATTRIBUTES_FN_W); + } + } + + return TRUE; +} +#endif + +static BOOL CALLBACK InitializeSspiModuleInt(PINIT_ONCE once, PVOID param, PVOID* context) +{ + BOOL status = FALSE; +#if defined(WITH_NATIVE_SSPI) + DWORD flags = 0; + + if (param) + flags = *(DWORD*)param; + +#endif + sspi_GlobalInit(); + g_Log = WLog_Get("com.winpr.sspi"); +#if defined(WITH_NATIVE_SSPI) + + if (flags && (flags & SSPI_INTERFACE_NATIVE)) + { + status = InitializeSspiModule_Native(); + } + else if (flags && (flags & SSPI_INTERFACE_WINPR)) + { + g_SspiW = winpr_InitSecurityInterfaceW(); + g_SspiA = winpr_InitSecurityInterfaceA(); + status = TRUE; + } + + if (!status && ShouldUseNativeSspi()) + { + status = InitializeSspiModule_Native(); + } + +#endif + + if (!status) + { + g_SspiW = winpr_InitSecurityInterfaceW(); + g_SspiA = winpr_InitSecurityInterfaceA(); + } + + return TRUE; +} + +const char* GetSecurityStatusString(SECURITY_STATUS status) +{ + switch (status) + { + case SEC_E_OK: + return "SEC_E_OK"; + + case SEC_E_INSUFFICIENT_MEMORY: + return "SEC_E_INSUFFICIENT_MEMORY"; + + case SEC_E_INVALID_HANDLE: + return "SEC_E_INVALID_HANDLE"; + + case SEC_E_UNSUPPORTED_FUNCTION: + return "SEC_E_UNSUPPORTED_FUNCTION"; + + case SEC_E_TARGET_UNKNOWN: + return "SEC_E_TARGET_UNKNOWN"; + + case SEC_E_INTERNAL_ERROR: + return "SEC_E_INTERNAL_ERROR"; + + case SEC_E_SECPKG_NOT_FOUND: + return "SEC_E_SECPKG_NOT_FOUND"; + + case SEC_E_NOT_OWNER: + return "SEC_E_NOT_OWNER"; + + case SEC_E_CANNOT_INSTALL: + return "SEC_E_CANNOT_INSTALL"; + + case SEC_E_INVALID_TOKEN: + return "SEC_E_INVALID_TOKEN"; + + case SEC_E_CANNOT_PACK: + return "SEC_E_CANNOT_PACK"; + + case SEC_E_QOP_NOT_SUPPORTED: + return "SEC_E_QOP_NOT_SUPPORTED"; + + case SEC_E_NO_IMPERSONATION: + return "SEC_E_NO_IMPERSONATION"; + + case SEC_E_LOGON_DENIED: + return "SEC_E_LOGON_DENIED"; + + case SEC_E_UNKNOWN_CREDENTIALS: + return "SEC_E_UNKNOWN_CREDENTIALS"; + + case SEC_E_NO_CREDENTIALS: + return "SEC_E_NO_CREDENTIALS"; + + case SEC_E_MESSAGE_ALTERED: + return "SEC_E_MESSAGE_ALTERED"; + + case SEC_E_OUT_OF_SEQUENCE: + return "SEC_E_OUT_OF_SEQUENCE"; + + case SEC_E_NO_AUTHENTICATING_AUTHORITY: + return "SEC_E_NO_AUTHENTICATING_AUTHORITY"; + + case SEC_E_BAD_PKGID: + return "SEC_E_BAD_PKGID"; + + case SEC_E_CONTEXT_EXPIRED: + return "SEC_E_CONTEXT_EXPIRED"; + + case SEC_E_INCOMPLETE_MESSAGE: + return "SEC_E_INCOMPLETE_MESSAGE"; + + case SEC_E_INCOMPLETE_CREDENTIALS: + return "SEC_E_INCOMPLETE_CREDENTIALS"; + + case SEC_E_BUFFER_TOO_SMALL: + return "SEC_E_BUFFER_TOO_SMALL"; + + case SEC_E_WRONG_PRINCIPAL: + return "SEC_E_WRONG_PRINCIPAL"; + + case SEC_E_TIME_SKEW: + return "SEC_E_TIME_SKEW"; + + case SEC_E_UNTRUSTED_ROOT: + return "SEC_E_UNTRUSTED_ROOT"; + + case SEC_E_ILLEGAL_MESSAGE: + return "SEC_E_ILLEGAL_MESSAGE"; + + case SEC_E_CERT_UNKNOWN: + return "SEC_E_CERT_UNKNOWN"; + + case SEC_E_CERT_EXPIRED: + return "SEC_E_CERT_EXPIRED"; + + case SEC_E_ENCRYPT_FAILURE: + return "SEC_E_ENCRYPT_FAILURE"; + + case SEC_E_DECRYPT_FAILURE: + return "SEC_E_DECRYPT_FAILURE"; + + case SEC_E_ALGORITHM_MISMATCH: + return "SEC_E_ALGORITHM_MISMATCH"; + + case SEC_E_SECURITY_QOS_FAILED: + return "SEC_E_SECURITY_QOS_FAILED"; + + case SEC_E_UNFINISHED_CONTEXT_DELETED: + return "SEC_E_UNFINISHED_CONTEXT_DELETED"; + + case SEC_E_NO_TGT_REPLY: + return "SEC_E_NO_TGT_REPLY"; + + case SEC_E_NO_IP_ADDRESSES: + return "SEC_E_NO_IP_ADDRESSES"; + + case SEC_E_WRONG_CREDENTIAL_HANDLE: + return "SEC_E_WRONG_CREDENTIAL_HANDLE"; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + return "SEC_E_CRYPTO_SYSTEM_INVALID"; + + case SEC_E_MAX_REFERRALS_EXCEEDED: + return "SEC_E_MAX_REFERRALS_EXCEEDED"; + + case SEC_E_MUST_BE_KDC: + return "SEC_E_MUST_BE_KDC"; + + case SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: + return "SEC_E_STRONG_CRYPTO_NOT_SUPPORTED"; + + case SEC_E_TOO_MANY_PRINCIPALS: + return "SEC_E_TOO_MANY_PRINCIPALS"; + + case SEC_E_NO_PA_DATA: + return "SEC_E_NO_PA_DATA"; + + case SEC_E_PKINIT_NAME_MISMATCH: + return "SEC_E_PKINIT_NAME_MISMATCH"; + + case SEC_E_SMARTCARD_LOGON_REQUIRED: + return "SEC_E_SMARTCARD_LOGON_REQUIRED"; + + case SEC_E_SHUTDOWN_IN_PROGRESS: + return "SEC_E_SHUTDOWN_IN_PROGRESS"; + + case SEC_E_KDC_INVALID_REQUEST: + return "SEC_E_KDC_INVALID_REQUEST"; + + case SEC_E_KDC_UNABLE_TO_REFER: + return "SEC_E_KDC_UNABLE_TO_REFER"; + + case SEC_E_KDC_UNKNOWN_ETYPE: + return "SEC_E_KDC_UNKNOWN_ETYPE"; + + case SEC_E_UNSUPPORTED_PREAUTH: + return "SEC_E_UNSUPPORTED_PREAUTH"; + + case SEC_E_DELEGATION_REQUIRED: + return "SEC_E_DELEGATION_REQUIRED"; + + case SEC_E_BAD_BINDINGS: + return "SEC_E_BAD_BINDINGS"; + + case SEC_E_MULTIPLE_ACCOUNTS: + return "SEC_E_MULTIPLE_ACCOUNTS"; + + case SEC_E_NO_KERB_KEY: + return "SEC_E_NO_KERB_KEY"; + + case SEC_E_CERT_WRONG_USAGE: + return "SEC_E_CERT_WRONG_USAGE"; + + case SEC_E_DOWNGRADE_DETECTED: + return "SEC_E_DOWNGRADE_DETECTED"; + + case SEC_E_SMARTCARD_CERT_REVOKED: + return "SEC_E_SMARTCARD_CERT_REVOKED"; + + case SEC_E_ISSUING_CA_UNTRUSTED: + return "SEC_E_ISSUING_CA_UNTRUSTED"; + + case SEC_E_REVOCATION_OFFLINE_C: + return "SEC_E_REVOCATION_OFFLINE_C"; + + case SEC_E_PKINIT_CLIENT_FAILURE: + return "SEC_E_PKINIT_CLIENT_FAILURE"; + + case SEC_E_SMARTCARD_CERT_EXPIRED: + return "SEC_E_SMARTCARD_CERT_EXPIRED"; + + case SEC_E_NO_S4U_PROT_SUPPORT: + return "SEC_E_NO_S4U_PROT_SUPPORT"; + + case SEC_E_CROSSREALM_DELEGATION_FAILURE: + return "SEC_E_CROSSREALM_DELEGATION_FAILURE"; + + case SEC_E_REVOCATION_OFFLINE_KDC: + return "SEC_E_REVOCATION_OFFLINE_KDC"; + + case SEC_E_ISSUING_CA_UNTRUSTED_KDC: + return "SEC_E_ISSUING_CA_UNTRUSTED_KDC"; + + case SEC_E_KDC_CERT_EXPIRED: + return "SEC_E_KDC_CERT_EXPIRED"; + + case SEC_E_KDC_CERT_REVOKED: + return "SEC_E_KDC_CERT_REVOKED"; + + case SEC_E_INVALID_PARAMETER: + return "SEC_E_INVALID_PARAMETER"; + + case SEC_E_DELEGATION_POLICY: + return "SEC_E_DELEGATION_POLICY"; + + case SEC_E_POLICY_NLTM_ONLY: + return "SEC_E_POLICY_NLTM_ONLY"; + + case SEC_E_NO_CONTEXT: + return "SEC_E_NO_CONTEXT"; + + case SEC_E_PKU2U_CERT_FAILURE: + return "SEC_E_PKU2U_CERT_FAILURE"; + + case SEC_E_MUTUAL_AUTH_FAILED: + return "SEC_E_MUTUAL_AUTH_FAILED"; + + case SEC_I_CONTINUE_NEEDED: + return "SEC_I_CONTINUE_NEEDED"; + + case SEC_I_COMPLETE_NEEDED: + return "SEC_I_COMPLETE_NEEDED"; + + case SEC_I_COMPLETE_AND_CONTINUE: + return "SEC_I_COMPLETE_AND_CONTINUE"; + + case SEC_I_LOCAL_LOGON: + return "SEC_I_LOCAL_LOGON"; + + case SEC_I_CONTEXT_EXPIRED: + return "SEC_I_CONTEXT_EXPIRED"; + + case SEC_I_INCOMPLETE_CREDENTIALS: + return "SEC_I_INCOMPLETE_CREDENTIALS"; + + case SEC_I_RENEGOTIATE: + return "SEC_I_RENEGOTIATE"; + + case SEC_I_NO_LSA_CONTEXT: + return "SEC_I_NO_LSA_CONTEXT"; + + case SEC_I_SIGNATURE_NEEDED: + return "SEC_I_SIGNATURE_NEEDED"; + + case SEC_I_NO_RENEGOTIATION: + return "SEC_I_NO_RENEGOTIATION"; + default: + break; + } + + return NtStatus2Tag(status); +} + +BOOL IsSecurityStatusError(SECURITY_STATUS status) +{ + BOOL error = TRUE; + + switch (status) + { + case SEC_E_OK: + case SEC_I_CONTINUE_NEEDED: + case SEC_I_COMPLETE_NEEDED: + case SEC_I_COMPLETE_AND_CONTINUE: + case SEC_I_LOCAL_LOGON: + case SEC_I_CONTEXT_EXPIRED: + case SEC_I_INCOMPLETE_CREDENTIALS: + case SEC_I_RENEGOTIATE: + case SEC_I_NO_LSA_CONTEXT: + case SEC_I_SIGNATURE_NEEDED: + case SEC_I_NO_RENEGOTIATION: + error = FALSE; + break; + default: + break; + } + + return error; +} + +SecurityFunctionTableW* SEC_ENTRY InitSecurityInterfaceExW(DWORD flags) +{ + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, &flags, NULL); + WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceExW"); + return g_SspiW; +} + +SecurityFunctionTableA* SEC_ENTRY InitSecurityInterfaceExA(DWORD flags) +{ + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, &flags, NULL); + WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceExA"); + return g_SspiA; +} + +/** + * Standard SSPI API + */ + +/* Package Management */ + +SECURITY_STATUS SEC_ENTRY sspi_EnumerateSecurityPackagesW(ULONG* pcPackages, + PSecPkgInfoW* ppPackageInfo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->EnumerateSecurityPackagesW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->EnumerateSecurityPackagesW(pcPackages, ppPackageInfo); + WLog_Print(g_Log, WLOG_DEBUG, "EnumerateSecurityPackagesW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_EnumerateSecurityPackagesA(ULONG* pcPackages, + PSecPkgInfoA* ppPackageInfo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->EnumerateSecurityPackagesA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->EnumerateSecurityPackagesA(pcPackages, ppPackageInfo); + WLog_Print(g_Log, WLOG_DEBUG, "EnumerateSecurityPackagesA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SecurityFunctionTableW* SEC_ENTRY sspi_InitSecurityInterfaceW(void) +{ + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceW"); + return g_SspiW; +} + +SecurityFunctionTableA* SEC_ENTRY sspi_InitSecurityInterfaceA(void) +{ + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceA"); + return g_SspiA; +} + +SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, + PSecPkgInfoW* ppPackageInfo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->QuerySecurityPackageInfoW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->QuerySecurityPackageInfoW(pszPackageName, ppPackageInfo); + WLog_Print(g_Log, WLOG_DEBUG, "QuerySecurityPackageInfoW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageName, + PSecPkgInfoA* ppPackageInfo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->QuerySecurityPackageInfoA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->QuerySecurityPackageInfoA(pszPackageName, ppPackageInfo); + WLog_Print(g_Log, WLOG_DEBUG, "QuerySecurityPackageInfoA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +/* Credential Management */ + +SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->AcquireCredentialsHandleW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, + phCredential, ptsExpiry); + WLog_Print(g_Log, WLOG_DEBUG, "AcquireCredentialsHandleW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->AcquireCredentialsHandleA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, + phCredential, ptsExpiry); + WLog_Print(g_Log, WLOG_DEBUG, "AcquireCredentialsHandleA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_ExportSecurityContext(PCtxtHandle phContext, ULONG fFlags, + PSecBuffer pPackedContext, HANDLE* pToken) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->ExportSecurityContext)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->ExportSecurityContext(phContext, fFlags, pPackedContext, pToken); + WLog_Print(g_Log, WLOG_DEBUG, "ExportSecurityContext: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_FreeCredentialsHandle(PCredHandle phCredential) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->FreeCredentialsHandle)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->FreeCredentialsHandle(phCredential); + WLog_Print(g_Log, WLOG_DEBUG, "FreeCredentialsHandle: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_ImportSecurityContextW(SEC_WCHAR* pszPackage, + PSecBuffer pPackedContext, HANDLE pToken, + PCtxtHandle phContext) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->ImportSecurityContextW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->ImportSecurityContextW(pszPackage, pPackedContext, pToken, phContext); + WLog_Print(g_Log, WLOG_DEBUG, "ImportSecurityContextW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_ImportSecurityContextA(SEC_CHAR* pszPackage, + PSecBuffer pPackedContext, HANDLE pToken, + PCtxtHandle phContext) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->ImportSecurityContextA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->ImportSecurityContextA(pszPackage, pPackedContext, pToken, phContext); + WLog_Print(g_Log, WLOG_DEBUG, "ImportSecurityContextA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->QueryCredentialsAttributesW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "QueryCredentialsAttributesW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->QueryCredentialsAttributesA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->QueryCredentialsAttributesA(phCredential, ulAttribute, pBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "QueryCredentialsAttributesA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +/* Context Management */ + +SECURITY_STATUS SEC_ENTRY sspi_AcceptSecurityContext(PCredHandle phCredential, + PCtxtHandle phContext, PSecBufferDesc pInput, + ULONG fContextReq, ULONG TargetDataRep, + PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, + PTimeStamp ptsTimeStamp) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->AcceptSecurityContext)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = + g_SspiW->AcceptSecurityContext(phCredential, phContext, pInput, fContextReq, TargetDataRep, + phNewContext, pOutput, pfContextAttr, ptsTimeStamp); + WLog_Print(g_Log, WLOG_DEBUG, "AcceptSecurityContext: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_ApplyControlToken(PCtxtHandle phContext, PSecBufferDesc pInput) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->ApplyControlToken)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->ApplyControlToken(phContext, pInput); + WLog_Print(g_Log, WLOG_DEBUG, "ApplyControlToken: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_CompleteAuthToken(PCtxtHandle phContext, PSecBufferDesc pToken) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->CompleteAuthToken)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->CompleteAuthToken(phContext, pToken); + WLog_Print(g_Log, WLOG_DEBUG, "CompleteAuthToken: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_DeleteSecurityContext(PCtxtHandle phContext) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->DeleteSecurityContext)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->DeleteSecurityContext(phContext); + WLog_Print(g_Log, WLOG_DEBUG, "DeleteSecurityContext: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_FreeContextBuffer(void* pvContextBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->FreeContextBuffer)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->FreeContextBuffer(pvContextBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "FreeContextBuffer: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_ImpersonateSecurityContext(PCtxtHandle phContext) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->ImpersonateSecurityContext)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->ImpersonateSecurityContext(phContext); + WLog_Print(g_Log, WLOG_DEBUG, "ImpersonateSecurityContext: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->InitializeSecurityContextW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->InitializeSecurityContextW( + phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + WLog_Print(g_Log, WLOG_DEBUG, "InitializeSecurityContextW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->InitializeSecurityContextA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->InitializeSecurityContextA( + phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + WLog_Print(g_Log, WLOG_DEBUG, "InitializeSecurityContextA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QueryContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, + void* pBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->QueryContextAttributesW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->QueryContextAttributesW(phContext, ulAttribute, pBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "QueryContextAttributesW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QueryContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, + void* pBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->QueryContextAttributesA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->QueryContextAttributesA(phContext, ulAttribute, pBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "QueryContextAttributesA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityContextToken(PCtxtHandle phContext, HANDLE* phToken) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->QuerySecurityContextToken)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->QuerySecurityContextToken(phContext, phToken); + WLog_Print(g_Log, WLOG_DEBUG, "QuerySecurityContextToken: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_SetContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->SetContextAttributesW)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "SetContextAttributesW: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_SetContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiA && g_SspiA->SetContextAttributesA)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiA->SetContextAttributesA(phContext, ulAttribute, pBuffer, cbBuffer); + WLog_Print(g_Log, WLOG_DEBUG, "SetContextAttributesA: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_RevertSecurityContext(PCtxtHandle phContext) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->RevertSecurityContext)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->RevertSecurityContext(phContext); + WLog_Print(g_Log, WLOG_DEBUG, "RevertSecurityContext: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +/* Message Support */ + +SECURITY_STATUS SEC_ENTRY sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, + ULONG MessageSeqNo, PULONG pfQOP) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->DecryptMessage)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->DecryptMessage(phContext, pMessage, MessageSeqNo, pfQOP); + WLog_Print(g_Log, WLOG_DEBUG, "DecryptMessage: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->EncryptMessage)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->EncryptMessage(phContext, fQOP, pMessage, MessageSeqNo); + WLog_Print(g_Log, WLOG_DEBUG, "EncryptMessage: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->MakeSignature)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->MakeSignature(phContext, fQOP, pMessage, MessageSeqNo); + WLog_Print(g_Log, WLOG_DEBUG, "MakeSignature: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +SECURITY_STATUS SEC_ENTRY sspi_VerifySignature(PCtxtHandle phContext, PSecBufferDesc pMessage, + ULONG MessageSeqNo, PULONG pfQOP) +{ + SECURITY_STATUS status = 0; + InitOnceExecuteOnce(&g_Initialized, InitializeSspiModuleInt, NULL, NULL); + + if (!(g_SspiW && g_SspiW->VerifySignature)) + { + WLog_Print(g_Log, WLOG_WARN, "Security module does not provide an implementation"); + + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = g_SspiW->VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP); + WLog_Print(g_Log, WLOG_DEBUG, "VerifySignature: %s (0x%08" PRIX32 ")", + GetSecurityStatusString(status), status); + return status; +} + +WINPR_PRAGMA_DIAG_POP + +static void zfree(WCHAR* str, size_t len, BOOL isWCHAR) +{ + if (str) + memset(str, 0, len * (isWCHAR ? sizeof(WCHAR) : sizeof(char))); + free(str); +} + +void sspi_FreeAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity) +{ + if (!identity) + return; + + const BOOL wc = (identity->Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE) != 0; + zfree(identity->User, identity->UserLength, wc); + zfree(identity->Domain, identity->DomainLength, wc); + + /* identity->PasswordLength does have a dual use. In Pass The Hash (PTH) mode the maximum + * password length (512) is added to the real length to mark this as a hash. when we free up + * this field without removing these additional bytes we would corrupt the stack. + */ + size_t len = identity->PasswordLength; + if (len > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) + len -= SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; + zfree(identity->Password, len, wc); + + const SEC_WINNT_AUTH_IDENTITY empty = { 0 }; + *identity = empty; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.h new file mode 100644 index 0000000000000000000000000000000000000000..f6791f939998b963c0c38386f08909f642bbffcc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi.h @@ -0,0 +1,93 @@ +/** + * WinPR: Windows Portable Runtime + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_SSPI_PRIVATE_H + +#include + +#define SCHANNEL_CB_MAX_TOKEN 0x00006000 + +#define SSPI_CREDENTIALS_PASSWORD_HASH 0x00000001 + +#define SSPI_CREDENTIALS_HASH_LENGTH_OFFSET 512 + +typedef struct +{ + DWORD flags; + ULONG fCredentialUse; + SEC_GET_KEY_FN pGetKeyFn; + void* pvGetKeyArgument; + SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINPR_NTLM_SETTINGS ntlmSettings; + SEC_WINPR_KERBEROS_SETTINGS kerbSettings; +} SSPI_CREDENTIALS; + +SSPI_CREDENTIALS* sspi_CredentialsNew(void); +void sspi_CredentialsFree(SSPI_CREDENTIALS* credentials); + +PSecBuffer sspi_FindSecBuffer(PSecBufferDesc pMessage, ULONG BufferType); + +SecHandle* sspi_SecureHandleAlloc(void); +void sspi_SecureHandleInvalidate(SecHandle* handle); +void* sspi_SecureHandleGetLowerPointer(SecHandle* handle); +void sspi_SecureHandleSetLowerPointer(SecHandle* handle, void* pointer); +void* sspi_SecureHandleGetUpperPointer(SecHandle* handle); +void sspi_SecureHandleSetUpperPointer(SecHandle* handle, void* pointer); +void sspi_SecureHandleFree(SecHandle* handle); + +enum SecurityFunctionTableIndex +{ + EnumerateSecurityPackagesIndex = 1, + Reserved1Index = 2, + QueryCredentialsAttributesIndex = 3, + AcquireCredentialsHandleIndex = 4, + FreeCredentialsHandleIndex = 5, + Reserved2Index = 6, + InitializeSecurityContextIndex = 7, + AcceptSecurityContextIndex = 8, + CompleteAuthTokenIndex = 9, + DeleteSecurityContextIndex = 10, + ApplyControlTokenIndex = 11, + QueryContextAttributesIndex = 12, + ImpersonateSecurityContextIndex = 13, + RevertSecurityContextIndex = 14, + MakeSignatureIndex = 15, + VerifySignatureIndex = 16, + FreeContextBufferIndex = 17, + QuerySecurityPackageInfoIndex = 18, + Reserved3Index = 19, + Reserved4Index = 20, + ExportSecurityContextIndex = 21, + ImportSecurityContextIndex = 22, + AddCredentialsIndex = 23, + Reserved8Index = 24, + QuerySecurityContextTokenIndex = 25, + EncryptMessageIndex = 26, + DecryptMessageIndex = 27, + SetContextAttributesIndex = 28, + SetCredentialsAttributesIndex = 29 +}; + +BOOL IsSecurityStatusError(SECURITY_STATUS status); + +#include "sspi_gss.h" +#include "sspi_winpr.h" + +#endif /* WINPR_SSPI_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_export.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_export.c new file mode 100644 index 0000000000000000000000000000000000000000..32258cf5eb2d5ecbc040056a582671b784d55655 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_export.c @@ -0,0 +1,345 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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 +#include +#include + +#ifdef _WIN32 +#define SEC_ENTRY __stdcall +#define SSPI_EXPORT __declspec(dllexport) +#else +#include +#define SEC_ENTRY +#define SSPI_EXPORT WINPR_API +#endif + +#ifdef _WIN32 +typedef long LONG; +typedef unsigned long ULONG; +#endif +typedef LONG SECURITY_STATUS; + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_MISSING_PROTOTYPES + +#ifdef SSPI_DLL + +/** + * Standard SSPI API + */ + +/* Package Management */ + +extern SECURITY_STATUS SEC_ENTRY sspi_EnumerateSecurityPackagesW(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY EnumerateSecurityPackagesW(void* pcPackages, + void* ppPackageInfo) +{ + return sspi_EnumerateSecurityPackagesW(pcPackages, ppPackageInfo); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_EnumerateSecurityPackagesA(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY EnumerateSecurityPackagesA(void* pcPackages, + void* ppPackageInfo) +{ + return sspi_EnumerateSecurityPackagesA(pcPackages, ppPackageInfo); +} + +extern void* SEC_ENTRY sspi_InitSecurityInterfaceW(void); + +SSPI_EXPORT void* SEC_ENTRY InitSecurityInterfaceW(void) +{ + return sspi_InitSecurityInterfaceW(); +} + +extern void* SEC_ENTRY sspi_InitSecurityInterfaceA(void); + +SSPI_EXPORT void* SEC_ENTRY InitSecurityInterfaceA(void) +{ + return sspi_InitSecurityInterfaceA(); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoW(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QuerySecurityPackageInfoW(void* pszPackageName, + void* ppPackageInfo) +{ + return sspi_QuerySecurityPackageInfoW(pszPackageName, ppPackageInfo); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoA(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QuerySecurityPackageInfoA(void* pszPackageName, + void* ppPackageInfo) +{ + return sspi_QuerySecurityPackageInfoA(pszPackageName, ppPackageInfo); +} + +/* Credential Management */ + +extern SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleW(void*, void*, ULONG, void*, void*, + void*, void*, void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY AcquireCredentialsHandleW( + void* pszPrincipal, void* pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, + void* pGetKeyFn, void* pvGetKeyArgument, void* phCredential, void* ptsExpiry) +{ + return sspi_AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, + ptsExpiry); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleA(void*, void*, ULONG, void*, void*, + void*, void*, void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY AcquireCredentialsHandleA( + void* pszPrincipal, void* pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, + void* pGetKeyFn, void* pvGetKeyArgument, void* phCredential, void* ptsExpiry) +{ + return sspi_AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, + ptsExpiry); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_ExportSecurityContext(void*, ULONG, void*, void**); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY ExportSecurityContext(void* phContext, ULONG fFlags, + void* pPackedContext, void** pToken) +{ + return sspi_ExportSecurityContext(phContext, fFlags, pPackedContext, pToken); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_FreeCredentialsHandle(void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY FreeCredentialsHandle(void* phCredential) +{ + return sspi_FreeCredentialsHandle(phCredential); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_ImportSecurityContextW(void*, void*, void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY ImportSecurityContextW(void* pszPackage, void* pPackedContext, + void* pToken, void* phContext) +{ + return sspi_ImportSecurityContextW(pszPackage, pPackedContext, pToken, phContext); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_ImportSecurityContextA(void*, void*, void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY ImportSecurityContextA(void* pszPackage, void* pPackedContext, + void* pToken, void* phContext) +{ + return sspi_ImportSecurityContextA(pszPackage, pPackedContext, pToken, phContext); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QueryCredentialsAttributesW(void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesW(void* phCredential, + ULONG ulAttribute, void* pBuffer) +{ + return sspi_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QueryCredentialsAttributesA(void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesA(void* phCredential, + ULONG ulAttribute, void* pBuffer) +{ + return sspi_QueryCredentialsAttributesA(phCredential, ulAttribute, pBuffer); +} + +/* Context Management */ + +extern SECURITY_STATUS SEC_ENTRY sspi_AcceptSecurityContext(void*, void*, void*, ULONG, ULONG, + void*, void*, void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY AcceptSecurityContext(void* phCredential, void* phContext, + void* pInput, ULONG fContextReq, + ULONG TargetDataRep, void* phNewContext, + void* pOutput, void* pfContextAttr, + void* ptsTimeStamp) +{ + return sspi_AcceptSecurityContext(phCredential, phContext, pInput, fContextReq, TargetDataRep, + phNewContext, pOutput, pfContextAttr, ptsTimeStamp); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_ApplyControlToken(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY ApplyControlToken(void* phContext, void* pInput) +{ + return sspi_ApplyControlToken(phContext, pInput); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_CompleteAuthToken(void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY CompleteAuthToken(void* phContext, void* pToken) +{ + return sspi_CompleteAuthToken(phContext, pToken); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_DeleteSecurityContext(void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(void* phContext) +{ + return sspi_DeleteSecurityContext(phContext); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_FreeContextBuffer(void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY FreeContextBuffer(void* pvContextBuffer) +{ + return sspi_FreeContextBuffer(pvContextBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_ImpersonateSecurityContext(void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY ImpersonateSecurityContext(void* phContext) +{ + return sspi_ImpersonateSecurityContext(phContext); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextW(void*, void*, void*, ULONG, ULONG, + ULONG, void*, ULONG, void*, void*, + void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY InitializeSecurityContextW( + void* phCredential, void* phContext, void* pszTargetName, ULONG fContextReq, ULONG Reserved1, + ULONG TargetDataRep, void* pInput, ULONG Reserved2, void* phNewContext, void* pOutput, + void* pfContextAttr, void* ptsExpiry) +{ + return sspi_InitializeSecurityContextW(phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextA(void*, void*, void*, ULONG, ULONG, + ULONG, void*, ULONG, void*, void*, + void*, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY InitializeSecurityContextA( + void* phCredential, void* phContext, void* pszTargetName, ULONG fContextReq, ULONG Reserved1, + ULONG TargetDataRep, void* pInput, ULONG Reserved2, void* phNewContext, void* pOutput, + void* pfContextAttr, void* ptsExpiry) +{ + return sspi_InitializeSecurityContextA(phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QueryContextAttributesW(void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QueryContextAttributesW(void* phContext, ULONG ulAttribute, + void* pBuffer) +{ + return sspi_QueryContextAttributesW(phContext, ulAttribute, pBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QueryContextAttributesA(void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QueryContextAttributesA(void* phContext, ULONG ulAttribute, + void* pBuffer) +{ + return sspi_QueryContextAttributesA(phContext, ulAttribute, pBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityContextToken(void*, void**); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY QuerySecurityContextToken(void* phContext, void** phToken) +{ + return sspi_QuerySecurityContextToken(phContext, phToken); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_SetContextAttributesW(void*, ULONG, void*, ULONG); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY SetContextAttributesW(void* phContext, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return sspi_SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_SetContextAttributesA(void*, ULONG, void*, ULONG); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY SetContextAttributesA(void* phContext, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return sspi_SetContextAttributesA(phContext, ulAttribute, pBuffer, cbBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_SetCredentialsAttributesW(void*, ULONG, void*, ULONG); + +static SECURITY_STATUS SEC_ENTRY SetCredentialsAttributesW(void* phCredential, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return sspi_SetCredentialsAttributesW(phCredential, ulAttribute, pBuffer, cbBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_SetCredentialsAttributesA(void*, ULONG, void*, ULONG); + +static SECURITY_STATUS SEC_ENTRY SetCredentialsAttributesA(void* phCredential, ULONG ulAttribute, + void* pBuffer, ULONG cbBuffer) +{ + return sspi_SetCredentialsAttributesA(phCredential, ulAttribute, pBuffer, cbBuffer); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_RevertSecurityContext(void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY RevertSecurityContext(void* phContext) +{ + return sspi_RevertSecurityContext(phContext); +} + +/* Message Support */ + +extern SECURITY_STATUS SEC_ENTRY sspi_DecryptMessage(void*, void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY DecryptMessage(void* phContext, void* pMessage, + ULONG MessageSeqNo, void* pfQOP) +{ + return sspi_DecryptMessage(phContext, pMessage, MessageSeqNo, pfQOP); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_EncryptMessage(void*, ULONG, void*, ULONG); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY EncryptMessage(void* phContext, ULONG fQOP, void* pMessage, + ULONG MessageSeqNo) +{ + return sspi_EncryptMessage(phContext, fQOP, pMessage, MessageSeqNo); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_MakeSignature(void*, ULONG, void*, ULONG); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY MakeSignature(void* phContext, ULONG fQOP, void* pMessage, + ULONG MessageSeqNo) +{ + return sspi_MakeSignature(phContext, fQOP, pMessage, MessageSeqNo); +} + +extern SECURITY_STATUS SEC_ENTRY sspi_VerifySignature(void*, void*, ULONG, void*); + +SSPI_EXPORT SECURITY_STATUS SEC_ENTRY VerifySignature(void* phContext, void* pMessage, + ULONG MessageSeqNo, void* pfQOP) +{ + return sspi_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP); +} + +#endif /* SSPI_DLL */ + +WINPR_PRAGMA_DIAG_POP diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.c new file mode 100644 index 0000000000000000000000000000000000000000..26c3927dcf616acfae97f638aa1f4cd039e85aa7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.c @@ -0,0 +1,120 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Generic Security Service Application Program Interface (GSSAPI) + * + * Copyright 2015 ANSSI, Author Thomas Calderon + * Copyright 2015 Marc-Andre Moreau + * Copyright 2017 Dorian Ducournau + * + * 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 +#include +#include +#include +#include + +#include "sspi_gss.h" + +BOOL sspi_gss_wrap_token(SecBuffer* buf, const WinPrAsn1_OID* oid, uint16_t tok_id, + const sspi_gss_data* token) +{ + WinPrAsn1Encoder* enc = NULL; + BYTE tok_id_buf[2]; + WinPrAsn1_MemoryChunk mc = { 2, tok_id_buf }; + wStream s; + size_t len = 0; + BOOL ret = FALSE; + + WINPR_ASSERT(buf); + WINPR_ASSERT(oid); + WINPR_ASSERT(token); + + winpr_Data_Write_UINT16_BE(tok_id_buf, tok_id); + + enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER); + if (!enc) + return FALSE; + + /* initialContextToken [APPLICATION 0] */ + if (!WinPrAsn1EncAppContainer(enc, 0)) + goto cleanup; + + /* thisMech OID */ + if (!WinPrAsn1EncOID(enc, oid)) + goto cleanup; + + /* TOK_ID */ + if (!WinPrAsn1EncRawContent(enc, &mc)) + goto cleanup; + + /* innerToken */ + mc.data = (BYTE*)token->data; + mc.len = token->length; + if (!WinPrAsn1EncRawContent(enc, &mc)) + goto cleanup; + + if (!WinPrAsn1EncEndContainer(enc)) + goto cleanup; + + if (!WinPrAsn1EncStreamSize(enc, &len) || len > buf->cbBuffer) + goto cleanup; + + Stream_StaticInit(&s, buf->pvBuffer, len); + if (WinPrAsn1EncToStream(enc, &s)) + { + buf->cbBuffer = (UINT32)len; + ret = TRUE; + } + +cleanup: + WinPrAsn1Encoder_Free(&enc); + return ret; +} + +BOOL sspi_gss_unwrap_token(const SecBuffer* buf, WinPrAsn1_OID* oid, uint16_t* tok_id, + sspi_gss_data* token) +{ + WinPrAsn1Decoder dec; + WinPrAsn1Decoder dec2; + WinPrAsn1_tagId tag = 0; + wStream sbuffer = { 0 }; + wStream* s = NULL; + + WINPR_ASSERT(buf); + WINPR_ASSERT(oid); + WINPR_ASSERT(token); + + WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, buf->pvBuffer, buf->cbBuffer); + + if (!WinPrAsn1DecReadApp(&dec, &tag, &dec2) || tag != 0) + return FALSE; + + if (!WinPrAsn1DecReadOID(&dec2, oid, FALSE)) + return FALSE; + + sbuffer = WinPrAsn1DecGetStream(&dec2); + s = &sbuffer; + + if (Stream_Length(s) < 2) + return FALSE; + + if (tok_id) + Stream_Read_UINT16_BE(s, *tok_id); + + token->data = Stream_Pointer(s); + token->length = (UINT)Stream_GetRemainingLength(s); + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.h new file mode 100644 index 0000000000000000000000000000000000000000..205f86afb43725c3fe5d0a4a863997fad939fa05 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_gss.h @@ -0,0 +1,85 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Generic Security Service Application Program Interface (GSSAPI) + * + * Copyright 2015 ANSSI, Author Thomas Calderon + * Copyright 2015 Marc-Andre Moreau + * Copyright 2017 Dorian Ducournau + * + * 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_GSS_PRIVATE_H +#define WINPR_SSPI_GSS_PRIVATE_H + +#include +#include + +#ifdef WITH_KRB5_MIT +#include +typedef krb5_data sspi_gss_data; +#elif defined(WITH_KRB5_HEIMDAL) +#include +typedef krb5_data sspi_gss_data; +#else +typedef struct +{ + int32_t magic; + unsigned int length; + char* data; +} sspi_gss_data; +#endif + +#define SSPI_GSS_C_DELEG_FLAG 1 +#define SSPI_GSS_C_MUTUAL_FLAG 2 +#define SSPI_GSS_C_REPLAY_FLAG 4 +#define SSPI_GSS_C_SEQUENCE_FLAG 8 +#define SSPI_GSS_C_CONF_FLAG 16 +#define SSPI_GSS_C_INTEG_FLAG 32 + +#define FLAG_SENDER_IS_ACCEPTOR 0x01 +#define FLAG_WRAP_CONFIDENTIAL 0x02 +#define FLAG_ACCEPTOR_SUBKEY 0x04 + +#define KG_USAGE_ACCEPTOR_SEAL 22 +#define KG_USAGE_ACCEPTOR_SIGN 23 +#define KG_USAGE_INITIATOR_SEAL 24 +#define KG_USAGE_INITIATOR_SIGN 25 + +#define TOK_ID_AP_REQ 0x0100 +#define TOK_ID_AP_REP 0x0200 +#define TOK_ID_ERROR 0x0300 +#define TOK_ID_TGT_REQ 0x0400 +#define TOK_ID_TGT_REP 0x0401 + +#define TOK_ID_MIC 0x0404 +#define TOK_ID_WRAP 0x0504 +#define TOK_ID_MIC_V1 0x0101 +#define TOK_ID_WRAP_V1 0x0201 + +#define GSS_CHECKSUM_TYPE 0x8003 + +static INLINE BOOL sspi_gss_oid_compare(const WinPrAsn1_OID* oid1, const WinPrAsn1_OID* oid2) +{ + WINPR_ASSERT(oid1); + WINPR_ASSERT(oid2); + + return (oid1->len == oid2->len) && (memcmp(oid1->data, oid2->data, oid1->len) == 0); +} + +BOOL sspi_gss_wrap_token(SecBuffer* buf, const WinPrAsn1_OID* oid, uint16_t tok_id, + const sspi_gss_data* token); +BOOL sspi_gss_unwrap_token(const SecBuffer* buf, WinPrAsn1_OID* oid, uint16_t* tok_id, + sspi_gss_data* token); + +#endif /* WINPR_SSPI_GSS_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.c new file mode 100644 index 0000000000000000000000000000000000000000..3ff1f207cbb4036a37a2e949a3149a54663bc4b8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.c @@ -0,0 +1,2240 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * Copyright 2017 Dorian Ducournau + * + * 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 +#include +#include + +#include +#include +#include +#include + +#include "sspi.h" + +#include "sspi_winpr.h" + +#include "../log.h" +#define TAG WINPR_TAG("sspi") + +/* Authentication Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/aa374731/ */ + +#include "NTLM/ntlm.h" +#include "NTLM/ntlm_export.h" +#include "CredSSP/credssp.h" +#include "Kerberos/kerberos.h" +#include "Negotiate/negotiate.h" +#include "Schannel/schannel.h" + +static const SecPkgInfoA* SecPkgInfoA_LIST[] = { &NTLM_SecPkgInfoA, &KERBEROS_SecPkgInfoA, + &NEGOTIATE_SecPkgInfoA, &CREDSSP_SecPkgInfoA, + &SCHANNEL_SecPkgInfoA }; + +static const SecPkgInfoW* SecPkgInfoW_LIST[] = { &NTLM_SecPkgInfoW, &KERBEROS_SecPkgInfoW, + &NEGOTIATE_SecPkgInfoW, &CREDSSP_SecPkgInfoW, + &SCHANNEL_SecPkgInfoW }; + +static SecurityFunctionTableA winpr_SecurityFunctionTableA; +static SecurityFunctionTableW winpr_SecurityFunctionTableW; + +typedef struct +{ + const SEC_CHAR* Name; + const SecurityFunctionTableA* SecurityFunctionTable; +} SecurityFunctionTableA_NAME; + +typedef struct +{ + const SEC_WCHAR* Name; + const SecurityFunctionTableW* SecurityFunctionTable; +} SecurityFunctionTableW_NAME; + +static const SecurityFunctionTableA_NAME SecurityFunctionTableA_NAME_LIST[] = { + { "NTLM", &NTLM_SecurityFunctionTableA }, + { "Kerberos", &KERBEROS_SecurityFunctionTableA }, + { "Negotiate", &NEGOTIATE_SecurityFunctionTableA }, + { "CREDSSP", &CREDSSP_SecurityFunctionTableA }, + { "Schannel", &SCHANNEL_SecurityFunctionTableA } +}; + +static WCHAR BUFFER_NAME_LIST_W[5][32] = { 0 }; + +static const SecurityFunctionTableW_NAME SecurityFunctionTableW_NAME_LIST[] = { + { BUFFER_NAME_LIST_W[0], &NTLM_SecurityFunctionTableW }, + { BUFFER_NAME_LIST_W[1], &KERBEROS_SecurityFunctionTableW }, + { BUFFER_NAME_LIST_W[2], &NEGOTIATE_SecurityFunctionTableW }, + { BUFFER_NAME_LIST_W[3], &CREDSSP_SecurityFunctionTableW }, + { BUFFER_NAME_LIST_W[4], &SCHANNEL_SecurityFunctionTableW } +}; + +#define SecHandle_LOWER_MAX 0xFFFFFFFF +#define SecHandle_UPPER_MAX 0xFFFFFFFE + +typedef struct +{ + void* contextBuffer; + UINT32 allocatorIndex; +} CONTEXT_BUFFER_ALLOC_ENTRY; + +typedef struct +{ + UINT32 cEntries; + UINT32 cMaxEntries; + CONTEXT_BUFFER_ALLOC_ENTRY* entries; +} CONTEXT_BUFFER_ALLOC_TABLE; + +static CONTEXT_BUFFER_ALLOC_TABLE ContextBufferAllocTable = { 0 }; + +static int sspi_ContextBufferAllocTableNew(void) +{ + size_t size = 0; + ContextBufferAllocTable.entries = NULL; + ContextBufferAllocTable.cEntries = 0; + ContextBufferAllocTable.cMaxEntries = 4; + size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries; + ContextBufferAllocTable.entries = (CONTEXT_BUFFER_ALLOC_ENTRY*)calloc(1, size); + + if (!ContextBufferAllocTable.entries) + return -1; + + return 1; +} + +static int sspi_ContextBufferAllocTableGrow(void) +{ + size_t size = 0; + CONTEXT_BUFFER_ALLOC_ENTRY* entries = NULL; + ContextBufferAllocTable.cEntries = 0; + ContextBufferAllocTable.cMaxEntries *= 2; + size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries; + + if (!size) + return -1; + + entries = (CONTEXT_BUFFER_ALLOC_ENTRY*)realloc(ContextBufferAllocTable.entries, size); + + if (!entries) + { + free(ContextBufferAllocTable.entries); + return -1; + } + + ContextBufferAllocTable.entries = entries; + ZeroMemory((void*)&ContextBufferAllocTable.entries[ContextBufferAllocTable.cMaxEntries / 2], + size / 2); + return 1; +} + +static void sspi_ContextBufferAllocTableFree(void) +{ + if (ContextBufferAllocTable.cEntries != 0) + WLog_ERR(TAG, "ContextBufferAllocTable.entries == %" PRIu32, + ContextBufferAllocTable.cEntries); + + ContextBufferAllocTable.cEntries = ContextBufferAllocTable.cMaxEntries = 0; + free(ContextBufferAllocTable.entries); + ContextBufferAllocTable.entries = NULL; +} + +static void* sspi_ContextBufferAlloc(UINT32 allocatorIndex, size_t size) +{ + void* contextBuffer = NULL; + + for (UINT32 index = 0; index < ContextBufferAllocTable.cMaxEntries; index++) + { + if (!ContextBufferAllocTable.entries[index].contextBuffer) + { + contextBuffer = calloc(1, size); + + if (!contextBuffer) + return NULL; + + ContextBufferAllocTable.cEntries++; + ContextBufferAllocTable.entries[index].contextBuffer = contextBuffer; + ContextBufferAllocTable.entries[index].allocatorIndex = allocatorIndex; + return ContextBufferAllocTable.entries[index].contextBuffer; + } + } + + /* no available entry was found, the table needs to be grown */ + + if (sspi_ContextBufferAllocTableGrow() < 0) + return NULL; + + /* the next call to sspi_ContextBufferAlloc() should now succeed */ + return sspi_ContextBufferAlloc(allocatorIndex, size); +} + +SSPI_CREDENTIALS* sspi_CredentialsNew(void) +{ + SSPI_CREDENTIALS* credentials = NULL; + credentials = (SSPI_CREDENTIALS*)calloc(1, sizeof(SSPI_CREDENTIALS)); + return credentials; +} + +void sspi_CredentialsFree(SSPI_CREDENTIALS* credentials) +{ + size_t userLength = 0; + size_t domainLength = 0; + size_t passwordLength = 0; + + if (!credentials) + return; + + if (credentials->ntlmSettings.samFile) + free(credentials->ntlmSettings.samFile); + + userLength = credentials->identity.UserLength; + domainLength = credentials->identity.DomainLength; + passwordLength = credentials->identity.PasswordLength; + + if (passwordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) /* [pth] */ + passwordLength -= SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; + + if (credentials->identity.Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE) + { + userLength *= 2; + domainLength *= 2; + passwordLength *= 2; + } + + if (credentials->identity.User) + memset(credentials->identity.User, 0, userLength); + if (credentials->identity.Domain) + memset(credentials->identity.Domain, 0, domainLength); + if (credentials->identity.Password) + memset(credentials->identity.Password, 0, passwordLength); + free(credentials->identity.User); + free(credentials->identity.Domain); + free(credentials->identity.Password); + free(credentials); +} + +void* sspi_SecBufferAlloc(PSecBuffer SecBuffer, ULONG size) +{ + if (!SecBuffer) + return NULL; + + SecBuffer->pvBuffer = calloc(1, size); + + if (!SecBuffer->pvBuffer) + return NULL; + + SecBuffer->cbBuffer = size; + return SecBuffer->pvBuffer; +} + +void sspi_SecBufferFree(PSecBuffer SecBuffer) +{ + if (!SecBuffer) + return; + + if (SecBuffer->pvBuffer) + memset(SecBuffer->pvBuffer, 0, SecBuffer->cbBuffer); + + free(SecBuffer->pvBuffer); + SecBuffer->pvBuffer = NULL; + SecBuffer->cbBuffer = 0; +} + +SecHandle* sspi_SecureHandleAlloc(void) +{ + SecHandle* handle = (SecHandle*)calloc(1, sizeof(SecHandle)); + + if (!handle) + return NULL; + + SecInvalidateHandle(handle); + return handle; +} + +void* sspi_SecureHandleGetLowerPointer(SecHandle* handle) +{ + void* pointer = NULL; + + if (!handle || !SecIsValidHandle(handle) || !handle->dwLower) + return NULL; + + pointer = (void*)~((size_t)handle->dwLower); + return pointer; +} + +void sspi_SecureHandleInvalidate(SecHandle* handle) +{ + if (!handle) + return; + + handle->dwLower = 0; + handle->dwUpper = 0; +} + +void sspi_SecureHandleSetLowerPointer(SecHandle* handle, void* pointer) +{ + if (!handle) + return; + + handle->dwLower = (ULONG_PTR)(~((size_t)pointer)); +} + +void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) +{ + void* pointer = NULL; + + if (!handle || !SecIsValidHandle(handle) || !handle->dwUpper) + return NULL; + + pointer = (void*)~((size_t)handle->dwUpper); + return pointer; +} + +void sspi_SecureHandleSetUpperPointer(SecHandle* handle, void* pointer) +{ + if (!handle) + return; + + handle->dwUpper = (ULONG_PTR)(~((size_t)pointer)); +} + +void sspi_SecureHandleFree(SecHandle* handle) +{ + free(handle); +} + +int sspi_SetAuthIdentityW(SEC_WINNT_AUTH_IDENTITY* identity, const WCHAR* user, const WCHAR* domain, + const WCHAR* password) +{ + return sspi_SetAuthIdentityWithLengthW(identity, user, user ? _wcslen(user) : 0, domain, + domain ? _wcslen(domain) : 0, password, + password ? _wcslen(password) : 0); +} + +static BOOL copy(WCHAR** dst, ULONG* dstLen, const WCHAR* what, size_t len) +{ + WINPR_ASSERT(dst); + WINPR_ASSERT(dstLen); + + *dst = NULL; + *dstLen = 0; + + if (len > UINT32_MAX) + return FALSE; + + /* Case what="" and len=0 should allocate an empty string */ + if (!what && (len != 0)) + return FALSE; + if (!what && (len == 0)) + return TRUE; + + *dst = calloc(sizeof(WCHAR), len + 1); + if (!*dst) + return FALSE; + + memcpy(*dst, what, len * sizeof(WCHAR)); + *dstLen = WINPR_ASSERTING_INT_CAST(UINT32, len); + return TRUE; +} + +int sspi_SetAuthIdentityWithLengthW(SEC_WINNT_AUTH_IDENTITY* identity, const WCHAR* user, + size_t userLen, const WCHAR* domain, size_t domainLen, + const WCHAR* password, size_t passwordLen) +{ + WINPR_ASSERT(identity); + sspi_FreeAuthIdentity(identity); + identity->Flags &= (uint32_t)~SEC_WINNT_AUTH_IDENTITY_ANSI; + identity->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE; + + if (!copy(&identity->User, &identity->UserLength, user, userLen)) + return -1; + + if (!copy(&identity->Domain, &identity->DomainLength, domain, domainLen)) + return -1; + + if (!copy(&identity->Password, &identity->PasswordLength, password, passwordLen)) + return -1; + + return 1; +} + +static void zfree(WCHAR* str, size_t len) +{ + if (str) + memset(str, 0, len * sizeof(WCHAR)); + free(str); +} + +int sspi_SetAuthIdentityA(SEC_WINNT_AUTH_IDENTITY* identity, const char* user, const char* domain, + const char* password) +{ + int rc = 0; + size_t unicodeUserLenW = 0; + size_t unicodeDomainLenW = 0; + size_t unicodePasswordLenW = 0; + LPWSTR unicodeUser = NULL; + LPWSTR unicodeDomain = NULL; + LPWSTR unicodePassword = NULL; + + if (user) + unicodeUser = ConvertUtf8ToWCharAlloc(user, &unicodeUserLenW); + + if (domain) + unicodeDomain = ConvertUtf8ToWCharAlloc(domain, &unicodeDomainLenW); + + if (password) + unicodePassword = ConvertUtf8ToWCharAlloc(password, &unicodePasswordLenW); + + rc = sspi_SetAuthIdentityWithLengthW(identity, unicodeUser, unicodeUserLenW, unicodeDomain, + unicodeDomainLenW, unicodePassword, unicodePasswordLenW); + + zfree(unicodeUser, unicodeUserLenW); + zfree(unicodeDomain, unicodeDomainLenW); + zfree(unicodePassword, unicodePasswordLenW); + return rc; +} + +UINT32 sspi_GetAuthIdentityVersion(const void* identity) +{ + UINT32 version = 0; + + if (!identity) + return 0; + + version = *((const UINT32*)identity); + + if ((version == SEC_WINNT_AUTH_IDENTITY_VERSION) || + (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2)) + { + return version; + } + + return 0; // SEC_WINNT_AUTH_IDENTITY (no version) +} + +UINT32 sspi_GetAuthIdentityFlags(const void* identity) +{ + UINT32 version = 0; + UINT32 flags = 0; + + if (!identity) + return 0; + + version = sspi_GetAuthIdentityVersion(identity); + + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + flags = ((const SEC_WINNT_AUTH_IDENTITY_EX*)identity)->Flags; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + flags = ((const SEC_WINNT_AUTH_IDENTITY_EX2*)identity)->Flags; + } + else // SEC_WINNT_AUTH_IDENTITY + { + flags = ((const SEC_WINNT_AUTH_IDENTITY*)identity)->Flags; + } + + return flags; +} + +BOOL sspi_GetAuthIdentityUserDomainW(const void* identity, const WCHAR** pUser, UINT32* pUserLength, + const WCHAR** pDomain, UINT32* pDomainLength) +{ + UINT32 version = 0; + + if (!identity) + return FALSE; + + version = sspi_GetAuthIdentityVersion(identity); + + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXW* id = (const SEC_WINNT_AUTH_IDENTITY_EXW*)identity; + *pUser = (const WCHAR*)id->User; + *pUserLength = id->UserLength; + *pDomain = (const WCHAR*)id->Domain; + *pDomainLength = id->DomainLength; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + const SEC_WINNT_AUTH_IDENTITY_EX2* id = (const SEC_WINNT_AUTH_IDENTITY_EX2*)identity; + UINT32 UserOffset = id->UserOffset; + UINT32 DomainOffset = id->DomainOffset; + *pUser = (const WCHAR*)&((const uint8_t*)identity)[UserOffset]; + *pUserLength = id->UserLength / 2; + *pDomain = (const WCHAR*)&((const uint8_t*)identity)[DomainOffset]; + *pDomainLength = id->DomainLength / 2; + } + else // SEC_WINNT_AUTH_IDENTITY + { + const SEC_WINNT_AUTH_IDENTITY_W* id = (const SEC_WINNT_AUTH_IDENTITY_W*)identity; + *pUser = (const WCHAR*)id->User; + *pUserLength = id->UserLength; + *pDomain = (const WCHAR*)id->Domain; + *pDomainLength = id->DomainLength; + } + + return TRUE; +} + +BOOL sspi_GetAuthIdentityUserDomainA(const void* identity, const char** pUser, UINT32* pUserLength, + const char** pDomain, UINT32* pDomainLength) +{ + UINT32 version = 0; + + if (!identity) + return FALSE; + + version = sspi_GetAuthIdentityVersion(identity); + + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXA* id = (const SEC_WINNT_AUTH_IDENTITY_EXA*)identity; + *pUser = (const char*)id->User; + *pUserLength = id->UserLength; + *pDomain = (const char*)id->Domain; + *pDomainLength = id->DomainLength; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + const SEC_WINNT_AUTH_IDENTITY_EX2* id = (const SEC_WINNT_AUTH_IDENTITY_EX2*)identity; + UINT32 UserOffset = id->UserOffset; + UINT32 DomainOffset = id->DomainOffset; + *pUser = (const char*)&((const uint8_t*)identity)[UserOffset]; + *pUserLength = id->UserLength; + *pDomain = (const char*)&((const uint8_t*)identity)[DomainOffset]; + *pDomainLength = id->DomainLength; + } + else // SEC_WINNT_AUTH_IDENTITY + { + const SEC_WINNT_AUTH_IDENTITY_A* id = (const SEC_WINNT_AUTH_IDENTITY_A*)identity; + *pUser = (const char*)id->User; + *pUserLength = id->UserLength; + *pDomain = (const char*)id->Domain; + *pDomainLength = id->DomainLength; + } + + return TRUE; +} + +BOOL sspi_GetAuthIdentityPasswordW(const void* identity, const WCHAR** pPassword, + UINT32* pPasswordLength) +{ + UINT32 version = 0; + + if (!identity) + return FALSE; + + version = sspi_GetAuthIdentityVersion(identity); + + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXW* id = (const SEC_WINNT_AUTH_IDENTITY_EXW*)identity; + *pPassword = (const WCHAR*)id->Password; + *pPasswordLength = id->PasswordLength; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + return FALSE; // TODO: packed credentials + } + else // SEC_WINNT_AUTH_IDENTITY + { + const SEC_WINNT_AUTH_IDENTITY_W* id = (const SEC_WINNT_AUTH_IDENTITY_W*)identity; + *pPassword = (const WCHAR*)id->Password; + *pPasswordLength = id->PasswordLength; + } + + return TRUE; +} + +BOOL sspi_GetAuthIdentityPasswordA(const void* identity, const char** pPassword, + UINT32* pPasswordLength) +{ + UINT32 version = 0; + + if (!identity) + return FALSE; + + version = sspi_GetAuthIdentityVersion(identity); + + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXA* id = (const SEC_WINNT_AUTH_IDENTITY_EXA*)identity; + *pPassword = (const char*)id->Password; + *pPasswordLength = id->PasswordLength; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + return FALSE; // TODO: packed credentials + } + else // SEC_WINNT_AUTH_IDENTITY + { + const SEC_WINNT_AUTH_IDENTITY_A* id = (const SEC_WINNT_AUTH_IDENTITY_A*)identity; + *pPassword = (const char*)id->Password; + *pPasswordLength = id->PasswordLength; + } + + return TRUE; +} + +BOOL sspi_CopyAuthIdentityFieldsA(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, char** pUser, + char** pDomain, char** pPassword) +{ + BOOL success = FALSE; + const char* UserA = NULL; + const char* DomainA = NULL; + const char* PasswordA = NULL; + const WCHAR* UserW = NULL; + const WCHAR* DomainW = NULL; + const WCHAR* PasswordW = NULL; + UINT32 UserLength = 0; + UINT32 DomainLength = 0; + UINT32 PasswordLength = 0; + + if (!identity || !pUser || !pDomain || !pPassword) + return FALSE; + + *pUser = *pDomain = *pPassword = NULL; + + UINT32 identityFlags = sspi_GetAuthIdentityFlags(identity); + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_ANSI) + { + if (!sspi_GetAuthIdentityUserDomainA(identity, &UserA, &UserLength, &DomainA, + &DomainLength)) + goto cleanup; + + if (!sspi_GetAuthIdentityPasswordA(identity, &PasswordA, &PasswordLength)) + goto cleanup; + + if (UserA && UserLength) + { + *pUser = _strdup(UserA); + + if (!(*pUser)) + goto cleanup; + } + + if (DomainA && DomainLength) + { + *pDomain = _strdup(DomainA); + + if (!(*pDomain)) + goto cleanup; + } + + if (PasswordA && PasswordLength) + { + *pPassword = _strdup(PasswordA); + + if (!(*pPassword)) + goto cleanup; + } + + success = TRUE; + } + else + { + if (!sspi_GetAuthIdentityUserDomainW(identity, &UserW, &UserLength, &DomainW, + &DomainLength)) + goto cleanup; + + if (!sspi_GetAuthIdentityPasswordW(identity, &PasswordW, &PasswordLength)) + goto cleanup; + + if (UserW && (UserLength > 0)) + { + *pUser = ConvertWCharNToUtf8Alloc(UserW, UserLength, NULL); + if (!(*pUser)) + goto cleanup; + } + + if (DomainW && (DomainLength > 0)) + { + *pDomain = ConvertWCharNToUtf8Alloc(DomainW, DomainLength, NULL); + if (!(*pDomain)) + goto cleanup; + } + + if (PasswordW && (PasswordLength > 0)) + { + *pPassword = ConvertWCharNToUtf8Alloc(PasswordW, PasswordLength, NULL); + if (!(*pPassword)) + goto cleanup; + } + + success = TRUE; + } + +cleanup: + return success; +} + +BOOL sspi_CopyAuthIdentityFieldsW(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, WCHAR** pUser, + WCHAR** pDomain, WCHAR** pPassword) +{ + BOOL success = FALSE; + const char* UserA = NULL; + const char* DomainA = NULL; + const char* PasswordA = NULL; + const WCHAR* UserW = NULL; + const WCHAR* DomainW = NULL; + const WCHAR* PasswordW = NULL; + UINT32 UserLength = 0; + UINT32 DomainLength = 0; + UINT32 PasswordLength = 0; + + if (!identity || !pUser || !pDomain || !pPassword) + return FALSE; + + *pUser = *pDomain = *pPassword = NULL; + + UINT32 identityFlags = sspi_GetAuthIdentityFlags(identity); + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_ANSI) + { + if (!sspi_GetAuthIdentityUserDomainA(identity, &UserA, &UserLength, &DomainA, + &DomainLength)) + goto cleanup; + + if (!sspi_GetAuthIdentityPasswordA(identity, &PasswordA, &PasswordLength)) + goto cleanup; + + if (UserA && (UserLength > 0)) + { + WCHAR* ptr = ConvertUtf8NToWCharAlloc(UserA, UserLength, NULL); + *pUser = ptr; + + if (!ptr) + goto cleanup; + } + + if (DomainA && (DomainLength > 0)) + { + WCHAR* ptr = ConvertUtf8NToWCharAlloc(DomainA, DomainLength, NULL); + *pDomain = ptr; + if (!ptr) + goto cleanup; + } + + if (PasswordA && (PasswordLength > 0)) + { + WCHAR* ptr = ConvertUtf8NToWCharAlloc(PasswordA, PasswordLength, NULL); + + *pPassword = ptr; + if (!ptr) + goto cleanup; + } + + success = TRUE; + } + else + { + if (!sspi_GetAuthIdentityUserDomainW(identity, &UserW, &UserLength, &DomainW, + &DomainLength)) + goto cleanup; + + if (!sspi_GetAuthIdentityPasswordW(identity, &PasswordW, &PasswordLength)) + goto cleanup; + + if (UserW && UserLength) + { + *pUser = _wcsdup(UserW); + + if (!(*pUser)) + goto cleanup; + } + + if (DomainW && DomainLength) + { + *pDomain = _wcsdup(DomainW); + + if (!(*pDomain)) + goto cleanup; + } + + if (PasswordW && PasswordLength) + { + *pPassword = _wcsdup(PasswordW); + + if (!(*pPassword)) + goto cleanup; + } + + success = TRUE; + } + +cleanup: + return success; +} + +BOOL sspi_CopyAuthPackageListA(const SEC_WINNT_AUTH_IDENTITY_INFO* identity, char** pPackageList) +{ + UINT32 version = 0; + UINT32 identityFlags = 0; + char* PackageList = NULL; + const char* PackageListA = NULL; + const WCHAR* PackageListW = NULL; + UINT32 PackageListLength = 0; + UINT32 PackageListOffset = 0; + const void* pAuthData = (const void*)identity; + + if (!pAuthData) + return FALSE; + + version = sspi_GetAuthIdentityVersion(pAuthData); + identityFlags = sspi_GetAuthIdentityFlags(pAuthData); + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_ANSI) + { + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXA* ad = (const SEC_WINNT_AUTH_IDENTITY_EXA*)pAuthData; + PackageListA = (const char*)ad->PackageList; + PackageListLength = ad->PackageListLength; + } + + if (PackageListA && PackageListLength) + { + PackageList = _strdup(PackageListA); + } + } + else + { + if (version == SEC_WINNT_AUTH_IDENTITY_VERSION) + { + const SEC_WINNT_AUTH_IDENTITY_EXW* ad = (const SEC_WINNT_AUTH_IDENTITY_EXW*)pAuthData; + PackageListW = (const WCHAR*)ad->PackageList; + PackageListLength = ad->PackageListLength; + } + else if (version == SEC_WINNT_AUTH_IDENTITY_VERSION_2) + { + const SEC_WINNT_AUTH_IDENTITY_EX2* ad = (const SEC_WINNT_AUTH_IDENTITY_EX2*)pAuthData; + PackageListOffset = ad->PackageListOffset; + PackageListW = (const WCHAR*)&((const uint8_t*)pAuthData)[PackageListOffset]; + PackageListLength = ad->PackageListLength / 2; + } + + if (PackageListW && (PackageListLength > 0)) + PackageList = ConvertWCharNToUtf8Alloc(PackageListW, PackageListLength, NULL); + } + + if (PackageList) + { + *pPackageList = PackageList; + return TRUE; + } + + return FALSE; +} + +int sspi_CopyAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, + const SEC_WINNT_AUTH_IDENTITY_INFO* srcIdentity) +{ + int status = 0; + UINT32 identityFlags = 0; + const char* UserA = NULL; + const char* DomainA = NULL; + const char* PasswordA = NULL; + const WCHAR* UserW = NULL; + const WCHAR* DomainW = NULL; + const WCHAR* PasswordW = NULL; + UINT32 UserLength = 0; + UINT32 DomainLength = 0; + UINT32 PasswordLength = 0; + + sspi_FreeAuthIdentity(identity); + + identityFlags = sspi_GetAuthIdentityFlags(srcIdentity); + + identity->Flags = identityFlags; + + if (identityFlags & SEC_WINNT_AUTH_IDENTITY_ANSI) + { + if (!sspi_GetAuthIdentityUserDomainA(srcIdentity, &UserA, &UserLength, &DomainA, + &DomainLength)) + { + return -1; + } + + if (!sspi_GetAuthIdentityPasswordA(srcIdentity, &PasswordA, &PasswordLength)) + { + return -1; + } + + status = sspi_SetAuthIdentity(identity, UserA, DomainA, PasswordA); + + if (status <= 0) + return -1; + + identity->Flags &= (uint32_t)~SEC_WINNT_AUTH_IDENTITY_ANSI; + identity->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE; + return 1; + } + + identity->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE; + + if (!sspi_GetAuthIdentityUserDomainW(srcIdentity, &UserW, &UserLength, &DomainW, &DomainLength)) + { + return -1; + } + + if (!sspi_GetAuthIdentityPasswordW(srcIdentity, &PasswordW, &PasswordLength)) + { + return -1; + } + + /* login/password authentication */ + identity->UserLength = UserLength; + + if (identity->UserLength > 0) + { + identity->User = (UINT16*)calloc((identity->UserLength + 1), sizeof(WCHAR)); + + if (!identity->User) + return -1; + + CopyMemory(identity->User, UserW, identity->UserLength * sizeof(WCHAR)); + identity->User[identity->UserLength] = 0; + } + + identity->DomainLength = DomainLength; + + if (identity->DomainLength > 0) + { + identity->Domain = (UINT16*)calloc((identity->DomainLength + 1), sizeof(WCHAR)); + + if (!identity->Domain) + return -1; + + CopyMemory(identity->Domain, DomainW, identity->DomainLength * sizeof(WCHAR)); + identity->Domain[identity->DomainLength] = 0; + } + + identity->PasswordLength = PasswordLength; + + if (identity->PasswordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) + identity->PasswordLength -= SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; + + if (PasswordW) + { + identity->Password = (UINT16*)calloc((identity->PasswordLength + 1), sizeof(WCHAR)); + + if (!identity->Password) + return -1; + + CopyMemory(identity->Password, PasswordW, identity->PasswordLength * sizeof(WCHAR)); + identity->Password[identity->PasswordLength] = 0; + } + + identity->PasswordLength = PasswordLength; + /* End of login/password authentication */ + return 1; +} + +PSecBuffer sspi_FindSecBuffer(PSecBufferDesc pMessage, ULONG BufferType) +{ + PSecBuffer pSecBuffer = NULL; + + for (UINT32 index = 0; index < pMessage->cBuffers; index++) + { + if (pMessage->pBuffers[index].BufferType == BufferType) + { + pSecBuffer = &pMessage->pBuffers[index]; + break; + } + } + + return pSecBuffer; +} + +static BOOL WINPR_init(void) +{ + + for (size_t x = 0; x < ARRAYSIZE(SecurityFunctionTableA_NAME_LIST); x++) + { + const SecurityFunctionTableA_NAME* cur = &SecurityFunctionTableA_NAME_LIST[x]; + InitializeConstWCharFromUtf8(cur->Name, BUFFER_NAME_LIST_W[x], + ARRAYSIZE(BUFFER_NAME_LIST_W[x])); + } + return TRUE; +} + +static BOOL CALLBACK sspi_init(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context) +{ + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + sspi_ContextBufferAllocTableNew(); + if (!SCHANNEL_init()) + return FALSE; + if (!KERBEROS_init()) + return FALSE; + if (!NTLM_init()) + return FALSE; + if (!CREDSSP_init()) + return FALSE; + if (!NEGOTIATE_init()) + return FALSE; + return WINPR_init(); +} + +void sspi_GlobalInit(void) +{ + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + DWORD flags = 0; + InitOnceExecuteOnce(&once, sspi_init, &flags, NULL); +} + +void sspi_GlobalFinish(void) +{ + sspi_ContextBufferAllocTableFree(); +} + +static const SecurityFunctionTableA* sspi_GetSecurityFunctionTableAByNameA(const SEC_CHAR* Name) +{ + size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); + + for (size_t index = 0; index < cPackages; index++) + { + if (strcmp(Name, SecurityFunctionTableA_NAME_LIST[index].Name) == 0) + { + return SecurityFunctionTableA_NAME_LIST[index].SecurityFunctionTable; + } + } + + return NULL; +} + +static const SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameW(const SEC_WCHAR* Name) +{ + size_t cPackages = ARRAYSIZE(SecPkgInfoW_LIST); + + for (size_t index = 0; index < cPackages; index++) + { + if (_wcscmp(Name, SecurityFunctionTableW_NAME_LIST[index].Name) == 0) + { + return SecurityFunctionTableW_NAME_LIST[index].SecurityFunctionTable; + } + } + + return NULL; +} + +static const SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameA(const SEC_CHAR* Name) +{ + SEC_WCHAR* NameW = NULL; + const SecurityFunctionTableW* table = NULL; + + if (!Name) + return NULL; + + NameW = ConvertUtf8ToWCharAlloc(Name, NULL); + + if (!NameW) + return NULL; + + table = sspi_GetSecurityFunctionTableWByNameW(NameW); + free(NameW); + return table; +} + +static void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer); +static void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer); + +static void sspi_ContextBufferFree(void* contextBuffer) +{ + UINT32 allocatorIndex = 0; + + for (size_t index = 0; index < ContextBufferAllocTable.cMaxEntries; index++) + { + if (contextBuffer == ContextBufferAllocTable.entries[index].contextBuffer) + { + contextBuffer = ContextBufferAllocTable.entries[index].contextBuffer; + allocatorIndex = ContextBufferAllocTable.entries[index].allocatorIndex; + ContextBufferAllocTable.cEntries--; + ContextBufferAllocTable.entries[index].allocatorIndex = 0; + ContextBufferAllocTable.entries[index].contextBuffer = NULL; + + switch (allocatorIndex) + { + case EnumerateSecurityPackagesIndex: + FreeContextBuffer_EnumerateSecurityPackages(contextBuffer); + break; + + case QuerySecurityPackageInfoIndex: + FreeContextBuffer_QuerySecurityPackageInfo(contextBuffer); + break; + default: + break; + } + } + } +} + +/** + * Standard SSPI API + */ + +/* Package Management */ + +static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPackages, + PSecPkgInfoW* ppPackageInfo) +{ + const size_t cPackages = ARRAYSIZE(SecPkgInfoW_LIST); + const size_t size = sizeof(SecPkgInfoW) * cPackages; + SecPkgInfoW* pPackageInfo = + (SecPkgInfoW*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); + + WINPR_ASSERT(cPackages <= UINT32_MAX); + + if (!pPackageInfo) + return SEC_E_INSUFFICIENT_MEMORY; + + for (size_t index = 0; index < cPackages; index++) + { + pPackageInfo[index].fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities; + pPackageInfo[index].wVersion = SecPkgInfoW_LIST[index]->wVersion; + pPackageInfo[index].wRPCID = SecPkgInfoW_LIST[index]->wRPCID; + pPackageInfo[index].cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken; + pPackageInfo[index].Name = _wcsdup(SecPkgInfoW_LIST[index]->Name); + pPackageInfo[index].Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment); + } + + *(pcPackages) = (UINT32)cPackages; + *(ppPackageInfo) = pPackageInfo; + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPackages, + PSecPkgInfoA* ppPackageInfo) +{ + const size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); + const size_t size = sizeof(SecPkgInfoA) * cPackages; + SecPkgInfoA* pPackageInfo = + (SecPkgInfoA*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); + + WINPR_ASSERT(cPackages <= UINT32_MAX); + + if (!pPackageInfo) + return SEC_E_INSUFFICIENT_MEMORY; + + for (size_t index = 0; index < cPackages; index++) + { + pPackageInfo[index].fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities; + pPackageInfo[index].wVersion = SecPkgInfoA_LIST[index]->wVersion; + pPackageInfo[index].wRPCID = SecPkgInfoA_LIST[index]->wRPCID; + pPackageInfo[index].cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; + pPackageInfo[index].Name = _strdup(SecPkgInfoA_LIST[index]->Name); + pPackageInfo[index].Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); + + if (!pPackageInfo[index].Name || !pPackageInfo[index].Comment) + { + sspi_ContextBufferFree(pPackageInfo); + return SEC_E_INSUFFICIENT_MEMORY; + } + } + + *(pcPackages) = (UINT32)cPackages; + *(ppPackageInfo) = pPackageInfo; + return SEC_E_OK; +} + +static void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer) +{ + SecPkgInfoA* pPackageInfo = (SecPkgInfoA*)contextBuffer; + size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); + + if (!pPackageInfo) + return; + + for (size_t index = 0; index < cPackages; index++) + { + free(pPackageInfo[index].Name); + free(pPackageInfo[index].Comment); + } + + free(pPackageInfo); +} + +SecurityFunctionTableW* SEC_ENTRY winpr_InitSecurityInterfaceW(void) +{ + return &winpr_SecurityFunctionTableW; +} + +SecurityFunctionTableA* SEC_ENTRY winpr_InitSecurityInterfaceA(void) +{ + return &winpr_SecurityFunctionTableA; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, + PSecPkgInfoW* ppPackageInfo) +{ + size_t cPackages = ARRAYSIZE(SecPkgInfoW_LIST); + + for (size_t index = 0; index < cPackages; index++) + { + if (_wcscmp(pszPackageName, SecPkgInfoW_LIST[index]->Name) == 0) + { + size_t size = sizeof(SecPkgInfoW); + SecPkgInfoW* pPackageInfo = + (SecPkgInfoW*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size); + + if (!pPackageInfo) + return SEC_E_INSUFFICIENT_MEMORY; + + pPackageInfo->fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities; + pPackageInfo->wVersion = SecPkgInfoW_LIST[index]->wVersion; + pPackageInfo->wRPCID = SecPkgInfoW_LIST[index]->wRPCID; + pPackageInfo->cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken; + pPackageInfo->Name = _wcsdup(SecPkgInfoW_LIST[index]->Name); + pPackageInfo->Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment); + *(ppPackageInfo) = pPackageInfo; + return SEC_E_OK; + } + } + + *(ppPackageInfo) = NULL; + return SEC_E_SECPKG_NOT_FOUND; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageName, + PSecPkgInfoA* ppPackageInfo) +{ + size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); + + for (size_t index = 0; index < cPackages; index++) + { + if (strcmp(pszPackageName, SecPkgInfoA_LIST[index]->Name) == 0) + { + size_t size = sizeof(SecPkgInfoA); + SecPkgInfoA* pPackageInfo = + (SecPkgInfoA*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size); + + if (!pPackageInfo) + return SEC_E_INSUFFICIENT_MEMORY; + + pPackageInfo->fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities; + pPackageInfo->wVersion = SecPkgInfoA_LIST[index]->wVersion; + pPackageInfo->wRPCID = SecPkgInfoA_LIST[index]->wRPCID; + pPackageInfo->cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; + pPackageInfo->Name = _strdup(SecPkgInfoA_LIST[index]->Name); + pPackageInfo->Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); + + if (!pPackageInfo->Name || !pPackageInfo->Comment) + { + sspi_ContextBufferFree(pPackageInfo); + return SEC_E_INSUFFICIENT_MEMORY; + } + + *(ppPackageInfo) = pPackageInfo; + return SEC_E_OK; + } + } + + *(ppPackageInfo) = NULL; + return SEC_E_SECPKG_NOT_FOUND; +} + +void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer) +{ + SecPkgInfo* pPackageInfo = (SecPkgInfo*)contextBuffer; + + if (!pPackageInfo) + return; + + free(pPackageInfo->Name); + free(pPackageInfo->Comment); + free(pPackageInfo); +} + +/* Credential Management */ + +static SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleW( + SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = sspi_GetSecurityFunctionTableWByNameW(pszPackage); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->AcquireCredentialsHandleW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, + ptsExpiry); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "AcquireCredentialsHandleW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleA( + SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, + void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, + PTimeStamp ptsExpiry) +{ + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = sspi_GetSecurityFunctionTableAByNameA(pszPackage); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->AcquireCredentialsHandleA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, + pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, + ptsExpiry); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "AcquireCredentialsHandleA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_ExportSecurityContext(PCtxtHandle phContext, ULONG fFlags, + PSecBuffer pPackedContext, + HANDLE* pToken) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->ExportSecurityContext) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->ExportSecurityContext(phContext, fFlags, pPackedContext, pToken); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "ExportSecurityContext status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_FreeCredentialsHandle(PCredHandle phCredential) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->FreeCredentialsHandle) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->FreeCredentialsHandle(phCredential); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "FreeCredentialsHandle status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextW(SEC_WCHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, PCtxtHandle phContext) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->ImportSecurityContextW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->ImportSecurityContextW(pszPackage, pPackedContext, pToken, phContext); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "ImportSecurityContextW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextA(SEC_CHAR* pszPackage, + PSecBuffer pPackedContext, + HANDLE pToken, PCtxtHandle phContext) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->ImportSecurityContextA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->ImportSecurityContextA(pszPackage, pPackedContext, pToken, phContext); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "ImportSecurityContextA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + SEC_WCHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_WCHAR*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameW(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->QueryCredentialsAttributesW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "QueryCredentialsAttributesW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->QueryCredentialsAttributesA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->QueryCredentialsAttributesA(phCredential, ulAttribute, pBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "QueryCredentialsAttributesA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_SetCredentialsAttributesW(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + SEC_WCHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_WCHAR*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameW(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->SetCredentialsAttributesW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->SetCredentialsAttributesW(phCredential, ulAttribute, pBuffer, cbBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "SetCredentialsAttributesW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_SetCredentialsAttributesA(PCredHandle phCredential, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->SetCredentialsAttributesA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->SetCredentialsAttributesA(phCredential, ulAttribute, pBuffer, cbBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "SetCredentialsAttributesA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +/* Context Management */ + +static SECURITY_STATUS SEC_ENTRY +winpr_AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, + ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->AcceptSecurityContext) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = + table->AcceptSecurityContext(phCredential, phContext, pInput, fContextReq, TargetDataRep, + phNewContext, pOutput, pfContextAttr, ptsTimeStamp); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "AcceptSecurityContext status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_ApplyControlToken(PCtxtHandle phContext, + PSecBufferDesc pInput) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->ApplyControlToken) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->ApplyControlToken(phContext, pInput); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "ApplyControlToken status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_CompleteAuthToken(PCtxtHandle phContext, + PSecBufferDesc pToken) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->CompleteAuthToken) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->CompleteAuthToken(phContext, pToken); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "CompleteAuthToken status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_DeleteSecurityContext(PCtxtHandle phContext) +{ + const char* Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + const SecurityFunctionTableA* table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->DeleteSecurityContext) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + const SECURITY_STATUS status = table->DeleteSecurityContext(phContext); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "DeleteSecurityContext status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_FreeContextBuffer(void* pvContextBuffer) +{ + if (!pvContextBuffer) + return SEC_E_INVALID_HANDLE; + + sspi_ContextBufferFree(pvContextBuffer); + return SEC_E_OK; +} + +static SECURITY_STATUS SEC_ENTRY winpr_ImpersonateSecurityContext(PCtxtHandle phContext) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->ImpersonateSecurityContext) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->ImpersonateSecurityContext(phContext); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "ImpersonateSecurityContext status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextW( + PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->InitializeSecurityContextW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->InitializeSecurityContextW(phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "InitializeSecurityContextW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextA( + PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, + ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phCredential); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->InitializeSecurityContextA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->InitializeSecurityContextA(phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "InitializeSecurityContextA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->QueryContextAttributesW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->QueryContextAttributesW(phContext, ulAttribute, pBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "QueryContextAttributesW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->QueryContextAttributesA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->QueryContextAttributesA(phContext, ulAttribute, pBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "QueryContextAttributesA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityContextToken(PCtxtHandle phContext, + HANDLE* phToken) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->QuerySecurityContextToken) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->QuerySecurityContextToken(phContext, phToken); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "QuerySecurityContextToken status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesW(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->SetContextAttributesW) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "SetContextAttributesW status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesA(PCtxtHandle phContext, + ULONG ulAttribute, void* pBuffer, + ULONG cbBuffer) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->SetContextAttributesA) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->SetContextAttributesA(phContext, ulAttribute, pBuffer, cbBuffer); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "SetContextAttributesA status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_RevertSecurityContext(PCtxtHandle phContext) +{ + SEC_CHAR* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableW* table = NULL; + Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableWByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->RevertSecurityContext) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->RevertSecurityContext(phContext); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "RevertSecurityContext status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +/* Message Support */ + +static SECURITY_STATUS SEC_ENTRY winpr_DecryptMessage(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->DecryptMessage) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->DecryptMessage(phContext, pMessage, MessageSeqNo, pfQOP); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "DecryptMessage status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->EncryptMessage) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->EncryptMessage(phContext, fQOP, pMessage, MessageSeqNo); + + if (status != SEC_E_OK) + { + WLog_ERR(TAG, "EncryptMessage status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), + status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_MakeSignature(PCtxtHandle phContext, ULONG fQOP, + PSecBufferDesc pMessage, ULONG MessageSeqNo) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->MakeSignature) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->MakeSignature(phContext, fQOP, pMessage, MessageSeqNo); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "MakeSignature status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), + status); + } + + return status; +} + +static SECURITY_STATUS SEC_ENTRY winpr_VerifySignature(PCtxtHandle phContext, + PSecBufferDesc pMessage, ULONG MessageSeqNo, + PULONG pfQOP) +{ + char* Name = NULL; + SECURITY_STATUS status = 0; + const SecurityFunctionTableA* table = NULL; + Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); + + if (!Name) + return SEC_E_SECPKG_NOT_FOUND; + + table = sspi_GetSecurityFunctionTableAByNameA(Name); + + if (!table) + return SEC_E_SECPKG_NOT_FOUND; + + if (!table->VerifySignature) + { + WLog_WARN(TAG, "Security module does not provide an implementation"); + return SEC_E_UNSUPPORTED_FUNCTION; + } + + status = table->VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP); + + if (IsSecurityStatusError(status)) + { + WLog_WARN(TAG, "VerifySignature status %s [0x%08" PRIX32 "]", + GetSecurityStatusString(status), status); + } + + return status; +} + +static SecurityFunctionTableA winpr_SecurityFunctionTableA = { + 3, /* dwVersion */ + winpr_EnumerateSecurityPackagesA, /* EnumerateSecurityPackages */ + winpr_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ + winpr_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ + winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + winpr_InitializeSecurityContextA, /* InitializeSecurityContext */ + winpr_AcceptSecurityContext, /* AcceptSecurityContext */ + winpr_CompleteAuthToken, /* CompleteAuthToken */ + winpr_DeleteSecurityContext, /* DeleteSecurityContext */ + winpr_ApplyControlToken, /* ApplyControlToken */ + winpr_QueryContextAttributesA, /* QueryContextAttributes */ + winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + winpr_RevertSecurityContext, /* RevertSecurityContext */ + winpr_MakeSignature, /* MakeSignature */ + winpr_VerifySignature, /* VerifySignature */ + winpr_FreeContextBuffer, /* FreeContextBuffer */ + winpr_QuerySecurityPackageInfoA, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + winpr_ExportSecurityContext, /* ExportSecurityContext */ + winpr_ImportSecurityContextA, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */ + winpr_EncryptMessage, /* EncryptMessage */ + winpr_DecryptMessage, /* DecryptMessage */ + winpr_SetContextAttributesA, /* SetContextAttributes */ + winpr_SetCredentialsAttributesA, /* SetCredentialsAttributes */ +}; + +static SecurityFunctionTableW winpr_SecurityFunctionTableW = { + 3, /* dwVersion */ + winpr_EnumerateSecurityPackagesW, /* EnumerateSecurityPackages */ + winpr_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ + winpr_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ + winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */ + NULL, /* Reserved2 */ + winpr_InitializeSecurityContextW, /* InitializeSecurityContext */ + winpr_AcceptSecurityContext, /* AcceptSecurityContext */ + winpr_CompleteAuthToken, /* CompleteAuthToken */ + winpr_DeleteSecurityContext, /* DeleteSecurityContext */ + winpr_ApplyControlToken, /* ApplyControlToken */ + winpr_QueryContextAttributesW, /* QueryContextAttributes */ + winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ + winpr_RevertSecurityContext, /* RevertSecurityContext */ + winpr_MakeSignature, /* MakeSignature */ + winpr_VerifySignature, /* VerifySignature */ + winpr_FreeContextBuffer, /* FreeContextBuffer */ + winpr_QuerySecurityPackageInfoW, /* QuerySecurityPackageInfo */ + NULL, /* Reserved3 */ + NULL, /* Reserved4 */ + winpr_ExportSecurityContext, /* ExportSecurityContext */ + winpr_ImportSecurityContextW, /* ImportSecurityContext */ + NULL, /* AddCredentials */ + NULL, /* Reserved8 */ + winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */ + winpr_EncryptMessage, /* EncryptMessage */ + winpr_DecryptMessage, /* DecryptMessage */ + winpr_SetContextAttributesW, /* SetContextAttributes */ + winpr_SetCredentialsAttributesW, /* SetCredentialsAttributes */ +}; diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.h new file mode 100644 index 0000000000000000000000000000000000000000..2f7b55afb9011e391aeffc76b6b4d48ba863770d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/sspi_winpr.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * Security Support Provider Interface (SSPI) + * + * Copyright 2012-2014 Marc-Andre Moreau + * + * 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_WINPR_H +#define WINPR_SSPI_WINPR_H + +#include + +SecurityFunctionTableW* SEC_ENTRY winpr_InitSecurityInterfaceW(void); +SecurityFunctionTableA* SEC_ENTRY winpr_InitSecurityInterfaceA(void); + +#endif /* WINPR_SSPI_WINPR_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f894aa170152374351eef102327ec681f1b0cb3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/CMakeLists.txt @@ -0,0 +1,34 @@ +set(MODULE_NAME "TestSspi") +set(MODULE_PREFIX "TEST_SSPI") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS + TestQuerySecurityPackageInfo.c TestEnumerateSecurityPackages.c TestInitializeSecurityContext.c + TestAcquireCredentialsHandle.c TestCredSSP.c + #TestSchannel.c + TestNTLM.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +include_directories(SYSTEM ${OPENSSL_INCLUDE_DIR}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +if(WIN32) + set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} secur32 crypt32) +endif() + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c new file mode 100644 index 0000000000000000000000000000000000000000..05466c8c1c83a60cbd847c509e8a1b568efaf34d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c @@ -0,0 +1,60 @@ + +#include +#include +#include +#include + +static const char* test_User = "User"; +static const char* test_Domain = "Domain"; +static const char* test_Password = "Password"; + +int TestAcquireCredentialsHandle(int argc, char* argv[]) +{ + int rc = -1; + SECURITY_STATUS status = 0; + CredHandle credentials = { 0 }; + TimeStamp expiration; + SEC_WINNT_AUTH_IDENTITY identity; + SecurityFunctionTable* table = NULL; + SecPkgCredentials_Names credential_names; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + sspi_GlobalInit(); + table = InitSecurityInterfaceEx(0); + identity.User = (UINT16*)_strdup(test_User); + identity.Domain = (UINT16*)_strdup(test_Domain); + identity.Password = (UINT16*)_strdup(test_Password); + + if (!identity.User || !identity.Domain || !identity.Password) + goto fail; + + identity.UserLength = strlen(test_User); + identity.DomainLength = strlen(test_Domain); + identity.PasswordLength = strlen(test_Password); + identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + status = table->AcquireCredentialsHandle(NULL, NTLM_SSP_NAME, SECPKG_CRED_OUTBOUND, NULL, + &identity, NULL, NULL, &credentials, &expiration); + + if (status != SEC_E_OK) + goto fail; + + status = + table->QueryCredentialsAttributes(&credentials, SECPKG_CRED_ATTR_NAMES, &credential_names); + + if (status != SEC_E_OK) + goto fail; + + rc = 0; +fail: + + if (SecIsValidHandle(&credentials)) + table->FreeCredentialsHandle(&credentials); + + free(identity.User); + free(identity.Domain); + free(identity.Password); + sspi_GlobalFinish(); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestCredSSP.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestCredSSP.c new file mode 100644 index 0000000000000000000000000000000000000000..b56d9e2d39228fded7c98dac335e92b94e0e8b20 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestCredSSP.c @@ -0,0 +1,8 @@ + +#include +#include + +int TestCredSSP(int argc, char* argv[]) +{ + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestEnumerateSecurityPackages.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestEnumerateSecurityPackages.c new file mode 100644 index 0000000000000000000000000000000000000000..9de23c09e900cbf969f70961afc199b9acda90c4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestEnumerateSecurityPackages.c @@ -0,0 +1,40 @@ + +#include +#include +#include +#include +#include + +int TestEnumerateSecurityPackages(int argc, char* argv[]) +{ + ULONG cPackages = 0; + SECURITY_STATUS status = 0; + SecPkgInfo* pPackageInfo = NULL; + SecurityFunctionTable* table = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + sspi_GlobalInit(); + table = InitSecurityInterfaceEx(0); + + status = table->EnumerateSecurityPackages(&cPackages, &pPackageInfo); + + if (status != SEC_E_OK) + { + sspi_GlobalFinish(); + return -1; + } + + _tprintf(_T("\nEnumerateSecurityPackages (%") _T(PRIu32) _T("):\n"), cPackages); + + for (size_t index = 0; index < cPackages; index++) + { + _tprintf(_T("\"%s\", \"%s\"\n"), pPackageInfo[index].Name, pPackageInfo[index].Comment); + } + + table->FreeContextBuffer(pPackageInfo); + sspi_GlobalFinish(); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c new file mode 100644 index 0000000000000000000000000000000000000000..88f5a7c19b444715e51a25a2984c726d008c9a3d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c @@ -0,0 +1,115 @@ + +#include +#include +#include +#include + +static const char* test_User = "User"; +static const char* test_Domain = "Domain"; +static const char* test_Password = "Password"; + +int TestInitializeSecurityContext(int argc, char* argv[]) +{ + int rc = -1; + UINT32 cbMaxLen = 0; + UINT32 fContextReq = 0; + void* output_buffer = NULL; + CtxtHandle context; + ULONG pfContextAttr = 0; + SECURITY_STATUS status = 0; + CredHandle credentials = { 0 }; + TimeStamp expiration; + PSecPkgInfo pPackageInfo = NULL; + SEC_WINNT_AUTH_IDENTITY identity = { 0 }; + SecurityFunctionTable* table = NULL; + PSecBuffer p_SecBuffer = NULL; + SecBuffer output_SecBuffer; + SecBufferDesc output_SecBuffer_desc; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + sspi_GlobalInit(); + table = InitSecurityInterfaceEx(0); + status = table->QuerySecurityPackageInfo(NTLM_SSP_NAME, &pPackageInfo); + + if (status != SEC_E_OK) + { + printf("QuerySecurityPackageInfo status: 0x%08" PRIX32 "\n", status); + goto fail; + } + + cbMaxLen = pPackageInfo->cbMaxToken; + identity.User = (UINT16*)_strdup(test_User); + identity.Domain = (UINT16*)_strdup(test_Domain); + identity.Password = (UINT16*)_strdup(test_Password); + + if (!identity.User || !identity.Domain || !identity.Password) + goto fail; + + identity.UserLength = strlen(test_User); + identity.DomainLength = strlen(test_Domain); + identity.PasswordLength = strlen(test_Password); + identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + status = table->AcquireCredentialsHandle(NULL, NTLM_SSP_NAME, SECPKG_CRED_OUTBOUND, NULL, + &identity, NULL, NULL, &credentials, &expiration); + + if (status != SEC_E_OK) + { + printf("AcquireCredentialsHandle status: 0x%08" PRIX32 "\n", status); + goto fail; + } + + fContextReq = ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_CONFIDENTIALITY | + ISC_REQ_DELEGATE; + output_buffer = malloc(cbMaxLen); + + if (!output_buffer) + { + printf("Memory allocation failed\n"); + goto fail; + } + + output_SecBuffer_desc.ulVersion = 0; + output_SecBuffer_desc.cBuffers = 1; + output_SecBuffer_desc.pBuffers = &output_SecBuffer; + output_SecBuffer.cbBuffer = cbMaxLen; + output_SecBuffer.BufferType = SECBUFFER_TOKEN; + output_SecBuffer.pvBuffer = output_buffer; + status = table->InitializeSecurityContext(&credentials, NULL, NULL, fContextReq, 0, 0, NULL, 0, + &context, &output_SecBuffer_desc, &pfContextAttr, + &expiration); + + if (status != SEC_I_CONTINUE_NEEDED) + { + printf("InitializeSecurityContext status: 0x%08" PRIX32 "\n", status); + goto fail; + } + + printf("cBuffers: %" PRIu32 " ulVersion: %" PRIu32 "\n", output_SecBuffer_desc.cBuffers, + output_SecBuffer_desc.ulVersion); + p_SecBuffer = &output_SecBuffer_desc.pBuffers[0]; + printf("BufferType: 0x%08" PRIX32 " cbBuffer: %" PRIu32 "\n", p_SecBuffer->BufferType, + p_SecBuffer->cbBuffer); + status = table->DeleteSecurityContext(&context); + + if (status != SEC_E_OK) + { + printf("DeleteSecurityContext status: 0x%08" PRIX32 "\n", status); + goto fail; + } + + rc = 0; +fail: + free(identity.User); + free(identity.Domain); + free(identity.Password); + free(output_buffer); + + if (SecIsValidHandle(&credentials)) + table->FreeCredentialsHandle(&credentials); + + table->FreeContextBuffer(pPackageInfo); + sspi_GlobalFinish(); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestNTLM.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestNTLM.c new file mode 100644 index 0000000000000000000000000000000000000000..a466922457efa704d58fec9b39ff6ba5151d5d32 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestNTLM.c @@ -0,0 +1,795 @@ + +#include +#include +#include +#include +#include + +struct test_input_t +{ + const char* user; + const char* domain; + const char* pwd; + const BYTE* ntlm; + const BYTE* ntlmv2; + BOOL dynamic; + BOOL expected; +}; + +typedef struct +{ + CtxtHandle context; + ULONG cbMaxToken; + ULONG fContextReq; + ULONG pfContextAttr; + TimeStamp expiration; + PSecBuffer pBuffer; + SecBuffer inputBuffer[2]; + SecBuffer outputBuffer[2]; + BOOL haveContext; + BOOL haveInputBuffer; + BOOL UseNtlmV2Hash; + LPTSTR ServicePrincipalName; + SecBufferDesc inputBufferDesc; + SecBufferDesc outputBufferDesc; + CredHandle credentials; + BOOL confidentiality; + SecPkgInfo* pPackageInfo; + SecurityFunctionTable* table; + SEC_WINNT_AUTH_IDENTITY identity; +} TEST_NTLM_SERVER; + +static BYTE TEST_NTLM_TIMESTAMP[8] = { 0x33, 0x57, 0xbd, 0xb1, 0x07, 0x8b, 0xcf, 0x01 }; + +static BYTE TEST_NTLM_CLIENT_CHALLENGE[8] = { 0x20, 0xc0, 0x2b, 0x3d, 0xc0, 0x61, 0xa7, 0x73 }; + +static BYTE TEST_NTLM_SERVER_CHALLENGE[8] = { 0xa4, 0xf1, 0xba, 0xa6, 0x7c, 0xdc, 0x1a, 0x12 }; + +static BYTE TEST_NTLM_NEGOTIATE[] = + "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x01\x00\x00\x00\x07\x82\x08\xa2" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x06\x03\x80\x25\x00\x00\x00\x0f"; + +static BYTE TEST_NTLM_CHALLENGE[] = + "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x02\x00\x00\x00\x00\x00\x00\x00" + "\x38\x00\x00\x00\x07\x82\x88\xa2\xa4\xf1\xba\xa6\x7c\xdc\x1a\x12" + "\x00\x00\x00\x00\x00\x00\x00\x00\x66\x00\x66\x00\x38\x00\x00\x00" + "\x06\x03\x80\x25\x00\x00\x00\x0f\x02\x00\x0e\x00\x4e\x00\x45\x00" + "\x57\x00\x59\x00\x45\x00\x41\x00\x52\x00\x01\x00\x0e\x00\x4e\x00" + "\x45\x00\x57\x00\x59\x00\x45\x00\x41\x00\x52\x00\x04\x00\x1c\x00" + "\x6c\x00\x61\x00\x62\x00\x2e\x00\x77\x00\x61\x00\x79\x00\x6b\x00" + "\x2e\x00\x6c\x00\x6f\x00\x63\x00\x61\x00\x6c\x00\x03\x00\x0e\x00" + "\x6e\x00\x65\x00\x77\x00\x79\x00\x65\x00\x61\x00\x72\x00\x07\x00" + "\x08\x00\x33\x57\xbd\xb1\x07\x8b\xcf\x01\x00\x00\x00\x00"; + +static BYTE TEST_NTLM_AUTHENTICATE[] = + "\x4e\x54\x4c\x4d\x53\x53\x50\x00\x03\x00\x00\x00\x18\x00\x18\x00" + "\x82\x00\x00\x00\x08\x01\x08\x01\x9a\x00\x00\x00\x0c\x00\x0c\x00" + "\x58\x00\x00\x00\x10\x00\x10\x00\x64\x00\x00\x00\x0e\x00\x0e\x00" + "\x74\x00\x00\x00\x00\x00\x00\x00\xa2\x01\x00\x00\x05\x82\x88\xa2" + "\x06\x03\x80\x25\x00\x00\x00\x0f\x12\xe5\x5a\xf5\x80\xee\x3f\x29" + "\xe1\xde\x90\x4d\x73\x77\x06\x25\x44\x00\x6f\x00\x6d\x00\x61\x00" + "\x69\x00\x6e\x00\x55\x00\x73\x00\x65\x00\x72\x00\x6e\x00\x61\x00" + "\x6d\x00\x65\x00\x4e\x00\x45\x00\x57\x00\x59\x00\x45\x00\x41\x00" + "\x52\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x62\x14\x68\xc8\x98\x12" + "\xe7\x39\xd8\x76\x1b\xe9\xf7\x54\xb5\xe3\x01\x01\x00\x00\x00\x00" + "\x00\x00\x33\x57\xbd\xb1\x07\x8b\xcf\x01\x20\xc0\x2b\x3d\xc0\x61" + "\xa7\x73\x00\x00\x00\x00\x02\x00\x0e\x00\x4e\x00\x45\x00\x57\x00" + "\x59\x00\x45\x00\x41\x00\x52\x00\x01\x00\x0e\x00\x4e\x00\x45\x00" + "\x57\x00\x59\x00\x45\x00\x41\x00\x52\x00\x04\x00\x1c\x00\x6c\x00" + "\x61\x00\x62\x00\x2e\x00\x77\x00\x61\x00\x79\x00\x6b\x00\x2e\x00" + "\x6c\x00\x6f\x00\x63\x00\x61\x00\x6c\x00\x03\x00\x0e\x00\x6e\x00" + "\x65\x00\x77\x00\x79\x00\x65\x00\x61\x00\x72\x00\x07\x00\x08\x00" + "\x33\x57\xbd\xb1\x07\x8b\xcf\x01\x06\x00\x04\x00\x02\x00\x00\x00" + "\x08\x00\x30\x00\x30\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" + "\x00\x20\x00\x00\x1e\x10\xf5\x2c\x54\x2f\x2e\x77\x1c\x13\xbf\xc3" + "\x3f\xe1\x7b\x28\x7e\x0b\x93\x5a\x39\xd2\xce\x12\xd7\xbd\x8c\x4e" + "\x2b\xb5\x0b\xf5\x0a\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\x1a\x00\x48\x00\x54\x00" + "\x54\x00\x50\x00\x2f\x00\x72\x00\x77\x00\x2e\x00\x6c\x00\x6f\x00" + "\x63\x00\x61\x00\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00"; + +#define TEST_SSPI_INTERFACE SSPI_INTERFACE_WINPR + +static const char* TEST_NTLM_USER = "Username"; +static const char* TEST_NTLM_DOMAIN = "Domain"; +static const char* TEST_NTLM_PASSWORD = "P4ss123!"; + +// static const char* TEST_NTLM_HASH_STRING = "d5922a65c4d5c082ca444af1be0001db"; + +static const BYTE TEST_NTLM_HASH[16] = { 0xd5, 0x92, 0x2a, 0x65, 0xc4, 0xd5, 0xc0, 0x82, + 0xca, 0x44, 0x4a, 0xf1, 0xbe, 0x00, 0x01, 0xdb }; + +// static const char* TEST_NTLM_HASH_V2_STRING = "4c7f706f7dde05a9d1a0f4e7ffe3bfb8"; + +static const BYTE TEST_NTLM_V2_HASH[16] = { 0x4c, 0x7f, 0x70, 0x6f, 0x7d, 0xde, 0x05, 0xa9, + 0xd1, 0xa0, 0xf4, 0xe7, 0xff, 0xe3, 0xbf, 0xb8 }; + +static const BYTE TEST_EMPTY_PWD_NTLM_HASH[] = { 0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, + 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0 }; + +static const BYTE TEST_EMPTY_PWD_NTLM_V2_HASH[] = { + 0x0b, 0xce, 0x54, 0x87, 0x4e, 0x94, 0x20, 0x9e, 0x34, 0x48, 0x97, 0xc1, 0x60, 0x03, 0x6e, 0x3b +}; + +#define NTLM_PACKAGE_NAME NTLM_SSP_NAME + +typedef struct +{ + CtxtHandle context; + ULONG cbMaxToken; + ULONG fContextReq; + ULONG pfContextAttr; + TimeStamp expiration; + PSecBuffer pBuffer; + SecBuffer inputBuffer[2]; + SecBuffer outputBuffer[2]; + BOOL haveContext; + BOOL haveInputBuffer; + LPTSTR ServicePrincipalName; + SecBufferDesc inputBufferDesc; + SecBufferDesc outputBufferDesc; + CredHandle credentials; + BOOL confidentiality; + SecPkgInfo* pPackageInfo; + SecurityFunctionTable* table; + SEC_WINNT_AUTH_IDENTITY identity; +} TEST_NTLM_CLIENT; + +static int test_ntlm_client_init(TEST_NTLM_CLIENT* ntlm, const char* user, const char* domain, + const char* password) +{ + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + + WINPR_ASSERT(ntlm); + + SecInvalidateHandle(&(ntlm->context)); + ntlm->table = InitSecurityInterfaceEx(TEST_SSPI_INTERFACE); + if (!ntlm->table) + return -1; + const int rc = sspi_SetAuthIdentity(&(ntlm->identity), user, domain, password); + if (rc < 0) + return rc; + + status = ntlm->table->QuerySecurityPackageInfo(NTLM_PACKAGE_NAME, &ntlm->pPackageInfo); + + if (status != SEC_E_OK) + { + (void)fprintf(stderr, "QuerySecurityPackageInfo status: %s (0x%08" PRIX32 ")\n", + GetSecurityStatusString(status), status); + return -1; + } + + ntlm->cbMaxToken = ntlm->pPackageInfo->cbMaxToken; + status = ntlm->table->AcquireCredentialsHandle(NULL, NTLM_PACKAGE_NAME, SECPKG_CRED_OUTBOUND, + NULL, &ntlm->identity, NULL, NULL, + &ntlm->credentials, &ntlm->expiration); + + if (status != SEC_E_OK) + { + (void)fprintf(stderr, "AcquireCredentialsHandle status: %s (0x%08" PRIX32 ")\n", + GetSecurityStatusString(status), status); + return -1; + } + + ntlm->haveContext = FALSE; + ntlm->haveInputBuffer = FALSE; + ZeroMemory(&ntlm->inputBuffer, sizeof(SecBuffer)); + ZeroMemory(&ntlm->outputBuffer, sizeof(SecBuffer)); + ntlm->fContextReq = 0; +#if 0 + /* HTTP authentication flags */ + ntlm->fContextReq |= ISC_REQ_CONFIDENTIALITY; +#endif + /* NLA authentication flags */ + ntlm->fContextReq |= ISC_REQ_MUTUAL_AUTH; + ntlm->fContextReq |= ISC_REQ_CONFIDENTIALITY; + ntlm->fContextReq |= ISC_REQ_USE_SESSION_KEY; + return 1; +} + +static void test_ntlm_client_uninit(TEST_NTLM_CLIENT* ntlm) +{ + if (!ntlm) + return; + + if (ntlm->outputBuffer[0].pvBuffer) + { + free(ntlm->outputBuffer[0].pvBuffer); + ntlm->outputBuffer[0].pvBuffer = NULL; + } + + free(ntlm->identity.User); + free(ntlm->identity.Domain); + free(ntlm->identity.Password); + free(ntlm->ServicePrincipalName); + + if (ntlm->table) + { + SECURITY_STATUS status = ntlm->table->FreeCredentialsHandle(&ntlm->credentials); + WINPR_ASSERT((status == SEC_E_OK) || (status == SEC_E_SECPKG_NOT_FOUND) || + (status == SEC_E_UNSUPPORTED_FUNCTION)); + + status = ntlm->table->FreeContextBuffer(ntlm->pPackageInfo); + WINPR_ASSERT((status == SEC_E_OK) || (status = SEC_E_INVALID_HANDLE)); + + status = ntlm->table->DeleteSecurityContext(&ntlm->context); + WINPR_ASSERT((status == SEC_E_OK) || (status == SEC_E_SECPKG_NOT_FOUND) || + (status == SEC_E_UNSUPPORTED_FUNCTION)); + } +} + +/** + * SSPI Client Ceremony + * + * -------------- + * ( Client Begin ) + * -------------- + * | + * | + * \|/ + * -----------+-------------- + * | AcquireCredentialsHandle | + * -------------------------- + * | + * | + * \|/ + * -------------+-------------- + * +---------------> / InitializeSecurityContext / + * | ---------------------------- + * | | + * | | + * | \|/ + * --------------------------- ---------+------------- ---------------------- + * / Receive blob from server / < Received security blob? > --Yes-> / Send blob to server / + * -------------+------------- ----------------------- ---------------------- + * /|\ | | + * | No | + * Yes \|/ | + * | ------------+----------- | + * +---------------- < Received Continue Needed > <-----------------+ + * ------------------------ + * | + * No + * \|/ + * ------+------- + * ( Client End ) + * -------------- + */ +static BOOL IsSecurityStatusError(SECURITY_STATUS status) +{ + BOOL error = TRUE; + + switch (status) + { + case SEC_E_OK: + case SEC_I_CONTINUE_NEEDED: + case SEC_I_COMPLETE_NEEDED: + case SEC_I_COMPLETE_AND_CONTINUE: + case SEC_I_LOCAL_LOGON: + case SEC_I_CONTEXT_EXPIRED: + case SEC_I_INCOMPLETE_CREDENTIALS: + case SEC_I_RENEGOTIATE: + case SEC_I_NO_LSA_CONTEXT: + case SEC_I_SIGNATURE_NEEDED: + case SEC_I_NO_RENEGOTIATION: + error = FALSE; + break; + default: + break; + } + + return error; +} + +static int test_ntlm_client_authenticate(TEST_NTLM_CLIENT* ntlm) +{ + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + + WINPR_ASSERT(ntlm); + if (ntlm->outputBuffer[0].pvBuffer) + { + free(ntlm->outputBuffer[0].pvBuffer); + ntlm->outputBuffer[0].pvBuffer = NULL; + } + + ntlm->outputBufferDesc.ulVersion = SECBUFFER_VERSION; + ntlm->outputBufferDesc.cBuffers = 1; + ntlm->outputBufferDesc.pBuffers = ntlm->outputBuffer; + ntlm->outputBuffer[0].BufferType = SECBUFFER_TOKEN; + ntlm->outputBuffer[0].cbBuffer = ntlm->cbMaxToken; + ntlm->outputBuffer[0].pvBuffer = malloc(ntlm->outputBuffer[0].cbBuffer); + + if (!ntlm->outputBuffer[0].pvBuffer) + return -1; + + if (ntlm->haveInputBuffer) + { + ntlm->inputBufferDesc.ulVersion = SECBUFFER_VERSION; + ntlm->inputBufferDesc.cBuffers = 1; + ntlm->inputBufferDesc.pBuffers = ntlm->inputBuffer; + ntlm->inputBuffer[0].BufferType = SECBUFFER_TOKEN; + } + + if ((!ntlm) || (!ntlm->table)) + { + (void)fprintf(stderr, "ntlm_authenticate: invalid ntlm context\n"); + return -1; + } + + status = ntlm->table->InitializeSecurityContext( + &ntlm->credentials, (ntlm->haveContext) ? &ntlm->context : NULL, + (ntlm->ServicePrincipalName) ? ntlm->ServicePrincipalName : NULL, ntlm->fContextReq, 0, + SECURITY_NATIVE_DREP, (ntlm->haveInputBuffer) ? &ntlm->inputBufferDesc : NULL, 0, + &ntlm->context, &ntlm->outputBufferDesc, &ntlm->pfContextAttr, &ntlm->expiration); + + if (IsSecurityStatusError(status)) + return -1; + + if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) + { + if (ntlm->table->CompleteAuthToken) + { + SECURITY_STATUS rc = + ntlm->table->CompleteAuthToken(&ntlm->context, &ntlm->outputBufferDesc); + if (rc != SEC_E_OK) + return -1; + } + + if (status == SEC_I_COMPLETE_NEEDED) + status = SEC_E_OK; + else if (status == SEC_I_COMPLETE_AND_CONTINUE) + status = SEC_I_CONTINUE_NEEDED; + } + + if (ntlm->haveInputBuffer) + { + free(ntlm->inputBuffer[0].pvBuffer); + } + + ntlm->haveInputBuffer = TRUE; + ntlm->haveContext = TRUE; + return (status == SEC_I_CONTINUE_NEEDED) ? 1 : 0; +} + +static TEST_NTLM_CLIENT* test_ntlm_client_new(void) +{ + TEST_NTLM_CLIENT* ntlm = (TEST_NTLM_CLIENT*)calloc(1, sizeof(TEST_NTLM_CLIENT)); + + if (!ntlm) + return NULL; + + return ntlm; +} + +static void test_ntlm_client_free(TEST_NTLM_CLIENT* ntlm) +{ + if (!ntlm) + return; + + test_ntlm_client_uninit(ntlm); + free(ntlm); +} + +static int test_ntlm_server_init(TEST_NTLM_SERVER* ntlm) +{ + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + + WINPR_ASSERT(ntlm); + + ntlm->UseNtlmV2Hash = TRUE; + SecInvalidateHandle(&(ntlm->context)); + ntlm->table = InitSecurityInterfaceEx(TEST_SSPI_INTERFACE); + if (!ntlm->table) + return SEC_E_INTERNAL_ERROR; + + status = ntlm->table->QuerySecurityPackageInfo(NTLM_PACKAGE_NAME, &ntlm->pPackageInfo); + + if (status != SEC_E_OK) + { + (void)fprintf(stderr, "QuerySecurityPackageInfo status: %s (0x%08" PRIX32 ")\n", + GetSecurityStatusString(status), status); + return -1; + } + + ntlm->cbMaxToken = ntlm->pPackageInfo->cbMaxToken; + status = ntlm->table->AcquireCredentialsHandle(NULL, NTLM_PACKAGE_NAME, SECPKG_CRED_INBOUND, + NULL, NULL, NULL, NULL, &ntlm->credentials, + &ntlm->expiration); + + if (status != SEC_E_OK) + { + (void)fprintf(stderr, "AcquireCredentialsHandle status: %s (0x%08" PRIX32 ")\n", + GetSecurityStatusString(status), status); + return -1; + } + + ntlm->haveContext = FALSE; + ntlm->haveInputBuffer = FALSE; + ZeroMemory(&ntlm->inputBuffer, sizeof(SecBuffer)); + ZeroMemory(&ntlm->outputBuffer, sizeof(SecBuffer)); + ntlm->fContextReq = 0; + /* NLA authentication flags */ + ntlm->fContextReq |= ASC_REQ_MUTUAL_AUTH; + ntlm->fContextReq |= ASC_REQ_CONFIDENTIALITY; + ntlm->fContextReq |= ASC_REQ_CONNECTION; + ntlm->fContextReq |= ASC_REQ_USE_SESSION_KEY; + ntlm->fContextReq |= ASC_REQ_REPLAY_DETECT; + ntlm->fContextReq |= ASC_REQ_SEQUENCE_DETECT; + ntlm->fContextReq |= ASC_REQ_EXTENDED_ERROR; + return 1; +} + +static void test_ntlm_server_uninit(TEST_NTLM_SERVER* ntlm) +{ + if (!ntlm) + return; + + if (ntlm->outputBuffer[0].pvBuffer) + { + free(ntlm->outputBuffer[0].pvBuffer); + ntlm->outputBuffer[0].pvBuffer = NULL; + } + + free(ntlm->identity.User); + free(ntlm->identity.Domain); + free(ntlm->identity.Password); + free(ntlm->ServicePrincipalName); + + if (ntlm->table) + { + SECURITY_STATUS status = ntlm->table->FreeCredentialsHandle(&ntlm->credentials); + WINPR_ASSERT(status == SEC_E_OK); + status = ntlm->table->FreeContextBuffer(ntlm->pPackageInfo); + WINPR_ASSERT(status == SEC_E_OK); + status = ntlm->table->DeleteSecurityContext(&ntlm->context); + WINPR_ASSERT(status == SEC_E_OK); + } +} + +static int test_ntlm_server_authenticate(const struct test_input_t* targ, TEST_NTLM_SERVER* ntlm) +{ + SECURITY_STATUS status = SEC_E_INTERNAL_ERROR; + + WINPR_ASSERT(ntlm); + WINPR_ASSERT(targ); + + ntlm->inputBufferDesc.ulVersion = SECBUFFER_VERSION; + ntlm->inputBufferDesc.cBuffers = 1; + ntlm->inputBufferDesc.pBuffers = ntlm->inputBuffer; + ntlm->inputBuffer[0].BufferType = SECBUFFER_TOKEN; + ntlm->outputBufferDesc.ulVersion = SECBUFFER_VERSION; + ntlm->outputBufferDesc.cBuffers = 1; + ntlm->outputBufferDesc.pBuffers = &ntlm->outputBuffer[0]; + ntlm->outputBuffer[0].BufferType = SECBUFFER_TOKEN; + ntlm->outputBuffer[0].cbBuffer = ntlm->cbMaxToken; + ntlm->outputBuffer[0].pvBuffer = malloc(ntlm->outputBuffer[0].cbBuffer); + + if (!ntlm->outputBuffer[0].pvBuffer) + return -1; + + status = ntlm->table->AcceptSecurityContext( + &ntlm->credentials, ntlm->haveContext ? &ntlm->context : NULL, &ntlm->inputBufferDesc, + ntlm->fContextReq, SECURITY_NATIVE_DREP, &ntlm->context, &ntlm->outputBufferDesc, + &ntlm->pfContextAttr, &ntlm->expiration); + + if (status == SEC_I_CONTINUE_NEEDED) + { + SecPkgContext_AuthNtlmHash AuthNtlmHash = { 0 }; + + if (ntlm->UseNtlmV2Hash) + { + AuthNtlmHash.Version = 2; + CopyMemory(AuthNtlmHash.NtlmHash, targ->ntlmv2, 16); + } + else + { + AuthNtlmHash.Version = 1; + CopyMemory(AuthNtlmHash.NtlmHash, targ->ntlm, 16); + } + + status = + ntlm->table->SetContextAttributes(&ntlm->context, SECPKG_ATTR_AUTH_NTLM_HASH, + &AuthNtlmHash, sizeof(SecPkgContext_AuthNtlmHash)); + } + + if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED)) + { + (void)fprintf(stderr, "AcceptSecurityContext status: %s (0x%08" PRIX32 ")\n", + GetSecurityStatusString(status), status); + return -1; /* Access Denied */ + } + + ntlm->haveContext = TRUE; + return (status == SEC_I_CONTINUE_NEEDED) ? 1 : 0; +} + +static TEST_NTLM_SERVER* test_ntlm_server_new(void) +{ + TEST_NTLM_SERVER* ntlm = (TEST_NTLM_SERVER*)calloc(1, sizeof(TEST_NTLM_SERVER)); + + if (!ntlm) + return NULL; + + return ntlm; +} + +static void test_ntlm_server_free(TEST_NTLM_SERVER* ntlm) +{ + if (!ntlm) + return; + + test_ntlm_server_uninit(ntlm); + free(ntlm); +} + +static BOOL test_default(const struct test_input_t* arg) +{ + BOOL rc = FALSE; + PSecBuffer pSecBuffer = NULL; + + WINPR_ASSERT(arg); + + printf("testcase {user=%s, domain=%s, password=%s, dynamic=%s}\n", arg->user, arg->domain, + arg->pwd, arg->dynamic ? "TRUE" : "FALSE"); + + /** + * Client Initialization + */ + TEST_NTLM_CLIENT* client = test_ntlm_client_new(); + TEST_NTLM_SERVER* server = test_ntlm_server_new(); + + if (!client || !server) + { + printf("Memory allocation failed\n"); + goto fail; + } + + int status = test_ntlm_client_init(client, arg->user, arg->domain, arg->pwd); + + if (status < 0) + { + printf("test_ntlm_client_init failure\n"); + goto fail; + } + + /** + * Server Initialization + */ + + status = test_ntlm_server_init(server); + + if (status < 0) + { + printf("test_ntlm_server_init failure\n"); + goto fail; + } + + /** + * Client -> Negotiate Message + */ + status = test_ntlm_client_authenticate(client); + + if (status < 0) + { + printf("test_ntlm_client_authenticate failure\n"); + goto fail; + } + + if (!arg->dynamic) + { + SecPkgContext_AuthNtlmTimestamp AuthNtlmTimestamp = { 0 }; + SecPkgContext_AuthNtlmClientChallenge AuthNtlmClientChallenge = { 0 }; + SecPkgContext_AuthNtlmServerChallenge AuthNtlmServerChallenge = { 0 }; + CopyMemory(AuthNtlmTimestamp.Timestamp, TEST_NTLM_TIMESTAMP, 8); + AuthNtlmTimestamp.ChallengeOrResponse = TRUE; + SECURITY_STATUS rc = client->table->SetContextAttributes( + &client->context, SECPKG_ATTR_AUTH_NTLM_TIMESTAMP, &AuthNtlmTimestamp, + sizeof(SecPkgContext_AuthNtlmTimestamp)); + WINPR_ASSERT((rc == SEC_E_OK) || (rc == SEC_E_SECPKG_NOT_FOUND)); + + AuthNtlmTimestamp.ChallengeOrResponse = FALSE; + rc = client->table->SetContextAttributes(&client->context, SECPKG_ATTR_AUTH_NTLM_TIMESTAMP, + &AuthNtlmTimestamp, + sizeof(SecPkgContext_AuthNtlmTimestamp)); + WINPR_ASSERT((rc == SEC_E_OK) || (rc == SEC_E_SECPKG_NOT_FOUND)); + + CopyMemory(AuthNtlmClientChallenge.ClientChallenge, TEST_NTLM_CLIENT_CHALLENGE, 8); + CopyMemory(AuthNtlmServerChallenge.ServerChallenge, TEST_NTLM_SERVER_CHALLENGE, 8); + rc = client->table->SetContextAttributes( + &client->context, SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE, &AuthNtlmClientChallenge, + sizeof(SecPkgContext_AuthNtlmClientChallenge)); + WINPR_ASSERT((rc == SEC_E_OK) || (rc == SEC_E_SECPKG_NOT_FOUND)); + + rc = client->table->SetContextAttributes( + &client->context, SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE, &AuthNtlmServerChallenge, + sizeof(SecPkgContext_AuthNtlmServerChallenge)); + WINPR_ASSERT((rc == SEC_E_OK) || (rc == SEC_E_SECPKG_NOT_FOUND)); + } + + pSecBuffer = &(client->outputBuffer[0]); + + if (!arg->dynamic) + { + pSecBuffer->cbBuffer = sizeof(TEST_NTLM_NEGOTIATE) - 1; + free(pSecBuffer->pvBuffer); + pSecBuffer->pvBuffer = malloc(pSecBuffer->cbBuffer); + + if (!pSecBuffer->pvBuffer) + { + printf("Memory allocation failed\n"); + goto fail; + } + + CopyMemory(pSecBuffer->pvBuffer, TEST_NTLM_NEGOTIATE, pSecBuffer->cbBuffer); + } + + (void)fprintf(stderr, "NTLM_NEGOTIATE (length = %" PRIu32 "):\n", pSecBuffer->cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)pSecBuffer->pvBuffer, pSecBuffer->cbBuffer); + /** + * Server <- Negotiate Message + * Server -> Challenge Message + */ + server->haveInputBuffer = TRUE; + server->inputBuffer[0].BufferType = SECBUFFER_TOKEN; + server->inputBuffer[0].pvBuffer = pSecBuffer->pvBuffer; + server->inputBuffer[0].cbBuffer = pSecBuffer->cbBuffer; + status = test_ntlm_server_authenticate(arg, server); + + if (status < 0) + { + printf("test_ntlm_server_authenticate failure\n"); + goto fail; + } + + if (!arg->dynamic) + { + SecPkgContext_AuthNtlmTimestamp AuthNtlmTimestamp = { 0 }; + SecPkgContext_AuthNtlmClientChallenge AuthNtlmClientChallenge = { 0 }; + SecPkgContext_AuthNtlmServerChallenge AuthNtlmServerChallenge = { 0 }; + CopyMemory(AuthNtlmTimestamp.Timestamp, TEST_NTLM_TIMESTAMP, 8); + AuthNtlmTimestamp.ChallengeOrResponse = TRUE; + SECURITY_STATUS rc = client->table->SetContextAttributes( + &server->context, SECPKG_ATTR_AUTH_NTLM_TIMESTAMP, &AuthNtlmTimestamp, + sizeof(SecPkgContext_AuthNtlmTimestamp)); + WINPR_ASSERT(rc == SEC_E_OK); + + AuthNtlmTimestamp.ChallengeOrResponse = FALSE; + rc = client->table->SetContextAttributes(&server->context, SECPKG_ATTR_AUTH_NTLM_TIMESTAMP, + &AuthNtlmTimestamp, + sizeof(SecPkgContext_AuthNtlmTimestamp)); + WINPR_ASSERT(rc == SEC_E_OK); + + CopyMemory(AuthNtlmClientChallenge.ClientChallenge, TEST_NTLM_CLIENT_CHALLENGE, 8); + CopyMemory(AuthNtlmServerChallenge.ServerChallenge, TEST_NTLM_SERVER_CHALLENGE, 8); + rc = server->table->SetContextAttributes( + &server->context, SECPKG_ATTR_AUTH_NTLM_CLIENT_CHALLENGE, &AuthNtlmClientChallenge, + sizeof(SecPkgContext_AuthNtlmClientChallenge)); + WINPR_ASSERT(rc == SEC_E_OK); + + rc = server->table->SetContextAttributes( + &server->context, SECPKG_ATTR_AUTH_NTLM_SERVER_CHALLENGE, &AuthNtlmServerChallenge, + sizeof(SecPkgContext_AuthNtlmServerChallenge)); + WINPR_ASSERT(rc == SEC_E_OK); + } + + pSecBuffer = &(server->outputBuffer[0]); + + if (!arg->dynamic) + { + SecPkgContext_AuthNtlmMessage AuthNtlmMessage = { 0 }; + pSecBuffer->cbBuffer = sizeof(TEST_NTLM_CHALLENGE) - 1; + free(pSecBuffer->pvBuffer); + pSecBuffer->pvBuffer = malloc(pSecBuffer->cbBuffer); + + if (!pSecBuffer->pvBuffer) + { + printf("Memory allocation failed\n"); + goto fail; + } + + CopyMemory(pSecBuffer->pvBuffer, TEST_NTLM_CHALLENGE, pSecBuffer->cbBuffer); + AuthNtlmMessage.type = 2; + AuthNtlmMessage.length = pSecBuffer->cbBuffer; + AuthNtlmMessage.buffer = (BYTE*)pSecBuffer->pvBuffer; + SECURITY_STATUS rc = server->table->SetContextAttributes( + &server->context, SECPKG_ATTR_AUTH_NTLM_MESSAGE, &AuthNtlmMessage, + sizeof(SecPkgContext_AuthNtlmMessage)); + if (rc != SEC_E_OK) + goto fail; + } + + (void)fprintf(stderr, "NTLM_CHALLENGE (length = %" PRIu32 "):\n", pSecBuffer->cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)pSecBuffer->pvBuffer, pSecBuffer->cbBuffer); + /** + * Client <- Challenge Message + * Client -> Authenticate Message + */ + client->haveInputBuffer = TRUE; + client->inputBuffer[0].BufferType = SECBUFFER_TOKEN; + client->inputBuffer[0].pvBuffer = pSecBuffer->pvBuffer; + client->inputBuffer[0].cbBuffer = pSecBuffer->cbBuffer; + status = test_ntlm_client_authenticate(client); + + if (status < 0) + { + printf("test_ntlm_client_authenticate failure\n"); + goto fail; + } + + pSecBuffer = &(client->outputBuffer[0]); + + if (!arg->dynamic) + { + pSecBuffer->cbBuffer = sizeof(TEST_NTLM_AUTHENTICATE) - 1; + free(pSecBuffer->pvBuffer); + pSecBuffer->pvBuffer = malloc(pSecBuffer->cbBuffer); + + if (!pSecBuffer->pvBuffer) + { + printf("Memory allocation failed\n"); + goto fail; + } + + CopyMemory(pSecBuffer->pvBuffer, TEST_NTLM_AUTHENTICATE, pSecBuffer->cbBuffer); + } + + (void)fprintf(stderr, "NTLM_AUTHENTICATE (length = %" PRIu32 "):\n", pSecBuffer->cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)pSecBuffer->pvBuffer, pSecBuffer->cbBuffer); + /** + * Server <- Authenticate Message + */ + server->haveInputBuffer = TRUE; + server->inputBuffer[0].BufferType = SECBUFFER_TOKEN; + server->inputBuffer[0].pvBuffer = pSecBuffer->pvBuffer; + server->inputBuffer[0].cbBuffer = pSecBuffer->cbBuffer; + status = test_ntlm_server_authenticate(arg, server); + + if (status < 0) + { + printf("test_ntlm_server_authenticate failure\n"); + goto fail; + } + + rc = TRUE; + +fail: + /** + * Cleanup & Termination + */ + test_ntlm_client_free(client); + test_ntlm_server_free(server); + + printf("testcase {user=%s, domain=%s, password=%s, dynamic=%s} returns %d\n", arg->user, + arg->domain, arg->pwd, arg->dynamic ? "TRUE" : "FALSE", rc); + return rc; +} + +int TestNTLM(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + const struct test_input_t inputs[] = { + { TEST_NTLM_USER, TEST_NTLM_DOMAIN, TEST_NTLM_PASSWORD, TEST_NTLM_HASH, TEST_NTLM_V2_HASH, + TRUE, TRUE }, + { TEST_NTLM_USER, TEST_NTLM_DOMAIN, TEST_NTLM_PASSWORD, TEST_NTLM_HASH, TEST_NTLM_V2_HASH, + FALSE, TRUE }, + { TEST_NTLM_USER, TEST_NTLM_DOMAIN, "", TEST_EMPTY_PWD_NTLM_HASH, + TEST_EMPTY_PWD_NTLM_V2_HASH, TRUE, TRUE }, + { TEST_NTLM_USER, TEST_NTLM_DOMAIN, NULL, TEST_EMPTY_PWD_NTLM_HASH, + TEST_EMPTY_PWD_NTLM_V2_HASH, TRUE, FALSE } + }; + + int rc = 0; + for (size_t x = 0; x < ARRAYSIZE(inputs); x++) + { + const struct test_input_t* cur = &inputs[x]; + const BOOL res = test_default(cur); + if (res != cur->expected) + rc = -1; + } + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestQuerySecurityPackageInfo.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestQuerySecurityPackageInfo.c new file mode 100644 index 0000000000000000000000000000000000000000..5d1ca007933ef0580648b523729067d63020a20c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestQuerySecurityPackageInfo.c @@ -0,0 +1,34 @@ + +#include +#include +#include +#include + +int TestQuerySecurityPackageInfo(int argc, char* argv[]) +{ + int rc = 0; + SECURITY_STATUS status = 0; + SecPkgInfo* pPackageInfo = NULL; + SecurityFunctionTable* table = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + sspi_GlobalInit(); + table = InitSecurityInterfaceEx(0); + + status = table->QuerySecurityPackageInfo(NTLM_SSP_NAME, &pPackageInfo); + + if (status != SEC_E_OK) + rc = -1; + else + { + _tprintf(_T("\nQuerySecurityPackageInfo:\n")); + _tprintf(_T("\"%s\", \"%s\"\n"), pPackageInfo->Name, pPackageInfo->Comment); + rc = 0; + } + + table->FreeContextBuffer(pPackageInfo); + sspi_GlobalFinish(); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestSchannel.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestSchannel.c new file mode 100644 index 0000000000000000000000000000000000000000..6e504376d729a39b5b403b31a7071c173887c6f6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspi/test/TestSchannel.c @@ -0,0 +1,854 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static BOOL g_ClientWait = FALSE; +static BOOL g_ServerWait = FALSE; + +static HANDLE g_ClientReadPipe = NULL; +static HANDLE g_ClientWritePipe = NULL; +static HANDLE g_ServerReadPipe = NULL; +static HANDLE g_ServerWritePipe = NULL; + +static const BYTE test_localhost_crt[1029] = { + 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, + 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A, 0x4D, 0x49, 0x49, 0x43, + 0x79, 0x6A, 0x43, 0x43, 0x41, 0x62, 0x4B, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x45, + 0x63, 0x61, 0x64, 0x63, 0x72, 0x7A, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, + 0x39, 0x77, 0x30, 0x42, 0x41, 0x51, 0x55, 0x46, 0x41, 0x44, 0x41, 0x55, 0x4D, 0x52, 0x49, 0x77, + 0x45, 0x41, 0x59, 0x44, 0x56, 0x51, 0x51, 0x44, 0x45, 0x77, 0x6C, 0x73, 0x0A, 0x62, 0x32, 0x4E, + 0x68, 0x62, 0x47, 0x68, 0x76, 0x63, 0x33, 0x51, 0x77, 0x48, 0x68, 0x63, 0x4E, 0x4D, 0x54, 0x4D, + 0x78, 0x4D, 0x44, 0x45, 0x78, 0x4D, 0x44, 0x59, 0x78, 0x4E, 0x7A, 0x55, 0x31, 0x57, 0x68, 0x63, + 0x4E, 0x4D, 0x54, 0x51, 0x78, 0x4D, 0x44, 0x45, 0x78, 0x4D, 0x44, 0x59, 0x78, 0x4E, 0x7A, 0x55, + 0x31, 0x57, 0x6A, 0x41, 0x55, 0x4D, 0x52, 0x49, 0x77, 0x45, 0x41, 0x59, 0x44, 0x0A, 0x56, 0x51, + 0x51, 0x44, 0x45, 0x77, 0x6C, 0x73, 0x62, 0x32, 0x4E, 0x68, 0x62, 0x47, 0x68, 0x76, 0x63, 0x33, + 0x51, 0x77, 0x67, 0x67, 0x45, 0x69, 0x4D, 0x41, 0x30, 0x47, 0x43, 0x53, 0x71, 0x47, 0x53, 0x49, + 0x62, 0x33, 0x44, 0x51, 0x45, 0x42, 0x41, 0x51, 0x55, 0x41, 0x41, 0x34, 0x49, 0x42, 0x44, 0x77, + 0x41, 0x77, 0x67, 0x67, 0x45, 0x4B, 0x41, 0x6F, 0x49, 0x42, 0x41, 0x51, 0x43, 0x33, 0x0A, 0x65, + 0x6E, 0x33, 0x68, 0x5A, 0x4F, 0x53, 0x33, 0x6B, 0x51, 0x2F, 0x55, 0x54, 0x30, 0x53, 0x45, 0x6C, + 0x30, 0x48, 0x6E, 0x50, 0x79, 0x64, 0x48, 0x75, 0x35, 0x39, 0x61, 0x69, 0x71, 0x64, 0x73, 0x64, + 0x53, 0x55, 0x74, 0x6E, 0x43, 0x41, 0x37, 0x46, 0x66, 0x74, 0x30, 0x4F, 0x36, 0x51, 0x79, 0x68, + 0x49, 0x71, 0x58, 0x7A, 0x30, 0x47, 0x32, 0x53, 0x76, 0x77, 0x4C, 0x54, 0x62, 0x79, 0x68, 0x0A, + 0x59, 0x54, 0x68, 0x31, 0x36, 0x78, 0x31, 0x72, 0x45, 0x48, 0x68, 0x31, 0x57, 0x47, 0x5A, 0x6D, + 0x36, 0x77, 0x64, 0x2B, 0x4B, 0x76, 0x38, 0x6B, 0x31, 0x6B, 0x2F, 0x36, 0x6F, 0x41, 0x2F, 0x4F, + 0x51, 0x76, 0x65, 0x61, 0x38, 0x6B, 0x63, 0x45, 0x64, 0x53, 0x72, 0x54, 0x64, 0x75, 0x71, 0x4A, + 0x33, 0x65, 0x66, 0x74, 0x48, 0x4A, 0x4A, 0x6E, 0x43, 0x4B, 0x30, 0x41, 0x62, 0x68, 0x34, 0x39, + 0x0A, 0x41, 0x47, 0x41, 0x50, 0x39, 0x79, 0x58, 0x77, 0x77, 0x59, 0x41, 0x6A, 0x51, 0x49, 0x52, + 0x6E, 0x38, 0x2B, 0x4F, 0x63, 0x63, 0x48, 0x74, 0x6F, 0x4E, 0x75, 0x75, 0x79, 0x52, 0x63, 0x6B, + 0x49, 0x50, 0x71, 0x75, 0x70, 0x78, 0x79, 0x31, 0x4A, 0x5A, 0x4B, 0x39, 0x64, 0x76, 0x76, 0x62, + 0x34, 0x79, 0x53, 0x6B, 0x49, 0x75, 0x7A, 0x62, 0x79, 0x50, 0x6F, 0x54, 0x41, 0x79, 0x61, 0x55, + 0x2B, 0x0A, 0x51, 0x72, 0x70, 0x34, 0x78, 0x67, 0x64, 0x4B, 0x46, 0x54, 0x70, 0x6B, 0x50, 0x46, + 0x34, 0x33, 0x6A, 0x32, 0x4D, 0x6D, 0x5A, 0x72, 0x46, 0x63, 0x42, 0x76, 0x79, 0x6A, 0x69, 0x35, + 0x6A, 0x4F, 0x37, 0x74, 0x66, 0x6F, 0x56, 0x61, 0x6B, 0x59, 0x47, 0x53, 0x2F, 0x4C, 0x63, 0x78, + 0x77, 0x47, 0x2B, 0x77, 0x51, 0x77, 0x63, 0x4F, 0x43, 0x54, 0x42, 0x45, 0x78, 0x2F, 0x7A, 0x31, + 0x53, 0x30, 0x0A, 0x37, 0x49, 0x2F, 0x6A, 0x62, 0x44, 0x79, 0x53, 0x4E, 0x68, 0x44, 0x35, 0x63, + 0x61, 0x63, 0x54, 0x75, 0x4E, 0x36, 0x50, 0x68, 0x33, 0x58, 0x30, 0x71, 0x70, 0x47, 0x73, 0x37, + 0x79, 0x50, 0x6B, 0x4E, 0x79, 0x69, 0x4A, 0x33, 0x57, 0x52, 0x69, 0x6C, 0x35, 0x75, 0x57, 0x73, + 0x4B, 0x65, 0x79, 0x63, 0x64, 0x71, 0x42, 0x4E, 0x72, 0x34, 0x75, 0x32, 0x62, 0x49, 0x52, 0x6E, + 0x63, 0x54, 0x51, 0x0A, 0x46, 0x72, 0x68, 0x73, 0x58, 0x39, 0x69, 0x77, 0x37, 0x35, 0x76, 0x75, + 0x53, 0x64, 0x35, 0x46, 0x39, 0x37, 0x56, 0x70, 0x41, 0x67, 0x4D, 0x42, 0x41, 0x41, 0x47, 0x6A, + 0x4A, 0x44, 0x41, 0x69, 0x4D, 0x42, 0x4D, 0x47, 0x41, 0x31, 0x55, 0x64, 0x4A, 0x51, 0x51, 0x4D, + 0x4D, 0x41, 0x6F, 0x47, 0x43, 0x43, 0x73, 0x47, 0x41, 0x51, 0x55, 0x46, 0x42, 0x77, 0x4D, 0x42, + 0x4D, 0x41, 0x73, 0x47, 0x0A, 0x41, 0x31, 0x55, 0x64, 0x44, 0x77, 0x51, 0x45, 0x41, 0x77, 0x49, + 0x45, 0x4D, 0x44, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, 0x39, 0x77, 0x30, + 0x42, 0x41, 0x51, 0x55, 0x46, 0x41, 0x41, 0x4F, 0x43, 0x41, 0x51, 0x45, 0x41, 0x49, 0x51, 0x66, + 0x75, 0x2F, 0x77, 0x39, 0x45, 0x34, 0x4C, 0x6F, 0x67, 0x30, 0x71, 0x35, 0x4B, 0x53, 0x38, 0x71, + 0x46, 0x78, 0x62, 0x36, 0x6F, 0x0A, 0x36, 0x31, 0x62, 0x35, 0x37, 0x6F, 0x6D, 0x6E, 0x46, 0x59, + 0x52, 0x34, 0x47, 0x43, 0x67, 0x33, 0x6F, 0x6A, 0x4F, 0x4C, 0x54, 0x66, 0x38, 0x7A, 0x6A, 0x4D, + 0x43, 0x52, 0x6D, 0x75, 0x59, 0x32, 0x76, 0x30, 0x4E, 0x34, 0x78, 0x66, 0x68, 0x69, 0x35, 0x4B, + 0x69, 0x59, 0x67, 0x64, 0x76, 0x4E, 0x4C, 0x4F, 0x33, 0x52, 0x42, 0x6D, 0x4E, 0x50, 0x76, 0x59, + 0x58, 0x50, 0x52, 0x46, 0x41, 0x76, 0x0A, 0x66, 0x61, 0x76, 0x66, 0x57, 0x75, 0x6C, 0x44, 0x31, + 0x64, 0x50, 0x36, 0x31, 0x69, 0x35, 0x62, 0x36, 0x59, 0x66, 0x56, 0x6C, 0x78, 0x62, 0x31, 0x61, + 0x57, 0x46, 0x37, 0x4C, 0x5A, 0x44, 0x32, 0x55, 0x6E, 0x63, 0x41, 0x6A, 0x37, 0x4E, 0x38, 0x78, + 0x38, 0x2B, 0x36, 0x58, 0x6B, 0x30, 0x6B, 0x63, 0x70, 0x58, 0x46, 0x38, 0x6C, 0x77, 0x58, 0x48, + 0x55, 0x57, 0x57, 0x55, 0x6D, 0x73, 0x2B, 0x0A, 0x4B, 0x56, 0x44, 0x34, 0x34, 0x39, 0x68, 0x6F, + 0x4D, 0x2B, 0x77, 0x4E, 0x4A, 0x49, 0x61, 0x4F, 0x52, 0x39, 0x4C, 0x46, 0x2B, 0x6B, 0x6F, 0x32, + 0x32, 0x37, 0x7A, 0x74, 0x37, 0x54, 0x41, 0x47, 0x64, 0x56, 0x35, 0x4A, 0x75, 0x7A, 0x71, 0x38, + 0x32, 0x2F, 0x6B, 0x75, 0x73, 0x6F, 0x65, 0x32, 0x69, 0x75, 0x57, 0x77, 0x54, 0x65, 0x42, 0x6C, + 0x53, 0x5A, 0x6E, 0x6B, 0x42, 0x38, 0x63, 0x64, 0x0A, 0x77, 0x4D, 0x30, 0x5A, 0x42, 0x58, 0x6D, + 0x34, 0x35, 0x48, 0x38, 0x6F, 0x79, 0x75, 0x36, 0x4A, 0x71, 0x59, 0x71, 0x45, 0x6D, 0x75, 0x4A, + 0x51, 0x64, 0x67, 0x79, 0x52, 0x2B, 0x63, 0x53, 0x53, 0x41, 0x7A, 0x2B, 0x4F, 0x32, 0x6D, 0x61, + 0x62, 0x68, 0x50, 0x5A, 0x65, 0x49, 0x76, 0x78, 0x65, 0x67, 0x6A, 0x6A, 0x61, 0x5A, 0x61, 0x46, + 0x4F, 0x71, 0x74, 0x73, 0x2B, 0x64, 0x33, 0x72, 0x39, 0x0A, 0x79, 0x71, 0x4A, 0x78, 0x67, 0x75, + 0x39, 0x43, 0x38, 0x39, 0x5A, 0x69, 0x33, 0x39, 0x57, 0x34, 0x38, 0x46, 0x66, 0x46, 0x63, 0x49, + 0x58, 0x4A, 0x4F, 0x6B, 0x39, 0x43, 0x4E, 0x46, 0x41, 0x2F, 0x69, 0x70, 0x54, 0x57, 0x6A, 0x74, + 0x74, 0x4E, 0x2F, 0x6B, 0x4F, 0x6B, 0x5A, 0x42, 0x70, 0x6F, 0x6A, 0x2F, 0x32, 0x6A, 0x4E, 0x45, + 0x62, 0x4F, 0x59, 0x7A, 0x7A, 0x6E, 0x4B, 0x77, 0x3D, 0x3D, 0x0A, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, + 0x45, 0x4E, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2D, + 0x2D, 0x2D, 0x2D, 0x2D, 0x0A +}; + +static const BYTE test_localhost_key[1704] = { + 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, + 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A, 0x4D, 0x49, 0x49, 0x45, + 0x76, 0x51, 0x49, 0x42, 0x41, 0x44, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, + 0x39, 0x77, 0x30, 0x42, 0x41, 0x51, 0x45, 0x46, 0x41, 0x41, 0x53, 0x43, 0x42, 0x4B, 0x63, 0x77, + 0x67, 0x67, 0x53, 0x6A, 0x41, 0x67, 0x45, 0x41, 0x41, 0x6F, 0x49, 0x42, 0x41, 0x51, 0x43, 0x33, + 0x65, 0x6E, 0x33, 0x68, 0x5A, 0x4F, 0x53, 0x33, 0x6B, 0x51, 0x2F, 0x55, 0x0A, 0x54, 0x30, 0x53, + 0x45, 0x6C, 0x30, 0x48, 0x6E, 0x50, 0x79, 0x64, 0x48, 0x75, 0x35, 0x39, 0x61, 0x69, 0x71, 0x64, + 0x73, 0x64, 0x53, 0x55, 0x74, 0x6E, 0x43, 0x41, 0x37, 0x46, 0x66, 0x74, 0x30, 0x4F, 0x36, 0x51, + 0x79, 0x68, 0x49, 0x71, 0x58, 0x7A, 0x30, 0x47, 0x32, 0x53, 0x76, 0x77, 0x4C, 0x54, 0x62, 0x79, + 0x68, 0x59, 0x54, 0x68, 0x31, 0x36, 0x78, 0x31, 0x72, 0x45, 0x48, 0x68, 0x31, 0x0A, 0x57, 0x47, + 0x5A, 0x6D, 0x36, 0x77, 0x64, 0x2B, 0x4B, 0x76, 0x38, 0x6B, 0x31, 0x6B, 0x2F, 0x36, 0x6F, 0x41, + 0x2F, 0x4F, 0x51, 0x76, 0x65, 0x61, 0x38, 0x6B, 0x63, 0x45, 0x64, 0x53, 0x72, 0x54, 0x64, 0x75, + 0x71, 0x4A, 0x33, 0x65, 0x66, 0x74, 0x48, 0x4A, 0x4A, 0x6E, 0x43, 0x4B, 0x30, 0x41, 0x62, 0x68, + 0x34, 0x39, 0x41, 0x47, 0x41, 0x50, 0x39, 0x79, 0x58, 0x77, 0x77, 0x59, 0x41, 0x6A, 0x0A, 0x51, + 0x49, 0x52, 0x6E, 0x38, 0x2B, 0x4F, 0x63, 0x63, 0x48, 0x74, 0x6F, 0x4E, 0x75, 0x75, 0x79, 0x52, + 0x63, 0x6B, 0x49, 0x50, 0x71, 0x75, 0x70, 0x78, 0x79, 0x31, 0x4A, 0x5A, 0x4B, 0x39, 0x64, 0x76, + 0x76, 0x62, 0x34, 0x79, 0x53, 0x6B, 0x49, 0x75, 0x7A, 0x62, 0x79, 0x50, 0x6F, 0x54, 0x41, 0x79, + 0x61, 0x55, 0x2B, 0x51, 0x72, 0x70, 0x34, 0x78, 0x67, 0x64, 0x4B, 0x46, 0x54, 0x70, 0x6B, 0x0A, + 0x50, 0x46, 0x34, 0x33, 0x6A, 0x32, 0x4D, 0x6D, 0x5A, 0x72, 0x46, 0x63, 0x42, 0x76, 0x79, 0x6A, + 0x69, 0x35, 0x6A, 0x4F, 0x37, 0x74, 0x66, 0x6F, 0x56, 0x61, 0x6B, 0x59, 0x47, 0x53, 0x2F, 0x4C, + 0x63, 0x78, 0x77, 0x47, 0x2B, 0x77, 0x51, 0x77, 0x63, 0x4F, 0x43, 0x54, 0x42, 0x45, 0x78, 0x2F, + 0x7A, 0x31, 0x53, 0x30, 0x37, 0x49, 0x2F, 0x6A, 0x62, 0x44, 0x79, 0x53, 0x4E, 0x68, 0x44, 0x35, + 0x0A, 0x63, 0x61, 0x63, 0x54, 0x75, 0x4E, 0x36, 0x50, 0x68, 0x33, 0x58, 0x30, 0x71, 0x70, 0x47, + 0x73, 0x37, 0x79, 0x50, 0x6B, 0x4E, 0x79, 0x69, 0x4A, 0x33, 0x57, 0x52, 0x69, 0x6C, 0x35, 0x75, + 0x57, 0x73, 0x4B, 0x65, 0x79, 0x63, 0x64, 0x71, 0x42, 0x4E, 0x72, 0x34, 0x75, 0x32, 0x62, 0x49, + 0x52, 0x6E, 0x63, 0x54, 0x51, 0x46, 0x72, 0x68, 0x73, 0x58, 0x39, 0x69, 0x77, 0x37, 0x35, 0x76, + 0x75, 0x0A, 0x53, 0x64, 0x35, 0x46, 0x39, 0x37, 0x56, 0x70, 0x41, 0x67, 0x4D, 0x42, 0x41, 0x41, + 0x45, 0x43, 0x67, 0x67, 0x45, 0x41, 0x42, 0x36, 0x6A, 0x6C, 0x65, 0x48, 0x4E, 0x74, 0x32, 0x50, + 0x77, 0x46, 0x58, 0x53, 0x65, 0x79, 0x42, 0x4A, 0x63, 0x4C, 0x2B, 0x55, 0x74, 0x35, 0x71, 0x46, + 0x54, 0x38, 0x34, 0x68, 0x72, 0x48, 0x77, 0x6F, 0x39, 0x68, 0x62, 0x66, 0x59, 0x47, 0x6F, 0x6E, + 0x44, 0x59, 0x0A, 0x66, 0x70, 0x47, 0x2B, 0x32, 0x52, 0x30, 0x50, 0x62, 0x43, 0x63, 0x4B, 0x35, + 0x30, 0x46, 0x61, 0x4A, 0x46, 0x36, 0x71, 0x63, 0x56, 0x4A, 0x4E, 0x75, 0x52, 0x36, 0x48, 0x71, + 0x2B, 0x43, 0x55, 0x4A, 0x74, 0x48, 0x35, 0x39, 0x48, 0x48, 0x37, 0x62, 0x68, 0x6A, 0x39, 0x62, + 0x64, 0x78, 0x45, 0x6D, 0x6F, 0x48, 0x30, 0x4A, 0x76, 0x68, 0x45, 0x76, 0x67, 0x4D, 0x2F, 0x55, + 0x38, 0x42, 0x51, 0x0A, 0x65, 0x57, 0x4F, 0x4E, 0x68, 0x78, 0x50, 0x73, 0x69, 0x73, 0x6D, 0x57, + 0x6B, 0x78, 0x61, 0x5A, 0x6F, 0x6C, 0x72, 0x32, 0x69, 0x44, 0x56, 0x72, 0x7A, 0x54, 0x37, 0x55, + 0x4A, 0x71, 0x6A, 0x74, 0x59, 0x49, 0x74, 0x67, 0x2B, 0x37, 0x59, 0x43, 0x32, 0x70, 0x55, 0x58, + 0x6B, 0x64, 0x49, 0x35, 0x4A, 0x4D, 0x67, 0x6C, 0x44, 0x47, 0x4D, 0x52, 0x5A, 0x35, 0x55, 0x5A, + 0x48, 0x75, 0x63, 0x7A, 0x0A, 0x41, 0x56, 0x2B, 0x71, 0x77, 0x77, 0x33, 0x65, 0x45, 0x52, 0x74, + 0x78, 0x44, 0x50, 0x61, 0x61, 0x61, 0x34, 0x54, 0x39, 0x50, 0x64, 0x33, 0x44, 0x31, 0x6D, 0x62, + 0x71, 0x58, 0x66, 0x75, 0x45, 0x68, 0x42, 0x6D, 0x33, 0x51, 0x6F, 0x2B, 0x75, 0x7A, 0x51, 0x32, + 0x36, 0x76, 0x73, 0x66, 0x48, 0x75, 0x56, 0x76, 0x61, 0x39, 0x38, 0x32, 0x4F, 0x6A, 0x41, 0x55, + 0x6A, 0x6E, 0x64, 0x30, 0x70, 0x0A, 0x77, 0x43, 0x53, 0x6E, 0x42, 0x49, 0x48, 0x67, 0x70, 0x73, + 0x30, 0x79, 0x61, 0x45, 0x50, 0x63, 0x37, 0x46, 0x78, 0x39, 0x71, 0x45, 0x63, 0x6D, 0x33, 0x70, + 0x7A, 0x41, 0x56, 0x31, 0x69, 0x72, 0x31, 0x4E, 0x4E, 0x63, 0x51, 0x47, 0x55, 0x45, 0x75, 0x45, + 0x6C, 0x4A, 0x78, 0x76, 0x2B, 0x69, 0x57, 0x34, 0x6D, 0x35, 0x70, 0x7A, 0x4C, 0x6A, 0x64, 0x53, + 0x63, 0x49, 0x30, 0x59, 0x45, 0x73, 0x0A, 0x4D, 0x61, 0x33, 0x78, 0x32, 0x79, 0x48, 0x74, 0x6E, + 0x77, 0x79, 0x65, 0x4C, 0x4D, 0x54, 0x4B, 0x6C, 0x72, 0x46, 0x4B, 0x70, 0x55, 0x4E, 0x4A, 0x62, + 0x78, 0x73, 0x35, 0x32, 0x62, 0x5A, 0x4B, 0x71, 0x49, 0x56, 0x33, 0x33, 0x4A, 0x53, 0x34, 0x41, + 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x73, 0x4C, 0x54, 0x49, 0x68, 0x35, 0x59, 0x38, 0x4C, 0x2F, + 0x48, 0x33, 0x64, 0x74, 0x68, 0x63, 0x62, 0x0A, 0x53, 0x43, 0x45, 0x77, 0x32, 0x64, 0x42, 0x49, + 0x76, 0x49, 0x79, 0x54, 0x7A, 0x39, 0x53, 0x72, 0x62, 0x33, 0x58, 0x37, 0x37, 0x41, 0x77, 0x57, + 0x45, 0x4C, 0x53, 0x4D, 0x49, 0x57, 0x53, 0x50, 0x55, 0x43, 0x4B, 0x54, 0x49, 0x70, 0x6A, 0x4D, + 0x73, 0x6E, 0x7A, 0x6B, 0x46, 0x67, 0x32, 0x32, 0x59, 0x32, 0x53, 0x75, 0x47, 0x38, 0x4C, 0x72, + 0x50, 0x6D, 0x76, 0x73, 0x46, 0x4A, 0x34, 0x30, 0x0A, 0x32, 0x67, 0x35, 0x44, 0x55, 0x6C, 0x59, + 0x33, 0x59, 0x6D, 0x53, 0x4F, 0x46, 0x61, 0x45, 0x4A, 0x54, 0x70, 0x55, 0x47, 0x44, 0x4D, 0x79, + 0x65, 0x33, 0x74, 0x36, 0x4F, 0x30, 0x6C, 0x63, 0x51, 0x41, 0x66, 0x79, 0x6D, 0x58, 0x66, 0x41, + 0x38, 0x74, 0x50, 0x42, 0x48, 0x6A, 0x5A, 0x78, 0x56, 0x61, 0x38, 0x78, 0x78, 0x52, 0x5A, 0x6E, + 0x56, 0x43, 0x31, 0x41, 0x62, 0x75, 0x49, 0x49, 0x52, 0x0A, 0x6E, 0x77, 0x72, 0x4E, 0x46, 0x2B, + 0x42, 0x6F, 0x53, 0x4B, 0x55, 0x41, 0x73, 0x78, 0x2B, 0x46, 0x75, 0x35, 0x5A, 0x4A, 0x4B, 0x4F, + 0x66, 0x79, 0x4D, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x47, 0x34, 0x50, 0x52, 0x39, 0x2F, 0x58, + 0x58, 0x6B, 0x51, 0x54, 0x36, 0x6B, 0x7A, 0x4B, 0x64, 0x34, 0x50, 0x6C, 0x50, 0x4D, 0x63, 0x2B, + 0x4B, 0x51, 0x79, 0x4C, 0x45, 0x6C, 0x4B, 0x39, 0x71, 0x47, 0x0A, 0x41, 0x6D, 0x6E, 0x2F, 0x31, + 0x68, 0x64, 0x69, 0x57, 0x57, 0x4F, 0x52, 0x57, 0x46, 0x62, 0x32, 0x38, 0x30, 0x4D, 0x77, 0x76, + 0x77, 0x41, 0x64, 0x78, 0x72, 0x66, 0x65, 0x4C, 0x57, 0x4D, 0x57, 0x32, 0x66, 0x76, 0x4C, 0x59, + 0x4B, 0x66, 0x6C, 0x4F, 0x35, 0x50, 0x51, 0x44, 0x59, 0x67, 0x4B, 0x4A, 0x78, 0x35, 0x79, 0x50, + 0x37, 0x52, 0x64, 0x38, 0x2F, 0x64, 0x50, 0x79, 0x5A, 0x59, 0x36, 0x0A, 0x7A, 0x56, 0x37, 0x47, + 0x47, 0x6B, 0x51, 0x5A, 0x42, 0x4B, 0x36, 0x79, 0x74, 0x61, 0x66, 0x32, 0x35, 0x44, 0x50, 0x67, + 0x50, 0x72, 0x32, 0x77, 0x73, 0x59, 0x4D, 0x43, 0x6C, 0x53, 0x74, 0x6C, 0x56, 0x74, 0x72, 0x6D, + 0x4F, 0x78, 0x59, 0x55, 0x56, 0x77, 0x42, 0x59, 0x4F, 0x69, 0x36, 0x45, 0x62, 0x50, 0x69, 0x6B, + 0x78, 0x47, 0x48, 0x5A, 0x70, 0x59, 0x6F, 0x5A, 0x5A, 0x70, 0x68, 0x4A, 0x0A, 0x4E, 0x61, 0x38, + 0x4F, 0x4C, 0x31, 0x69, 0x77, 0x75, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x42, 0x55, 0x55, 0x31, + 0x54, 0x79, 0x5A, 0x2B, 0x4A, 0x5A, 0x43, 0x64, 0x79, 0x72, 0x33, 0x58, 0x43, 0x63, 0x77, 0x77, + 0x58, 0x2F, 0x48, 0x49, 0x73, 0x31, 0x34, 0x6B, 0x4B, 0x42, 0x48, 0x68, 0x44, 0x79, 0x33, 0x78, + 0x37, 0x74, 0x50, 0x38, 0x2F, 0x6F, 0x48, 0x54, 0x6F, 0x72, 0x76, 0x79, 0x74, 0x0A, 0x41, 0x68, + 0x38, 0x4B, 0x36, 0x4B, 0x72, 0x43, 0x41, 0x75, 0x65, 0x50, 0x6D, 0x79, 0x32, 0x6D, 0x4F, 0x54, + 0x31, 0x54, 0x39, 0x6F, 0x31, 0x61, 0x47, 0x55, 0x49, 0x6C, 0x66, 0x38, 0x72, 0x76, 0x33, 0x2F, + 0x30, 0x45, 0x78, 0x67, 0x53, 0x6B, 0x57, 0x50, 0x6D, 0x4F, 0x41, 0x38, 0x35, 0x49, 0x32, 0x2F, + 0x58, 0x48, 0x65, 0x66, 0x71, 0x54, 0x6F, 0x45, 0x48, 0x30, 0x44, 0x65, 0x41, 0x4E, 0x0A, 0x7A, + 0x6C, 0x4B, 0x4C, 0x71, 0x79, 0x44, 0x56, 0x30, 0x42, 0x56, 0x4E, 0x76, 0x48, 0x42, 0x57, 0x79, + 0x32, 0x49, 0x51, 0x35, 0x62, 0x50, 0x42, 0x57, 0x76, 0x30, 0x37, 0x63, 0x34, 0x2B, 0x6A, 0x39, + 0x4E, 0x62, 0x57, 0x67, 0x64, 0x44, 0x43, 0x43, 0x35, 0x52, 0x6B, 0x4F, 0x6A, 0x70, 0x33, 0x4D, + 0x4E, 0x45, 0x58, 0x47, 0x56, 0x43, 0x69, 0x51, 0x51, 0x4B, 0x42, 0x67, 0x43, 0x7A, 0x4D, 0x0A, + 0x77, 0x65, 0x61, 0x62, 0x73, 0x50, 0x48, 0x68, 0x44, 0x4B, 0x5A, 0x38, 0x2F, 0x34, 0x43, 0x6A, + 0x73, 0x61, 0x62, 0x4E, 0x75, 0x41, 0x7A, 0x62, 0x57, 0x4B, 0x52, 0x42, 0x38, 0x37, 0x44, 0x61, + 0x58, 0x46, 0x78, 0x6F, 0x4D, 0x73, 0x35, 0x52, 0x79, 0x6F, 0x38, 0x55, 0x4D, 0x6B, 0x72, 0x67, + 0x30, 0x35, 0x4C, 0x6F, 0x67, 0x37, 0x4D, 0x78, 0x62, 0x33, 0x76, 0x61, 0x42, 0x34, 0x63, 0x2F, + 0x0A, 0x52, 0x57, 0x77, 0x7A, 0x38, 0x72, 0x34, 0x39, 0x70, 0x48, 0x64, 0x71, 0x68, 0x4F, 0x6D, + 0x63, 0x6C, 0x45, 0x77, 0x79, 0x4D, 0x34, 0x51, 0x79, 0x6A, 0x39, 0x52, 0x6D, 0x57, 0x62, 0x51, + 0x58, 0x54, 0x54, 0x45, 0x63, 0x2B, 0x35, 0x67, 0x54, 0x4B, 0x50, 0x4E, 0x53, 0x33, 0x6D, 0x70, + 0x4D, 0x54, 0x36, 0x39, 0x46, 0x45, 0x74, 0x2F, 0x35, 0x72, 0x4D, 0x52, 0x70, 0x4B, 0x2B, 0x52, + 0x68, 0x0A, 0x49, 0x32, 0x42, 0x58, 0x6B, 0x51, 0x71, 0x31, 0x36, 0x6E, 0x72, 0x31, 0x61, 0x45, + 0x4D, 0x6D, 0x64, 0x51, 0x42, 0x51, 0x79, 0x4B, 0x59, 0x4A, 0x6C, 0x30, 0x6C, 0x50, 0x68, 0x69, + 0x42, 0x2F, 0x75, 0x6C, 0x5A, 0x63, 0x72, 0x67, 0x4C, 0x70, 0x41, 0x6F, 0x47, 0x41, 0x65, 0x30, + 0x65, 0x74, 0x50, 0x4A, 0x77, 0x6D, 0x51, 0x46, 0x6B, 0x6A, 0x4D, 0x70, 0x66, 0x4D, 0x44, 0x61, + 0x4E, 0x34, 0x0A, 0x70, 0x7A, 0x71, 0x45, 0x51, 0x72, 0x52, 0x35, 0x4B, 0x35, 0x4D, 0x6E, 0x54, + 0x48, 0x76, 0x47, 0x67, 0x2F, 0x70, 0x6A, 0x57, 0x6A, 0x43, 0x57, 0x58, 0x56, 0x48, 0x67, 0x35, + 0x76, 0x36, 0x46, 0x6F, 0x5A, 0x48, 0x35, 0x6E, 0x59, 0x2B, 0x56, 0x2F, 0x57, 0x75, 0x57, 0x38, + 0x38, 0x6A, 0x6C, 0x4B, 0x53, 0x50, 0x6C, 0x77, 0x6A, 0x50, 0x7A, 0x41, 0x67, 0x7A, 0x47, 0x33, + 0x45, 0x41, 0x55, 0x0A, 0x71, 0x57, 0x6B, 0x42, 0x67, 0x30, 0x71, 0x75, 0x50, 0x4D, 0x72, 0x54, + 0x6B, 0x73, 0x69, 0x6E, 0x58, 0x50, 0x2B, 0x58, 0x6B, 0x51, 0x65, 0x46, 0x66, 0x58, 0x61, 0x33, + 0x38, 0x6A, 0x72, 0x70, 0x62, 0x4B, 0x46, 0x4F, 0x72, 0x7A, 0x49, 0x6F, 0x6A, 0x69, 0x65, 0x6C, + 0x4B, 0x55, 0x4D, 0x50, 0x4D, 0x78, 0x2F, 0x78, 0x70, 0x53, 0x6A, 0x63, 0x55, 0x42, 0x68, 0x62, + 0x4E, 0x34, 0x45, 0x54, 0x0A, 0x4F, 0x30, 0x66, 0x63, 0x57, 0x47, 0x6F, 0x61, 0x56, 0x50, 0x72, + 0x63, 0x6E, 0x38, 0x62, 0x58, 0x4D, 0x54, 0x45, 0x4E, 0x53, 0x31, 0x41, 0x3D, 0x0A, 0x2D, 0x2D, + 0x2D, 0x2D, 0x2D, 0x45, 0x4E, 0x44, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, + 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A +}; + +static const BYTE test_DummyMessage[64] = { + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, + 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, + 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD +}; + +static const BYTE test_LastDummyMessage[64] = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +static int schannel_send(PSecurityFunctionTable table, HANDLE hPipe, PCtxtHandle phContext, + BYTE* buffer, UINT32 length) +{ + BYTE* ioBuffer; + UINT32 ioBufferLength; + BYTE* pMessageBuffer; + SecBuffer Buffers[4] = { 0 }; + SecBufferDesc Message; + SECURITY_STATUS status; + DWORD NumberOfBytesWritten; + SecPkgContext_StreamSizes StreamSizes = { 0 }; + + status = table->QueryContextAttributes(phContext, SECPKG_ATTR_STREAM_SIZES, &StreamSizes); + ioBufferLength = StreamSizes.cbHeader + StreamSizes.cbMaximumMessage + StreamSizes.cbTrailer; + ioBuffer = (BYTE*)calloc(1, ioBufferLength); + if (!ioBuffer) + return -1; + pMessageBuffer = ioBuffer + StreamSizes.cbHeader; + CopyMemory(pMessageBuffer, buffer, length); + Buffers[0].pvBuffer = ioBuffer; + Buffers[0].cbBuffer = StreamSizes.cbHeader; + Buffers[0].BufferType = SECBUFFER_STREAM_HEADER; + Buffers[1].pvBuffer = pMessageBuffer; + Buffers[1].cbBuffer = length; + Buffers[1].BufferType = SECBUFFER_DATA; + Buffers[2].pvBuffer = pMessageBuffer + length; + Buffers[2].cbBuffer = StreamSizes.cbTrailer; + Buffers[2].BufferType = SECBUFFER_STREAM_TRAILER; + Buffers[3].pvBuffer = NULL; + Buffers[3].cbBuffer = 0; + Buffers[3].BufferType = SECBUFFER_EMPTY; + Message.ulVersion = SECBUFFER_VERSION; + Message.cBuffers = 4; + Message.pBuffers = Buffers; + ioBufferLength = + Message.pBuffers[0].cbBuffer + Message.pBuffers[1].cbBuffer + Message.pBuffers[2].cbBuffer; + status = table->EncryptMessage(phContext, 0, &Message, 0); + printf("EncryptMessage status: 0x%08" PRIX32 "\n", status); + printf("EncryptMessage output: cBuffers: %" PRIu32 " [0]: %" PRIu32 " / %" PRIu32 + " [1]: %" PRIu32 " / %" PRIu32 " [2]: %" PRIu32 " / %" PRIu32 " [3]: %" PRIu32 + " / %" PRIu32 "\n", + Message.cBuffers, Message.pBuffers[0].cbBuffer, Message.pBuffers[0].BufferType, + Message.pBuffers[1].cbBuffer, Message.pBuffers[1].BufferType, + Message.pBuffers[2].cbBuffer, Message.pBuffers[2].BufferType, + Message.pBuffers[3].cbBuffer, Message.pBuffers[3].BufferType); + + if (status != SEC_E_OK) + return -1; + + printf("Client > Server (%" PRIu32 ")\n", ioBufferLength); + winpr_HexDump("sspi.test", WLOG_DEBUG, ioBuffer, ioBufferLength); + + if (!WriteFile(hPipe, ioBuffer, ioBufferLength, &NumberOfBytesWritten, NULL)) + { + printf("schannel_send: failed to write to pipe\n"); + return -1; + } + + return 0; +} + +static int schannel_recv(PSecurityFunctionTable table, HANDLE hPipe, PCtxtHandle phContext) +{ + BYTE* ioBuffer; + UINT32 ioBufferLength; + // BYTE* pMessageBuffer; + SecBuffer Buffers[4] = { 0 }; + SecBufferDesc Message; + SECURITY_STATUS status; + DWORD NumberOfBytesRead; + SecPkgContext_StreamSizes StreamSizes = { 0 }; + + status = table->QueryContextAttributes(phContext, SECPKG_ATTR_STREAM_SIZES, &StreamSizes); + ioBufferLength = StreamSizes.cbHeader + StreamSizes.cbMaximumMessage + StreamSizes.cbTrailer; + ioBuffer = (BYTE*)calloc(1, ioBufferLength); + if (!ioBuffer) + return -1; + + if (!ReadFile(hPipe, ioBuffer, ioBufferLength, &NumberOfBytesRead, NULL)) + { + printf("schannel_recv: failed to read from pipe\n"); + return -1; + } + + Buffers[0].pvBuffer = ioBuffer; + Buffers[0].cbBuffer = NumberOfBytesRead; + Buffers[0].BufferType = SECBUFFER_DATA; + Buffers[1].pvBuffer = NULL; + Buffers[1].cbBuffer = 0; + Buffers[1].BufferType = SECBUFFER_EMPTY; + Buffers[2].pvBuffer = NULL; + Buffers[2].cbBuffer = 0; + Buffers[2].BufferType = SECBUFFER_EMPTY; + Buffers[3].pvBuffer = NULL; + Buffers[3].cbBuffer = 0; + Buffers[3].BufferType = SECBUFFER_EMPTY; + Message.ulVersion = SECBUFFER_VERSION; + Message.cBuffers = 4; + Message.pBuffers = Buffers; + status = table->DecryptMessage(phContext, &Message, 0, NULL); + printf("DecryptMessage status: 0x%08" PRIX32 "\n", status); + printf("DecryptMessage output: cBuffers: %" PRIu32 " [0]: %" PRIu32 " / %" PRIu32 + " [1]: %" PRIu32 " / %" PRIu32 " [2]: %" PRIu32 " / %" PRIu32 " [3]: %" PRIu32 + " / %" PRIu32 "\n", + Message.cBuffers, Message.pBuffers[0].cbBuffer, Message.pBuffers[0].BufferType, + Message.pBuffers[1].cbBuffer, Message.pBuffers[1].BufferType, + Message.pBuffers[2].cbBuffer, Message.pBuffers[2].BufferType, + Message.pBuffers[3].cbBuffer, Message.pBuffers[3].BufferType); + + if (status != SEC_E_OK) + return -1; + + printf("Decrypted Message (%" PRIu32 ")\n", Message.pBuffers[1].cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)Message.pBuffers[1].pvBuffer, + Message.pBuffers[1].cbBuffer); + + if (memcmp(Message.pBuffers[1].pvBuffer, test_LastDummyMessage, + sizeof(test_LastDummyMessage)) == 0) + return -1; + + return 0; +} + +static DWORD WINAPI schannel_test_server_thread(LPVOID arg) +{ + BOOL extraData; + BYTE* lpTokenIn; + BYTE* lpTokenOut; + TimeStamp expiry; + UINT32 cbMaxToken; + UINT32 fContextReq; + ULONG fContextAttr; + SCHANNEL_CRED cred = { 0 }; + CtxtHandle context; + CredHandle credentials; + DWORD cchNameString; + LPTSTR pszNameString; + HCERTSTORE hCertStore; + PCCERT_CONTEXT pCertContext; + PSecBuffer pSecBuffer; + SecBuffer SecBuffer_in[2] = { 0 }; + SecBuffer SecBuffer_out[2] = { 0 }; + SecBufferDesc SecBufferDesc_in; + SecBufferDesc SecBufferDesc_out; + DWORD NumberOfBytesRead; + SECURITY_STATUS status; + PSecPkgInfo pPackageInfo; + PSecurityFunctionTable table; + DWORD NumberOfBytesWritten; + printf("Starting Server\n"); + SecInvalidateHandle(&context); + SecInvalidateHandle(&credentials); + table = InitSecurityInterface(); + status = QuerySecurityPackageInfo(SCHANNEL_NAME, &pPackageInfo); + + if (status != SEC_E_OK) + { + printf("QuerySecurityPackageInfo failure: 0x%08" PRIX32 "\n", status); + return 0; + } + + cbMaxToken = pPackageInfo->cbMaxToken; + hCertStore = CertOpenSystemStore(0, _T("MY")); + + if (!hCertStore) + { + printf("Error opening system store\n"); + // return NULL; + } + +#ifdef CERT_FIND_HAS_PRIVATE_KEY + pCertContext = CertFindCertificateInStore(hCertStore, X509_ASN_ENCODING, 0, + CERT_FIND_HAS_PRIVATE_KEY, NULL, NULL); +#else + pCertContext = + CertFindCertificateInStore(hCertStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, NULL); +#endif + + if (!pCertContext) + { + printf("Error finding certificate in store\n"); + // return NULL; + } + + cchNameString = + CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0); + pszNameString = (LPTSTR)malloc(cchNameString * sizeof(TCHAR)); + if (!pszNameString) + { + printf("Memory allocation failed\n"); + return 0; + } + cchNameString = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, + pszNameString, cchNameString); + _tprintf(_T("Certificate Name: %s\n"), pszNameString); + cred.dwVersion = SCHANNEL_CRED_VERSION; + cred.cCreds = 1; + cred.paCred = &pCertContext; + cred.cSupportedAlgs = 0; + cred.palgSupportedAlgs = NULL; + cred.grbitEnabledProtocols = SP_PROT_TLS1_SERVER; + cred.dwFlags = SCH_CRED_NO_SYSTEM_MAPPER; + status = table->AcquireCredentialsHandle(NULL, SCHANNEL_NAME, SECPKG_CRED_INBOUND, NULL, &cred, + NULL, NULL, &credentials, NULL); + + if (status != SEC_E_OK) + { + printf("AcquireCredentialsHandle failure: 0x%08" PRIX32 "\n", status); + return 0; + } + + extraData = FALSE; + g_ServerWait = TRUE; + if (!(lpTokenIn = (BYTE*)malloc(cbMaxToken))) + { + printf("Memory allocation failed\n"); + return 0; + } + if (!(lpTokenOut = (BYTE*)malloc(cbMaxToken))) + { + printf("Memory allocation failed\n"); + free(lpTokenIn); + return 0; + } + fContextReq = ASC_REQ_STREAM | ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | + ASC_REQ_CONFIDENTIALITY | ASC_REQ_EXTENDED_ERROR; + + do + { + if (!extraData) + { + if (g_ServerWait) + { + if (!ReadFile(g_ServerReadPipe, lpTokenIn, cbMaxToken, &NumberOfBytesRead, NULL)) + { + printf("Failed to read from server pipe\n"); + return NULL; + } + } + else + { + NumberOfBytesRead = 0; + } + } + + extraData = FALSE; + g_ServerWait = TRUE; + SecBuffer_in[0].BufferType = SECBUFFER_TOKEN; + SecBuffer_in[0].pvBuffer = lpTokenIn; + SecBuffer_in[0].cbBuffer = NumberOfBytesRead; + SecBuffer_in[1].BufferType = SECBUFFER_EMPTY; + SecBuffer_in[1].pvBuffer = NULL; + SecBuffer_in[1].cbBuffer = 0; + SecBufferDesc_in.ulVersion = SECBUFFER_VERSION; + SecBufferDesc_in.cBuffers = 2; + SecBufferDesc_in.pBuffers = SecBuffer_in; + SecBuffer_out[0].BufferType = SECBUFFER_TOKEN; + SecBuffer_out[0].pvBuffer = lpTokenOut; + SecBuffer_out[0].cbBuffer = cbMaxToken; + SecBufferDesc_out.ulVersion = SECBUFFER_VERSION; + SecBufferDesc_out.cBuffers = 1; + SecBufferDesc_out.pBuffers = SecBuffer_out; + status = table->AcceptSecurityContext( + &credentials, SecIsValidHandle(&context) ? &context : NULL, &SecBufferDesc_in, + fContextReq, 0, &context, &SecBufferDesc_out, &fContextAttr, &expiry); + + if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED) && + (status != SEC_E_INCOMPLETE_MESSAGE)) + { + printf("AcceptSecurityContext unexpected status: 0x%08" PRIX32 "\n", status); + return NULL; + } + + NumberOfBytesWritten = 0; + + if (status == SEC_E_OK) + printf("AcceptSecurityContext status: SEC_E_OK\n"); + else if (status == SEC_I_CONTINUE_NEEDED) + printf("AcceptSecurityContext status: SEC_I_CONTINUE_NEEDED\n"); + else if (status == SEC_E_INCOMPLETE_MESSAGE) + printf("AcceptSecurityContext status: SEC_E_INCOMPLETE_MESSAGE\n"); + + printf("Server cBuffers: %" PRIu32 " pBuffers[0]: %" PRIu32 " type: %" PRIu32 "\n", + SecBufferDesc_out.cBuffers, SecBufferDesc_out.pBuffers[0].cbBuffer, + SecBufferDesc_out.pBuffers[0].BufferType); + printf("Server Input cBuffers: %" PRIu32 " pBuffers[0]: %" PRIu32 " type: %" PRIu32 + " pBuffers[1]: %" PRIu32 " type: %" PRIu32 "\n", + SecBufferDesc_in.cBuffers, SecBufferDesc_in.pBuffers[0].cbBuffer, + SecBufferDesc_in.pBuffers[0].BufferType, SecBufferDesc_in.pBuffers[1].cbBuffer, + SecBufferDesc_in.pBuffers[1].BufferType); + + if (SecBufferDesc_in.pBuffers[1].BufferType == SECBUFFER_EXTRA) + { + printf("AcceptSecurityContext SECBUFFER_EXTRA\n"); + pSecBuffer = &SecBufferDesc_in.pBuffers[1]; + CopyMemory(lpTokenIn, &lpTokenIn[NumberOfBytesRead - pSecBuffer->cbBuffer], + pSecBuffer->cbBuffer); + NumberOfBytesRead = pSecBuffer->cbBuffer; + continue; + } + + if (status != SEC_E_INCOMPLETE_MESSAGE) + { + pSecBuffer = &SecBufferDesc_out.pBuffers[0]; + + if (pSecBuffer->cbBuffer > 0) + { + printf("Server > Client (%" PRIu32 ")\n", pSecBuffer->cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)pSecBuffer->pvBuffer, + pSecBuffer->cbBuffer); + + if (!WriteFile(g_ClientWritePipe, pSecBuffer->pvBuffer, pSecBuffer->cbBuffer, + &NumberOfBytesWritten, NULL)) + { + printf("failed to write to client pipe\n"); + return NULL; + } + } + } + + if (status == SEC_E_OK) + { + printf("Server Handshake Complete\n"); + break; + } + } while (1); + + do + { + if (schannel_recv(table, g_ServerReadPipe, &context) < 0) + break; + } while (1); + + return 0; +} + +static int dump_test_certificate_files(void) +{ + FILE* fp; + char* fullpath = NULL; + int ret = -1; + + /* + * Output Certificate File + */ + fullpath = GetCombinedPath("/tmp", "localhost.crt"); + if (!fullpath) + return -1; + + fp = winpr_fopen(fullpath, "w+"); + if (fp) + { + if (fwrite((void*)test_localhost_crt, sizeof(test_localhost_crt), 1, fp) != 1) + goto out_fail; + fclose(fp); + fp = NULL; + } + free(fullpath); + + /* + * Output Private Key File + */ + fullpath = GetCombinedPath("/tmp", "localhost.key"); + if (!fullpath) + return -1; + fp = winpr_fopen(fullpath, "w+"); + if (fp && fwrite((void*)test_localhost_key, sizeof(test_localhost_key), 1, fp) != 1) + goto out_fail; + + ret = 1; +out_fail: + free(fullpath); + if (fp) + fclose(fp); + return ret; +} + +int TestSchannel(int argc, char* argv[]) +{ + int count; + ALG_ID algId; + HANDLE thread; + BYTE* lpTokenIn; + BYTE* lpTokenOut; + TimeStamp expiry; + UINT32 cbMaxToken; + SCHANNEL_CRED cred = { 0 }; + UINT32 fContextReq; + ULONG fContextAttr; + CtxtHandle context; + CredHandle credentials; + SECURITY_STATUS status; + PSecPkgInfo pPackageInfo; + PSecBuffer pSecBuffer; + PSecurityFunctionTable table; + DWORD NumberOfBytesRead; + DWORD NumberOfBytesWritten; + SecPkgCred_SupportedAlgs SupportedAlgs = { 0 }; + SecPkgCred_CipherStrengths CipherStrengths = { 0 }; + SecPkgCred_SupportedProtocols SupportedProtocols = { 0 }; + return 0; /* disable by default - causes crash */ + sspi_GlobalInit(); + dump_test_certificate_files(); + SecInvalidateHandle(&context); + SecInvalidateHandle(&credentials); + + if (!CreatePipe(&g_ClientReadPipe, &g_ClientWritePipe, NULL, 0)) + { + printf("Failed to create client pipe\n"); + return -1; + } + + if (!CreatePipe(&g_ServerReadPipe, &g_ServerWritePipe, NULL, 0)) + { + printf("Failed to create server pipe\n"); + return -1; + } + + if (!(thread = CreateThread(NULL, 0, schannel_test_server_thread, NULL, 0, NULL))) + { + printf("Failed to create server thread\n"); + return -1; + } + + table = InitSecurityInterface(); + status = QuerySecurityPackageInfo(SCHANNEL_NAME, &pPackageInfo); + + if (status != SEC_E_OK) + { + printf("QuerySecurityPackageInfo failure: 0x%08" PRIX32 "\n", status); + return -1; + } + + cbMaxToken = pPackageInfo->cbMaxToken; + cred.dwVersion = SCHANNEL_CRED_VERSION; + cred.cCreds = 0; + cred.paCred = NULL; + cred.cSupportedAlgs = 0; + cred.palgSupportedAlgs = NULL; + cred.grbitEnabledProtocols = SP_PROT_SSL3TLS1_CLIENTS; + cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS; + cred.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION; + cred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK; + status = table->AcquireCredentialsHandle(NULL, SCHANNEL_NAME, SECPKG_CRED_OUTBOUND, NULL, &cred, + NULL, NULL, &credentials, NULL); + + if (status != SEC_E_OK) + { + printf("AcquireCredentialsHandle failure: 0x%08" PRIX32 "\n", status); + return -1; + } + + status = + table->QueryCredentialsAttributes(&credentials, SECPKG_ATTR_SUPPORTED_ALGS, &SupportedAlgs); + + if (status != SEC_E_OK) + { + printf("QueryCredentialsAttributes SECPKG_ATTR_SUPPORTED_ALGS failure: 0x%08" PRIX32 "\n", + status); + return -1; + } + + /** + * SupportedAlgs: 15 + * 0x660E 0x6610 0x6801 0x6603 0x6601 0x8003 0x8004 + * 0x800C 0x800D 0x800E 0x2400 0xAA02 0xAE06 0x2200 0x2203 + */ + printf("SupportedAlgs: %" PRIu32 "\n", SupportedAlgs.cSupportedAlgs); + + for (DWORD index = 0; index < SupportedAlgs.cSupportedAlgs; index++) + { + algId = SupportedAlgs.palgSupportedAlgs[index]; + printf("\t0x%08" PRIX32 " CLASS: %" PRIu32 " TYPE: %" PRIu32 " SID: %" PRIu32 "\n", algId, + ((GET_ALG_CLASS(algId)) >> 13), ((GET_ALG_TYPE(algId)) >> 9), GET_ALG_SID(algId)); + } + + printf("\n"); + status = table->QueryCredentialsAttributes(&credentials, SECPKG_ATTR_CIPHER_STRENGTHS, + &CipherStrengths); + + if (status != SEC_E_OK) + { + printf("QueryCredentialsAttributes SECPKG_ATTR_CIPHER_STRENGTHS failure: 0x%08" PRIX32 "\n", + status); + return -1; + } + + /* CipherStrengths: Minimum: 40 Maximum: 256 */ + printf("CipherStrengths: Minimum: %" PRIu32 " Maximum: %" PRIu32 "\n", + CipherStrengths.dwMinimumCipherStrength, CipherStrengths.dwMaximumCipherStrength); + status = table->QueryCredentialsAttributes(&credentials, SECPKG_ATTR_SUPPORTED_PROTOCOLS, + &SupportedProtocols); + + if (status != SEC_E_OK) + { + printf("QueryCredentialsAttributes SECPKG_ATTR_SUPPORTED_PROTOCOLS failure: 0x%08" PRIX32 + "\n", + status); + return -1; + } + + /* SupportedProtocols: 0x208A0 */ + printf("SupportedProtocols: 0x%08" PRIX32 "\n", SupportedProtocols.grbitProtocol); + fContextReq = ISC_REQ_STREAM | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | + ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | + ISC_REQ_MANUAL_CRED_VALIDATION | ISC_REQ_INTEGRITY; + if (!(lpTokenIn = (BYTE*)malloc(cbMaxToken))) + { + printf("Memory allocation failed\n"); + return -1; + } + if (!(lpTokenOut = (BYTE*)malloc(cbMaxToken))) + { + printf("Memory allocation failed\n"); + return -1; + } + g_ClientWait = FALSE; + + do + { + SecBuffer SecBuffer_in[2] = { 0 }; + SecBuffer SecBuffer_out[1] = { 0 }; + SecBufferDesc SecBufferDesc_in = { 0 }; + SecBufferDesc SecBufferDesc_out = { 0 }; + if (g_ClientWait) + { + if (!ReadFile(g_ClientReadPipe, lpTokenIn, cbMaxToken, &NumberOfBytesRead, NULL)) + { + printf("failed to read from server pipe\n"); + return -1; + } + } + else + { + NumberOfBytesRead = 0; + } + + g_ClientWait = TRUE; + printf("NumberOfBytesRead: %" PRIu32 "\n", NumberOfBytesRead); + SecBuffer_in[0].BufferType = SECBUFFER_TOKEN; + SecBuffer_in[0].pvBuffer = lpTokenIn; + SecBuffer_in[0].cbBuffer = NumberOfBytesRead; + SecBuffer_in[1].pvBuffer = NULL; + SecBuffer_in[1].cbBuffer = 0; + SecBuffer_in[1].BufferType = SECBUFFER_EMPTY; + SecBufferDesc_in.ulVersion = SECBUFFER_VERSION; + SecBufferDesc_in.cBuffers = 2; + SecBufferDesc_in.pBuffers = SecBuffer_in; + SecBuffer_out[0].BufferType = SECBUFFER_TOKEN; + SecBuffer_out[0].pvBuffer = lpTokenOut; + SecBuffer_out[0].cbBuffer = cbMaxToken; + SecBufferDesc_out.ulVersion = SECBUFFER_VERSION; + SecBufferDesc_out.cBuffers = 1; + SecBufferDesc_out.pBuffers = SecBuffer_out; + status = table->InitializeSecurityContext( + &credentials, SecIsValidHandle(&context) ? &context : NULL, _T("localhost"), + fContextReq, 0, 0, &SecBufferDesc_in, 0, &context, &SecBufferDesc_out, &fContextAttr, + &expiry); + + if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED) && + (status != SEC_E_INCOMPLETE_MESSAGE)) + { + printf("InitializeSecurityContext unexpected status: 0x%08" PRIX32 "\n", status); + return -1; + } + + NumberOfBytesWritten = 0; + + if (status == SEC_E_OK) + printf("InitializeSecurityContext status: SEC_E_OK\n"); + else if (status == SEC_I_CONTINUE_NEEDED) + printf("InitializeSecurityContext status: SEC_I_CONTINUE_NEEDED\n"); + else if (status == SEC_E_INCOMPLETE_MESSAGE) + printf("InitializeSecurityContext status: SEC_E_INCOMPLETE_MESSAGE\n"); + + printf("Client Output cBuffers: %" PRIu32 " pBuffers[0]: %" PRIu32 " type: %" PRIu32 "\n", + SecBufferDesc_out.cBuffers, SecBufferDesc_out.pBuffers[0].cbBuffer, + SecBufferDesc_out.pBuffers[0].BufferType); + printf("Client Input cBuffers: %" PRIu32 " pBuffers[0]: %" PRIu32 " type: %" PRIu32 + " pBuffers[1]: %" PRIu32 " type: %" PRIu32 "\n", + SecBufferDesc_in.cBuffers, SecBufferDesc_in.pBuffers[0].cbBuffer, + SecBufferDesc_in.pBuffers[0].BufferType, SecBufferDesc_in.pBuffers[1].cbBuffer, + SecBufferDesc_in.pBuffers[1].BufferType); + + if (status != SEC_E_INCOMPLETE_MESSAGE) + { + pSecBuffer = &SecBufferDesc_out.pBuffers[0]; + + if (pSecBuffer->cbBuffer > 0) + { + printf("Client > Server (%" PRIu32 ")\n", pSecBuffer->cbBuffer); + winpr_HexDump("sspi.test", WLOG_DEBUG, (BYTE*)pSecBuffer->pvBuffer, + pSecBuffer->cbBuffer); + + if (!WriteFile(g_ServerWritePipe, pSecBuffer->pvBuffer, pSecBuffer->cbBuffer, + &NumberOfBytesWritten, NULL)) + { + printf("failed to write to server pipe\n"); + return -1; + } + } + } + + if (status == SEC_E_OK) + { + printf("Client Handshake Complete\n"); + break; + } + } while (1); + + count = 0; + + do + { + if (schannel_send(table, g_ServerWritePipe, &context, test_DummyMessage, + sizeof(test_DummyMessage)) < 0) + break; + + for (DWORD index = 0; index < sizeof(test_DummyMessage); index++) + { + BYTE b, ln, hn; + b = test_DummyMessage[index]; + ln = (b & 0x0F); + hn = ((b & 0xF0) >> 4); + ln = (ln + 1) % 0xF; + hn = (ln + 1) % 0xF; + b = (ln | (hn << 4)); + test_DummyMessage[index] = b; + } + + Sleep(100); + count++; + } while (count < 3); + + schannel_send(table, g_ServerWritePipe, &context, test_LastDummyMessage, + sizeof(test_LastDummyMessage)); + (void)WaitForSingleObject(thread, INFINITE); + sspi_GlobalFinish(); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f50585e3d3141ee586601e2f03a7aa9206b8f20a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/CMakeLists.txt @@ -0,0 +1,18 @@ +# WinPR: Windows Portable Runtime +# libwinpr-sspicli cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(sspicli.c) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..953a96cbd5e180cd9686744939644d18996c833e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/ModuleOptions.cmake @@ -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 "sspicli") +set(MINWIN_LONG_NAME "Authentication Functions") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/sspicli.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/sspicli.c new file mode 100644 index 0000000000000000000000000000000000000000..b1a3f0c616915c41d3eda8e722a1250d9cf12027 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sspicli/sspicli.c @@ -0,0 +1,286 @@ +/** + * WinPR: Windows Portable Runtime + * Security Support Provider Interface + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +/** + * sspicli.dll: + * + * EnumerateSecurityPackagesA + * EnumerateSecurityPackagesW + * GetUserNameExW + * ImportSecurityContextA + * LogonUser + * LogonUserEx + * LogonUserExExW + * SspiCompareAuthIdentities + * SspiCopyAuthIdentity + * SspiDecryptAuthIdentity + * SspiEncodeAuthIdentityAsStrings + * SspiEncodeStringsAsAuthIdentity + * SspiEncryptAuthIdentity + * SspiExcludePackage + * SspiFreeAuthIdentity + * SspiGetTargetHostName + * SspiIsAuthIdentityEncrypted + * SspiLocalFree + * SspiMarshalAuthIdentity + * SspiPrepareForCredRead + * SspiPrepareForCredWrite + * SspiUnmarshalAuthIdentity + * SspiValidateAuthIdentity + * SspiZeroAuthIdentity + */ + +#ifndef _WIN32 + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#if defined(WINPR_HAVE_GETPWUID_R) +#include +#endif + +#include + +#include +#include + +#include "../handle/handle.h" + +#include "../security/security.h" + +static BOOL LogonUserCloseHandle(HANDLE handle); + +static BOOL LogonUserIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_ACCESS_TOKEN, FALSE); +} + +static int LogonUserGetFd(HANDLE handle) +{ + WINPR_ACCESS_TOKEN* pLogonUser = (WINPR_ACCESS_TOKEN*)handle; + + if (!LogonUserIsHandled(handle)) + return -1; + + /* TODO: File fd not supported */ + (void)pLogonUser; + return -1; +} + +BOOL LogonUserCloseHandle(HANDLE handle) +{ + WINPR_ACCESS_TOKEN* token = (WINPR_ACCESS_TOKEN*)handle; + + if (!handle || !LogonUserIsHandled(handle)) + return FALSE; + + free(token->Username); + free(token->Domain); + free(token); + return TRUE; +} + +static HANDLE_OPS ops = { LogonUserIsHandled, + LogonUserCloseHandle, + LogonUserGetFd, + NULL, /* CleanupHandle */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +BOOL LogonUserA(LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword, DWORD dwLogonType, + DWORD dwLogonProvider, PHANDLE phToken) +{ + if (!lpszUsername) + return FALSE; + + WINPR_ACCESS_TOKEN* token = (WINPR_ACCESS_TOKEN*)calloc(1, sizeof(WINPR_ACCESS_TOKEN)); + + if (!token) + return FALSE; + + WINPR_HANDLE_SET_TYPE_AND_MODE(token, HANDLE_TYPE_ACCESS_TOKEN, WINPR_FD_READ); + token->common.ops = &ops; + token->Username = _strdup(lpszUsername); + + if (!token->Username) + goto fail; + + if (lpszDomain) + { + token->Domain = _strdup(lpszDomain); + + if (!token->Domain) + goto fail; + } + + long buflen = sysconf(_SC_GETPW_R_SIZE_MAX); + if (buflen < 0) + buflen = 8196; + + const size_t s = 1ULL + (size_t)buflen; + char* buf = (char*)calloc(s, sizeof(char)); + if (!buf) + goto fail; + + struct passwd pwd = { 0 }; + struct passwd* pw = NULL; + const int rc = + getpwnam_r(lpszUsername, &pwd, buf, WINPR_ASSERTING_INT_CAST(size_t, buflen), &pw); + free(buf); + if ((rc == 0) && pw) + { + token->UserId = (DWORD)pw->pw_uid; + token->GroupId = (DWORD)pw->pw_gid; + } + + *((ULONG_PTR*)phToken) = (ULONG_PTR)token; + return TRUE; + +fail: + free(token->Username); + free(token->Domain); + free(token); + return FALSE; +} + +BOOL LogonUserW(LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword, DWORD dwLogonType, + DWORD dwLogonProvider, PHANDLE phToken) +{ + return TRUE; +} + +BOOL LogonUserExA(LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword, DWORD dwLogonType, + DWORD dwLogonProvider, PHANDLE phToken, PSID* ppLogonSid, PVOID* ppProfileBuffer, + LPDWORD pdwProfileLength, PQUOTA_LIMITS pQuotaLimits) +{ + return TRUE; +} + +BOOL LogonUserExW(LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword, DWORD dwLogonType, + DWORD dwLogonProvider, PHANDLE phToken, PSID* ppLogonSid, PVOID* ppProfileBuffer, + LPDWORD pdwProfileLength, PQUOTA_LIMITS pQuotaLimits) +{ + return TRUE; +} + +BOOL GetUserNameExA(EXTENDED_NAME_FORMAT NameFormat, LPSTR lpNameBuffer, PULONG nSize) +{ + WINPR_ASSERT(lpNameBuffer); + WINPR_ASSERT(nSize); + + switch (NameFormat) + { + case NameSamCompatible: +#if defined(WINPR_HAVE_GETPWUID_R) + { + int rc = 0; + struct passwd pwd = { 0 }; + struct passwd* result = NULL; + uid_t uid = getuid(); + + rc = getpwuid_r(uid, &pwd, lpNameBuffer, *nSize, &result); + if (rc != 0) + return FALSE; + if (result == NULL) + return FALSE; + } +#elif defined(WINPR_HAVE_GETLOGIN_R) + if (getlogin_r(lpNameBuffer, *nSize) != 0) + return FALSE; +#else + { + const char* name = getlogin(); + if (!name) + return FALSE; + strncpy(lpNameBuffer, name, strnlen(name, *nSize)); + } +#endif + const size_t len = strnlen(lpNameBuffer, *nSize); + if (len > UINT32_MAX) + return FALSE; + *nSize = (ULONG)len; + return TRUE; + + case NameFullyQualifiedDN: + case NameDisplay: + case NameUniqueId: + case NameCanonical: + case NameUserPrincipal: + case NameCanonicalEx: + case NameServicePrincipal: + case NameDnsDomain: + break; + + default: + break; + } + + return FALSE; +} + +BOOL GetUserNameExW(EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG nSize) +{ + BOOL rc = FALSE; + char* name = NULL; + + WINPR_ASSERT(nSize); + WINPR_ASSERT(lpNameBuffer); + + name = calloc(1, *nSize + 1); + if (!name) + goto fail; + + if (!GetUserNameExA(NameFormat, name, nSize)) + goto fail; + + const SSIZE_T res = ConvertUtf8ToWChar(name, lpNameBuffer, *nSize); + if ((res < 0) || (res >= UINT32_MAX)) + goto fail; + + *nSize = (UINT32)res + 1; + rc = TRUE; +fail: + free(name); + return rc; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..50de638eb625e0010fa441c7cd2907310d171552 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/CMakeLists.txt @@ -0,0 +1,41 @@ +# WinPR: Windows Portable Runtime +# libwinpr-synch cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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( + address.c + barrier.c + critical.c + event.c + init.c + mutex.c + pollset.c + pollset.h + semaphore.c + sleep.c + synch.h + timer.c + wait.c +) + +if(FREEBSD) + winpr_system_include_directory_add(${EPOLLSHIM_INCLUDE_DIR}) + winpr_library_add_private(${EPOLLSHIM_LIBS}) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..87e1b2789e7fa2c81b90cd20b7f1bdd6d33cf010 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "synch") +set(MINWIN_LONG_NAME "Synchronization Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/address.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/address.c new file mode 100644 index 0000000000000000000000000000000000000000..c6b10abc42b20e7ac8e34b942ee1e117ba6a1c63 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/address.c @@ -0,0 +1,46 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +/** + * WakeByAddressAll + * WakeByAddressSingle + * WaitOnAddress + */ + +#ifndef _WIN32 + +VOID WakeByAddressAll(PVOID Address) +{ +} + +VOID WakeByAddressSingle(PVOID Address) +{ +} + +BOOL WaitOnAddress(VOID volatile* Address, PVOID CompareAddress, size_t AddressSize, + DWORD dwMilliseconds) +{ + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/barrier.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/barrier.c new file mode 100644 index 0000000000000000000000000000000000000000..8d2680bc231ad1d7fc8dc0e34856ab9df857bd43 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/barrier.c @@ -0,0 +1,262 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2016 Norbert Federa + * + * 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 + +#include +#include + +#include "synch.h" + +#include + +#ifdef WINPR_SYNCHRONIZATION_BARRIER + +#include +#include +#include +#include + +/** + * WinPR uses the internal RTL_BARRIER struct members exactly like Windows: + * + * DWORD Reserved1: number of threads that have not yet entered the barrier + * DWORD Reserved2: number of threads required to enter the barrier + * ULONG_PTR Reserved3[2]; two synchronization events (manual reset events) + * DWORD Reserved4; number of processors + * DWORD Reserved5; spincount + */ + +#ifdef _WIN32 + +static HMODULE g_Kernel32 = NULL; +static BOOL g_NativeBarrier = FALSE; +static INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; + +typedef BOOL(WINAPI* fnInitializeSynchronizationBarrier)(LPSYNCHRONIZATION_BARRIER lpBarrier, + LONG lTotalThreads, LONG lSpinCount); +typedef BOOL(WINAPI* fnEnterSynchronizationBarrier)(LPSYNCHRONIZATION_BARRIER lpBarrier, + DWORD dwFlags); +typedef BOOL(WINAPI* fnDeleteSynchronizationBarrier)(LPSYNCHRONIZATION_BARRIER lpBarrier); + +static fnInitializeSynchronizationBarrier pfnInitializeSynchronizationBarrier = NULL; +static fnEnterSynchronizationBarrier pfnEnterSynchronizationBarrier = NULL; +static fnDeleteSynchronizationBarrier pfnDeleteSynchronizationBarrier = NULL; + +static BOOL CALLBACK InitOnce_Barrier(PINIT_ONCE once, PVOID param, PVOID* context) +{ + g_Kernel32 = LoadLibraryA("kernel32.dll"); + + if (!g_Kernel32) + return TRUE; + + pfnInitializeSynchronizationBarrier = GetProcAddressAs( + g_Kernel32, "InitializeSynchronizationBarrier", fnInitializeSynchronizationBarrier); + + pfnEnterSynchronizationBarrier = + GetProcAddressAs(g_Kernel32, "EnterSynchronizationBarrier", fnEnterSynchronizationBarrier); + pfnDeleteSynchronizationBarrier = GetProcAddressAs(g_Kernel32, "DeleteSynchronizationBarrier", + fnDeleteSynchronizationBarrier); + + if (pfnInitializeSynchronizationBarrier && pfnEnterSynchronizationBarrier && + pfnDeleteSynchronizationBarrier) + { + g_NativeBarrier = TRUE; + } + + return TRUE; +} + +#endif + +BOOL WINAPI winpr_InitializeSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier, + LONG lTotalThreads, LONG lSpinCount) +{ + SYSTEM_INFO sysinfo; + HANDLE hEvent0 = NULL; + HANDLE hEvent1 = NULL; + +#ifdef _WIN32 + InitOnceExecuteOnce(&g_InitOnce, InitOnce_Barrier, NULL, NULL); + + if (g_NativeBarrier) + return pfnInitializeSynchronizationBarrier(lpBarrier, lTotalThreads, lSpinCount); +#endif + + if (!lpBarrier || lTotalThreads < 1 || lSpinCount < -1) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + ZeroMemory(lpBarrier, sizeof(SYNCHRONIZATION_BARRIER)); + + if (lSpinCount == -1) + lSpinCount = 2000; + + if (!(hEvent0 = CreateEvent(NULL, TRUE, FALSE, NULL))) + return FALSE; + + if (!(hEvent1 = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + (void)CloseHandle(hEvent0); + return FALSE; + } + + GetNativeSystemInfo(&sysinfo); + + WINPR_ASSERT(lTotalThreads >= 0); + lpBarrier->Reserved1 = (DWORD)lTotalThreads; + lpBarrier->Reserved2 = (DWORD)lTotalThreads; + lpBarrier->Reserved3[0] = (ULONG_PTR)hEvent0; + lpBarrier->Reserved3[1] = (ULONG_PTR)hEvent1; + lpBarrier->Reserved4 = sysinfo.dwNumberOfProcessors; + WINPR_ASSERT(lSpinCount >= 0); + lpBarrier->Reserved5 = (DWORD)lSpinCount; + + return TRUE; +} + +BOOL WINAPI winpr_EnterSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier, DWORD dwFlags) +{ + LONG remainingThreads = 0; + HANDLE hCurrentEvent = NULL; + HANDLE hDormantEvent = NULL; + +#ifdef _WIN32 + if (g_NativeBarrier) + return pfnEnterSynchronizationBarrier(lpBarrier, dwFlags); +#endif + + if (!lpBarrier) + return FALSE; + + /** + * dwFlags according to + * https://msdn.microsoft.com/en-us/library/windows/desktop/hh706889(v=vs.85).aspx + * + * SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY (0x01) + * Specifies that the thread entering the barrier should block + * immediately until the last thread enters the barrier. + * + * SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY (0x02) + * Specifies that the thread entering the barrier should spin until the + * last thread enters the barrier, even if the spinning thread exceeds + * the barrier's maximum spin count. + * + * SYNCHRONIZATION_BARRIER_FLAGS_NO_DELETE (0x04) + * Specifies that the function can skip the work required to ensure + * that it is safe to delete the barrier, which can improve + * performance. All threads that enter this barrier must specify the + * flag; otherwise, the flag is ignored. This flag should be used only + * if the barrier will never be deleted. + */ + + hCurrentEvent = (HANDLE)lpBarrier->Reserved3[0]; + hDormantEvent = (HANDLE)lpBarrier->Reserved3[1]; + + remainingThreads = InterlockedDecrement((LONG*)&lpBarrier->Reserved1); + + WINPR_ASSERT(remainingThreads >= 0); + + if (remainingThreads > 0) + { + DWORD dwProcessors = lpBarrier->Reserved4; + BOOL spinOnly = (dwFlags & SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY) ? TRUE : FALSE; + BOOL blockOnly = (dwFlags & SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY) ? TRUE : FALSE; + BOOL block = TRUE; + + /** + * If SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY is set we will + * always spin and trust that the user knows what he/she/it + * is doing. Otherwise we'll only spin if the flag + * SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY is not set and + * the number of remaining threads is less than the number + * of processors. + */ + + if (spinOnly || (((ULONG)remainingThreads < dwProcessors) && !blockOnly)) + { + DWORD dwSpinCount = lpBarrier->Reserved5; + DWORD sp = 0; + /** + * nb: we must let the compiler know that our comparand + * can change between the iterations in the loop below + */ + volatile ULONG_PTR* cmp = &lpBarrier->Reserved3[0]; + /* we spin until the last thread _completed_ the event switch */ + while ((block = (*cmp == (ULONG_PTR)hCurrentEvent))) + if (!spinOnly && ++sp > dwSpinCount) + break; + } + + if (block) + (void)WaitForSingleObject(hCurrentEvent, INFINITE); + + return FALSE; + } + + /* reset the dormant event first */ + (void)ResetEvent(hDormantEvent); + + /* reset the remaining counter */ + lpBarrier->Reserved1 = lpBarrier->Reserved2; + + /* switch events - this will also unblock the spinning threads */ + lpBarrier->Reserved3[1] = (ULONG_PTR)hCurrentEvent; + lpBarrier->Reserved3[0] = (ULONG_PTR)hDormantEvent; + + /* signal the blocked threads */ + (void)SetEvent(hCurrentEvent); + + return TRUE; +} + +BOOL WINAPI winpr_DeleteSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier) +{ +#ifdef _WIN32 + if (g_NativeBarrier) + return pfnDeleteSynchronizationBarrier(lpBarrier); +#endif + + /** + * According to https://msdn.microsoft.com/en-us/library/windows/desktop/hh706887(v=vs.85).aspx + * Return value: + * The DeleteSynchronizationBarrier function always returns TRUE. + */ + + if (!lpBarrier) + return TRUE; + + while (lpBarrier->Reserved1 != lpBarrier->Reserved2) + SwitchToThread(); + + if (lpBarrier->Reserved3[0]) + (void)CloseHandle((HANDLE)lpBarrier->Reserved3[0]); + + if (lpBarrier->Reserved3[1]) + (void)CloseHandle((HANDLE)lpBarrier->Reserved3[1]); + + ZeroMemory(lpBarrier, sizeof(SYNCHRONIZATION_BARRIER)); + + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/critical.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/critical.c new file mode 100644 index 0000000000000000000000000000000000000000..2c82cb9ed2196123ee98d2549322629f12e51dd6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/critical.c @@ -0,0 +1,272 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Norbert Federa + * + * 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 + +#include +#include +#include +#include +#include +#include + +#include "synch.h" + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#if defined(__APPLE__) +#include +#include +#include +#endif + +#ifndef _WIN32 + +#include "../log.h" +#define TAG WINPR_TAG("synch.critical") + +VOID InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + InitializeCriticalSectionEx(lpCriticalSection, 0, 0); +} + +BOOL InitializeCriticalSectionEx(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount, + DWORD Flags) +{ + WINPR_ASSERT(lpCriticalSection); + /** + * See http://msdn.microsoft.com/en-us/library/ff541979(v=vs.85).aspx + * - The LockCount field indicates the number of times that any thread has + * called the EnterCriticalSection routine for this critical section, + * minus one. This field starts at -1 for an unlocked critical section. + * Each call of EnterCriticalSection increments this value; each call of + * LeaveCriticalSection decrements it. + * - The RecursionCount field indicates the number of times that the owning + * thread has called EnterCriticalSection for this critical section. + */ + if (Flags != 0) + { + WLog_WARN(TAG, "Flags unimplemented"); + } + + lpCriticalSection->DebugInfo = NULL; + lpCriticalSection->LockCount = -1; + lpCriticalSection->SpinCount = 0; + lpCriticalSection->RecursionCount = 0; + lpCriticalSection->OwningThread = NULL; + lpCriticalSection->LockSemaphore = (winpr_sem_t*)malloc(sizeof(winpr_sem_t)); + + if (!lpCriticalSection->LockSemaphore) + return FALSE; + +#if defined(__APPLE__) + + if (semaphore_create(mach_task_self(), lpCriticalSection->LockSemaphore, SYNC_POLICY_FIFO, 0) != + KERN_SUCCESS) + goto out_fail; + +#else + + if (sem_init(lpCriticalSection->LockSemaphore, 0, 0) != 0) + goto out_fail; + +#endif + SetCriticalSectionSpinCount(lpCriticalSection, dwSpinCount); + return TRUE; +out_fail: + free(lpCriticalSection->LockSemaphore); + return FALSE; +} + +BOOL InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount) +{ + return InitializeCriticalSectionEx(lpCriticalSection, dwSpinCount, 0); +} + +DWORD SetCriticalSectionSpinCount(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount) +{ + WINPR_ASSERT(lpCriticalSection); +#if !defined(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT) + SYSTEM_INFO sysinfo; + DWORD dwPreviousSpinCount = lpCriticalSection->SpinCount; + + if (dwSpinCount) + { + /* Don't spin on uniprocessor systems! */ + GetNativeSystemInfo(&sysinfo); + + if (sysinfo.dwNumberOfProcessors < 2) + dwSpinCount = 0; + } + + lpCriticalSection->SpinCount = dwSpinCount; + return dwPreviousSpinCount; +#else + return 0; +#endif +} + +static VOID WaitForCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + WINPR_ASSERT(lpCriticalSection); +#if defined(__APPLE__) + semaphore_wait(*((winpr_sem_t*)lpCriticalSection->LockSemaphore)); +#else + sem_wait((winpr_sem_t*)lpCriticalSection->LockSemaphore); +#endif +} + +static VOID UnWaitCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + WINPR_ASSERT(lpCriticalSection); +#if defined __APPLE__ + semaphore_signal(*((winpr_sem_t*)lpCriticalSection->LockSemaphore)); +#else + sem_post((winpr_sem_t*)lpCriticalSection->LockSemaphore); +#endif +} + +VOID EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + WINPR_ASSERT(lpCriticalSection); +#if !defined(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT) + ULONG SpinCount = lpCriticalSection->SpinCount; + + /* If we're lucky or if the current thread is already owner we can return early */ + if (SpinCount && TryEnterCriticalSection(lpCriticalSection)) + return; + + /* Spin requested times but don't compete with another waiting thread */ + while (SpinCount-- && lpCriticalSection->LockCount < 1) + { + /* Atomically try to acquire and check the if the section is free. */ + if (InterlockedCompareExchange(&lpCriticalSection->LockCount, 0, -1) == -1) + { + lpCriticalSection->RecursionCount = 1; + lpCriticalSection->OwningThread = (HANDLE)(ULONG_PTR)GetCurrentThreadId(); + return; + } + + /* Failed to get the lock. Let the scheduler know that we're spinning. */ + if (sched_yield() != 0) + { + /** + * On some operating systems sched_yield is a stub. + * usleep should at least trigger a context switch if any thread is waiting. + * A ThreadYield() would be nice in winpr ... + */ + usleep(1); + } + } + +#endif + + /* First try the fastest possible path to get the lock. */ + if (InterlockedIncrement(&lpCriticalSection->LockCount)) + { + /* Section is already locked. Check if it is owned by the current thread. */ + if (lpCriticalSection->OwningThread == (HANDLE)(ULONG_PTR)GetCurrentThreadId()) + { + /* Recursion. No need to wait. */ + lpCriticalSection->RecursionCount++; + return; + } + + /* Section is locked by another thread. We have to wait. */ + WaitForCriticalSection(lpCriticalSection); + } + + /* We got the lock. Own it ... */ + lpCriticalSection->RecursionCount = 1; + lpCriticalSection->OwningThread = (HANDLE)(ULONG_PTR)GetCurrentThreadId(); +} + +BOOL TryEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + HANDLE current_thread = (HANDLE)(ULONG_PTR)GetCurrentThreadId(); + + WINPR_ASSERT(lpCriticalSection); + + /* Atomically acquire the the lock if the section is free. */ + if (InterlockedCompareExchange(&lpCriticalSection->LockCount, 0, -1) == -1) + { + lpCriticalSection->RecursionCount = 1; + lpCriticalSection->OwningThread = current_thread; + return TRUE; + } + + /* Section is already locked. Check if it is owned by the current thread. */ + if (lpCriticalSection->OwningThread == current_thread) + { + /* Recursion, return success */ + lpCriticalSection->RecursionCount++; + InterlockedIncrement(&lpCriticalSection->LockCount); + return TRUE; + } + + return FALSE; +} + +VOID LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + WINPR_ASSERT(lpCriticalSection); + + /* Decrement RecursionCount and check if this is the last LeaveCriticalSection call ...*/ + if (--lpCriticalSection->RecursionCount < 1) + { + /* Last recursion, clear owner, unlock and if there are other waiting threads ... */ + lpCriticalSection->OwningThread = NULL; + + if (InterlockedDecrement(&lpCriticalSection->LockCount) >= 0) + { + /* ...signal the semaphore to unblock the next waiting thread */ + UnWaitCriticalSection(lpCriticalSection); + } + } + else + { + (void)InterlockedDecrement(&lpCriticalSection->LockCount); + } +} + +VOID DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection) +{ + WINPR_ASSERT(lpCriticalSection); + + lpCriticalSection->LockCount = -1; + lpCriticalSection->SpinCount = 0; + lpCriticalSection->RecursionCount = 0; + lpCriticalSection->OwningThread = NULL; + + if (lpCriticalSection->LockSemaphore != NULL) + { +#if defined __APPLE__ + semaphore_destroy(mach_task_self(), *((winpr_sem_t*)lpCriticalSection->LockSemaphore)); +#else + sem_destroy((winpr_sem_t*)lpCriticalSection->LockSemaphore); +#endif + free(lpCriticalSection->LockSemaphore); + lpCriticalSection->LockSemaphore = NULL; + } +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.c new file mode 100644 index 0000000000000000000000000000000000000000..2541083e59eee7e7f9fa66343b36f0384cf21816 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.c @@ -0,0 +1,582 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2017 Armin Novak + * Copyright 2017 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 + +#include +#include +#include + +#include + +#ifndef _WIN32 + +#include "synch.h" + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifdef WINPR_HAVE_SYS_EVENTFD_H +#include +#endif + +#include +#include + +#include "../handle/handle.h" +#include "../pipe/pipe.h" + +#include "../log.h" +#include "event.h" +#define TAG WINPR_TAG("synch.event") + +#if defined(WITH_DEBUG_EVENTS) +static wArrayList* global_event_list = NULL; + +static void dump_event(WINPR_EVENT* event, size_t index) +{ + char** msg = NULL; + size_t used = 0; +#if 0 + void* stack = winpr_backtrace(20); + WLog_DBG(TAG, "Called from:"); + msg = winpr_backtrace_symbols(stack, &used); + + for (size_t i = 0; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); + winpr_backtrace_free(stack); +#endif + WLog_DBG(TAG, "Event handle created still not closed! [%" PRIuz ", %p]", index, event); + msg = winpr_backtrace_symbols(event->create_stack, &used); + + for (size_t i = 2; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); +} +#endif /* WITH_DEBUG_EVENTS */ + +#ifdef WINPR_HAVE_SYS_EVENTFD_H +#if !defined(WITH_EVENTFD_READ_WRITE) +static int eventfd_read(int fd, eventfd_t* value) +{ + return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1; +} + +static int eventfd_write(int fd, eventfd_t value) +{ + return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1; +} +#endif +#endif + +#ifndef WINPR_HAVE_SYS_EVENTFD_H +static BOOL set_non_blocking_fd(int fd) +{ + int flags; + flags = fcntl(fd, F_GETFL); + if (flags < 0) + return FALSE; + + return fcntl(fd, F_SETFL, flags | O_NONBLOCK) >= 0; +} +#endif /* !WINPR_HAVE_SYS_EVENTFD_H */ + +BOOL winpr_event_init(WINPR_EVENT_IMPL* event) +{ +#ifdef WINPR_HAVE_SYS_EVENTFD_H + event->fds[1] = -1; + event->fds[0] = eventfd(0, EFD_NONBLOCK); + + return event->fds[0] >= 0; +#else + if (pipe(event->fds) < 0) + return FALSE; + + if (!set_non_blocking_fd(event->fds[0]) || !set_non_blocking_fd(event->fds[1])) + goto out_error; + + return TRUE; + +out_error: + winpr_event_uninit(event); + return FALSE; +#endif +} + +void winpr_event_init_from_fd(WINPR_EVENT_IMPL* event, int fd) +{ + event->fds[0] = fd; +#ifndef WINPR_HAVE_SYS_EVENTFD_H + event->fds[1] = fd; +#endif +} + +BOOL winpr_event_set(WINPR_EVENT_IMPL* event) +{ + int ret = 0; + do + { +#ifdef WINPR_HAVE_SYS_EVENTFD_H + eventfd_t value = 1; + ret = eventfd_write(event->fds[0], value); +#else + ret = write(event->fds[1], "-", 1); +#endif + } while (ret < 0 && errno == EINTR); + + return ret >= 0; +} + +BOOL winpr_event_reset(WINPR_EVENT_IMPL* event) +{ + int ret = 0; + do + { + do + { +#ifdef WINPR_HAVE_SYS_EVENTFD_H + eventfd_t value = 1; + ret = eventfd_read(event->fds[0], &value); +#else + char value; + ret = read(event->fds[0], &value, 1); +#endif + } while (ret < 0 && errno == EINTR); + } while (ret >= 0); + + return (errno == EAGAIN); +} + +void winpr_event_uninit(WINPR_EVENT_IMPL* event) +{ + if (event->fds[0] >= 0) + { + close(event->fds[0]); + event->fds[0] = -1; + } + + if (event->fds[1] >= 0) + { + close(event->fds[1]); + event->fds[1] = -1; + } +} + +static BOOL EventCloseHandle(HANDLE handle); + +static BOOL EventIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_EVENT, FALSE); +} + +static int EventGetFd(HANDLE handle) +{ + WINPR_EVENT* event = (WINPR_EVENT*)handle; + + if (!EventIsHandled(handle)) + return -1; + + return event->impl.fds[0]; +} + +static BOOL EventCloseHandle_(WINPR_EVENT* event) +{ + if (!event) + return FALSE; + + if (event->bAttached) + { + // don't close attached file descriptor + event->impl.fds[0] = -1; // mark as invalid + } + + winpr_event_uninit(&event->impl); + +#if defined(WITH_DEBUG_EVENTS) + if (global_event_list) + { + ArrayList_Remove(global_event_list, event); + if (ArrayList_Count(global_event_list) < 1) + { + ArrayList_Free(global_event_list); + global_event_list = NULL; + } + } + + winpr_backtrace_free(event->create_stack); +#endif + free(event->name); + free(event); + return TRUE; +} + +static BOOL EventCloseHandle(HANDLE handle) +{ + WINPR_EVENT* event = (WINPR_EVENT*)handle; + + if (!EventIsHandled(handle)) + return FALSE; + + return EventCloseHandle_(event); +} + +static HANDLE_OPS ops = { EventIsHandled, + EventCloseHandle, + EventGetFd, + NULL, /* CleanupHandle */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +HANDLE CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, + LPCWSTR lpName) +{ + HANDLE handle = NULL; + char* name = NULL; + + if (lpName) + { + name = ConvertWCharToUtf8Alloc(lpName, NULL); + if (!name) + return NULL; + } + + handle = CreateEventA(lpEventAttributes, bManualReset, bInitialState, name); + free(name); + return handle; +} + +HANDLE CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, + LPCSTR lpName) +{ + WINPR_EVENT* event = (WINPR_EVENT*)calloc(1, sizeof(WINPR_EVENT)); + + if (lpEventAttributes) + WLog_WARN(TAG, "[%s] does not support lpEventAttributes", lpName); + + if (!event) + return NULL; + + if (lpName) + event->name = strdup(lpName); + + event->impl.fds[0] = -1; + event->impl.fds[1] = -1; + event->bAttached = FALSE; + event->bManualReset = bManualReset; + event->common.ops = &ops; + WINPR_HANDLE_SET_TYPE_AND_MODE(event, HANDLE_TYPE_EVENT, FD_READ); + + if (!event->bManualReset) + WLog_ERR(TAG, "auto-reset events not yet implemented"); + + if (!winpr_event_init(&event->impl)) + goto fail; + + if (bInitialState) + { + if (!SetEvent(event)) + goto fail; + } + +#if defined(WITH_DEBUG_EVENTS) + event->create_stack = winpr_backtrace(20); + if (!global_event_list) + global_event_list = ArrayList_New(TRUE); + + if (global_event_list) + ArrayList_Append(global_event_list, event); +#endif + return (HANDLE)event; +fail: + EventCloseHandle_(event); + return NULL; +} + +HANDLE CreateEventExW(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCWSTR lpName, DWORD dwFlags, + DWORD dwDesiredAccess) +{ + BOOL initial = FALSE; + BOOL manual = FALSE; + + if (dwFlags & CREATE_EVENT_INITIAL_SET) + initial = TRUE; + + if (dwFlags & CREATE_EVENT_MANUAL_RESET) + manual = TRUE; + + if (dwDesiredAccess != 0) + WLog_WARN(TAG, "[%s] does not support dwDesiredAccess 0x%08" PRIx32, lpName, + dwDesiredAccess); + + return CreateEventW(lpEventAttributes, manual, initial, lpName); +} + +HANDLE CreateEventExA(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCSTR lpName, DWORD dwFlags, + DWORD dwDesiredAccess) +{ + BOOL initial = FALSE; + BOOL manual = FALSE; + + if (dwFlags & CREATE_EVENT_INITIAL_SET) + initial = TRUE; + + if (dwFlags & CREATE_EVENT_MANUAL_RESET) + manual = TRUE; + + if (dwDesiredAccess != 0) + WLog_WARN(TAG, "[%s] does not support dwDesiredAccess 0x%08" PRIx32, lpName, + dwDesiredAccess); + + return CreateEventA(lpEventAttributes, manual, initial, lpName); +} + +HANDLE OpenEventW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName) +{ + /* TODO: Implement */ + WINPR_UNUSED(dwDesiredAccess); + WINPR_UNUSED(bInheritHandle); + WINPR_UNUSED(lpName); + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +HANDLE OpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) +{ + /* TODO: Implement */ + WINPR_UNUSED(dwDesiredAccess); + WINPR_UNUSED(bInheritHandle); + WINPR_UNUSED(lpName); + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +BOOL SetEvent(HANDLE hEvent) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_EVENT* event = NULL; + + if (!winpr_Handle_GetInfo(hEvent, &Type, &Object) || Type != HANDLE_TYPE_EVENT) + { + WLog_ERR(TAG, "SetEvent: hEvent is not an event"); + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + event = (WINPR_EVENT*)Object; + return winpr_event_set(&event->impl); +} + +BOOL ResetEvent(HANDLE hEvent) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_EVENT* event = NULL; + + if (!winpr_Handle_GetInfo(hEvent, &Type, &Object) || Type != HANDLE_TYPE_EVENT) + { + WLog_ERR(TAG, "ResetEvent: hEvent is not an event"); + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + event = (WINPR_EVENT*)Object; + return winpr_event_reset(&event->impl); +} + +#endif + +HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, + BOOL bInitialState, int FileDescriptor, ULONG mode) +{ +#ifndef _WIN32 + WINPR_EVENT* event = NULL; + HANDLE handle = NULL; + event = (WINPR_EVENT*)calloc(1, sizeof(WINPR_EVENT)); + + if (event) + { + event->impl.fds[0] = -1; + event->impl.fds[1] = -1; + event->bAttached = TRUE; + event->bManualReset = bManualReset; + winpr_event_init_from_fd(&event->impl, FileDescriptor); + event->common.ops = &ops; + WINPR_HANDLE_SET_TYPE_AND_MODE(event, HANDLE_TYPE_EVENT, mode); + handle = (HANDLE)event; + } + + return handle; +#else + return NULL; +#endif +} + +HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, + BOOL bInitialState, int FileDescriptor, ULONG mode) +{ + return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, bInitialState, + FileDescriptor, mode); +} + +/** + * Returns an event based on the handle returned by GetEventWaitObject() + */ +HANDLE CreateWaitObjectEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, + BOOL bInitialState, void* pObject) +{ +#ifndef _WIN32 + return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, bInitialState, + (int)(ULONG_PTR)pObject, WINPR_FD_READ); +#else + HANDLE hEvent = NULL; + DuplicateHandle(GetCurrentProcess(), pObject, GetCurrentProcess(), &hEvent, 0, FALSE, + DUPLICATE_SAME_ACCESS); + return hEvent; +#endif +} + +/* + * Returns inner file descriptor for usage with select() + * This file descriptor is not usable on Windows + */ + +int GetEventFileDescriptor(HANDLE hEvent) +{ +#ifndef _WIN32 + return winpr_Handle_getFd(hEvent); +#else + return -1; +#endif +} + +/* + * Set inner file descriptor for usage with select() + * This file descriptor is not usable on Windows + */ + +int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor, ULONG mode) +{ +#ifndef _WIN32 + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_EVENT* event = NULL; + + if (!winpr_Handle_GetInfo(hEvent, &Type, &Object) || Type != HANDLE_TYPE_EVENT) + { + WLog_ERR(TAG, "SetEventFileDescriptor: hEvent is not an event"); + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + + event = (WINPR_EVENT*)Object; + + if (!event->bAttached && event->impl.fds[0] >= 0 && event->impl.fds[0] != FileDescriptor) + close(event->impl.fds[0]); + + event->bAttached = TRUE; + event->common.Mode = mode; + event->impl.fds[0] = FileDescriptor; + return 0; +#else + return -1; +#endif +} + +/** + * Returns platform-specific wait object as a void pointer + * + * On Windows, the returned object is the same as the hEvent + * argument and is an event HANDLE usable in WaitForMultipleObjects + * + * On other platforms, the returned object can be cast to an int + * to obtain a file descriptor usable in select() + */ + +void* GetEventWaitObject(HANDLE hEvent) +{ +#ifndef _WIN32 + int fd = 0; + void* obj = NULL; + fd = GetEventFileDescriptor(hEvent); + obj = ((void*)(long)fd); + return obj; +#else + return hEvent; +#endif +} +#if defined(WITH_DEBUG_EVENTS) +#include +#include +#include +#include + +static BOOL dump_handle_list(void* data, size_t index, va_list ap) +{ + WINPR_EVENT* event = data; + dump_event(event, index); + return TRUE; +} + +void DumpEventHandles_(const char* fkt, const char* file, size_t line) +{ + struct rlimit r = { 0 }; + int rc = getrlimit(RLIMIT_NOFILE, &r); + if (rc >= 0) + { + size_t count = 0; + for (rlim_t x = 0; x < r.rlim_cur; x++) + { + int flags = fcntl(x, F_GETFD); + if (flags >= 0) + count++; + } + WLog_INFO(TAG, "------- limits [%d/%d] open files %" PRIuz, r.rlim_cur, r.rlim_max, count); + } + WLog_DBG(TAG, "--------- Start dump [%s %s:%" PRIuz "]", fkt, file, line); + if (global_event_list) + { + ArrayList_Lock(global_event_list); + ArrayList_ForEach(global_event_list, dump_handle_list); + ArrayList_Unlock(global_event_list); + } + WLog_DBG(TAG, "--------- End dump [%s %s:%" PRIuz "]", fkt, file, line); +} +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.h new file mode 100644 index 0000000000000000000000000000000000000000..0f57374a7225b9c24382df4676bfc385a14ae662 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/event.h @@ -0,0 +1,57 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * event implementation + * + * Copyright 2021 David Fort + * + * 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_LIBWINPR_SYNCH_EVENT_H_ +#define WINPR_LIBWINPR_SYNCH_EVENT_H_ + +#include "../handle/handle.h" + +#include + +#ifdef WINPR_HAVE_SYS_EVENTFD_H +#include +#endif + +struct winpr_event_impl +{ + int fds[2]; +}; + +typedef struct winpr_event_impl WINPR_EVENT_IMPL; + +struct winpr_event +{ + WINPR_HANDLE common; + + WINPR_EVENT_IMPL impl; + BOOL bAttached; + BOOL bManualReset; + char* name; +#if defined(WITH_DEBUG_EVENTS) + void* create_stack; +#endif +}; +typedef struct winpr_event WINPR_EVENT; + +BOOL winpr_event_init(WINPR_EVENT_IMPL* event); +void winpr_event_init_from_fd(WINPR_EVENT_IMPL* event, int fd); +BOOL winpr_event_set(WINPR_EVENT_IMPL* event); +BOOL winpr_event_reset(WINPR_EVENT_IMPL* event); +void winpr_event_uninit(WINPR_EVENT_IMPL* event); + +#endif /* WINPR_LIBWINPR_SYNCH_EVENT_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/init.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/init.c new file mode 100644 index 0000000000000000000000000000000000000000..0e383ebe2a71471c622472e7441bdb70f3dd0a61 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/init.c @@ -0,0 +1,96 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Thincast Technologies GmbH + * Copyright 2014 Norbert Federa + * + * 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 + +#include +#include + +#include "../log.h" +#define TAG WINPR_TAG("sync") + +#if (!defined(_WIN32)) || (defined(_WIN32) && (_WIN32_WINNT < 0x0600)) + +BOOL winpr_InitOnceBeginInitialize(LPINIT_ONCE lpInitOnce, DWORD dwFlags, PBOOL fPending, + LPVOID* lpContext) +{ + WLog_ERR(TAG, "not implemented"); + return FALSE; +} + +BOOL winpr_InitOnceComplete(LPINIT_ONCE lpInitOnce, DWORD dwFlags, LPVOID lpContext) +{ + WLog_ERR(TAG, "not implemented"); + return FALSE; +} + +VOID winpr_InitOnceInitialize(PINIT_ONCE InitOnce) +{ + WLog_ERR(TAG, "not implemented"); +} + +BOOL winpr_InitOnceExecuteOnce(PINIT_ONCE InitOnce, PINIT_ONCE_FN InitFn, PVOID Parameter, + LPVOID* Context) +{ + for (;;) + { + switch ((ULONG_PTR)InitOnce->Ptr & 3) + { + case 2: + /* already completed successfully */ + return TRUE; + + case 0: + + /* first time */ + if (InterlockedCompareExchangePointer(&InitOnce->Ptr, (PVOID)1, (PVOID)0) != + (PVOID)0) + { + /* some other thread was faster */ + break; + } + + /* it's our job to call the init function */ + if (InitFn(InitOnce, Parameter, Context)) + { + /* success */ + InitOnce->Ptr = (PVOID)2; + return TRUE; + } + + /* the init function returned an error, reset the status */ + InitOnce->Ptr = (PVOID)0; + return FALSE; + + case 1: + /* in progress */ + break; + + default: + WLog_ERR(TAG, "internal error"); + return FALSE; + } + + Sleep(5); + } +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/mutex.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/mutex.c new file mode 100644 index 0000000000000000000000000000000000000000..6a85db6763b5cce796d6c6bf99a48ed4c44b71e3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/mutex.c @@ -0,0 +1,247 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include "synch.h" + +#ifndef _WIN32 + +#include + +#include "../handle/handle.h" + +#include "../log.h" +#define TAG WINPR_TAG("sync.mutex") + +static BOOL MutexCloseHandle(HANDLE handle); + +static BOOL MutexIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_MUTEX, FALSE); +} + +static int MutexGetFd(HANDLE handle) +{ + WINPR_MUTEX* mux = (WINPR_MUTEX*)handle; + + if (!MutexIsHandled(handle)) + return -1; + + /* TODO: Mutex does not support file handles... */ + (void)mux; + return -1; +} + +BOOL MutexCloseHandle(HANDLE handle) +{ + WINPR_MUTEX* mutex = (WINPR_MUTEX*)handle; + int rc = 0; + + if (!MutexIsHandled(handle)) + return FALSE; + + if ((rc = pthread_mutex_destroy(&mutex->mutex))) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pthread_mutex_destroy failed with %s [%d]", + winpr_strerror(rc, ebuffer, sizeof(ebuffer)), rc); +#if defined(WITH_DEBUG_MUTEX) + { + size_t used = 0; + void* stack = winpr_backtrace(20); + char** msg = NULL; + + if (stack) + msg = winpr_backtrace_symbols(stack, &used); + + if (msg) + { + for (size_t i = 0; i < used; i++) + WLog_ERR(TAG, "%2" PRIdz ": %s", i, msg[i]); + } + + free(msg); + winpr_backtrace_free(stack); + } +#endif + /** + * Note: unfortunately we may not return FALSE here since CloseHandle(hmutex) on + * Windows always seems to succeed independently of the mutex object locking state + */ + } + + free(mutex->name); + free(handle); + return TRUE; +} + +static HANDLE_OPS ops = { MutexIsHandled, + MutexCloseHandle, + MutexGetFd, + NULL, /* CleanupHandle */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName) +{ + HANDLE handle = NULL; + char* name = NULL; + + if (lpName) + { + name = ConvertWCharToUtf8Alloc(lpName, NULL); + if (!name) + return NULL; + } + + handle = CreateMutexA(lpMutexAttributes, bInitialOwner, name); + free(name); + return handle; +} + +HANDLE CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName) +{ + HANDLE handle = NULL; + WINPR_MUTEX* mutex = NULL; + mutex = (WINPR_MUTEX*)calloc(1, sizeof(WINPR_MUTEX)); + + if (lpMutexAttributes) + WLog_WARN(TAG, "[%s] does not support lpMutexAttributes", lpName); + + if (mutex) + { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&mutex->mutex, &attr); + WINPR_HANDLE_SET_TYPE_AND_MODE(mutex, HANDLE_TYPE_MUTEX, WINPR_FD_READ); + mutex->common.ops = &ops; + handle = (HANDLE)mutex; + + if (bInitialOwner) + pthread_mutex_lock(&mutex->mutex); + + if (lpName) + mutex->name = strdup(lpName); /* Non runtime relevant information, skip NULL check */ + } + + return handle; +} + +HANDLE CreateMutexExA(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCSTR lpName, DWORD dwFlags, + DWORD dwDesiredAccess) +{ + BOOL initial = FALSE; + /* TODO: support access modes */ + + if (dwDesiredAccess != 0) + WLog_WARN(TAG, "[%s] does not support dwDesiredAccess 0x%08" PRIx32, lpName, + dwDesiredAccess); + + if (dwFlags & CREATE_MUTEX_INITIAL_OWNER) + initial = TRUE; + + return CreateMutexA(lpMutexAttributes, initial, lpName); +} + +HANDLE CreateMutexExW(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCWSTR lpName, DWORD dwFlags, + DWORD dwDesiredAccess) +{ + BOOL initial = FALSE; + + /* TODO: support access modes */ + if (dwDesiredAccess != 0) + WLog_WARN(TAG, "[%s] does not support dwDesiredAccess 0x%08" PRIx32, lpName, + dwDesiredAccess); + + if (dwFlags & CREATE_MUTEX_INITIAL_OWNER) + initial = TRUE; + + return CreateMutexW(lpMutexAttributes, initial, lpName); +} + +HANDLE OpenMutexA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) +{ + /* TODO: Implement */ + WINPR_UNUSED(dwDesiredAccess); + WINPR_UNUSED(bInheritHandle); + WINPR_UNUSED(lpName); + WLog_ERR(TAG, "TODO: Implement"); + return NULL; +} + +HANDLE OpenMutexW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName) +{ + /* TODO: Implement */ + WINPR_UNUSED(dwDesiredAccess); + WINPR_UNUSED(bInheritHandle); + WINPR_UNUSED(lpName); + WLog_ERR(TAG, "TODO: Implement"); + return NULL; +} + +BOOL ReleaseMutex(HANDLE hMutex) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + + if (!winpr_Handle_GetInfo(hMutex, &Type, &Object)) + return FALSE; + + if (Type == HANDLE_TYPE_MUTEX) + { + WINPR_MUTEX* mutex = (WINPR_MUTEX*)Object; + int rc = pthread_mutex_unlock(&mutex->mutex); + + if (rc) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pthread_mutex_unlock failed with %s [%d]", + winpr_strerror(rc, ebuffer, sizeof(ebuffer)), rc); + return FALSE; + } + + return TRUE; + } + + return FALSE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.c new file mode 100644 index 0000000000000000000000000000000000000000..8711ea080efa25ac8eaa0286d89a663d3c412815 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.c @@ -0,0 +1,274 @@ +#ifndef _WIN32 +#include + +#include "pollset.h" +#include +#include +#include +#include "../log.h" + +#define TAG WINPR_TAG("sync.pollset") + +#ifdef WINPR_HAVE_POLL_H +static INT16 handle_mode_to_pollevent(ULONG mode) +{ + INT16 event = 0; + + if (mode & WINPR_FD_READ) + event |= POLLIN; + + if (mode & WINPR_FD_WRITE) + event |= POLLOUT; + + return event; +} +#endif + +BOOL pollset_init(WINPR_POLL_SET* set, size_t nhandles) +{ + WINPR_ASSERT(set); +#ifdef WINPR_HAVE_POLL_H + if (nhandles > MAXIMUM_WAIT_OBJECTS) + { + set->isStatic = FALSE; + set->pollset = calloc(nhandles, sizeof(*set->pollset)); + if (!set->pollset) + return FALSE; + } + else + { + set->pollset = set->staticSet; + set->isStatic = TRUE; + } +#else + set->fdIndex = calloc(nhandles, sizeof(*set->fdIndex)); + if (!set->fdIndex) + return FALSE; + + FD_ZERO(&set->rset_base); + FD_ZERO(&set->rset); + FD_ZERO(&set->wset_base); + FD_ZERO(&set->wset); + set->maxFd = 0; + set->nread = set->nwrite = 0; +#endif + + set->size = nhandles; + set->fillIndex = 0; + return TRUE; +} + +void pollset_uninit(WINPR_POLL_SET* set) +{ + WINPR_ASSERT(set); +#ifdef WINPR_HAVE_POLL_H + if (!set->isStatic) + free(set->pollset); +#else + free(set->fdIndex); +#endif +} + +void pollset_reset(WINPR_POLL_SET* set) +{ + WINPR_ASSERT(set); +#ifndef WINPR_HAVE_POLL_H + FD_ZERO(&set->rset_base); + FD_ZERO(&set->wset_base); + set->maxFd = 0; + set->nread = set->nwrite = 0; +#endif + set->fillIndex = 0; +} + +BOOL pollset_add(WINPR_POLL_SET* set, int fd, ULONG mode) +{ + WINPR_ASSERT(set); +#ifdef WINPR_HAVE_POLL_H + struct pollfd* item = NULL; + if (set->fillIndex == set->size) + return FALSE; + + item = &set->pollset[set->fillIndex]; + item->fd = fd; + item->revents = 0; + item->events = handle_mode_to_pollevent(mode); +#else + FdIndex* fdIndex = &set->fdIndex[set->fillIndex]; + if (mode & WINPR_FD_READ) + { + FD_SET(fd, &set->rset_base); + set->nread++; + } + + if (mode & WINPR_FD_WRITE) + { + FD_SET(fd, &set->wset_base); + set->nwrite++; + } + + if (fd > set->maxFd) + set->maxFd = fd; + + fdIndex->fd = fd; + fdIndex->mode = mode; +#endif + set->fillIndex++; + return TRUE; +} + +int pollset_poll(WINPR_POLL_SET* set, DWORD dwMilliseconds) +{ + WINPR_ASSERT(set); + int ret = 0; + UINT64 dueTime = 0; + UINT64 now = 0; + + now = GetTickCount64(); + if (dwMilliseconds == INFINITE) + dueTime = 0xFFFFFFFFFFFFFFFF; + else + dueTime = now + dwMilliseconds; + +#ifdef WINPR_HAVE_POLL_H + int timeout = 0; + + do + { + if (dwMilliseconds == INFINITE) + timeout = -1; + else + timeout = (int)(dueTime - now); + + ret = poll(set->pollset, set->fillIndex, timeout); + if (ret >= 0) + return ret; + + if (errno != EINTR) + return -1; + + now = GetTickCount64(); + } while (now < dueTime); + +#else + do + { + struct timeval staticTimeout; + struct timeval* timeout; + + fd_set* rset = NULL; + fd_set* wset = NULL; + + if (dwMilliseconds == INFINITE) + { + timeout = NULL; + } + else + { + long waitTime = (long)(dueTime - now); + + timeout = &staticTimeout; + timeout->tv_sec = waitTime / 1000; + timeout->tv_usec = (waitTime % 1000) * 1000; + } + + if (set->nread) + { + rset = &set->rset; + memcpy(rset, &set->rset_base, sizeof(*rset)); + } + + if (set->nwrite) + { + wset = &set->wset; + memcpy(wset, &set->wset_base, sizeof(*wset)); + } + + ret = select(set->maxFd + 1, rset, wset, NULL, timeout); + if (ret >= 0) + return ret; + + if (errno != EINTR) + return -1; + + now = GetTickCount64(); + + } while (now < dueTime); + + FD_ZERO(&set->rset); + FD_ZERO(&set->wset); +#endif + + return 0; /* timeout */ +} + +BOOL pollset_isSignaled(WINPR_POLL_SET* set, size_t idx) +{ + WINPR_ASSERT(set); + + if (idx > set->fillIndex) + { + WLog_ERR(TAG, "index=%d out of pollset(fillIndex=%" PRIuz ")", idx, set->fillIndex); + return FALSE; + } + +#ifdef WINPR_HAVE_POLL_H + return !!(set->pollset[idx].revents & set->pollset[idx].events); +#else + FdIndex* fdIndex = &set->fdIndex[idx]; + if (fdIndex->fd < 0) + return FALSE; + + if ((fdIndex->mode & WINPR_FD_READ) && FD_ISSET(fdIndex->fd, &set->rset)) + return TRUE; + + if ((fdIndex->mode & WINPR_FD_WRITE) && FD_ISSET(fdIndex->fd, &set->wset)) + return TRUE; + + return FALSE; +#endif +} + +BOOL pollset_isReadSignaled(WINPR_POLL_SET* set, size_t idx) +{ + WINPR_ASSERT(set); + + if (idx > set->fillIndex) + { + WLog_ERR(TAG, "index=%d out of pollset(fillIndex=%" PRIuz ")", idx, set->fillIndex); + return FALSE; + } + +#ifdef WINPR_HAVE_POLL_H + return !!(set->pollset[idx].revents & POLLIN); +#else + FdIndex* fdIndex = &set->fdIndex[idx]; + if (fdIndex->fd < 0) + return FALSE; + + return FD_ISSET(fdIndex->fd, &set->rset); +#endif +} + +BOOL pollset_isWriteSignaled(WINPR_POLL_SET* set, size_t idx) +{ + WINPR_ASSERT(set); + + if (idx > set->fillIndex) + { + WLog_ERR(TAG, "index=%d out of pollset(fillIndex=%" PRIuz ")", idx, set->fillIndex); + return FALSE; + } + +#ifdef WINPR_HAVE_POLL_H + return !!(set->pollset[idx].revents & POLLOUT); +#else + FdIndex* fdIndex = &set->fdIndex[idx]; + if (fdIndex->fd < 0) + return FALSE; + + return FD_ISSET(fdIndex->fd, &set->wset); +#endif +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.h new file mode 100644 index 0000000000000000000000000000000000000000..6e478e6c7fdd39ddc20aa60b97b92167e279c8c0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/pollset.h @@ -0,0 +1,74 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * pollset + * + * Copyright 2021 David Fort + * + * 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_LIBWINPR_SYNCH_POLLSET_H_ +#define WINPR_LIBWINPR_SYNCH_POLLSET_H_ + +#include +#include + +#include + +#ifndef _WIN32 + +#ifdef WINPR_HAVE_POLL_H +#include +#else +#include + +typedef struct +{ + int fd; + ULONG mode; +} FdIndex; +#endif + +struct winpr_poll_set +{ +#ifdef WINPR_HAVE_POLL_H + struct pollfd* pollset; + struct pollfd staticSet[MAXIMUM_WAIT_OBJECTS]; + BOOL isStatic; +#else + FdIndex* fdIndex; + fd_set rset_base; + fd_set rset; + fd_set wset_base; + fd_set wset; + int nread, nwrite; + int maxFd; +#endif + size_t fillIndex; + size_t size; +}; + +typedef struct winpr_poll_set WINPR_POLL_SET; + +BOOL pollset_init(WINPR_POLL_SET* set, size_t nhandles); +void pollset_uninit(WINPR_POLL_SET* set); +void pollset_reset(WINPR_POLL_SET* set); +BOOL pollset_add(WINPR_POLL_SET* set, int fd, ULONG mode); +int pollset_poll(WINPR_POLL_SET* set, DWORD dwMilliseconds); + +BOOL pollset_isSignaled(WINPR_POLL_SET* set, size_t idx); +BOOL pollset_isReadSignaled(WINPR_POLL_SET* set, size_t idx); +BOOL pollset_isWriteSignaled(WINPR_POLL_SET* set, size_t idx); + +#endif + +#endif /* WINPR_LIBWINPR_SYNCH_POLLSET_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/semaphore.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/semaphore.c new file mode 100644 index 0000000000000000000000000000000000000000..855675b038c1a3eb0a8d0de30fb160ab467d82a8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/semaphore.c @@ -0,0 +1,257 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include "synch.h" + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifndef _WIN32 + +#include +#include "../handle/handle.h" +#include "../log.h" +#define TAG WINPR_TAG("synch.semaphore") + +static BOOL SemaphoreCloseHandle(HANDLE handle); + +static BOOL SemaphoreIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_SEMAPHORE, FALSE); +} + +static int SemaphoreGetFd(HANDLE handle) +{ + WINPR_SEMAPHORE* sem = (WINPR_SEMAPHORE*)handle; + + if (!SemaphoreIsHandled(handle)) + return -1; + + return sem->pipe_fd[0]; +} + +static DWORD SemaphoreCleanupHandle(HANDLE handle) +{ + SSIZE_T length = 0; + WINPR_SEMAPHORE* sem = (WINPR_SEMAPHORE*)handle; + + if (!SemaphoreIsHandled(handle)) + return WAIT_FAILED; + + length = read(sem->pipe_fd[0], &length, 1); + + if (length != 1) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "semaphore read() failure [%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return WAIT_FAILED; + } + + return WAIT_OBJECT_0; +} + +BOOL SemaphoreCloseHandle(HANDLE handle) +{ + WINPR_SEMAPHORE* semaphore = (WINPR_SEMAPHORE*)handle; + + if (!SemaphoreIsHandled(handle)) + return FALSE; + +#ifdef WINPR_PIPE_SEMAPHORE + + if (semaphore->pipe_fd[0] != -1) + { + close(semaphore->pipe_fd[0]); + semaphore->pipe_fd[0] = -1; + + if (semaphore->pipe_fd[1] != -1) + { + close(semaphore->pipe_fd[1]); + semaphore->pipe_fd[1] = -1; + } + } + +#else +#if defined __APPLE__ + semaphore_destroy(mach_task_self(), *((winpr_sem_t*)semaphore->sem)); +#else + sem_destroy((winpr_sem_t*)semaphore->sem); +#endif +#endif + free(semaphore); + return TRUE; +} + +static HANDLE_OPS ops = { SemaphoreIsHandled, + SemaphoreCloseHandle, + SemaphoreGetFd, + SemaphoreCleanupHandle, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, + LONG lMaximumCount, LPCWSTR lpName) +{ + HANDLE handle = NULL; + WINPR_SEMAPHORE* semaphore = NULL; + semaphore = (WINPR_SEMAPHORE*)calloc(1, sizeof(WINPR_SEMAPHORE)); + + if (!semaphore) + return NULL; + + semaphore->pipe_fd[0] = -1; + semaphore->pipe_fd[1] = -1; + semaphore->sem = (winpr_sem_t*)NULL; + semaphore->common.ops = &ops; +#ifdef WINPR_PIPE_SEMAPHORE + + if (pipe(semaphore->pipe_fd) < 0) + { + WLog_ERR(TAG, "failed to create semaphore"); + free(semaphore); + return NULL; + } + + while (lInitialCount > 0) + { + if (write(semaphore->pipe_fd[1], "-", 1) != 1) + { + close(semaphore->pipe_fd[0]); + close(semaphore->pipe_fd[1]); + free(semaphore); + return NULL; + } + + lInitialCount--; + } + +#else + semaphore->sem = (winpr_sem_t*)malloc(sizeof(winpr_sem_t)); + + if (!semaphore->sem) + { + WLog_ERR(TAG, "failed to allocate semaphore memory"); + free(semaphore); + return NULL; + } + +#if defined __APPLE__ + + if (semaphore_create(mach_task_self(), semaphore->sem, SYNC_POLICY_FIFO, lMaximumCount) != + KERN_SUCCESS) +#else + if (sem_init(semaphore->sem, 0, lMaximumCount) == -1) +#endif + { + WLog_ERR(TAG, "failed to create semaphore"); + free(semaphore->sem); + free(semaphore); + return NULL; + } + +#endif + WINPR_HANDLE_SET_TYPE_AND_MODE(semaphore, HANDLE_TYPE_SEMAPHORE, WINPR_FD_READ); + handle = (HANDLE)semaphore; + return handle; +} + +HANDLE CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, + LONG lMaximumCount, LPCSTR lpName) +{ + return CreateSemaphoreW(lpSemaphoreAttributes, lInitialCount, lMaximumCount, NULL); +} + +HANDLE OpenSemaphoreW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName) +{ + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +HANDLE OpenSemaphoreA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) +{ + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +BOOL ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_SEMAPHORE* semaphore = NULL; + + if (!winpr_Handle_GetInfo(hSemaphore, &Type, &Object)) + return FALSE; + + if (Type == HANDLE_TYPE_SEMAPHORE) + { + semaphore = (WINPR_SEMAPHORE*)Object; +#ifdef WINPR_PIPE_SEMAPHORE + + if (semaphore->pipe_fd[0] != -1) + { + while (lReleaseCount > 0) + { + if (write(semaphore->pipe_fd[1], "-", 1) != 1) + return FALSE; + + lReleaseCount--; + } + } + +#else + + while (lReleaseCount > 0) + { +#if defined __APPLE__ + semaphore_signal(*((winpr_sem_t*)semaphore->sem)); +#else + sem_post((winpr_sem_t*)semaphore->sem); +#endif + } + +#endif + return TRUE; + } + + WLog_ERR(TAG, "called on a handle that is not a semaphore"); + return FALSE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/sleep.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/sleep.c new file mode 100644 index 0000000000000000000000000000000000000000..7708393d2d6bd03b41aa6435769bf0247e6800b6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/sleep.c @@ -0,0 +1,149 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#include "../log.h" +#include "../thread/apc.h" +#include "../thread/thread.h" +#include "../synch/pollset.h" + +#define TAG WINPR_TAG("synch.sleep") + +#ifndef _WIN32 + +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO +WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO + +#ifdef WINPR_HAVE_UNISTD_H +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) +#endif +#include +#endif + +WINPR_PRAGMA_DIAG_POP + +VOID Sleep(DWORD dwMilliseconds) +{ + usleep(dwMilliseconds * 1000); +} + +DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable) +{ + WINPR_THREAD* thread = winpr_GetCurrentThread(); + WINPR_POLL_SET pollset; + int status = 0; + DWORD ret = WAIT_FAILED; + BOOL autoSignalled = 0; + + if (thread) + { + /* treat re-entrancy if a completion is calling us */ + if (thread->apc.treatingCompletions) + bAlertable = FALSE; + } + else + { + /* called from a non WinPR thread */ + bAlertable = FALSE; + } + + if (!bAlertable || !thread->apc.length) + { + usleep(dwMilliseconds * 1000); + return 0; + } + + if (!pollset_init(&pollset, thread->apc.length)) + { + WLog_ERR(TAG, "unable to initialize pollset"); + return WAIT_FAILED; + } + + if (!apc_collectFds(thread, &pollset, &autoSignalled)) + { + WLog_ERR(TAG, "unable to APC file descriptors"); + goto out; + } + + if (!autoSignalled) + { + /* we poll and wait only if no APC member is ready */ + status = pollset_poll(&pollset, dwMilliseconds); + if (status < 0) + { + WLog_ERR(TAG, "polling of apc fds failed"); + goto out; + } + } + + if (apc_executeCompletions(thread, &pollset, 0)) + { + ret = WAIT_IO_COMPLETION; + } + else + { + /* according to the spec return value is 0 see + * https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleepex*/ + ret = 0; + } +out: + pollset_uninit(&pollset); + return ret; +} + +#endif + +VOID USleep(DWORD dwMicroseconds) +{ +#ifndef _WIN32 + usleep(dwMicroseconds); +#else + static LARGE_INTEGER freq = { 0 }; + LARGE_INTEGER t1 = { 0 }; + LARGE_INTEGER t2 = { 0 }; + + QueryPerformanceCounter(&t1); + + if (freq.QuadPart == 0) + { + QueryPerformanceFrequency(&freq); + } + + // in order to save cpu cycles we use Sleep() for the large share ... + if (dwMicroseconds >= 1000) + { + Sleep(dwMicroseconds / 1000); + } + // ... and busy loop until all the requested micro seconds have passed + do + { + QueryPerformanceCounter(&t2); + } while (((t2.QuadPart - t1.QuadPart) * 1000000) / freq.QuadPart < dwMicroseconds); +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/synch.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/synch.h new file mode 100644 index 0000000000000000000000000000000000000000..5a9f08c1ce644cbd9196897e8da846c32d0b7a00 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/synch.h @@ -0,0 +1,159 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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_PRIVATE_H +#define WINPR_SYNCH_PRIVATE_H + +#include + +#include + +#include + +#include "../handle/handle.h" +#include "../thread/apc.h" +#include "event.h" + +#ifndef _WIN32 + +#define WINPR_PIPE_SEMAPHORE 1 + +#if defined __APPLE__ +#include +#include +#include +#include +#include +#include +#define winpr_sem_t semaphore_t +#else +#include +#include +#define winpr_sem_t sem_t +#endif + +struct winpr_mutex +{ + WINPR_HANDLE common; + char* name; + pthread_mutex_t mutex; +}; +typedef struct winpr_mutex WINPR_MUTEX; + +struct winpr_semaphore +{ + WINPR_HANDLE common; + + int pipe_fd[2]; + winpr_sem_t* sem; +}; +typedef struct winpr_semaphore WINPR_SEMAPHORE; + +#ifdef WINPR_HAVE_SYS_TIMERFD_H +#include +#include +#include +#include +#define TIMER_IMPL_TIMERFD + +#elif defined(WITH_POSIX_TIMER) +#include +#define TIMER_IMPL_POSIX + +#elif defined(__APPLE__) +#define TIMER_IMPL_DISPATCH +#include +#else +#warning missing timer implementation +#endif + +struct winpr_timer +{ + WINPR_HANDLE common; + + int fd; + BOOL bInit; + LONG lPeriod; + BOOL bManualReset; + PTIMERAPCROUTINE pfnCompletionRoutine; + LPVOID lpArgToCompletionRoutine; + +#ifdef TIMER_IMPL_TIMERFD + struct itimerspec timeout; +#endif + +#ifdef TIMER_IMPL_POSIX + WINPR_EVENT_IMPL event; + timer_t tid; + struct itimerspec timeout; +#endif + +#ifdef TIMER_IMPL_DISPATCH + WINPR_EVENT_IMPL event; + dispatch_queue_t queue; + dispatch_source_t source; + BOOL running; +#endif + char* name; + + WINPR_APC_ITEM apcItem; +}; +typedef struct winpr_timer WINPR_TIMER; + +typedef struct winpr_timer_queue_timer WINPR_TIMER_QUEUE_TIMER; + +struct winpr_timer_queue +{ + WINPR_HANDLE common; + + pthread_t thread; + pthread_attr_t attr; + pthread_mutex_t mutex; + pthread_cond_t cond; + pthread_mutex_t cond_mutex; + struct sched_param param; + + BOOL bCancelled; + WINPR_TIMER_QUEUE_TIMER* activeHead; + WINPR_TIMER_QUEUE_TIMER* inactiveHead; +}; +typedef struct winpr_timer_queue WINPR_TIMER_QUEUE; + +struct winpr_timer_queue_timer +{ + WINPR_HANDLE common; + + ULONG Flags; + DWORD DueTime; + DWORD Period; + PVOID Parameter; + WAITORTIMERCALLBACK Callback; + + int FireCount; + + struct timespec StartTime; + struct timespec ExpirationTime; + + WINPR_TIMER_QUEUE* timerQueue; + WINPR_TIMER_QUEUE_TIMER* next; +}; + +#endif + +#endif /* WINPR_SYNCH_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f0da185d5c2bf32dd4f7526703555ce00d1b0afc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/CMakeLists.txt @@ -0,0 +1,40 @@ +set(MODULE_NAME "TestSynch") +set(MODULE_PREFIX "TEST_SYNCH") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS + TestSynchInit.c + TestSynchEvent.c + TestSynchMutex.c + TestSynchBarrier.c + TestSynchCritical.c + TestSynchSemaphore.c + TestSynchThread.c + # TestSynchMultipleThreads.c + TestSynchTimerQueue.c + TestSynchWaitableTimer.c + TestSynchWaitableTimerAPC.c + TestSynchAPC.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +if(FREEBSD) + include_directories(SYSTEM ${EPOLLSHIM_INCLUDE_DIR}) +endif() + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchAPC.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchAPC.c new file mode 100644 index 0000000000000000000000000000000000000000..bfec7ee3d955ff14836b876f963312f4d24a3b48 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchAPC.c @@ -0,0 +1,173 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * TestSyncAPC + * + * Copyright 2021 David Fort + * + * 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 +#include +#include + +typedef struct +{ + BOOL error; + BOOL called; +} UserApcArg; + +static void CALLBACK userApc(ULONG_PTR arg) +{ + UserApcArg* userArg = (UserApcArg*)arg; + userArg->called = TRUE; +} + +static DWORD WINAPI uncleanThread(LPVOID lpThreadParameter) +{ + /* this thread post an APC that will never get executed */ + UserApcArg* userArg = (UserApcArg*)lpThreadParameter; + if (!QueueUserAPC((PAPCFUNC)userApc, _GetCurrentThread(), (ULONG_PTR)lpThreadParameter)) + { + userArg->error = TRUE; + return 1; + } + + return 0; +} + +static DWORD WINAPI cleanThread(LPVOID lpThreadParameter) +{ + Sleep(500); + + SleepEx(500, TRUE); + return 0; +} + +typedef struct +{ + HANDLE timer1; + DWORD timer1Calls; + HANDLE timer2; + DWORD timer2Calls; + BOOL endTest; +} UncleanCloseData; + +static VOID CALLBACK Timer1APCProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue) +{ + UncleanCloseData* data = (UncleanCloseData*)lpArg; + data->timer1Calls++; + (void)CloseHandle(data->timer2); + data->endTest = TRUE; +} + +static VOID CALLBACK Timer2APCProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue) +{ + UncleanCloseData* data = (UncleanCloseData*)lpArg; + data->timer2Calls++; +} + +static DWORD /*WINAPI*/ closeHandleTest(LPVOID lpThreadParameter) +{ + LARGE_INTEGER dueTime = { 0 }; + UncleanCloseData* data = (UncleanCloseData*)lpThreadParameter; + data->endTest = FALSE; + + dueTime.QuadPart = -500; + if (!SetWaitableTimer(data->timer1, &dueTime, 0, Timer1APCProc, lpThreadParameter, FALSE)) + return 1; + + dueTime.QuadPart = -900; + if (!SetWaitableTimer(data->timer2, &dueTime, 0, Timer2APCProc, lpThreadParameter, FALSE)) + return 1; + + while (!data->endTest) + { + SleepEx(100, TRUE); + } + return 0; +} + +int TestSynchAPC(int argc, char* argv[]) +{ + HANDLE thread = NULL; + UserApcArg userApcArg; + + userApcArg.error = FALSE; + userApcArg.called = FALSE; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* first post an APC and check it is executed during a SleepEx */ + if (!QueueUserAPC((PAPCFUNC)userApc, _GetCurrentThread(), (ULONG_PTR)&userApcArg)) + return 1; + + if (SleepEx(100, FALSE) != 0) + return 2; + + if (SleepEx(100, TRUE) != WAIT_IO_COMPLETION) + return 3; + + if (!userApcArg.called) + return 4; + + userApcArg.called = FALSE; + + /* test that the APC is cleaned up even when not called */ + thread = CreateThread(NULL, 0, uncleanThread, &userApcArg, 0, NULL); + if (!thread) + return 10; + (void)WaitForSingleObject(thread, INFINITE); + (void)CloseHandle(thread); + + if (userApcArg.called || userApcArg.error) + return 11; + + /* test a remote APC queuing */ + thread = CreateThread(NULL, 0, cleanThread, &userApcArg, 0, NULL); + if (!thread) + return 20; + + if (!QueueUserAPC((PAPCFUNC)userApc, thread, (ULONG_PTR)&userApcArg)) + return 21; + + (void)WaitForSingleObject(thread, INFINITE); + (void)CloseHandle(thread); + + if (!userApcArg.called) + return 22; + +#if 0 + /* test cleanup of timer completions */ + memset(&uncleanCloseData, 0, sizeof(uncleanCloseData)); + uncleanCloseData.timer1 = CreateWaitableTimerA(NULL, FALSE, NULL); + if (!uncleanCloseData.timer1) + return 31; + + uncleanCloseData.timer2 = CreateWaitableTimerA(NULL, FALSE, NULL); + if (!uncleanCloseData.timer2) + return 32; + + thread = CreateThread(NULL, 0, closeHandleTest, &uncleanCloseData, 0, NULL); + if (!thread) + return 33; + + (void)WaitForSingleObject(thread, INFINITE); +(void)CloseHandle(thread); + + if (uncleanCloseData.timer1Calls != 1 || uncleanCloseData.timer2Calls != 0) + return 34; +(void)CloseHandle(uncleanCloseData.timer1); +#endif + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchBarrier.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchBarrier.c new file mode 100644 index 0000000000000000000000000000000000000000..835ce7058eb9d501b6fe2e521ccd4f80276fc98e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchBarrier.c @@ -0,0 +1,266 @@ + +#include +#include +#include +#include +#include +#include + +#include "../synch.h" + +static SYNCHRONIZATION_BARRIER gBarrier; +static HANDLE gStartEvent = NULL; +static LONG gErrorCount = 0; + +#define MAX_SLEEP_MS 22 + +struct test_params +{ + LONG threadCount; + LONG trueCount; + LONG falseCount; + DWORD loops; + DWORD flags; +}; + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +static DWORD WINAPI test_synch_barrier_thread(LPVOID lpParam) +{ + BOOL status = FALSE; + struct test_params* p = (struct test_params*)lpParam; + + InterlockedIncrement(&p->threadCount); + + // printf("Thread #%03u entered.\n", tnum); + + /* wait for start event from main */ + if (WaitForSingleObject(gStartEvent, INFINITE) != WAIT_OBJECT_0) + { + InterlockedIncrement(&gErrorCount); + goto out; + } + + // printf("Thread #%03u unblocked.\n", tnum); + + for (DWORD i = 0; i < p->loops && gErrorCount == 0; i++) + { + /* simulate different execution times before the barrier */ + Sleep(1 + prand(MAX_SLEEP_MS)); + status = EnterSynchronizationBarrier(&gBarrier, p->flags); + + // printf("Thread #%03u status: %s\n", tnum, status ? "TRUE" : "FALSE"); + if (status) + InterlockedIncrement(&p->trueCount); + else + InterlockedIncrement(&p->falseCount); + } + +out: + // printf("Thread #%03u leaving.\n", tnum); + return 0; +} + +static BOOL TestSynchBarrierWithFlags(DWORD dwFlags, DWORD dwThreads, DWORD dwLoops) +{ + BOOL rc = FALSE; + DWORD dwStatus = 0; + + struct test_params p = { + .threadCount = 0, .trueCount = 0, .falseCount = 0, .loops = dwLoops, .flags = dwFlags + }; + DWORD expectedTrueCount = dwLoops; + DWORD expectedFalseCount = dwLoops * (dwThreads - 1); + + printf("%s: >> Testing with flags 0x%08" PRIx32 ". Using %" PRIu32 + " threads performing %" PRIu32 " loops\n", + __func__, dwFlags, dwThreads, dwLoops); + + HANDLE* threads = (HANDLE*)calloc(dwThreads, sizeof(HANDLE)); + if (!threads) + { + printf("%s: error allocatin thread array memory\n", __func__); + return FALSE; + } + + if (dwThreads > INT32_MAX) + goto fail; + + if (!InitializeSynchronizationBarrier(&gBarrier, (LONG)dwThreads, -1)) + { + printf("%s: InitializeSynchronizationBarrier failed. GetLastError() = 0x%08x", __func__, + GetLastError()); + goto fail; + } + + if (!(gStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("%s: CreateEvent failed with error 0x%08x", __func__, GetLastError()); + goto fail; + } + + DWORD i = 0; + for (; i < dwThreads; i++) + { + threads[i] = CreateThread(NULL, 0, test_synch_barrier_thread, &p, 0, NULL); + if (!threads[i]) + { + printf("%s: CreateThread failed for thread #%" PRIu32 " with error 0x%08x\n", __func__, + i, GetLastError()); + InterlockedIncrement(&gErrorCount); + break; + } + } + + if (i > 0) + { + if (!SetEvent(gStartEvent)) + { + printf("%s: SetEvent(gStartEvent) failed with error = 0x%08x)\n", __func__, + GetLastError()); + InterlockedIncrement(&gErrorCount); + } + + while (i--) + { + if (WAIT_OBJECT_0 != (dwStatus = WaitForSingleObject(threads[i], INFINITE))) + { + printf("%s: WaitForSingleObject(thread[%" PRIu32 "] unexpectedly returned %" PRIu32 + " (error = 0x%08x)\n", + __func__, i, dwStatus, GetLastError()); + InterlockedIncrement(&gErrorCount); + } + + if (!CloseHandle(threads[i])) + { + printf("%s: CloseHandle(thread[%" PRIu32 "]) failed with error = 0x%08x)\n", + __func__, i, GetLastError()); + InterlockedIncrement(&gErrorCount); + } + } + } + + if (!CloseHandle(gStartEvent)) + { + printf("%s: CloseHandle(gStartEvent) failed with error = 0x%08x)\n", __func__, + GetLastError()); + InterlockedIncrement(&gErrorCount); + } + + if (p.threadCount != (INT64)dwThreads) + InterlockedIncrement(&gErrorCount); + + if (p.trueCount != (INT64)expectedTrueCount) + InterlockedIncrement(&gErrorCount); + + if (p.falseCount != (INT64)expectedFalseCount) + InterlockedIncrement(&gErrorCount); + + printf("%s: error count: %" PRId32 "\n", __func__, gErrorCount); + printf("%s: thread count: %" PRId32 " (expected %" PRIu32 ")\n", __func__, p.threadCount, + dwThreads); + printf("%s: true count: %" PRId32 " (expected %" PRIu32 ")\n", __func__, p.trueCount, + expectedTrueCount); + printf("%s: false count: %" PRId32 " (expected %" PRIu32 ")\n", __func__, p.falseCount, + expectedFalseCount); + + rc = TRUE; +fail: + free((void*)threads); + DeleteSynchronizationBarrier(&gBarrier); + if (gErrorCount > 0) + { + printf("%s: Error test failed with %" PRId32 " reported errors\n", __func__, gErrorCount); + return FALSE; + } + + return rc; +} + +int TestSynchBarrier(int argc, char* argv[]) +{ + SYSTEM_INFO sysinfo; + DWORD dwMaxThreads = 0; + DWORD dwMinThreads = 0; + DWORD dwNumLoops = 10; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + GetNativeSystemInfo(&sysinfo); + printf("%s: Number of processors: %" PRIu32 "\n", __func__, sysinfo.dwNumberOfProcessors); + dwMinThreads = sysinfo.dwNumberOfProcessors; + dwMaxThreads = sysinfo.dwNumberOfProcessors * 4; + + if (dwMaxThreads > 32) + dwMaxThreads = 32; + + /* Test invalid parameters */ + if (InitializeSynchronizationBarrier(&gBarrier, 0, -1)) + { + (void)fprintf( + stderr, + "%s: InitializeSynchronizationBarrier unecpectedly succeeded with lTotalThreads = 0\n", + __func__); + return -1; + } + + if (InitializeSynchronizationBarrier(&gBarrier, -1, -1)) + { + (void)fprintf( + stderr, + "%s: InitializeSynchronizationBarrier unecpectedly succeeded with lTotalThreads = -1\n", + __func__); + return -1; + } + + if (InitializeSynchronizationBarrier(&gBarrier, 1, -2)) + { + (void)fprintf( + stderr, + "%s: InitializeSynchronizationBarrier unecpectedly succeeded with lSpinCount = -2\n", + __func__); + return -1; + } + + /* Functional tests */ + + if (!TestSynchBarrierWithFlags(0, dwMaxThreads, dwNumLoops)) + { + (void)fprintf( + stderr, + "%s: TestSynchBarrierWithFlags(0) unecpectedly succeeded with lTotalThreads = -1\n", + __func__); + return -1; + } + + if (!TestSynchBarrierWithFlags(SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY, dwMinThreads, + dwNumLoops)) + { + (void)fprintf(stderr, + "%s: TestSynchBarrierWithFlags(SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY) " + "unecpectedly succeeded with lTotalThreads = -1\n", + __func__); + return -1; + } + + if (!TestSynchBarrierWithFlags(SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY, dwMaxThreads, + dwNumLoops)) + { + (void)fprintf(stderr, + "%s: TestSynchBarrierWithFlags(SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY) " + "unecpectedly succeeded with lTotalThreads = -1\n", + __func__); + return -1; + } + + printf("%s: Test successfully completed\n", __func__); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchCritical.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchCritical.c new file mode 100644 index 0000000000000000000000000000000000000000..139885a81e95dc49aebadf3c0ca70f5f435e884f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchCritical.c @@ -0,0 +1,373 @@ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS 50 +#define TEST_SYNC_CRITICAL_TEST1_RUNS 4 + +static CRITICAL_SECTION critical; +static LONG gTestValueVulnerable = 0; +static LONG gTestValueSerialized = 0; + +static BOOL TestSynchCritical_TriggerAndCheckRaceCondition(HANDLE OwningThread, LONG RecursionCount) +{ + /* if called unprotected this will hopefully trigger a race condition ... */ + gTestValueVulnerable++; + + if (critical.OwningThread != OwningThread) + { + printf("CriticalSection failure: OwningThread is invalid\n"); + return FALSE; + } + if (critical.RecursionCount != RecursionCount) + { + printf("CriticalSection failure: RecursionCount is invalid\n"); + return FALSE; + } + + /* ... which we try to detect using the serialized counter */ + if (gTestValueVulnerable != InterlockedIncrement(&gTestValueSerialized)) + { + printf("CriticalSection failure: Data corruption detected\n"); + return FALSE; + } + + return TRUE; +} + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +/* this thread function shall increment the global dwTestValue until the PBOOL passed in arg is + * FALSE */ +static DWORD WINAPI TestSynchCritical_Test1(LPVOID arg) +{ + int rc = 0; + HANDLE hThread = (HANDLE)(ULONG_PTR)GetCurrentThreadId(); + + PBOOL pbContinueRunning = (PBOOL)arg; + + while (*pbContinueRunning) + { + EnterCriticalSection(&critical); + + rc = 1; + + if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc)) + return 1; + + /* add some random recursion level */ + UINT32 j = prand(5); + for (UINT32 i = 0; i < j; i++) + { + if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc++)) + return 2; + EnterCriticalSection(&critical); + } + for (UINT32 i = 0; i < j; i++) + { + if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc--)) + return 2; + LeaveCriticalSection(&critical); + } + + if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc)) + return 3; + + LeaveCriticalSection(&critical); + } + + return 0; +} + +/* this thread function tries to call TryEnterCriticalSection while the main thread holds the lock + */ +static DWORD WINAPI TestSynchCritical_Test2(LPVOID arg) +{ + WINPR_UNUSED(arg); + if (TryEnterCriticalSection(&critical) == TRUE) + { + LeaveCriticalSection(&critical); + return 1; + } + return 0; +} + +static DWORD WINAPI TestSynchCritical_Main(LPVOID arg) +{ + SYSTEM_INFO sysinfo; + DWORD dwPreviousSpinCount = 0; + DWORD dwSpinCount = 0; + DWORD dwSpinCountExpected = 0; + HANDLE hMainThread = NULL; + HANDLE* hThreads = NULL; + HANDLE hThread = NULL; + DWORD dwThreadCount = 0; + DWORD dwThreadExitCode = 0; + BOOL bTest1Running = 0; + + PBOOL pbThreadTerminated = (PBOOL)arg; + + GetNativeSystemInfo(&sysinfo); + + hMainThread = (HANDLE)(ULONG_PTR)GetCurrentThreadId(); + + /** + * Test SpinCount in SetCriticalSectionSpinCount, InitializeCriticalSectionEx and + * InitializeCriticalSectionAndSpinCount SpinCount must be forced to be zero on on uniprocessor + * systems and on systems where WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT is defined + */ + + dwSpinCount = 100; + InitializeCriticalSectionEx(&critical, dwSpinCount, 0); + while (--dwSpinCount) + { + dwPreviousSpinCount = SetCriticalSectionSpinCount(&critical, dwSpinCount); + dwSpinCountExpected = 0; +#if !defined(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT) + if (sysinfo.dwNumberOfProcessors > 1) + dwSpinCountExpected = dwSpinCount + 1; +#endif + if (dwPreviousSpinCount != dwSpinCountExpected) + { + printf("CriticalSection failure: SetCriticalSectionSpinCount returned %" PRIu32 + " (expected: %" PRIu32 ")\n", + dwPreviousSpinCount, dwSpinCountExpected); + goto fail; + } + + DeleteCriticalSection(&critical); + + if (dwSpinCount % 2 == 0) + InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount); + else + InitializeCriticalSectionEx(&critical, dwSpinCount, 0); + } + DeleteCriticalSection(&critical); + + /** + * Test single-threaded recursive + * TryEnterCriticalSection/EnterCriticalSection/LeaveCriticalSection + * + */ + + InitializeCriticalSection(&critical); + + int i = 0; + for (; i < 10; i++) + { + if (critical.RecursionCount != i) + { + printf("CriticalSection failure: RecursionCount field is %" PRId32 " instead of %d.\n", + critical.RecursionCount, i); + goto fail; + } + if (i % 2 == 0) + { + EnterCriticalSection(&critical); + } + else + { + if (TryEnterCriticalSection(&critical) == FALSE) + { + printf("CriticalSection failure: TryEnterCriticalSection failed where it should " + "not.\n"); + goto fail; + } + } + if (critical.OwningThread != hMainThread) + { + printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", + i); + goto fail; + } + } + while (--i >= 0) + { + LeaveCriticalSection(&critical); + if (critical.RecursionCount != i) + { + printf("CriticalSection failure: RecursionCount field is %" PRId32 " instead of %d.\n", + critical.RecursionCount, i); + goto fail; + } + if (critical.OwningThread != (i ? hMainThread : NULL)) + { + printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", + i); + goto fail; + } + } + DeleteCriticalSection(&critical); + + /** + * Test using multiple threads modifying the same value + */ + + dwThreadCount = sysinfo.dwNumberOfProcessors > 1 ? sysinfo.dwNumberOfProcessors : 2; + + hThreads = (HANDLE*)calloc(dwThreadCount, sizeof(HANDLE)); + if (!hThreads) + { + printf("Problem allocating memory\n"); + goto fail; + } + + for (int j = 0; j < TEST_SYNC_CRITICAL_TEST1_RUNS; j++) + { + dwSpinCount = j * 100; + InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount); + + gTestValueVulnerable = 0; + gTestValueSerialized = 0; + + /* the TestSynchCritical_Test1 threads shall run until bTest1Running is FALSE */ + bTest1Running = TRUE; + for (int i = 0; i < (int)dwThreadCount; i++) + { + if (!(hThreads[i] = + CreateThread(NULL, 0, TestSynchCritical_Test1, &bTest1Running, 0, NULL))) + { + printf("CriticalSection failure: Failed to create test_1 thread #%d\n", i); + goto fail; + } + } + + /* let it run for TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS ... */ + Sleep(TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS); + bTest1Running = FALSE; + + for (int i = 0; i < (int)dwThreadCount; i++) + { + if (WaitForSingleObject(hThreads[i], INFINITE) != WAIT_OBJECT_0) + { + printf("CriticalSection failure: Failed to wait for thread #%d\n", i); + goto fail; + } + GetExitCodeThread(hThreads[i], &dwThreadExitCode); + if (dwThreadExitCode != 0) + { + printf("CriticalSection failure: Thread #%d returned error code %" PRIu32 "\n", i, + dwThreadExitCode); + goto fail; + } + (void)CloseHandle(hThreads[i]); + } + + if (gTestValueVulnerable != gTestValueSerialized) + { + printf("CriticalSection failure: unexpected test value %" PRId32 " (expected %" PRId32 + ")\n", + gTestValueVulnerable, gTestValueSerialized); + goto fail; + } + + DeleteCriticalSection(&critical); + } + + free((void*)hThreads); + + /** + * TryEnterCriticalSection in thread must fail if we hold the lock in the main thread + */ + + InitializeCriticalSection(&critical); + + if (TryEnterCriticalSection(&critical) == FALSE) + { + printf("CriticalSection failure: TryEnterCriticalSection unexpectedly failed.\n"); + goto fail; + } + /* This thread tries to call TryEnterCriticalSection which must fail */ + if (!(hThread = CreateThread(NULL, 0, TestSynchCritical_Test2, NULL, 0, NULL))) + { + printf("CriticalSection failure: Failed to create test_2 thread\n"); + goto fail; + } + if (WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0) + { + printf("CriticalSection failure: Failed to wait for thread\n"); + goto fail; + } + GetExitCodeThread(hThread, &dwThreadExitCode); + if (dwThreadExitCode != 0) + { + printf("CriticalSection failure: Thread returned error code %" PRIu32 "\n", + dwThreadExitCode); + goto fail; + } + (void)CloseHandle(hThread); + + *pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */ + return 0; + +fail: + *pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */ + return 1; +} + +int TestSynchCritical(int argc, char* argv[]) +{ + BOOL bThreadTerminated = FALSE; + HANDLE hThread = NULL; + DWORD dwThreadExitCode = 0; + DWORD dwDeadLockDetectionTimeMs = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + dwDeadLockDetectionTimeMs = + 2 * TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS * TEST_SYNC_CRITICAL_TEST1_RUNS; + + printf("Deadlock will be assumed after %" PRIu32 " ms.\n", dwDeadLockDetectionTimeMs); + + if (!(hThread = CreateThread(NULL, 0, TestSynchCritical_Main, &bThreadTerminated, 0, NULL))) + { + printf("CriticalSection failure: Failed to create main thread\n"); + return -1; + } + + /** + * We have to be able to detect dead locks in this test. + * At the time of writing winpr's WaitForSingleObject has not implemented timeout for thread + * wait + * + * Workaround checking the value of bThreadTerminated which is passed in the thread arg + */ + + for (DWORD i = 0; i < dwDeadLockDetectionTimeMs; i += 10) + { + if (bThreadTerminated) + break; + + Sleep(10); + } + + if (!bThreadTerminated) + { + printf("CriticalSection failure: Possible dead lock detected\n"); + return -1; + } + + GetExitCodeThread(hThread, &dwThreadExitCode); + (void)CloseHandle(hThread); + + if (dwThreadExitCode != 0) + { + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchEvent.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchEvent.c new file mode 100644 index 0000000000000000000000000000000000000000..1db5666923e40cb2d5ddf922847a9fd2cf9d146c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchEvent.c @@ -0,0 +1,94 @@ + +#include +#include + +int TestSynchEvent(int argc, char* argv[]) +{ + HANDLE event = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + if (ResetEvent(NULL)) + { + printf("ResetEvent(NULL) unexpectedly succeeded\n"); + return -1; + } + + if (SetEvent(NULL)) + { + printf("SetEvent(NULL) unexpectedly succeeded\n"); + return -1; + } + + event = CreateEvent(NULL, TRUE, TRUE, NULL); + + if (!event) + { + printf("CreateEvent failure\n"); + return -1; + } + + if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) + { + printf("WaitForSingleObject failure 1\n"); + return -1; + } + + if (!ResetEvent(event)) + { + printf("ResetEvent failure with signaled event object\n"); + return -1; + } + + if (WaitForSingleObject(event, 0) != WAIT_TIMEOUT) + { + printf("WaitForSingleObject failure 2\n"); + return -1; + } + + if (!ResetEvent(event)) + { + /* Note: ResetEvent must also succeed if event is currently nonsignaled */ + printf("ResetEvent failure with nonsignaled event object\n"); + return -1; + } + + if (!SetEvent(event)) + { + printf("SetEvent failure with nonsignaled event object\n"); + return -1; + } + + if (WaitForSingleObject(event, 0) != WAIT_OBJECT_0) + { + printf("WaitForSingleObject failure 3\n"); + return -1; + } + + for (int i = 0; i < 10000; i++) + { + if (!SetEvent(event)) + { + printf("SetEvent failure with signaled event object (i = %d)\n", i); + return -1; + } + } + + if (!ResetEvent(event)) + { + printf("ResetEvent failure after multiple SetEvent calls\n"); + return -1; + } + + /* Independent of the amount of the previous SetEvent calls, a single + ResetEvent must be sufficient to get into nonsignaled state */ + + if (WaitForSingleObject(event, 0) != WAIT_TIMEOUT) + { + printf("WaitForSingleObject failure 4\n"); + return -1; + } + + (void)CloseHandle(event); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchInit.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchInit.c new file mode 100644 index 0000000000000000000000000000000000000000..dcb64b46835a6fc03dab5944f4405212f4146f95 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchInit.c @@ -0,0 +1,166 @@ +#include +#include +#include +#include +#include +#include + +#define TEST_NUM_THREADS 100 +#define TEST_NUM_FAILURES 10 + +static INIT_ONCE initOnceTest = INIT_ONCE_STATIC_INIT; + +static HANDLE hStartEvent = NULL; +static LONG* pErrors = NULL; +static LONG* pTestThreadFunctionCalls = NULL; +static LONG* pTestOnceFunctionCalls = NULL; +static LONG* pInitOnceExecuteOnceCalls = NULL; + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +static BOOL CALLBACK TestOnceFunction(PINIT_ONCE once, PVOID param, PVOID* context) +{ + LONG calls = InterlockedIncrement(pTestOnceFunctionCalls) - 1; + + WINPR_UNUSED(once); + WINPR_UNUSED(param); + WINPR_UNUSED(context); + + /* simulate execution time */ + Sleep(30 + prand(40)); + + if (calls < TEST_NUM_FAILURES) + { + /* simulated error */ + return FALSE; + } + if (calls == TEST_NUM_FAILURES) + { + return TRUE; + } + (void)fprintf(stderr, "%s: error: called again after success\n", __func__); + InterlockedIncrement(pErrors); + return FALSE; +} + +static DWORD WINAPI TestThreadFunction(LPVOID lpParam) +{ + LONG calls = 0; + BOOL ok = 0; + + WINPR_UNUSED(lpParam); + + InterlockedIncrement(pTestThreadFunctionCalls); + if (WaitForSingleObject(hStartEvent, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: error: failed to wait for start event\n", __func__); + InterlockedIncrement(pErrors); + return 0; + } + + ok = InitOnceExecuteOnce(&initOnceTest, TestOnceFunction, NULL, NULL); + calls = InterlockedIncrement(pInitOnceExecuteOnceCalls); + if (!ok && calls > TEST_NUM_FAILURES) + { + (void)fprintf(stderr, "%s: InitOnceExecuteOnce failed unexpectedly\n", __func__); + InterlockedIncrement(pErrors); + } + return 0; +} + +int TestSynchInit(int argc, char* argv[]) +{ + HANDLE hThreads[TEST_NUM_THREADS]; + DWORD dwCreatedThreads = 0; + BOOL result = FALSE; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + pErrors = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + pTestThreadFunctionCalls = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + pTestOnceFunctionCalls = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + pInitOnceExecuteOnceCalls = winpr_aligned_malloc(sizeof(LONG), sizeof(LONG)); + + if (!pErrors || !pTestThreadFunctionCalls || !pTestOnceFunctionCalls || + !pInitOnceExecuteOnceCalls) + { + (void)fprintf(stderr, "error: _aligned_malloc failed\n"); + goto out; + } + + *pErrors = 0; + *pTestThreadFunctionCalls = 0; + *pTestOnceFunctionCalls = 0; + *pInitOnceExecuteOnceCalls = 0; + + if (!(hStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + (void)fprintf(stderr, "error creating start event\n"); + InterlockedIncrement(pErrors); + goto out; + } + + for (DWORD i = 0; i < TEST_NUM_THREADS; i++) + { + if (!(hThreads[i] = CreateThread(NULL, 0, TestThreadFunction, NULL, 0, NULL))) + { + (void)fprintf(stderr, "error creating thread #%" PRIu32 "\n", i); + InterlockedIncrement(pErrors); + goto out; + } + dwCreatedThreads++; + } + + Sleep(100); + (void)SetEvent(hStartEvent); + + for (DWORD i = 0; i < dwCreatedThreads; i++) + { + if (WaitForSingleObject(hThreads[i], INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "error: error waiting for thread #%" PRIu32 "\n", i); + InterlockedIncrement(pErrors); + goto out; + } + } + + if (*pErrors == 0 && *pTestThreadFunctionCalls == TEST_NUM_THREADS && + *pInitOnceExecuteOnceCalls == TEST_NUM_THREADS && + *pTestOnceFunctionCalls == TEST_NUM_FAILURES + 1) + { + result = TRUE; + } + +out: + (void)fprintf(stderr, "Test result: %s\n", result ? "OK" : "ERROR"); + (void)fprintf(stderr, "Error count: %" PRId32 "\n", pErrors ? *pErrors : -1); + (void)fprintf(stderr, "Threads created: %" PRIu32 "\n", dwCreatedThreads); + (void)fprintf(stderr, "TestThreadFunctionCalls: %" PRId32 "\n", + pTestThreadFunctionCalls ? *pTestThreadFunctionCalls : -1); + (void)fprintf(stderr, "InitOnceExecuteOnceCalls: %" PRId32 "\n", + pInitOnceExecuteOnceCalls ? *pInitOnceExecuteOnceCalls : -1); + (void)fprintf(stderr, "TestOnceFunctionCalls: %" PRId32 "\n", + pTestOnceFunctionCalls ? *pTestOnceFunctionCalls : -1); + + winpr_aligned_free(pErrors); + winpr_aligned_free(pTestThreadFunctionCalls); + winpr_aligned_free(pTestOnceFunctionCalls); + winpr_aligned_free(pInitOnceExecuteOnceCalls); + + (void)CloseHandle(hStartEvent); + + for (DWORD i = 0; i < dwCreatedThreads; i++) + { + (void)CloseHandle(hThreads[i]); + } + + return (result ? 0 : 1); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMultipleThreads.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMultipleThreads.c new file mode 100644 index 0000000000000000000000000000000000000000..68f5880c74b4312b5f82b68eaa32b6df1cd3a163 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMultipleThreads.c @@ -0,0 +1,255 @@ + +#include + +#include +#include +#include +#include + +#define THREADS 8 + +static UINT32 prand(UINT32 max) +{ + UINT32 tmp = 0; + if (max <= 1) + return 1; + winpr_RAND(&tmp, sizeof(tmp)); + return tmp % (max - 1) + 1; +} + +static DWORD WINAPI test_thread(LPVOID arg) +{ + UINT32 timeout = 50 + prand(100); + WINPR_UNUSED(arg); + Sleep(timeout); + ExitThread(0); + return 0; +} + +static int start_threads(size_t count, HANDLE* threads) +{ + for (size_t i = 0; i < count; i++) + { + threads[i] = CreateThread(NULL, 0, test_thread, NULL, CREATE_SUSPENDED, NULL); + + if (!threads[i]) + { + (void)fprintf(stderr, "%s: CreateThread [%" PRIuz "] failure\n", __func__, i); + return -1; + } + } + + for (size_t i = 0; i < count; i++) + ResumeThread(threads[i]); + return 0; +} + +static int close_threads(DWORD count, HANDLE* threads) +{ + int rc = 0; + + for (DWORD i = 0; i < count; i++) + { + if (!threads[i]) + continue; + + if (!CloseHandle(threads[i])) + { + (void)fprintf(stderr, "%s: CloseHandle [%" PRIu32 "] failure\n", __func__, i); + rc = -1; + } + threads[i] = NULL; + } + + return rc; +} + +static BOOL TestWaitForAll(void) +{ + BOOL rc = FALSE; + HANDLE threads[THREADS] = { 0 }; + /* WaitForAll, timeout */ + if (start_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: start_threads failed\n", __func__); + goto fail; + } + + const DWORD ret = WaitForMultipleObjects(ARRAYSIZE(threads), threads, TRUE, 10); + if (ret != WAIT_TIMEOUT) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects bWaitAll, timeout 10 failed, ret=%d\n", + __func__, ret); + goto fail; + } + + if (WaitForMultipleObjects(ARRAYSIZE(threads), threads, TRUE, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects bWaitAll, INFINITE failed\n", __func__); + goto fail; + } + + rc = TRUE; +fail: + if (close_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: close_threads failed\n", __func__); + return FALSE; + } + + return rc; +} + +static BOOL TestWaitOne(void) +{ + BOOL rc = FALSE; + HANDLE threads[THREADS] = { 0 }; + /* WaitForAll, timeout */ + if (start_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: start_threads failed\n", __func__); + goto fail; + } + + const DWORD ret = WaitForMultipleObjects(ARRAYSIZE(threads), threads, FALSE, INFINITE); + if (ret > (WAIT_OBJECT_0 + ARRAYSIZE(threads))) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects INFINITE failed\n", __func__); + goto fail; + } + + if (WaitForMultipleObjects(ARRAYSIZE(threads), threads, TRUE, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects bWaitAll, INFINITE failed\n", __func__); + goto fail; + } + + rc = TRUE; +fail: + if (close_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: close_threads failed\n", __func__); + return FALSE; + } + + return rc; +} + +static BOOL TestWaitOneTimeout(void) +{ + BOOL rc = FALSE; + HANDLE threads[THREADS] = { 0 }; + /* WaitForAll, timeout */ + if (start_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: start_threads failed\n", __func__); + goto fail; + } + + const DWORD ret = WaitForMultipleObjects(ARRAYSIZE(threads), threads, FALSE, 1); + if (ret != WAIT_TIMEOUT) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects timeout 50 failed, ret=%d\n", __func__, + ret); + goto fail; + } + + if (WaitForMultipleObjects(ARRAYSIZE(threads), threads, TRUE, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects bWaitAll, INFINITE failed\n", __func__); + goto fail; + } + rc = TRUE; +fail: + if (close_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: close_threads failed\n", __func__); + return FALSE; + } + + return rc; +} + +static BOOL TestWaitOneTimeoutMultijoin(void) +{ + BOOL rc = FALSE; + HANDLE threads[THREADS] = { 0 }; + /* WaitForAll, timeout */ + if (start_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: start_threads failed\n", __func__); + goto fail; + } + + for (size_t i = 0; i < ARRAYSIZE(threads); i++) + { + const DWORD ret = WaitForMultipleObjects(ARRAYSIZE(threads), threads, FALSE, 0); + if (ret != WAIT_TIMEOUT) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects timeout 0 failed, ret=%d\n", __func__, + ret); + goto fail; + } + } + + if (WaitForMultipleObjects(ARRAYSIZE(threads), threads, TRUE, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: WaitForMultipleObjects bWaitAll, INFINITE failed\n", __func__); + goto fail; + } + + rc = TRUE; +fail: + if (close_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: close_threads failed\n", __func__); + return FALSE; + } + + return rc; +} + +static BOOL TestDetach(void) +{ + BOOL rc = FALSE; + HANDLE threads[THREADS] = { 0 }; + /* WaitForAll, timeout */ + if (start_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: start_threads failed\n", __func__); + goto fail; + } + + rc = TRUE; +fail: + if (close_threads(ARRAYSIZE(threads), threads)) + { + (void)fprintf(stderr, "%s: close_threads failed\n", __func__); + return FALSE; + } + + return rc; +} + +int TestSynchMultipleThreads(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!TestWaitForAll()) + return -1; + + if (!TestWaitOne()) + return -2; + + if (!TestWaitOneTimeout()) + return -3; + + if (!TestWaitOneTimeoutMultijoin()) + return -4; + + if (!TestDetach()) + return -5; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMutex.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMutex.c new file mode 100644 index 0000000000000000000000000000000000000000..9088b187242723f48c23fdb625d1535a893b6f21 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchMutex.c @@ -0,0 +1,258 @@ + +#include +#include +#include + +static BOOL test_mutex_basic(void) +{ + HANDLE mutex = NULL; + DWORD rc = 0; + + if (!(mutex = CreateMutex(NULL, FALSE, NULL))) + { + printf("%s: CreateMutex failed\n", __func__); + return FALSE; + } + + rc = WaitForSingleObject(mutex, INFINITE); + + if (rc != WAIT_OBJECT_0) + { + printf("%s: WaitForSingleObject on mutex failed with %" PRIu32 "\n", __func__, rc); + return FALSE; + } + + if (!ReleaseMutex(mutex)) + { + printf("%s: ReleaseMutex failed\n", __func__); + return FALSE; + } + + if (ReleaseMutex(mutex)) + { + printf("%s: ReleaseMutex unexpectedly succeeded on released mutex\n", __func__); + return FALSE; + } + + if (!CloseHandle(mutex)) + { + printf("%s: CloseHandle on mutex failed\n", __func__); + return FALSE; + } + + return TRUE; +} + +static BOOL test_mutex_recursive(void) +{ + HANDLE mutex = NULL; + DWORD rc = 0; + DWORD cnt = 50; + + if (!(mutex = CreateMutex(NULL, TRUE, NULL))) + { + printf("%s: CreateMutex failed\n", __func__); + return FALSE; + } + + for (UINT32 i = 0; i < cnt; i++) + { + rc = WaitForSingleObject(mutex, INFINITE); + + if (rc != WAIT_OBJECT_0) + { + printf("%s: WaitForSingleObject #%" PRIu32 " on mutex failed with %" PRIu32 "\n", + __func__, i, rc); + return FALSE; + } + } + + for (UINT32 i = 0; i < cnt; i++) + { + if (!ReleaseMutex(mutex)) + { + printf("%s: ReleaseMutex #%" PRIu32 " failed\n", __func__, i); + return FALSE; + } + } + + if (!ReleaseMutex(mutex)) + { + /* Note: The mutex was initially owned ! */ + printf("%s: Final ReleaseMutex failed\n", __func__); + return FALSE; + } + + if (ReleaseMutex(mutex)) + { + printf("%s: ReleaseMutex unexpectedly succeeded on released mutex\n", __func__); + return FALSE; + } + + if (!CloseHandle(mutex)) + { + printf("%s: CloseHandle on mutex failed\n", __func__); + return FALSE; + } + + return TRUE; +} + +static HANDLE thread1_mutex1 = NULL; +static HANDLE thread1_mutex2 = NULL; +static BOOL thread1_failed = TRUE; + +static DWORD WINAPI test_mutex_thread1(LPVOID lpParam) +{ + HANDLE hStartEvent = (HANDLE)lpParam; + DWORD rc = 0; + + if (WaitForSingleObject(hStartEvent, INFINITE) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: failed to wait for start event\n", __func__); + return 0; + } + + /** + * at this point: + * thread1_mutex1 is expected to be locked + * thread1_mutex2 is expected to be unlocked + * defined task: + * try to lock thread1_mutex1 (expected to fail) + * lock and unlock thread1_mutex2 (expected to work) + */ + rc = WaitForSingleObject(thread1_mutex1, 10); + + if (rc != WAIT_TIMEOUT) + { + (void)fprintf(stderr, + "%s: WaitForSingleObject on thread1_mutex1 unexpectedly returned %" PRIu32 + " instead of WAIT_TIMEOUT (%u)\n", + __func__, rc, WAIT_TIMEOUT); + return 0; + } + + rc = WaitForSingleObject(thread1_mutex2, 10); + + if (rc != WAIT_OBJECT_0) + { + (void)fprintf(stderr, + "%s: WaitForSingleObject on thread1_mutex2 unexpectedly returned %" PRIu32 + " instead of WAIT_OBJECT_0\n", + __func__, rc); + return 0; + } + + if (!ReleaseMutex(thread1_mutex2)) + { + (void)fprintf(stderr, "%s: ReleaseMutex failed on thread1_mutex2\n", __func__); + return 0; + } + + thread1_failed = FALSE; + return 0; +} + +static BOOL test_mutex_threading(void) +{ + HANDLE hThread = NULL; + HANDLE hStartEvent = NULL; + + if (!(thread1_mutex1 = CreateMutex(NULL, TRUE, NULL))) + { + printf("%s: CreateMutex thread1_mutex1 failed\n", __func__); + goto fail; + } + + if (!(thread1_mutex2 = CreateMutex(NULL, FALSE, NULL))) + { + printf("%s: CreateMutex thread1_mutex2 failed\n", __func__); + goto fail; + } + + if (!(hStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + (void)fprintf(stderr, "%s: error creating start event\n", __func__); + goto fail; + } + + thread1_failed = TRUE; + + if (!(hThread = CreateThread(NULL, 0, test_mutex_thread1, (LPVOID)hStartEvent, 0, NULL))) + { + (void)fprintf(stderr, "%s: error creating test_mutex_thread_1\n", __func__); + goto fail; + } + + Sleep(100); + + if (!thread1_failed) + { + (void)fprintf(stderr, "%s: thread1 premature success\n", __func__); + goto fail; + } + + (void)SetEvent(hStartEvent); + + if (WaitForSingleObject(hThread, 2000) != WAIT_OBJECT_0) + { + (void)fprintf(stderr, "%s: thread1 premature success\n", __func__); + goto fail; + } + + if (thread1_failed) + { + (void)fprintf(stderr, "%s: thread1 has not reported success\n", __func__); + goto fail; + } + + /** + * - thread1 must not have succeeded to lock thread1_mutex1 + * - thread1 must have locked and unlocked thread1_mutex2 + */ + + if (!ReleaseMutex(thread1_mutex1)) + { + printf("%s: ReleaseMutex unexpectedly failed on thread1_mutex1\n", __func__); + goto fail; + } + + if (ReleaseMutex(thread1_mutex2)) + { + printf("%s: ReleaseMutex unexpectedly succeeded on thread1_mutex2\n", __func__); + goto fail; + } + + (void)CloseHandle(hThread); + (void)CloseHandle(hStartEvent); + (void)CloseHandle(thread1_mutex1); + (void)CloseHandle(thread1_mutex2); + return TRUE; +fail: + (void)ReleaseMutex(thread1_mutex1); + (void)ReleaseMutex(thread1_mutex2); + (void)CloseHandle(thread1_mutex1); + (void)CloseHandle(thread1_mutex2); + (void)CloseHandle(hStartEvent); + (void)CloseHandle(hThread); + return FALSE; +} + +int TestSynchMutex(int argc, char* argv[]) +{ + int rc = 0; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_mutex_basic()) + rc += 1; + + if (!test_mutex_recursive()) + rc += 2; + + if (!test_mutex_threading()) + rc += 4; + + printf("TestSynchMutex result %d\n", rc); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchSemaphore.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchSemaphore.c new file mode 100644 index 0000000000000000000000000000000000000000..aa29dd4a1f6830c105d045496c84ba3182e7ffbe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchSemaphore.c @@ -0,0 +1,21 @@ + +#include +#include + +int TestSynchSemaphore(int argc, char* argv[]) +{ + HANDLE semaphore = NULL; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + semaphore = CreateSemaphore(NULL, 0, 1, NULL); + + if (!semaphore) + { + printf("CreateSemaphore failure\n"); + return -1; + } + + (void)CloseHandle(semaphore); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchThread.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchThread.c new file mode 100644 index 0000000000000000000000000000000000000000..58f7cb0808bc6cc93c79cc73b75dc48fd2915f4d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchThread.c @@ -0,0 +1,131 @@ + +#include +#include +#include + +static DWORD WINAPI test_thread(LPVOID arg) +{ + WINPR_UNUSED(arg); + Sleep(100); + ExitThread(0); + return 0; +} + +int TestSynchThread(int argc, char* argv[]) +{ + DWORD rc = 0; + HANDLE thread = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL); + + if (!thread) + { + printf("CreateThread failure\n"); + return -1; + } + + /* TryJoin should now fail. */ + rc = WaitForSingleObject(thread, 0); + + if (WAIT_TIMEOUT != rc) + { + printf("Timed WaitForSingleObject on running thread failed with %" PRIu32 "\n", rc); + return -3; + } + + /* Join the thread */ + rc = WaitForSingleObject(thread, INFINITE); + + if (WAIT_OBJECT_0 != rc) + { + printf("WaitForSingleObject on thread failed with %" PRIu32 "\n", rc); + return -2; + } + + /* TimedJoin should now succeed. */ + rc = WaitForSingleObject(thread, 0); + + if (WAIT_OBJECT_0 != rc) + { + printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc); + return -5; + } + + /* check that WaitForSingleObject works multiple times on a terminated thread */ + for (int i = 0; i < 4; i++) + { + rc = WaitForSingleObject(thread, 0); + if (WAIT_OBJECT_0 != rc) + { + printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc); + return -6; + } + } + + if (!CloseHandle(thread)) + { + printf("CloseHandle failed!"); + return -1; + } + + thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL); + + if (!thread) + { + printf("CreateThread failure\n"); + return -1; + } + + /* TryJoin should now fail. */ + rc = WaitForSingleObject(thread, 10); + + if (WAIT_TIMEOUT != rc) + { + printf("Timed WaitForSingleObject on running thread failed with %" PRIu32 "\n", rc); + return -3; + } + + /* Join the thread */ + rc = WaitForSingleObject(thread, INFINITE); + + if (WAIT_OBJECT_0 != rc) + { + printf("WaitForSingleObject on thread failed with %" PRIu32 "\n", rc); + return -2; + } + + /* TimedJoin should now succeed. */ + rc = WaitForSingleObject(thread, 0); + + if (WAIT_OBJECT_0 != rc) + { + printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc); + return -5; + } + + if (!CloseHandle(thread)) + { + printf("CloseHandle failed!"); + return -1; + } + + /* Thread detach test */ + thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL); + + if (!thread) + { + printf("CreateThread failure\n"); + return -1; + } + + if (!CloseHandle(thread)) + { + printf("CloseHandle failed!"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchTimerQueue.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchTimerQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..55a88d92d76726e92acfe21fa588aa97e3357eed --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchTimerQueue.c @@ -0,0 +1,125 @@ + +#include +#include +#include +#include + +#define FIRE_COUNT 5 +#define TIMER_COUNT 5 + +struct apc_data +{ + DWORD TimerId; + DWORD FireCount; + DWORD DueTime; + DWORD Period; + UINT32 StartTime; + DWORD MaxFireCount; + HANDLE CompletionEvent; +}; +typedef struct apc_data APC_DATA; + +static VOID CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired) +{ + UINT32 TimerTime = 0; + APC_DATA* apcData = NULL; + UINT32 expectedTime = 0; + UINT32 CurrentTime = GetTickCount(); + + WINPR_UNUSED(TimerOrWaitFired); + + if (!lpParam) + return; + + apcData = (APC_DATA*)lpParam; + + TimerTime = CurrentTime - apcData->StartTime; + expectedTime = apcData->DueTime + (apcData->Period * apcData->FireCount); + + apcData->FireCount++; + + printf("TimerRoutine: TimerId: %" PRIu32 " FireCount: %" PRIu32 " ActualTime: %" PRIu32 + " ExpectedTime: %" PRIu32 " Discrepancy: %" PRIu32 "\n", + apcData->TimerId, apcData->FireCount, TimerTime, expectedTime, TimerTime - expectedTime); + + Sleep(11); + + if (apcData->FireCount == apcData->MaxFireCount) + { + (void)SetEvent(apcData->CompletionEvent); + } +} + +int TestSynchTimerQueue(int argc, char* argv[]) +{ + HANDLE hTimerQueue = NULL; + HANDLE hTimers[TIMER_COUNT]; + APC_DATA apcData[TIMER_COUNT]; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + hTimerQueue = CreateTimerQueue(); + + if (!hTimerQueue) + { + printf("CreateTimerQueue failed (%" PRIu32 ")\n", GetLastError()); + return -1; + } + + for (DWORD index = 0; index < TIMER_COUNT; index++) + { + apcData[index].TimerId = index; + apcData[index].StartTime = GetTickCount(); + apcData[index].DueTime = (index * 10) + 50; + apcData[index].Period = 100; + apcData[index].FireCount = 0; + apcData[index].MaxFireCount = FIRE_COUNT; + + if (!(apcData[index].CompletionEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + { + printf("Failed to create apcData[%" PRIu32 "] event (%" PRIu32 ")\n", index, + GetLastError()); + return -1; + } + + if (!CreateTimerQueueTimer(&hTimers[index], hTimerQueue, TimerRoutine, &apcData[index], + apcData[index].DueTime, apcData[index].Period, 0)) + { + printf("CreateTimerQueueTimer failed (%" PRIu32 ")\n", GetLastError()); + return -1; + } + } + + for (DWORD index = 0; index < TIMER_COUNT; index++) + { + if (WaitForSingleObject(apcData[index].CompletionEvent, 2000) != WAIT_OBJECT_0) + { + printf("Failed to wait for timer queue timer #%" PRIu32 " (%" PRIu32 ")\n", index, + GetLastError()); + return -1; + } + } + + for (DWORD index = 0; index < TIMER_COUNT; index++) + { + /** + * Note: If the CompletionEvent parameter is INVALID_HANDLE_VALUE, the function waits + * for any running timer callback functions to complete before returning. + */ + if (!DeleteTimerQueueTimer(hTimerQueue, hTimers[index], INVALID_HANDLE_VALUE)) + { + printf("DeleteTimerQueueTimer failed (%" PRIu32 ")\n", GetLastError()); + return -1; + } + (void)CloseHandle(apcData[index].CompletionEvent); + } + + if (!DeleteTimerQueue(hTimerQueue)) + { + printf("DeleteTimerQueue failed (%" PRIu32 ")\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimer.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimer.c new file mode 100644 index 0000000000000000000000000000000000000000..06fa9418a4fcc7e9023007eb771f6b25244d8907 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimer.c @@ -0,0 +1,83 @@ + +#include +#include + +int TestSynchWaitableTimer(int argc, char* argv[]) +{ + DWORD status = 0; + HANDLE timer = NULL; + LONG period = 0; + LARGE_INTEGER due = { 0 }; + int result = -1; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + timer = CreateWaitableTimer(NULL, FALSE, NULL); + + if (!timer) + { + printf("CreateWaitableTimer failure\n"); + goto out; + } + + due.QuadPart = -1500000LL; /* 0.15 seconds */ + + if (!SetWaitableTimer(timer, &due, 0, NULL, NULL, 0)) + { + printf("SetWaitableTimer failure\n"); + goto out; + } + + status = WaitForSingleObject(timer, INFINITE); + + if (status != WAIT_OBJECT_0) + { + printf("WaitForSingleObject(timer, INFINITE) failure\n"); + goto out; + } + + printf("Timer Signaled\n"); + status = WaitForSingleObject(timer, 200); + + if (status != WAIT_TIMEOUT) + { + printf("WaitForSingleObject(timer, 200) failure: Actual: 0x%08" PRIX32 + ", Expected: 0x%08X\n", + status, WAIT_TIMEOUT); + goto out; + } + + due.QuadPart = 0; + period = 120; /* 0.12 seconds */ + + if (!SetWaitableTimer(timer, &due, period, NULL, NULL, 0)) + { + printf("SetWaitableTimer failure\n"); + goto out; + } + + if (WaitForSingleObject(timer, INFINITE) != WAIT_OBJECT_0) + { + printf("WaitForSingleObject(timer, INFINITE) failure\n"); + goto out; + } + + printf("Timer Signaled\n"); + + if (!SetWaitableTimer(timer, &due, period, NULL, NULL, 0)) + { + printf("SetWaitableTimer failure\n"); + goto out; + } + + if (WaitForMultipleObjects(1, &timer, FALSE, INFINITE) != WAIT_OBJECT_0) + { + printf("WaitForMultipleObjects(timer, INFINITE) failure\n"); + goto out; + } + + printf("Timer Signaled\n"); + result = 0; +out: + (void)CloseHandle(timer); + return result; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimerAPC.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimerAPC.c new file mode 100644 index 0000000000000000000000000000000000000000..924f75a0405c7037bc33355d3a4a51d6d3a480b5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/test/TestSynchWaitableTimerAPC.c @@ -0,0 +1,92 @@ + +#include +#include +#include + +static int g_Count = 0; +static HANDLE g_Event = NULL; + +struct apc_data +{ + UINT32 StartTime; +}; +typedef struct apc_data APC_DATA; + +static VOID CALLBACK TimerAPCProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue) +{ + APC_DATA* apcData = NULL; + UINT32 CurrentTime = GetTickCount(); + WINPR_UNUSED(dwTimerLowValue); + WINPR_UNUSED(dwTimerHighValue); + + if (!lpArg) + return; + + apcData = (APC_DATA*)lpArg; + printf("TimerAPCProc: time: %" PRIu32 "\n", CurrentTime - apcData->StartTime); + g_Count++; + + if (g_Count >= 5) + { + (void)SetEvent(g_Event); + } +} + +int TestSynchWaitableTimerAPC(int argc, char* argv[]) +{ + int status = -1; + DWORD rc = 0; + HANDLE hTimer = NULL; + BOOL bSuccess = 0; + LARGE_INTEGER due = { 0 }; + APC_DATA apcData = { 0 }; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + g_Event = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (!g_Event) + { + printf("Failed to create event\n"); + goto cleanup; + } + + hTimer = CreateWaitableTimer(NULL, FALSE, NULL); + if (!hTimer) + goto cleanup; + + due.QuadPart = -1000 * 100LL; /* 0.1 seconds */ + apcData.StartTime = GetTickCount(); + bSuccess = SetWaitableTimer(hTimer, &due, 10, TimerAPCProc, &apcData, FALSE); + + if (!bSuccess) + goto cleanup; + + /* nothing shall happen after 0.12 second, because thread is not in alertable state */ + rc = WaitForSingleObject(g_Event, 120); + if (rc != WAIT_TIMEOUT) + goto cleanup; + + for (;;) + { + rc = WaitForSingleObjectEx(g_Event, INFINITE, TRUE); + if (rc == WAIT_OBJECT_0) + break; + + if (rc == WAIT_IO_COMPLETION) + continue; + + printf("Failed to wait for completion event (%" PRIu32 ")\n", GetLastError()); + goto cleanup; + } + + status = 0; +cleanup: + + if (hTimer) + (void)CloseHandle(hTimer); + + if (g_Event) + (void)CloseHandle(g_Event); + + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/timer.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/timer.c new file mode 100644 index 0000000000000000000000000000000000000000..61a682af5d38665cfce130142c4f0b96d34e5fb3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/timer.c @@ -0,0 +1,1087 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2021 David Fort + * + * 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 + +#include +#include +#include +#include + +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#endif + +#include "event.h" +#include "synch.h" + +#ifndef _WIN32 + +#include "../handle/handle.h" +#include "../thread/thread.h" + +#include "../log.h" +#define TAG WINPR_TAG("synch.timer") + +static BOOL TimerCloseHandle(HANDLE handle); + +static BOOL TimerIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_TIMER, FALSE); +} + +static int TimerGetFd(HANDLE handle) +{ + WINPR_TIMER* timer = (WINPR_TIMER*)handle; + + if (!TimerIsHandled(handle)) + return -1; + + return timer->fd; +} + +static DWORD TimerCleanupHandle(HANDLE handle) +{ + WINPR_TIMER* timer = (WINPR_TIMER*)handle; + + if (!TimerIsHandled(handle)) + return WAIT_FAILED; + + if (timer->bManualReset) + return WAIT_OBJECT_0; + +#ifdef TIMER_IMPL_TIMERFD + SSIZE_T length = 0; + do + { + UINT64 expirations = 0; + length = read(timer->fd, (void*)&expirations, sizeof(UINT64)); + } while (length < 0 && errno == EINTR); + + if (length != 8) + { + if (length < 0) + { + char ebuffer[256] = { 0 }; + switch (errno) + { + case ETIMEDOUT: + case EAGAIN: + return WAIT_TIMEOUT; + + default: + break; + } + + WLog_ERR(TAG, "timer read() failure [%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + } + else + { + WLog_ERR(TAG, "timer read() failure - incorrect number of bytes read"); + } + + return WAIT_FAILED; + } +#elif defined(TIMER_IMPL_POSIX) || defined(TIMER_IMPL_DISPATCH) + if (!winpr_event_reset(&timer->event)) + { + WLog_ERR(TAG, "timer reset() failure"); + return WAIT_FAILED; + } +#endif + + return WAIT_OBJECT_0; +} + +typedef struct +{ + WINPR_APC_ITEM apcItem; + WINPR_TIMER* timer; +} TimerDeleter; + +static void TimerPostDelete_APC(LPVOID arg) +{ + TimerDeleter* deleter = (TimerDeleter*)arg; + WINPR_ASSERT(deleter); + free(deleter->timer); + deleter->apcItem.markedForFree = TRUE; + deleter->apcItem.markedForRemove = TRUE; +} + +BOOL TimerCloseHandle(HANDLE handle) +{ + WINPR_TIMER* timer = NULL; + timer = (WINPR_TIMER*)handle; + + if (!TimerIsHandled(handle)) + return FALSE; + +#ifdef TIMER_IMPL_TIMERFD + if (timer->fd != -1) + close(timer->fd); +#endif + +#ifdef TIMER_IMPL_POSIX + timer_delete(timer->tid); +#endif + +#ifdef TIMER_IMPL_DISPATCH + dispatch_release(timer->queue); + dispatch_release(timer->source); +#endif + +#if defined(TIMER_IMPL_POSIX) || defined(TIMER_IMPL_DISPATCH) + winpr_event_uninit(&timer->event); +#endif + + free(timer->name); + if (timer->apcItem.linked) + { + TimerDeleter* deleter = NULL; + WINPR_APC_ITEM* apcItem = NULL; + + switch (apc_remove(&timer->apcItem)) + { + case APC_REMOVE_OK: + break; + case APC_REMOVE_DELAY_FREE: + { + WINPR_THREAD* thread = winpr_GetCurrentThread(); + if (!thread) + return FALSE; + + deleter = calloc(1, sizeof(*deleter)); + if (!deleter) + { + WLog_ERR(TAG, "unable to allocate a timer deleter"); + return TRUE; + } + + deleter->timer = timer; + apcItem = &deleter->apcItem; + apcItem->type = APC_TYPE_HANDLE_FREE; + apcItem->alwaysSignaled = TRUE; + apcItem->completion = TimerPostDelete_APC; + apcItem->completionArgs = deleter; + apc_register(thread, apcItem); + return TRUE; + } + case APC_REMOVE_ERROR: + default: + WLog_ERR(TAG, "unable to remove timer from APC list"); + break; + } + } + + free(timer); + return TRUE; +} + +#ifdef TIMER_IMPL_POSIX + +static void WaitableTimerSignalHandler(int signum, siginfo_t* siginfo, void* arg) +{ + WINPR_TIMER* timer = siginfo->si_value.sival_ptr; + UINT64 data = 1; + WINPR_UNUSED(arg); + + if (!timer || (signum != SIGALRM)) + return; + + if (!winpr_event_set(&timer->event)) + WLog_ERR(TAG, "error when notifying event"); +} + +static INIT_ONCE TimerSignalHandler_InitOnce = INIT_ONCE_STATIC_INIT; + +static BOOL InstallTimerSignalHandler(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context) +{ + struct sigaction action; + sigemptyset(&action.sa_mask); + sigaddset(&action.sa_mask, SIGALRM); + action.sa_flags = SA_RESTART | SA_SIGINFO; + action.sa_sigaction = WaitableTimerSignalHandler; + sigaction(SIGALRM, &action, NULL); + return TRUE; +} +#endif + +#ifdef TIMER_IMPL_DISPATCH +static void WaitableTimerHandler(void* arg) +{ + WINPR_TIMER* timer = (WINPR_TIMER*)arg; + + if (!timer) + return; + + if (!winpr_event_set(&timer->event)) + WLog_ERR(TAG, "failed to write to pipe"); + + if (timer->lPeriod == 0) + { + if (timer->running) + dispatch_suspend(timer->source); + + timer->running = FALSE; + } +} +#endif + +static int InitializeWaitableTimer(WINPR_TIMER* timer) +{ + int result = 0; + +#ifdef TIMER_IMPL_TIMERFD + timer->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); + if (timer->fd <= 0) + return -1; +#elif defined(TIMER_IMPL_POSIX) + struct sigevent sigev = { 0 }; + InitOnceExecuteOnce(&TimerSignalHandler_InitOnce, InstallTimerSignalHandler, NULL, NULL); + sigev.sigev_notify = SIGEV_SIGNAL; + sigev.sigev_signo = SIGALRM; + sigev.sigev_value.sival_ptr = (void*)timer; + + if ((timer_create(CLOCK_MONOTONIC, &sigev, &(timer->tid))) != 0) + { + WLog_ERR(TAG, "timer_create"); + return -1; + } +#elif !defined(TIMER_IMPL_DISPATCH) + WLog_ERR(TAG, "os specific implementation is missing"); + result = -1; +#endif + + timer->bInit = TRUE; + return result; +} + +static BOOL timer_drain_fd(int fd) +{ + UINT64 expr = 0; + SSIZE_T ret = 0; + + do + { + ret = read(fd, &expr, sizeof(expr)); + } while (ret < 0 && errno == EINTR); + + return ret >= 0; +} + +static HANDLE_OPS ops = { TimerIsHandled, + TimerCloseHandle, + TimerGetFd, + TimerCleanupHandle, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +/** + * Waitable Timer + */ + +HANDLE CreateWaitableTimerA(LPSECURITY_ATTRIBUTES lpTimerAttributes, BOOL bManualReset, + LPCSTR lpTimerName) +{ + HANDLE handle = NULL; + WINPR_TIMER* timer = NULL; + + if (lpTimerAttributes) + WLog_WARN(TAG, "[%s] does not support lpTimerAttributes", lpTimerName); + + timer = (WINPR_TIMER*)calloc(1, sizeof(WINPR_TIMER)); + + if (timer) + { + WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER, WINPR_FD_READ); + handle = (HANDLE)timer; + timer->fd = -1; + timer->lPeriod = 0; + timer->bManualReset = bManualReset; + timer->pfnCompletionRoutine = NULL; + timer->lpArgToCompletionRoutine = NULL; + timer->bInit = FALSE; + + if (lpTimerName) + timer->name = strdup(lpTimerName); + + timer->common.ops = &ops; +#if defined(TIMER_IMPL_DISPATCH) || defined(TIMER_IMPL_POSIX) + if (!winpr_event_init(&timer->event)) + goto fail; + timer->fd = timer->event.fds[0]; +#endif + +#if defined(TIMER_IMPL_DISPATCH) + timer->queue = dispatch_queue_create(TAG, DISPATCH_QUEUE_SERIAL); + + if (!timer->queue) + goto fail; + + timer->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer->queue); + + if (!timer->source) + goto fail; + + dispatch_set_context(timer->source, timer); + dispatch_source_set_event_handler_f(timer->source, WaitableTimerHandler); +#endif + } + + return handle; + +#if defined(TIMER_IMPL_DISPATCH) || defined(TIMER_IMPL_POSIX) +fail: + TimerCloseHandle(handle); + return NULL; +#endif +} + +HANDLE CreateWaitableTimerW(LPSECURITY_ATTRIBUTES lpTimerAttributes, BOOL bManualReset, + LPCWSTR lpTimerName) +{ + HANDLE handle = NULL; + LPSTR name = NULL; + + if (lpTimerName) + { + name = ConvertWCharToUtf8Alloc(lpTimerName, NULL); + if (!name) + return NULL; + } + + handle = CreateWaitableTimerA(lpTimerAttributes, bManualReset, name); + free(name); + return handle; +} + +HANDLE CreateWaitableTimerExA(LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCSTR lpTimerName, + DWORD dwFlags, DWORD dwDesiredAccess) +{ + BOOL bManualReset = (dwFlags & CREATE_WAITABLE_TIMER_MANUAL_RESET) ? TRUE : FALSE; + + if (dwDesiredAccess != 0) + WLog_WARN(TAG, "[%s] does not support dwDesiredAccess 0x%08" PRIx32, lpTimerName, + dwDesiredAccess); + + return CreateWaitableTimerA(lpTimerAttributes, bManualReset, lpTimerName); +} + +HANDLE CreateWaitableTimerExW(LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCWSTR lpTimerName, + DWORD dwFlags, DWORD dwDesiredAccess) +{ + HANDLE handle = NULL; + LPSTR name = NULL; + + if (lpTimerName) + { + name = ConvertWCharToUtf8Alloc(lpTimerName, NULL); + if (!name) + return NULL; + } + + handle = CreateWaitableTimerExA(lpTimerAttributes, name, dwFlags, dwDesiredAccess); + free(name); + return handle; +} + +static void timerAPC(LPVOID arg) +{ + WINPR_TIMER* timer = (WINPR_TIMER*)arg; + WINPR_ASSERT(timer); + if (!timer->lPeriod) + { + /* this is a one time shot timer with a completion, let's remove us from + the APC list */ + switch (apc_remove(&timer->apcItem)) + { + case APC_REMOVE_OK: + case APC_REMOVE_DELAY_FREE: + break; + case APC_REMOVE_ERROR: + default: + WLog_ERR(TAG, "error removing the APC routine"); + } + } + + if (timer->pfnCompletionRoutine) + timer->pfnCompletionRoutine(timer->lpArgToCompletionRoutine, 0, 0); + +#ifdef TIMER_IMPL_TIMERFD + while (timer_drain_fd(timer->fd)) + ; +#elif defined(TIMER_IMPL_POSIX) || defined(TIMER_IMPL_DISPATCH) + winpr_event_reset(&timer->event); +#endif +} + +BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod, + PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, + BOOL fResume) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_TIMER* timer = NULL; + LONGLONG seconds = 0; + LONGLONG nanoseconds = 0; + int status = 0; + + if (!winpr_Handle_GetInfo(hTimer, &Type, &Object)) + return FALSE; + + if (Type != HANDLE_TYPE_TIMER) + return FALSE; + + if (!lpDueTime) + return FALSE; + + if (lPeriod < 0) + return FALSE; + + if (fResume) + { + WLog_ERR(TAG, "does not support fResume"); + return FALSE; + } + + timer = (WINPR_TIMER*)Object; + timer->lPeriod = lPeriod; /* milliseconds */ + timer->pfnCompletionRoutine = pfnCompletionRoutine; + timer->lpArgToCompletionRoutine = lpArgToCompletionRoutine; + + if (!timer->bInit) + { + if (InitializeWaitableTimer(timer) < 0) + return FALSE; + } + +#if defined(TIMER_IMPL_TIMERFD) || defined(TIMER_IMPL_POSIX) + ZeroMemory(&(timer->timeout), sizeof(struct itimerspec)); + + if (lpDueTime->QuadPart < 0) + { + LONGLONG due = lpDueTime->QuadPart * (-1); + /* due time is in 100 nanosecond intervals */ + seconds = (due / 10000000); + nanoseconds = ((due % 10000000) * 100); + } + else if (lpDueTime->QuadPart == 0) + { + seconds = nanoseconds = 0; + } + else + { + WLog_ERR(TAG, "absolute time not implemented"); + return FALSE; + } + + if (lPeriod > 0) + { + timer->timeout.it_interval.tv_sec = (lPeriod / 1000LL); /* seconds */ + timer->timeout.it_interval.tv_nsec = (1000000LL * (lPeriod % 1000LL)); /* nanoseconds */ + } + + if (lpDueTime->QuadPart != 0) + { + timer->timeout.it_value.tv_sec = seconds; /* seconds */ + timer->timeout.it_value.tv_nsec = nanoseconds; /* nanoseconds */ + } + else + { + timer->timeout.it_value.tv_sec = timer->timeout.it_interval.tv_sec; /* seconds */ + timer->timeout.it_value.tv_nsec = timer->timeout.it_interval.tv_nsec; /* nanoseconds */ + } + +#ifdef TIMER_IMPL_TIMERFD + status = timerfd_settime(timer->fd, 0, &(timer->timeout), NULL); + if (status) + { + WLog_ERR(TAG, "timerfd_settime failure: %d", status); + return FALSE; + } +#else + status = timer_settime(timer->tid, 0, &(timer->timeout), NULL); + if (status != 0) + { + WLog_ERR(TAG, "timer_settime failure"); + return FALSE; + } +#endif +#endif + +#ifdef TIMER_IMPL_DISPATCH + if (lpDueTime->QuadPart < 0) + { + LONGLONG due = lpDueTime->QuadPart * (-1); + /* due time is in 100 nanosecond intervals */ + seconds = (due / 10000000); + nanoseconds = due * 100; + } + else if (lpDueTime->QuadPart == 0) + { + seconds = nanoseconds = 0; + } + else + { + WLog_ERR(TAG, "absolute time not implemented"); + return FALSE; + } + + if (!winpr_event_reset(&timer->event)) + { + WLog_ERR(TAG, "error when resetting timer event"); + } + + { + if (timer->running) + dispatch_suspend(timer->source); + + dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, nanoseconds); + uint64_t interval = DISPATCH_TIME_FOREVER; + + if (lPeriod > 0) + interval = lPeriod * 1000000; + + dispatch_source_set_timer(timer->source, start, interval, 0); + dispatch_resume(timer->source); + timer->running = TRUE; + } +#endif + + if (pfnCompletionRoutine) + { + WINPR_APC_ITEM* apcItem = &timer->apcItem; + + /* install our APC routine that will call the completion */ + apcItem->type = APC_TYPE_TIMER; + apcItem->alwaysSignaled = FALSE; + apcItem->pollFd = timer->fd; + apcItem->pollMode = WINPR_FD_READ; + apcItem->completion = timerAPC; + apcItem->completionArgs = timer; + + if (!apcItem->linked) + { + WINPR_THREAD* thread = winpr_GetCurrentThread(); + if (!thread) + return FALSE; + + apc_register(thread, apcItem); + } + } + else + { + if (timer->apcItem.linked) + { + apc_remove(&timer->apcItem); + } + } + return TRUE; +} + +BOOL SetWaitableTimerEx(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod, + PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, + PREASON_CONTEXT WakeContext, ULONG TolerableDelay) +{ + return SetWaitableTimer(hTimer, lpDueTime, lPeriod, pfnCompletionRoutine, + lpArgToCompletionRoutine, FALSE); +} + +HANDLE OpenWaitableTimerA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpTimerName) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +HANDLE OpenWaitableTimerW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpTimerName) +{ + /* TODO: Implement */ + WLog_ERR(TAG, "not implemented"); + return NULL; +} + +BOOL CancelWaitableTimer(HANDLE hTimer) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + + if (!winpr_Handle_GetInfo(hTimer, &Type, &Object)) + return FALSE; + + if (Type != HANDLE_TYPE_TIMER) + return FALSE; + +#if defined(__APPLE__) + { + WINPR_TIMER* timer = (WINPR_TIMER*)Object; + if (timer->running) + dispatch_suspend(timer->source); + + timer->running = FALSE; + } +#endif + return TRUE; +} + +/* + * Returns inner file descriptor for usage with select() + * This file descriptor is not usable on Windows + */ + +int GetTimerFileDescriptor(HANDLE hTimer) +{ + WINPR_HANDLE* hdl = NULL; + ULONG type = 0; + + if (!winpr_Handle_GetInfo(hTimer, &type, &hdl) || type != HANDLE_TYPE_TIMER) + { + WLog_ERR(TAG, "GetTimerFileDescriptor: hTimer is not an timer"); + SetLastError(ERROR_INVALID_PARAMETER); + return -1; + } + + return winpr_Handle_getFd(hTimer); +} + +/** + * Timer-Queue Timer + */ + +/** + * Design, Performance, and Optimization of Timer Strategies for Real-time ORBs: + * http://www.cs.wustl.edu/~schmidt/Timer_Queue.html + */ + +static void timespec_add_ms(struct timespec* tspec, UINT32 ms) +{ + INT64 ns = 0; + WINPR_ASSERT(tspec); + ns = tspec->tv_nsec + (ms * 1000000LL); + tspec->tv_sec += (ns / 1000000000LL); + tspec->tv_nsec = (ns % 1000000000LL); +} + +static void timespec_gettimeofday(struct timespec* tspec) +{ + WINPR_ASSERT(tspec); + + const UINT64 ns = winpr_GetUnixTimeNS(); + tspec->tv_sec = WINPR_TIME_NS_TO_S(ns); + tspec->tv_nsec = WINPR_TIME_NS_REM_NS(ns); +} + +static INT64 timespec_compare(const struct timespec* tspec1, const struct timespec* tspec2) +{ + WINPR_ASSERT(tspec1); + WINPR_ASSERT(tspec2); + if (tspec1->tv_sec == tspec2->tv_sec) + return (tspec1->tv_nsec - tspec2->tv_nsec); + else + return (tspec1->tv_sec - tspec2->tv_sec); +} + +static void timespec_copy(struct timespec* dst, struct timespec* src) +{ + WINPR_ASSERT(dst); + WINPR_ASSERT(src); + dst->tv_sec = src->tv_sec; + dst->tv_nsec = src->tv_nsec; +} + +static void InsertTimerQueueTimer(WINPR_TIMER_QUEUE_TIMER** pHead, WINPR_TIMER_QUEUE_TIMER* timer) +{ + WINPR_TIMER_QUEUE_TIMER* node = NULL; + + WINPR_ASSERT(pHead); + WINPR_ASSERT(timer); + + if (!(*pHead)) + { + *pHead = timer; + timer->next = NULL; + return; + } + + node = *pHead; + + while (node->next) + { + if (timespec_compare(&(timer->ExpirationTime), &(node->ExpirationTime)) > 0) + { + if (timespec_compare(&(timer->ExpirationTime), &(node->next->ExpirationTime)) < 0) + break; + } + + node = node->next; + } + + if (node->next) + { + timer->next = node->next->next; + node->next = timer; + } + else + { + node->next = timer; + timer->next = NULL; + } +} + +static void RemoveTimerQueueTimer(WINPR_TIMER_QUEUE_TIMER** pHead, WINPR_TIMER_QUEUE_TIMER* timer) +{ + BOOL found = FALSE; + WINPR_TIMER_QUEUE_TIMER* node = NULL; + WINPR_TIMER_QUEUE_TIMER* prevNode = NULL; + + WINPR_ASSERT(pHead); + WINPR_ASSERT(timer); + if (timer == *pHead) + { + *pHead = timer->next; + timer->next = NULL; + return; + } + + node = *pHead; + prevNode = NULL; + + while (node) + { + if (node == timer) + { + found = TRUE; + break; + } + + prevNode = node; + node = node->next; + } + + if (found) + { + if (prevNode) + { + prevNode->next = timer->next; + } + + timer->next = NULL; + } +} + +static int FireExpiredTimerQueueTimers(WINPR_TIMER_QUEUE* timerQueue) +{ + struct timespec CurrentTime; + WINPR_TIMER_QUEUE_TIMER* node = NULL; + + WINPR_ASSERT(timerQueue); + + if (!timerQueue->activeHead) + return 0; + + timespec_gettimeofday(&CurrentTime); + node = timerQueue->activeHead; + + while (node) + { + if (timespec_compare(&CurrentTime, &(node->ExpirationTime)) >= 0) + { + node->Callback(node->Parameter, TRUE); + node->FireCount++; + timerQueue->activeHead = node->next; + node->next = NULL; + + if (node->Period) + { + timespec_add_ms(&(node->ExpirationTime), node->Period); + InsertTimerQueueTimer(&(timerQueue->activeHead), node); + } + else + { + InsertTimerQueueTimer(&(timerQueue->inactiveHead), node); + } + + node = timerQueue->activeHead; + } + else + { + break; + } + } + + return 0; +} + +static void* TimerQueueThread(void* arg) +{ + int status = 0; + struct timespec timeout; + WINPR_TIMER_QUEUE* timerQueue = (WINPR_TIMER_QUEUE*)arg; + + WINPR_ASSERT(timerQueue); + while (1) + { + pthread_mutex_lock(&(timerQueue->cond_mutex)); + timespec_gettimeofday(&timeout); + + if (!timerQueue->activeHead) + { + timespec_add_ms(&timeout, 50); + } + else + { + if (timespec_compare(&timeout, &(timerQueue->activeHead->ExpirationTime)) < 0) + { + timespec_copy(&timeout, &(timerQueue->activeHead->ExpirationTime)); + } + } + + status = pthread_cond_timedwait(&(timerQueue->cond), &(timerQueue->cond_mutex), &timeout); + FireExpiredTimerQueueTimers(timerQueue); + const BOOL bCancelled = timerQueue->bCancelled; + pthread_mutex_unlock(&(timerQueue->cond_mutex)); + + if ((status != ETIMEDOUT) && (status != 0)) + break; + + if (bCancelled) + break; + } + + return NULL; +} + +static int StartTimerQueueThread(WINPR_TIMER_QUEUE* timerQueue) +{ + WINPR_ASSERT(timerQueue); + pthread_cond_init(&(timerQueue->cond), NULL); + pthread_mutex_init(&(timerQueue->cond_mutex), NULL); + pthread_mutex_init(&(timerQueue->mutex), NULL); + pthread_attr_init(&(timerQueue->attr)); + timerQueue->param.sched_priority = sched_get_priority_max(SCHED_FIFO); + pthread_attr_setschedparam(&(timerQueue->attr), &(timerQueue->param)); + pthread_attr_setschedpolicy(&(timerQueue->attr), SCHED_FIFO); + pthread_create(&(timerQueue->thread), &(timerQueue->attr), TimerQueueThread, timerQueue); + return 0; +} + +HANDLE CreateTimerQueue(void) +{ + HANDLE handle = NULL; + WINPR_TIMER_QUEUE* timerQueue = NULL; + timerQueue = (WINPR_TIMER_QUEUE*)calloc(1, sizeof(WINPR_TIMER_QUEUE)); + + if (timerQueue) + { + WINPR_HANDLE_SET_TYPE_AND_MODE(timerQueue, HANDLE_TYPE_TIMER_QUEUE, WINPR_FD_READ); + handle = (HANDLE)timerQueue; + timerQueue->activeHead = NULL; + timerQueue->inactiveHead = NULL; + timerQueue->bCancelled = FALSE; + StartTimerQueueThread(timerQueue); + } + + return handle; +} + +BOOL DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent) +{ + void* rvalue = NULL; + WINPR_TIMER_QUEUE* timerQueue = NULL; + WINPR_TIMER_QUEUE_TIMER* node = NULL; + WINPR_TIMER_QUEUE_TIMER* nextNode = NULL; + + if (!TimerQueue) + return FALSE; + + timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue; + /* Cancel and delete timer queue timers */ + pthread_mutex_lock(&(timerQueue->cond_mutex)); + timerQueue->bCancelled = TRUE; + pthread_cond_signal(&(timerQueue->cond)); + pthread_mutex_unlock(&(timerQueue->cond_mutex)); + pthread_join(timerQueue->thread, &rvalue); + /** + * Quote from MSDN regarding CompletionEvent: + * If this parameter is INVALID_HANDLE_VALUE, the function waits for + * all callback functions to complete before returning. + * If this parameter is NULL, the function marks the timer for + * deletion and returns immediately. + * + * Note: The current WinPR implementation implicitly waits for any + * callback functions to complete (see pthread_join above) + */ + { + /* Move all active timers to the inactive timer list */ + node = timerQueue->activeHead; + + while (node) + { + InsertTimerQueueTimer(&(timerQueue->inactiveHead), node); + node = node->next; + } + + timerQueue->activeHead = NULL; + /* Once all timers are inactive, free them */ + node = timerQueue->inactiveHead; + + while (node) + { + nextNode = node->next; + free(node); + node = nextNode; + } + + timerQueue->inactiveHead = NULL; + } + /* Delete timer queue */ + pthread_cond_destroy(&(timerQueue->cond)); + pthread_mutex_destroy(&(timerQueue->cond_mutex)); + pthread_mutex_destroy(&(timerQueue->mutex)); + pthread_attr_destroy(&(timerQueue->attr)); + free(timerQueue); + + if (CompletionEvent && (CompletionEvent != INVALID_HANDLE_VALUE)) + (void)SetEvent(CompletionEvent); + + return TRUE; +} + +BOOL DeleteTimerQueue(HANDLE TimerQueue) +{ + return DeleteTimerQueueEx(TimerQueue, NULL); +} + +BOOL CreateTimerQueueTimer(HANDLE* phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback, + void* Parameter, DWORD DueTime, DWORD Period, ULONG Flags) +{ + struct timespec CurrentTime = { 0 }; + + if (!TimerQueue) + return FALSE; + + timespec_gettimeofday(&CurrentTime); + WINPR_TIMER_QUEUE* timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue; + WINPR_TIMER_QUEUE_TIMER* timer = calloc(1, sizeof(WINPR_TIMER_QUEUE_TIMER)); + + if (!timer) + return FALSE; + + WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER_QUEUE_TIMER, WINPR_FD_READ); + *phNewTimer = (HANDLE)timer; + timespec_copy(&(timer->StartTime), &CurrentTime); + timespec_add_ms(&(timer->StartTime), DueTime); + timespec_copy(&(timer->ExpirationTime), &(timer->StartTime)); + timer->Flags = Flags; + timer->DueTime = DueTime; + timer->Period = Period; + timer->Callback = Callback; + timer->Parameter = Parameter; + timer->timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue; + timer->FireCount = 0; + timer->next = NULL; + pthread_mutex_lock(&(timerQueue->cond_mutex)); + InsertTimerQueueTimer(&(timerQueue->activeHead), timer); + pthread_cond_signal(&(timerQueue->cond)); + pthread_mutex_unlock(&(timerQueue->cond_mutex)); + return TRUE; +} + +BOOL ChangeTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, ULONG DueTime, ULONG Period) +{ + struct timespec CurrentTime; + WINPR_TIMER_QUEUE* timerQueue = NULL; + WINPR_TIMER_QUEUE_TIMER* timer = NULL; + + if (!TimerQueue || !Timer) + return FALSE; + + timespec_gettimeofday(&CurrentTime); + timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue; + timer = (WINPR_TIMER_QUEUE_TIMER*)Timer; + pthread_mutex_lock(&(timerQueue->cond_mutex)); + RemoveTimerQueueTimer(&(timerQueue->activeHead), timer); + RemoveTimerQueueTimer(&(timerQueue->inactiveHead), timer); + timer->DueTime = DueTime; + timer->Period = Period; + timer->next = NULL; + timespec_copy(&(timer->StartTime), &CurrentTime); + timespec_add_ms(&(timer->StartTime), DueTime); + timespec_copy(&(timer->ExpirationTime), &(timer->StartTime)); + InsertTimerQueueTimer(&(timerQueue->activeHead), timer); + pthread_cond_signal(&(timerQueue->cond)); + pthread_mutex_unlock(&(timerQueue->cond_mutex)); + return TRUE; +} + +BOOL DeleteTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, HANDLE CompletionEvent) +{ + WINPR_TIMER_QUEUE* timerQueue = NULL; + WINPR_TIMER_QUEUE_TIMER* timer = NULL; + + if (!TimerQueue || !Timer) + return FALSE; + + timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue; + timer = (WINPR_TIMER_QUEUE_TIMER*)Timer; + pthread_mutex_lock(&(timerQueue->cond_mutex)); + /** + * Quote from MSDN regarding CompletionEvent: + * If this parameter is INVALID_HANDLE_VALUE, the function waits for + * all callback functions to complete before returning. + * If this parameter is NULL, the function marks the timer for + * deletion and returns immediately. + * + * Note: The current WinPR implementation implicitly waits for any + * callback functions to complete (see cond_mutex usage) + */ + RemoveTimerQueueTimer(&(timerQueue->activeHead), timer); + pthread_cond_signal(&(timerQueue->cond)); + pthread_mutex_unlock(&(timerQueue->cond_mutex)); + free(timer); + + if (CompletionEvent && (CompletionEvent != INVALID_HANDLE_VALUE)) + (void)SetEvent(CompletionEvent); + + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/wait.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/wait.c new file mode 100644 index 0000000000000000000000000000000000000000..48b226b95d43f9a3a5f64497c5ad1182f1012ded --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/synch/wait.c @@ -0,0 +1,538 @@ +/** + * WinPR: Windows Portable Runtime + * Synchronization Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Hardening + * + * 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 + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include +#include + +#include +#include +#include +#include + +#include "synch.h" +#include "pollset.h" +#include "../thread/thread.h" +#include +#include + +#include "../log.h" +#define TAG WINPR_TAG("sync.wait") + +/** + * WaitForSingleObject + * WaitForSingleObjectEx + * WaitForMultipleObjectsEx + * SignalObjectAndWait + */ + +#ifndef _WIN32 + +#include +#include +#include +#include + +#include "../handle/handle.h" + +#include "../pipe/pipe.h" + +static struct timespec ts_from_ns(void) +{ + const UINT64 ns = winpr_GetUnixTimeNS(); + struct timespec timeout = { 0 }; + timeout.tv_sec = WINPR_TIME_NS_TO_S(ns); + timeout.tv_nsec = WINPR_TIME_NS_REM_NS(ns); + return timeout; +} + +/** + * Drop in replacement for pthread_mutex_timedlock + * http://code.google.com/p/android/issues/detail?id=7807 + * http://aleksmaus.blogspot.ca/2011/12/missing-pthreadmutextimedlock-on.html + */ +#if !defined(WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK) +#include + +static long long ts_difftime(const struct timespec* o, const struct timespec* n) +{ + long long oldValue = o->tv_sec * 1000000000LL + o->tv_nsec; + long long newValue = n->tv_sec * 1000000000LL + n->tv_nsec; + return newValue - oldValue; +} + +#ifdef ANDROID +#if (__ANDROID_API__ >= 21) +#define CONST_NEEDED const +#else +#define CONST_NEEDED +#endif +#define STATIC_NEEDED +#else /* ANDROID */ +#define CONST_NEEDED const +#define STATIC_NEEDED static +#endif + +STATIC_NEEDED int pthread_mutex_timedlock(pthread_mutex_t* mutex, + CONST_NEEDED struct timespec* timeout) +{ + struct timespec timenow = { 0 }; + struct timespec sleepytime = { 0 }; + unsigned long long diff = 0; + int retcode = -1; + /* This is just to avoid a completely busy wait */ + timenow = ts_from_ns(); + diff = ts_difftime(&timenow, timeout); + sleepytime.tv_sec = diff / 1000000000LL; + sleepytime.tv_nsec = diff % 1000000000LL; + + while ((retcode = pthread_mutex_trylock(mutex)) == EBUSY) + { + timenow = ts_from_ns(); + + if (ts_difftime(timeout, &timenow) >= 0) + { + return ETIMEDOUT; + } + + nanosleep(&sleepytime, NULL); + } + + return retcode; +} +#endif + +static void ts_add_ms(struct timespec* ts, DWORD dwMilliseconds) +{ + ts->tv_sec += dwMilliseconds / 1000L; + ts->tv_nsec += (dwMilliseconds % 1000L) * 1000000L; + ts->tv_sec += ts->tv_nsec / 1000000000L; + ts->tv_nsec = ts->tv_nsec % 1000000000L; +} + +DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_POLL_SET pollset = { 0 }; + + if (!winpr_Handle_GetInfo(hHandle, &Type, &Object)) + { + WLog_ERR(TAG, "invalid hHandle."); + SetLastError(ERROR_INVALID_HANDLE); + return WAIT_FAILED; + } + + if (Type == HANDLE_TYPE_PROCESS && winpr_Handle_getFd(hHandle) == -1) + { + /* note: if we have pidfd support (under linux and we have managed to associate a + * pidfd with our process), we use the regular method with pollset below. + * If not (on other platforms) we do a waitpid */ + WINPR_PROCESS* process = (WINPR_PROCESS*)Object; + + do + { + DWORD status = 0; + DWORD waitDelay = 0; + int ret = waitpid(process->pid, &(process->status), WNOHANG); + if (ret == process->pid) + { + process->dwExitCode = (DWORD)process->status; + return WAIT_OBJECT_0; + } + else if (ret < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "waitpid failure [%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + SetLastError(ERROR_INTERNAL_ERROR); + return WAIT_FAILED; + } + + /* sleep by slices of 50ms */ + waitDelay = (dwMilliseconds < 50) ? dwMilliseconds : 50; + + status = SleepEx(waitDelay, bAlertable); + if (status != 0) + return status; + + dwMilliseconds -= waitDelay; + + } while (dwMilliseconds > 50); + + return WAIT_TIMEOUT; + } + + if (Type == HANDLE_TYPE_MUTEX) + { + WINPR_MUTEX* mutex = (WINPR_MUTEX*)Object; + + if (dwMilliseconds != INFINITE) + { + int status = 0; + struct timespec timeout = ts_from_ns(); + + ts_add_ms(&timeout, dwMilliseconds); + status = pthread_mutex_timedlock(&mutex->mutex, &timeout); + + if (ETIMEDOUT == status) + return WAIT_TIMEOUT; + } + else + { + pthread_mutex_lock(&mutex->mutex); + } + + return WAIT_OBJECT_0; + } + else + { + int status = -1; + WINPR_THREAD* thread = NULL; + BOOL isSet = FALSE; + size_t extraFds = 0; + DWORD ret = 0; + BOOL autoSignaled = FALSE; + + if (bAlertable) + { + thread = (WINPR_THREAD*)_GetCurrentThread(); + if (thread) + { + /* treat reentrancy, we can't switch to alertable state when we're already + treating completions */ + if (thread->apc.treatingCompletions) + bAlertable = FALSE; + else + extraFds = thread->apc.length; + } + else + { + /* called from a non WinPR thread */ + bAlertable = FALSE; + } + } + + int fd = winpr_Handle_getFd(Object); + if (fd < 0) + { + WLog_ERR(TAG, "winpr_Handle_getFd did not return a fd!"); + SetLastError(ERROR_INVALID_HANDLE); + return WAIT_FAILED; + } + + if (!pollset_init(&pollset, 1 + extraFds)) + { + WLog_ERR(TAG, "unable to initialize pollset"); + SetLastError(ERROR_INTERNAL_ERROR); + return WAIT_FAILED; + } + + if (!pollset_add(&pollset, fd, Object->Mode)) + { + WLog_ERR(TAG, "unable to add fd in pollset"); + goto out; + } + + if (bAlertable && !apc_collectFds(thread, &pollset, &autoSignaled)) + { + WLog_ERR(TAG, "unable to collect APC fds"); + goto out; + } + + if (!autoSignaled) + { + status = pollset_poll(&pollset, dwMilliseconds); + if (status < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pollset_poll() failure [%d] %s", errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + goto out; + } + } + + ret = WAIT_TIMEOUT; + if (bAlertable && apc_executeCompletions(thread, &pollset, 1)) + ret = WAIT_IO_COMPLETION; + + isSet = pollset_isSignaled(&pollset, 0); + pollset_uninit(&pollset); + + if (!isSet) + return ret; + + return winpr_Handle_cleanup(Object); + } + +out: + pollset_uninit(&pollset); + SetLastError(ERROR_INTERNAL_ERROR); + return WAIT_FAILED; +} + +DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) +{ + return WaitForSingleObjectEx(hHandle, dwMilliseconds, FALSE); +} + +DWORD WaitForMultipleObjectsEx(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, + DWORD dwMilliseconds, BOOL bAlertable) +{ + DWORD signalled = 0; + DWORD polled = 0; + DWORD poll_map[MAXIMUM_WAIT_OBJECTS] = { 0 }; + BOOL signalled_handles[MAXIMUM_WAIT_OBJECTS] = { FALSE }; + int fd = -1; + int status = -1; + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_THREAD* thread = NULL; + WINPR_POLL_SET pollset = { 0 }; + DWORD ret = WAIT_FAILED; + size_t extraFds = 0; + UINT64 now = 0; + UINT64 dueTime = 0; + + if (!nCount || (nCount > MAXIMUM_WAIT_OBJECTS)) + { + WLog_ERR(TAG, "invalid handles count(%" PRIu32 ")", nCount); + return WAIT_FAILED; + } + + if (bAlertable) + { + thread = winpr_GetCurrentThread(); + if (thread) + { + /* treat reentrancy, we can't switch to alertable state when we're already + treating completions */ + if (thread->apc.treatingCompletions) + bAlertable = FALSE; + else + extraFds = thread->apc.length; + } + else + { + /* most probably we're not called from WinPR thread, so we can't have any APC */ + bAlertable = FALSE; + } + } + + if (!pollset_init(&pollset, nCount + extraFds)) + { + WLog_ERR(TAG, "unable to initialize pollset for nCount=%" PRIu32 " extraCount=%" PRIu32 "", + nCount, extraFds); + return WAIT_FAILED; + } + + signalled = 0; + + now = GetTickCount64(); + if (dwMilliseconds != INFINITE) + dueTime = now + dwMilliseconds; + else + dueTime = 0xFFFFFFFFFFFFFFFF; + + do + { + BOOL autoSignaled = FALSE; + polled = 0; + + /* first collect file descriptors to poll */ + DWORD idx = 0; + for (; idx < nCount; idx++) + { + if (bWaitAll) + { + if (signalled_handles[idx]) + continue; + + poll_map[polled] = idx; + } + + if (!winpr_Handle_GetInfo(lpHandles[idx], &Type, &Object)) + { + WLog_ERR(TAG, "invalid event file descriptor at %" PRIu32, idx); + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + SetLastError(ERROR_INVALID_HANDLE); + goto out; + } + + fd = winpr_Handle_getFd(Object); + if (fd == -1) + { + WLog_ERR(TAG, "invalid file descriptor at %" PRIu32, idx); + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + SetLastError(ERROR_INVALID_HANDLE); + goto out; + } + + if (!pollset_add(&pollset, fd, Object->Mode)) + { + WLog_ERR(TAG, "unable to register fd in pollset at %" PRIu32, idx); + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + SetLastError(ERROR_INVALID_HANDLE); + goto out; + } + + polled++; + } + + /* treat file descriptors of the APC if needed */ + if (bAlertable && !apc_collectFds(thread, &pollset, &autoSignaled)) + { + WLog_ERR(TAG, "unable to register APC fds"); + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + SetLastError(ERROR_INTERNAL_ERROR); + goto out; + } + + /* poll file descriptors */ + status = 0; + if (!autoSignaled) + { + DWORD waitTime = 0; + + if (dwMilliseconds == INFINITE) + waitTime = INFINITE; + else + waitTime = (DWORD)(dueTime - now); + + status = pollset_poll(&pollset, waitTime); + if (status < 0) + { + char ebuffer[256] = { 0 }; +#ifdef WINPR_HAVE_POLL_H + WLog_ERR(TAG, "poll() handle %" PRIu32 " (%" PRIu32 ") failure [%d] %s", idx, + nCount, errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); +#else + WLog_ERR(TAG, "select() handle %" PRIu32 " (%" PRIu32 ") failure [%d] %s", idx, + nCount, errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); +#endif + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + SetLastError(ERROR_INTERNAL_ERROR); + goto out; + } + } + + /* give priority to the APC queue, to return WAIT_IO_COMPLETION */ + if (bAlertable && apc_executeCompletions(thread, &pollset, polled)) + { + ret = WAIT_IO_COMPLETION; + goto out; + } + + /* then treat pollset */ + if (status) + { + for (DWORD index = 0; index < polled; index++) + { + DWORD handlesIndex = 0; + BOOL signal_set = FALSE; + + if (bWaitAll) + handlesIndex = poll_map[index]; + else + handlesIndex = index; + + signal_set = pollset_isSignaled(&pollset, index); + if (signal_set) + { + DWORD rc = winpr_Handle_cleanup(lpHandles[handlesIndex]); + if (rc != WAIT_OBJECT_0) + { + WLog_ERR(TAG, "error in cleanup function for handle at index=%" PRIu32, + handlesIndex); + ret = rc; + goto out; + } + + if (bWaitAll) + { + signalled_handles[handlesIndex] = TRUE; + + /* Continue checks from last position. */ + for (; signalled < nCount; signalled++) + { + if (!signalled_handles[signalled]) + break; + } + } + else + { + ret = (WAIT_OBJECT_0 + handlesIndex); + goto out; + } + + if (signalled >= nCount) + { + ret = WAIT_OBJECT_0; + goto out; + } + } + } + } + + if (bAlertable && thread->apc.length > extraFds) + { + pollset_uninit(&pollset); + extraFds = thread->apc.length; + if (!pollset_init(&pollset, nCount + extraFds)) + { + WLog_ERR(TAG, "unable reallocate pollset"); + SetLastError(ERROR_INTERNAL_ERROR); + return WAIT_FAILED; + } + } + else + pollset_reset(&pollset); + + now = GetTickCount64(); + } while (now < dueTime); + + ret = WAIT_TIMEOUT; + +out: + pollset_uninit(&pollset); + return ret; +} + +DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, + DWORD dwMilliseconds) +{ + return WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, dwMilliseconds, FALSE); +} + +DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds, + BOOL bAlertable) +{ + if (!SetEvent(hObjectToSignal)) + return WAIT_FAILED; + + return WaitForSingleObjectEx(hObjectToWaitOn, dwMilliseconds, bAlertable); +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f4e98c270353f6018ddfa3568c3ef3a34e97a15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/CMakeLists.txt @@ -0,0 +1,30 @@ +# WinPR: Windows Portable Runtime +# libwinpr-sysinfo cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +if(ANDROID) + add_subdirectory(cpufeatures) +endif() + +winpr_module_add(sysinfo.c) + +if((NOT WIN32) AND (NOT APPLE) AND (NOT ANDROID) AND (NOT OPENBSD)) + winpr_library_add_private(rt) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..39fcc0e714410d30dff42f0ab24722802e470005 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "2") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "sysinfo") +set(MINWIN_LONG_NAME "System Information Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c84c274c0e4177bcbfc899bf873ca43bd390c433 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/CMakeLists.txt @@ -0,0 +1,19 @@ +# WinPR: Windows Portable Runtime +# libwinpr-sysinfo cmake build script +# +# Copyright 2017 Armin Novak +# Copyright 2017 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. + +winpr_module_add(cpu-features.c cpu-features.h) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/NOTICE b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..d6c092292c614ce80204df312cfb89cdbb946035 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/NOTICE @@ -0,0 +1,13 @@ +Copyright (C) 2016 The Android Open Source Project + +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. diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/README b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/README new file mode 100644 index 0000000000000000000000000000000000000000..ba85c2097374c8e52cac1bf7fc0541d2b7b06f7c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/README @@ -0,0 +1,4 @@ +Android CPUFeatures Library + +https://developer.android.com/ndk/guides/cpu-features.html +https://android.googlesource.com/platform/ndk/+/master/sources/android/cpufeatures diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.c new file mode 100644 index 0000000000000000000000000000000000000000..786dd85694cd00098386696781e6e7e1b3b6e4ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.c @@ -0,0 +1,1427 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* ChangeLog for this library: + * + * NDK r10e?: Add MIPS MSA feature. + * + * NDK r10: Support for 64-bit CPUs (Intel, ARM & MIPS). + * + * NDK r8d: Add android_setCpu(). + * + * NDK r8c: Add new ARM CPU features: VFPv2, VFP_D32, VFP_FP16, + * VFP_FMA, NEON_FMA, IDIV_ARM, IDIV_THUMB2 and iWMMXt. + * + * Rewrite the code to parse /proc/self/auxv instead of + * the "Features" field in /proc/cpuinfo. + * + * Dynamically allocate the buffer that hold the content + * of /proc/cpuinfo to deal with newer hardware. + * + * NDK r7c: Fix CPU count computation. The old method only reported the + * number of _active_ CPUs when the library was initialized, + * which could be less than the real total. + * + * NDK r5: Handle buggy kernels which report a CPU Architecture number of 7 + * for an ARMv6 CPU (see below). + * + * Handle kernels that only report 'neon', and not 'vfpv3' + * (VFPv3 is mandated by the ARM architecture is Neon is implemented) + * + * Handle kernels that only report 'vfpv3d16', and not 'vfpv3' + * + * Fix x86 compilation. Report ANDROID_CPU_FAMILY_X86 in + * android_getCpuFamily(). + * + * NDK r4: Initial release + */ + +#include "cpu-features.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static pthread_once_t g_once; +static int g_inited; +static AndroidCpuFamily g_cpuFamily; +static uint64_t g_cpuFeatures; +static int g_cpuCount; + +#ifdef __arm__ +static uint32_t g_cpuIdArm; +#endif + +static const int android_cpufeatures_debug = 0; + +#define D(...) \ + do \ + { \ + if (android_cpufeatures_debug) \ + { \ + printf(__VA_ARGS__); \ + fflush(stdout); \ + } \ + } while (0) + +#ifdef __i386__ +static __inline__ void x86_cpuid(int func, int values[4]) +{ + int a, b, c, d; + /* We need to preserve ebx since we're compiling PIC code */ + /* this means we can't use "=b" for the second output register */ + __asm__ __volatile__("push %%ebx\n" + "cpuid\n" + "mov %%ebx, %1\n" + "pop %%ebx\n" + : "=a"(a), "=r"(b), "=c"(c), "=d"(d) + : "a"(func)); + values[0] = a; + values[1] = b; + values[2] = c; + values[3] = d; +} +#elif defined(__x86_64__) +static __inline__ void x86_cpuid(int func, int values[4]) +{ + int64_t a, b, c, d; + /* We need to preserve ebx since we're compiling PIC code */ + /* this means we can't use "=b" for the second output register */ + __asm__ __volatile__("push %%rbx\n" + "cpuid\n" + "mov %%rbx, %1\n" + "pop %%rbx\n" + : "=a"(a), "=r"(b), "=c"(c), "=d"(d) + : "a"(func)); + values[0] = a; + values[1] = b; + values[2] = c; + values[3] = d; +} +#endif + +/* Get the size of a file by reading it until the end. This is needed + * because files under /proc do not always return a valid size when + * using fseek(0, SEEK_END) + ftell(). Nor can they be mmap()-ed. + */ +static int get_file_size(const char* pathname) +{ + int fd, result = 0; + char buffer[256]; + fd = open(pathname, O_RDONLY); + + if (fd < 0) + { + char ebuffer[256] = { 0 }; + D("Can't open %s: %s\n", pathname, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return -1; + } + + for (;;) + { + int ret = read(fd, buffer, sizeof buffer); + + if (ret < 0) + { + char ebuffer[256] = { 0 }; + if (errno == EINTR) + continue; + + D("Error while reading %s: %s\n", pathname, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + break; + } + + if (ret == 0) + break; + + result += ret; + } + + close(fd); + return result; +} + +/* Read the content of /proc/cpuinfo into a user-provided buffer. + * Return the length of the data, or -1 on error. Does *not* + * zero-terminate the content. Will not read more + * than 'buffsize' bytes. + */ +static int read_file(const char* pathname, char* buffer, size_t buffsize) +{ + int fd, count; + fd = open(pathname, O_RDONLY); + + if (fd < 0) + { + char ebuffer[256] = { 0 }; + D("Could not open %s: %s\n", pathname, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return -1; + } + + count = 0; + + while (count < (int)buffsize) + { + int ret = read(fd, buffer + count, buffsize - count); + + if (ret < 0) + { + char ebuffer[256] = { 0 }; + if (errno == EINTR) + continue; + + D("Error while reading from %s: %s\n", pathname, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + + if (count == 0) + count = -1; + + break; + } + + if (ret == 0) + break; + + count += ret; + } + + close(fd); + return count; +} + +#ifdef __arm__ +/* Extract the content of a the first occurrence of a given field in + * the content of /proc/cpuinfo and return it as a heap-allocated + * string that must be freed by the caller. + * + * Return NULL if not found + */ +static char* extract_cpuinfo_field(const char* buffer, int buflen, const char* field) +{ + int fieldlen = strlen(field); + const char* bufend = buffer + buflen; + char* result = NULL; + int len; + const char *p, *q; + /* Look for first field occurrence, and ensures it starts the line. */ + p = buffer; + + for (;;) + { + p = memmem(p, bufend - p, field, fieldlen); + + if (p == NULL) + goto EXIT; + + if (p == buffer || p[-1] == '\n') + break; + + p += fieldlen; + } + + /* Skip to the first column followed by a space */ + p += fieldlen; + p = memchr(p, ':', bufend - p); + + if (p == NULL || p[1] != ' ') + goto EXIT; + + /* Find the end of the line */ + p += 2; + q = memchr(p, '\n', bufend - p); + + if (q == NULL) + q = bufend; + + /* Copy the line into a heap-allocated buffer */ + len = q - p; + result = malloc(len + 1); + + if (result == NULL) + goto EXIT; + + memcpy(result, p, len); + result[len] = '\0'; +EXIT: + return result; +} + +/* Checks that a space-separated list of items contains one given 'item'. + * Returns 1 if found, 0 otherwise. + */ +static int has_list_item(const char* list, const char* item) +{ + const char* p = list; + int itemlen = strlen(item); + + if (list == NULL) + return 0; + + while (*p) + { + const char* q; + + /* skip spaces */ + while (*p == ' ' || *p == '\t') + p++; + + /* find end of current list item */ + q = p; + + while (*q && *q != ' ' && *q != '\t') + q++; + + if (itemlen == q - p && !memcmp(p, item, itemlen)) + return 1; + + /* skip to next item */ + p = q; + } + + return 0; +} +#endif /* __arm__ */ + +/* Parse a number starting from 'input', but not going further + * than 'limit'. Return the value into '*result'. + * + * NOTE: Does not skip over leading spaces, or deal with sign characters. + * NOTE: Ignores overflows. + * + * The function returns NULL in case of error (bad format), or the new + * position after the decimal number in case of success (which will always + * be <= 'limit'). + */ +static const char* parse_number(const char* input, const char* limit, int base, int* result) +{ + const char* p = input; + int val = 0; + + while (p < limit) + { + int d = (*p - '0'); + + if ((unsigned)d >= 10U) + { + d = (*p - 'a'); + + if ((unsigned)d >= 6U) + d = (*p - 'A'); + + if ((unsigned)d >= 6U) + break; + + d += 10; + } + + if (d >= base) + break; + + val = val * base + d; + p++; + } + + if (p == input) + return NULL; + + *result = val; + return p; +} + +static const char* parse_decimal(const char* input, const char* limit, int* result) +{ + return parse_number(input, limit, 10, result); +} + +#ifdef __arm__ +static const char* parse_hexadecimal(const char* input, const char* limit, int* result) +{ + return parse_number(input, limit, 16, result); +} +#endif /* __arm__ */ + +/* This small data type is used to represent a CPU list / mask, as read + * from sysfs on Linux. See http://www.kernel.org/doc/Documentation/cputopology.txt + * + * For now, we don't expect more than 32 cores on mobile devices, so keep + * everything simple. + */ +typedef struct +{ + uint32_t mask; +} CpuList; + +static __inline__ void cpulist_init(CpuList* list) +{ + list->mask = 0; +} + +static __inline__ void cpulist_and(CpuList* list1, CpuList* list2) +{ + list1->mask &= list2->mask; +} + +static __inline__ void cpulist_set(CpuList* list, int index) +{ + if ((unsigned)index < 32) + { + list->mask |= (uint32_t)(1U << index); + } +} + +static __inline__ int cpulist_count(CpuList* list) +{ + return __builtin_popcount(list->mask); +} + +/* Parse a textual list of cpus and store the result inside a CpuList object. + * Input format is the following: + * - comma-separated list of items (no spaces) + * - each item is either a single decimal number (cpu index), or a range made + * of two numbers separated by a single dash (-). Ranges are inclusive. + * + * Examples: 0 + * 2,4-127,128-143 + * 0-1 + */ +static void cpulist_parse(CpuList* list, const char* line, int line_len) +{ + const char* p = line; + const char* end = p + line_len; + const char* q; + + /* NOTE: the input line coming from sysfs typically contains a + * trailing newline, so take care of it in the code below + */ + while (p < end && *p != '\n') + { + int start_value = 0; + int end_value = 0; + /* Find the end of current item, and put it into 'q' */ + q = memchr(p, ',', end - p); + + if (q == NULL) + { + q = end; + } + + /* Get first value */ + p = parse_decimal(p, q, &start_value); + + if (p == NULL) + goto BAD_FORMAT; + + end_value = start_value; + + /* If we're not at the end of the item, expect a dash and + * and integer; extract end value. + */ + if (p < q && *p == '-') + { + p = parse_decimal(p + 1, q, &end_value); + + if (p == NULL) + goto BAD_FORMAT; + } + + /* Set bits CPU list bits */ + for (int val = start_value; val <= end_value; val++) + { + cpulist_set(list, val); + } + + /* Jump to next item */ + p = q; + + if (p < end) + p++; + } + +BAD_FORMAT:; +} + +/* Read a CPU list from one sysfs file */ +static void cpulist_read_from(CpuList* list, const char* filename) +{ + char file[64]; + int filelen; + cpulist_init(list); + filelen = read_file(filename, file, sizeof file); + + if (filelen < 0) + { + char ebuffer[256] = { 0 }; + D("Could not read %s: %s\n", filename, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return; + } + + cpulist_parse(list, file, filelen); +} +#if defined(__aarch64__) +// see kernel header +#define HWCAP_FP (1 << 0) +#define HWCAP_ASIMD (1 << 1) +#define HWCAP_AES (1 << 3) +#define HWCAP_PMULL (1 << 4) +#define HWCAP_SHA1 (1 << 5) +#define HWCAP_SHA2 (1 << 6) +#define HWCAP_CRC32 (1 << 7) +#endif + +#if defined(__arm__) + +// See kernel header. +#define HWCAP_VFP (1 << 6) +#define HWCAP_IWMMXT (1 << 9) +#define HWCAP_NEON (1 << 12) +#define HWCAP_VFPv3 (1 << 13) +#define HWCAP_VFPv3D16 (1 << 14) +#define HWCAP_VFPv4 (1 << 16) +#define HWCAP_IDIVA (1 << 17) +#define HWCAP_IDIVT (1 << 18) + +// see kernel header +#define HWCAP2_AES (1 << 0) +#define HWCAP2_PMULL (1 << 1) +#define HWCAP2_SHA1 (1 << 2) +#define HWCAP2_SHA2 (1 << 3) +#define HWCAP2_CRC32 (1 << 4) + +// This is the list of 32-bit ARMv7 optional features that are _always_ +// supported by ARMv8 CPUs, as mandated by the ARM Architecture Reference +// Manual. +#define HWCAP_SET_FOR_ARMV8 \ + (HWCAP_VFP | HWCAP_NEON | HWCAP_VFPv3 | HWCAP_VFPv4 | HWCAP_IDIVA | HWCAP_IDIVT) +#endif + +#if defined(__mips__) +// see kernel header +#define HWCAP_MIPS_R6 (1 << 0) +#define HWCAP_MIPS_MSA (1 << 1) +#endif + +#if defined(__arm__) || defined(__aarch64__) || defined(__mips__) + +#define AT_HWCAP 16 +#define AT_HWCAP2 26 + +// Probe the system's C library for a 'getauxval' function and call it if +// it exits, or return 0 for failure. This function is available since API +// level 20. +// +// This code does *NOT* check for '__ANDROID_API__ >= 20' to support the +// edge case where some NDK developers use headers for a platform that is +// newer than the one really targeted by their application. +// This is typically done to use newer native APIs only when running on more +// recent Android versions, and requires careful symbol management. +// +// Note that getauxval() can't really be re-implemented here, because +// its implementation does not parse /proc/self/auxv. Instead it depends +// on values that are passed by the kernel at process-init time to the +// C runtime initialization layer. +static uint32_t get_elf_hwcap_from_getauxval(int hwcap_type) +{ + typedef unsigned long getauxval_func_t(unsigned long); + dlerror(); + void* libc_handle = dlopen("libc.so", RTLD_NOW); + + if (!libc_handle) + { + D("Could not dlopen() C library: %s\n", dlerror()); + return 0; + } + + uint32_t ret = 0; + getauxval_func_t* func = (getauxval_func_t*)dlsym(libc_handle, "getauxval"); + + if (!func) + { + D("Could not find getauxval() in C library\n"); + } + else + { + // Note: getauxval() returns 0 on failure. Doesn't touch errno. + ret = (uint32_t)(*func)(hwcap_type); + } + + dlclose(libc_handle); + return ret; +} +#endif + +#if defined(__arm__) +// Parse /proc/self/auxv to extract the ELF HW capabilities bitmap for the +// current CPU. Note that this file is not accessible from regular +// application processes on some Android platform releases. +// On success, return new ELF hwcaps, or 0 on failure. +static uint32_t get_elf_hwcap_from_proc_self_auxv(void) +{ + const char filepath[] = "/proc/self/auxv"; + int fd = TEMP_FAILURE_RETRY(open(filepath, O_RDONLY)); + + if (fd < 0) + { + char ebuffer[256] = { 0 }; + D("Could not open %s: %s\n", filepath, winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return 0; + } + + struct + { + uint32_t tag; + uint32_t value; + } entry; + + uint32_t result = 0; + + for (;;) + { + int ret = TEMP_FAILURE_RETRY(read(fd, (char*)&entry, sizeof entry)); + + if (ret < 0) + { + char ebuffer[256] = { 0 }; + D("Error while reading %s: %s\n", filepath, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + break; + } + + // Detect end of list. + if (ret == 0 || (entry.tag == 0 && entry.value == 0)) + break; + + if (entry.tag == AT_HWCAP) + { + result = entry.value; + break; + } + } + + close(fd); + return result; +} + +/* Compute the ELF HWCAP flags from the content of /proc/cpuinfo. + * This works by parsing the 'Features' line, which lists which optional + * features the device's CPU supports, on top of its reference + * architecture. + */ +static uint32_t get_elf_hwcap_from_proc_cpuinfo(const char* cpuinfo, int cpuinfo_len) +{ + uint32_t hwcaps = 0; + long architecture = 0; + char* cpuArch = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "CPU architecture"); + + if (cpuArch) + { + architecture = strtol(cpuArch, NULL, 10); + free(cpuArch); + + if (architecture >= 8L) + { + // This is a 32-bit ARM binary running on a 64-bit ARM64 kernel. + // The 'Features' line only lists the optional features that the + // device's CPU supports, compared to its reference architecture + // which are of no use for this process. + D("Faking 32-bit ARM HWCaps on ARMv%ld CPU\n", architecture); + return HWCAP_SET_FOR_ARMV8; + } + } + + char* cpuFeatures = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "Features"); + + if (cpuFeatures != NULL) + { + D("Found cpuFeatures = '%s'\n", cpuFeatures); + + if (has_list_item(cpuFeatures, "vfp")) + hwcaps |= HWCAP_VFP; + + if (has_list_item(cpuFeatures, "vfpv3")) + hwcaps |= HWCAP_VFPv3; + + if (has_list_item(cpuFeatures, "vfpv3d16")) + hwcaps |= HWCAP_VFPv3D16; + + if (has_list_item(cpuFeatures, "vfpv4")) + hwcaps |= HWCAP_VFPv4; + + if (has_list_item(cpuFeatures, "neon")) + hwcaps |= HWCAP_NEON; + + if (has_list_item(cpuFeatures, "idiva")) + hwcaps |= HWCAP_IDIVA; + + if (has_list_item(cpuFeatures, "idivt")) + hwcaps |= HWCAP_IDIVT; + + if (has_list_item(cpuFeatures, "idiv")) + hwcaps |= HWCAP_IDIVA | HWCAP_IDIVT; + + if (has_list_item(cpuFeatures, "iwmmxt")) + hwcaps |= HWCAP_IWMMXT; + + free(cpuFeatures); + } + + return hwcaps; +} +#endif /* __arm__ */ + +/* Return the number of cpus present on a given device. + * + * To handle all weird kernel configurations, we need to compute the + * intersection of the 'present' and 'possible' CPU lists and count + * the result. + */ +static int get_cpu_count(void) +{ + CpuList cpus_present[1]; + CpuList cpus_possible[1]; + cpulist_read_from(cpus_present, "/sys/devices/system/cpu/present"); + cpulist_read_from(cpus_possible, "/sys/devices/system/cpu/possible"); + /* Compute the intersection of both sets to get the actual number of + * CPU cores that can be used on this device by the kernel. + */ + cpulist_and(cpus_present, cpus_possible); + return cpulist_count(cpus_present); +} + +static void android_cpuInitFamily(void) +{ +#if defined(__arm__) + g_cpuFamily = ANDROID_CPU_FAMILY_ARM; +#elif defined(__i386__) + g_cpuFamily = ANDROID_CPU_FAMILY_X86; +#elif defined(__mips64) + /* Needs to be before __mips__ since the compiler defines both */ + g_cpuFamily = ANDROID_CPU_FAMILY_MIPS64; +#elif defined(__mips__) + g_cpuFamily = ANDROID_CPU_FAMILY_MIPS; +#elif defined(__aarch64__) + g_cpuFamily = ANDROID_CPU_FAMILY_ARM64; +#elif defined(__x86_64__) + g_cpuFamily = ANDROID_CPU_FAMILY_X86_64; +#else + g_cpuFamily = ANDROID_CPU_FAMILY_UNKNOWN; +#endif +} + +static void android_cpuInit(void) +{ + char* cpuinfo = NULL; + int cpuinfo_len; + android_cpuInitFamily(); + g_cpuFeatures = 0; + g_cpuCount = 1; + g_inited = 1; + cpuinfo_len = get_file_size("/proc/cpuinfo"); + + if (cpuinfo_len < 0) + { + D("cpuinfo_len cannot be computed!"); + return; + } + + cpuinfo = malloc(cpuinfo_len); + + if (cpuinfo == NULL) + { + D("cpuinfo buffer could not be allocated"); + return; + } + + cpuinfo_len = read_file("/proc/cpuinfo", cpuinfo, cpuinfo_len); + D("cpuinfo_len is (%d):\n%.*s\n", cpuinfo_len, cpuinfo_len >= 0 ? cpuinfo_len : 0, cpuinfo); + + if (cpuinfo_len < 0) /* should not happen */ + { + free(cpuinfo); + return; + } + + /* Count the CPU cores, the value may be 0 for single-core CPUs */ + g_cpuCount = get_cpu_count(); + + if (g_cpuCount == 0) + { + g_cpuCount = 1; + } + + D("found cpuCount = %d\n", g_cpuCount); +#ifdef __arm__ + { + /* Extract architecture from the "CPU Architecture" field. + * The list is well-known, unlike the the output of + * the 'Processor' field which can vary greatly. + * + * See the definition of the 'proc_arch' array in + * $KERNEL/arch/arm/kernel/setup.c and the 'c_show' function in + * same file. + */ + char* cpuArch = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "CPU architecture"); + + if (cpuArch != NULL) + { + char* end; + long archNumber; + int hasARMv7 = 0; + D("found cpuArch = '%s'\n", cpuArch); + /* read the initial decimal number, ignore the rest */ + archNumber = strtol(cpuArch, &end, 10); + + /* Note that ARMv8 is upwards compatible with ARMv7. */ + if (end > cpuArch && archNumber >= 7) + { + hasARMv7 = 1; + } + + /* Unfortunately, it seems that certain ARMv6-based CPUs + * report an incorrect architecture number of 7! + * + * See http://code.google.com/p/android/issues/detail?id=10812 + * + * We try to correct this by looking at the 'elf_format' + * field reported by the 'Processor' field, which is of the + * form of "(v7l)" for an ARMv7-based CPU, and "(v6l)" for + * an ARMv6-one. + */ + if (hasARMv7) + { + char* cpuProc = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "Processor"); + + if (cpuProc != NULL) + { + D("found cpuProc = '%s'\n", cpuProc); + + if (has_list_item(cpuProc, "(v6l)")) + { + D("CPU processor and architecture mismatch!!\n"); + hasARMv7 = 0; + } + + free(cpuProc); + } + } + + if (hasARMv7) + { + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_ARMv7; + } + + /* The LDREX / STREX instructions are available from ARMv6 */ + if (archNumber >= 6) + { + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_LDREX_STREX; + } + + free(cpuArch); + } + + /* Extract the list of CPU features from ELF hwcaps */ + uint32_t hwcaps = 0; + hwcaps = get_elf_hwcap_from_getauxval(AT_HWCAP); + + if (!hwcaps) + { + D("Parsing /proc/self/auxv to extract ELF hwcaps!\n"); + hwcaps = get_elf_hwcap_from_proc_self_auxv(); + } + + if (!hwcaps) + { + // Parsing /proc/self/auxv will fail from regular application + // processes on some Android platform versions, when this happens + // parse proc/cpuinfo instead. + D("Parsing /proc/cpuinfo to extract ELF hwcaps!\n"); + hwcaps = get_elf_hwcap_from_proc_cpuinfo(cpuinfo, cpuinfo_len); + } + + if (hwcaps != 0) + { + int has_vfp = (hwcaps & HWCAP_VFP); + int has_vfpv3 = (hwcaps & HWCAP_VFPv3); + int has_vfpv3d16 = (hwcaps & HWCAP_VFPv3D16); + int has_vfpv4 = (hwcaps & HWCAP_VFPv4); + int has_neon = (hwcaps & HWCAP_NEON); + int has_idiva = (hwcaps & HWCAP_IDIVA); + int has_idivt = (hwcaps & HWCAP_IDIVT); + int has_iwmmxt = (hwcaps & HWCAP_IWMMXT); + + // The kernel does a poor job at ensuring consistency when + // describing CPU features. So lots of guessing is needed. + + // 'vfpv4' implies VFPv3|VFP_FMA|FP16 + if (has_vfpv4) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3 | ANDROID_CPU_ARM_FEATURE_VFP_FP16 | + ANDROID_CPU_ARM_FEATURE_VFP_FMA; + + // 'vfpv3' or 'vfpv3d16' imply VFPv3. Note that unlike GCC, + // a value of 'vfpv3' doesn't necessarily mean that the D32 + // feature is present, so be conservative. All CPUs in the + // field that support D32 also support NEON, so this should + // not be a problem in practice. + if (has_vfpv3 || has_vfpv3d16) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3; + + // 'vfp' is super ambiguous. Depending on the kernel, it can + // either mean VFPv2 or VFPv3. Make it depend on ARMv7. + if (has_vfp) + { + if (g_cpuFeatures & ANDROID_CPU_ARM_FEATURE_ARMv7) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3; + else + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv2; + } + + // Neon implies VFPv3|D32, and if vfpv4 is detected, NEON_FMA + if (has_neon) + { + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3 | ANDROID_CPU_ARM_FEATURE_NEON | + ANDROID_CPU_ARM_FEATURE_VFP_D32; + + if (has_vfpv4) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_NEON_FMA; + } + + // VFPv3 implies VFPv2 and ARMv7 + if (g_cpuFeatures & ANDROID_CPU_ARM_FEATURE_VFPv3) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv2 | ANDROID_CPU_ARM_FEATURE_ARMv7; + + if (has_idiva) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_IDIV_ARM; + + if (has_idivt) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2; + + if (has_iwmmxt) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_iWMMXt; + } + + /* Extract the list of CPU features from ELF hwcaps2 */ + uint32_t hwcaps2 = 0; + hwcaps2 = get_elf_hwcap_from_getauxval(AT_HWCAP2); + + if (hwcaps2 != 0) + { + int has_aes = (hwcaps2 & HWCAP2_AES); + int has_pmull = (hwcaps2 & HWCAP2_PMULL); + int has_sha1 = (hwcaps2 & HWCAP2_SHA1); + int has_sha2 = (hwcaps2 & HWCAP2_SHA2); + int has_crc32 = (hwcaps2 & HWCAP2_CRC32); + + if (has_aes) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_AES; + + if (has_pmull) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_PMULL; + + if (has_sha1) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_SHA1; + + if (has_sha2) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_SHA2; + + if (has_crc32) + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_CRC32; + } + + /* Extract the cpuid value from various fields */ + // The CPUID value is broken up in several entries in /proc/cpuinfo. + // This table is used to rebuild it from the entries. + static const struct CpuIdEntry + { + const char* field; + char format; + char bit_lshift; + char bit_length; + } cpu_id_entries[] = { + { "CPU implementer", 'x', 24, 8 }, + { "CPU variant", 'x', 20, 4 }, + { "CPU part", 'x', 4, 12 }, + { "CPU revision", 'd', 0, 4 }, + }; + D("Parsing /proc/cpuinfo to recover CPUID\n"); + + for (size_t i = 0; i < sizeof(cpu_id_entries) / sizeof(cpu_id_entries[0]); ++i) + { + const struct CpuIdEntry* entry = &cpu_id_entries[i]; + char* value = extract_cpuinfo_field(cpuinfo, cpuinfo_len, entry->field); + + if (value == NULL) + continue; + + D("field=%s value='%s'\n", entry->field, value); + char* value_end = value + strlen(value); + int val = 0; + const char* start = value; + const char* p; + + if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) + { + start += 2; + p = parse_hexadecimal(start, value_end, &val); + } + else if (entry->format == 'x') + p = parse_hexadecimal(value, value_end, &val); + else + p = parse_decimal(value, value_end, &val); + + if (p > (const char*)start) + { + val &= ((1 << entry->bit_length) - 1); + val <<= entry->bit_lshift; + g_cpuIdArm |= (uint32_t)val; + } + + free(value); + } + + // Handle kernel configuration bugs that prevent the correct + // reporting of CPU features. + static const struct CpuFix + { + uint32_t cpuid; + uint64_t or_flags; + } cpu_fixes[] = { + /* The Nexus 4 (Qualcomm Krait) kernel configuration + * forgets to report IDIV support. */ + { 0x510006f2, ANDROID_CPU_ARM_FEATURE_IDIV_ARM | ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 }, + { 0x510006f3, ANDROID_CPU_ARM_FEATURE_IDIV_ARM | ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 }, + }; + + for (size_t n = 0; n < sizeof(cpu_fixes) / sizeof(cpu_fixes[0]); ++n) + { + const struct CpuFix* entry = &cpu_fixes[n]; + + if (g_cpuIdArm == entry->cpuid) + g_cpuFeatures |= entry->or_flags; + } + + // Special case: The emulator-specific Android 4.2 kernel fails + // to report support for the 32-bit ARM IDIV instruction. + // Technically, this is a feature of the virtual CPU implemented + // by the emulator. Note that it could also support Thumb IDIV + // in the future, and this will have to be slightly updated. + char* hardware = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "Hardware"); + + if (hardware) + { + if (!strcmp(hardware, "Goldfish") && g_cpuIdArm == 0x4100c080 && + (g_cpuFamily & ANDROID_CPU_ARM_FEATURE_ARMv7) != 0) + { + g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_IDIV_ARM; + } + + free(hardware); + } + } +#endif /* __arm__ */ +#ifdef __aarch64__ + { + /* Extract the list of CPU features from ELF hwcaps */ + uint32_t hwcaps = 0; + hwcaps = get_elf_hwcap_from_getauxval(AT_HWCAP); + + if (hwcaps != 0) + { + int has_fp = (hwcaps & HWCAP_FP); + int has_asimd = (hwcaps & HWCAP_ASIMD); + int has_aes = (hwcaps & HWCAP_AES); + int has_pmull = (hwcaps & HWCAP_PMULL); + int has_sha1 = (hwcaps & HWCAP_SHA1); + int has_sha2 = (hwcaps & HWCAP_SHA2); + int has_crc32 = (hwcaps & HWCAP_CRC32); + + if (has_fp == 0) + { + D("ERROR: Floating-point unit missing, but is required by Android on AArch64 " + "CPUs\n"); + } + + if (has_asimd == 0) + { + D("ERROR: ASIMD unit missing, but is required by Android on AArch64 CPUs\n"); + } + + if (has_fp) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_FP; + + if (has_asimd) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_ASIMD; + + if (has_aes) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_AES; + + if (has_pmull) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_PMULL; + + if (has_sha1) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_SHA1; + + if (has_sha2) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_SHA2; + + if (has_crc32) + g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_CRC32; + } + } +#endif /* __aarch64__ */ +#if defined(__i386__) || defined(__x86_64__) + int regs[4]; + /* According to http://en.wikipedia.org/wiki/CPUID */ +#define VENDOR_INTEL_b 0x756e6547 +#define VENDOR_INTEL_c 0x6c65746e +#define VENDOR_INTEL_d 0x49656e69 + x86_cpuid(0, regs); + int vendorIsIntel = + (regs[1] == VENDOR_INTEL_b && regs[2] == VENDOR_INTEL_c && regs[3] == VENDOR_INTEL_d); + x86_cpuid(1, regs); + + if ((regs[2] & (1 << 9)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSSE3; + } + + if ((regs[2] & (1 << 23)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_POPCNT; + } + + if ((regs[2] & (1 << 19)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSE4_1; + } + + if ((regs[2] & (1 << 20)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSE4_2; + } + + if (vendorIsIntel && (regs[2] & (1 << 22)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_MOVBE; + } + + if ((regs[2] & (1 << 25)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AES_NI; + } + + if ((regs[2] & (1 << 28)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AVX; + } + + if ((regs[2] & (1 << 30)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_RDRAND; + } + + x86_cpuid(7, regs); + + if ((regs[1] & (1 << 5)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AVX2; + } + + if ((regs[1] & (1 << 29)) != 0) + { + g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SHA_NI; + } + +#endif +#if defined(__mips__) + { + /* MIPS and MIPS64 */ + /* Extract the list of CPU features from ELF hwcaps */ + uint32_t hwcaps = 0; + hwcaps = get_elf_hwcap_from_getauxval(AT_HWCAP); + + if (hwcaps != 0) + { + int has_r6 = (hwcaps & HWCAP_MIPS_R6); + int has_msa = (hwcaps & HWCAP_MIPS_MSA); + + if (has_r6) + g_cpuFeatures |= ANDROID_CPU_MIPS_FEATURE_R6; + + if (has_msa) + g_cpuFeatures |= ANDROID_CPU_MIPS_FEATURE_MSA; + } + } +#endif /* __mips__ */ + free(cpuinfo); +} + +AndroidCpuFamily android_getCpuFamily(void) +{ + pthread_once(&g_once, android_cpuInit); + return g_cpuFamily; +} + +uint64_t android_getCpuFeatures(void) +{ + pthread_once(&g_once, android_cpuInit); + return g_cpuFeatures; +} + +int android_getCpuCount(void) +{ + pthread_once(&g_once, android_cpuInit); + return g_cpuCount; +} + +static void android_cpuInitDummy(void) +{ + g_inited = 1; +} + +int android_setCpu(int cpu_count, uint64_t cpu_features) +{ + /* Fail if the library was already initialized. */ + if (g_inited) + return 0; + + android_cpuInitFamily(); + g_cpuCount = (cpu_count <= 0 ? 1 : cpu_count); + g_cpuFeatures = cpu_features; + pthread_once(&g_once, android_cpuInitDummy); + return 1; +} + +#ifdef __arm__ +uint32_t android_getCpuIdArm(void) +{ + pthread_once(&g_once, android_cpuInit); + return g_cpuIdArm; +} + +int android_setCpuArm(int cpu_count, uint64_t cpu_features, uint32_t cpu_id) +{ + if (!android_setCpu(cpu_count, cpu_features)) + return 0; + + g_cpuIdArm = cpu_id; + return 1; +} +#endif /* __arm__ */ + +/* + * Technical note: Making sense of ARM's FPU architecture versions. + * + * FPA was ARM's first attempt at an FPU architecture. There is no Android + * device that actually uses it since this technology was already obsolete + * when the project started. If you see references to FPA instructions + * somewhere, you can be sure that this doesn't apply to Android at all. + * + * FPA was followed by "VFP", soon renamed "VFPv1" due to the emergence of + * new versions / additions to it. ARM considers this obsolete right now, + * and no known Android device implements it either. + * + * VFPv2 added a few instructions to VFPv1, and is an *optional* extension + * supported by some ARMv5TE, ARMv6 and ARMv6T2 CPUs. Note that a device + * supporting the 'armeabi' ABI doesn't necessarily support these. + * + * VFPv3-D16 adds a few instructions on top of VFPv2 and is typically used + * on ARMv7-A CPUs which implement a FPU. Note that it is also mandated + * by the Android 'armeabi-v7a' ABI. The -D16 suffix in its name means + * that it provides 16 double-precision FPU registers (d0-d15) and 32 + * single-precision ones (s0-s31) which happen to be mapped to the same + * register banks. + * + * VFPv3-D32 is the name of an extension to VFPv3-D16 that provides 16 + * additional double precision registers (d16-d31). Note that there are + * still only 32 single precision registers. + * + * VFPv3xD is a *subset* of VFPv3-D16 that only provides single-precision + * registers. It is only used on ARMv7-M (i.e. on micro-controllers) which + * are not supported by Android. Note that it is not compatible with VFPv2. + * + * NOTE: The term 'VFPv3' usually designate either VFPv3-D16 or VFPv3-D32 + * depending on context. For example GCC uses it for VFPv3-D32, but + * the Linux kernel code uses it for VFPv3-D16 (especially in + * /proc/cpuinfo). Always try to use the full designation when + * possible. + * + * NEON, a.k.a. "ARM Advanced SIMD" is an extension that provides + * instructions to perform parallel computations on vectors of 8, 16, + * 32, 64 and 128 bit quantities. NEON requires VFPv32-D32 since all + * NEON registers are also mapped to the same register banks. + * + * VFPv4-D16, adds a few instructions on top of VFPv3-D16 in order to + * perform fused multiply-accumulate on VFP registers, as well as + * half-precision (16-bit) conversion operations. + * + * VFPv4-D32 is VFPv4-D16 with 32, instead of 16, FPU double precision + * registers. + * + * VPFv4-NEON is VFPv4-D32 with NEON instructions. It also adds fused + * multiply-accumulate instructions that work on the NEON registers. + * + * NOTE: Similarly, "VFPv4" might either reference VFPv4-D16 or VFPv4-D32 + * depending on context. + * + * The following information was determined by scanning the binutils-2.22 + * sources: + * + * Basic VFP instruction subsets: + * + * #define FPU_VFP_EXT_V1xD 0x08000000 // Base VFP instruction set. + * #define FPU_VFP_EXT_V1 0x04000000 // Double-precision insns. + * #define FPU_VFP_EXT_V2 0x02000000 // ARM10E VFPr1. + * #define FPU_VFP_EXT_V3xD 0x01000000 // VFPv3 single-precision. + * #define FPU_VFP_EXT_V3 0x00800000 // VFPv3 double-precision. + * #define FPU_NEON_EXT_V1 0x00400000 // Neon (SIMD) insns. + * #define FPU_VFP_EXT_D32 0x00200000 // Registers D16-D31. + * #define FPU_VFP_EXT_FP16 0x00100000 // Half-precision extensions. + * #define FPU_NEON_EXT_FMA 0x00080000 // Neon fused multiply-add + * #define FPU_VFP_EXT_FMA 0x00040000 // VFP fused multiply-add + * + * FPU types (excluding NEON) + * + * FPU_VFP_V1xD (EXT_V1xD) + * | + * +--------------------------+ + * | | + * FPU_VFP_V1 (+EXT_V1) FPU_VFP_V3xD (+EXT_V2+EXT_V3xD) + * | | + * | | + * FPU_VFP_V2 (+EXT_V2) FPU_VFP_V4_SP_D16 (+EXT_FP16+EXT_FMA) + * | + * FPU_VFP_V3D16 (+EXT_Vx3D+EXT_V3) + * | + * +--------------------------+ + * | | + * FPU_VFP_V3 (+EXT_D32) FPU_VFP_V4D16 (+EXT_FP16+EXT_FMA) + * | | + * | FPU_VFP_V4 (+EXT_D32) + * | + * FPU_VFP_HARD (+EXT_FMA+NEON_EXT_FMA) + * + * VFP architectures: + * + * ARCH_VFP_V1xD (EXT_V1xD) + * | + * +------------------+ + * | | + * | ARCH_VFP_V3xD (+EXT_V2+EXT_V3xD) + * | | + * | ARCH_VFP_V3xD_FP16 (+EXT_FP16) + * | | + * | ARCH_VFP_V4_SP_D16 (+EXT_FMA) + * | + * ARCH_VFP_V1 (+EXT_V1) + * | + * ARCH_VFP_V2 (+EXT_V2) + * | + * ARCH_VFP_V3D16 (+EXT_V3xD+EXT_V3) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V3D16_FP16 (+EXT_FP16) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V4_D16 (+EXT_FP16+EXT_FMA) + * | | + * | ARCH_VFP_V4 (+EXT_D32) + * | | + * | ARCH_NEON_VFP_V4 (+EXT_NEON+EXT_NEON_FMA) + * | + * ARCH_VFP_V3 (+EXT_D32) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V3_FP16 (+EXT_FP16) + * | + * ARCH_VFP_V3_PLUS_NEON_V1 (+EXT_NEON) + * | + * ARCH_NEON_FP16 (+EXT_FP16) + * + * -fpu= values and their correspondence with FPU architectures above: + * + * {"vfp", FPU_ARCH_VFP_V2}, + * {"vfp9", FPU_ARCH_VFP_V2}, + * {"vfp3", FPU_ARCH_VFP_V3}, // For backwards compatibility. + * {"vfp10", FPU_ARCH_VFP_V2}, + * {"vfp10-r0", FPU_ARCH_VFP_V1}, + * {"vfpxd", FPU_ARCH_VFP_V1xD}, + * {"vfpv2", FPU_ARCH_VFP_V2}, + * {"vfpv3", FPU_ARCH_VFP_V3}, + * {"vfpv3-fp16", FPU_ARCH_VFP_V3_FP16}, + * {"vfpv3-d16", FPU_ARCH_VFP_V3D16}, + * {"vfpv3-d16-fp16", FPU_ARCH_VFP_V3D16_FP16}, + * {"vfpv3xd", FPU_ARCH_VFP_V3xD}, + * {"vfpv3xd-fp16", FPU_ARCH_VFP_V3xD_FP16}, + * {"neon", FPU_ARCH_VFP_V3_PLUS_NEON_V1}, + * {"neon-fp16", FPU_ARCH_NEON_FP16}, + * {"vfpv4", FPU_ARCH_VFP_V4}, + * {"vfpv4-d16", FPU_ARCH_VFP_V4D16}, + * {"fpv4-sp-d16", FPU_ARCH_VFP_V4_SP_D16}, + * {"neon-vfpv4", FPU_ARCH_NEON_VFP_V4}, + * + * + * Simplified diagram that only includes FPUs supported by Android: + * Only ARCH_VFP_V3D16 is actually mandated by the armeabi-v7a ABI, + * all others are optional and must be probed at runtime. + * + * ARCH_VFP_V3D16 (EXT_V1xD+EXT_V1+EXT_V2+EXT_V3xD+EXT_V3) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V3D16_FP16 (+EXT_FP16) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V4_D16 (+EXT_FP16+EXT_FMA) + * | | + * | ARCH_VFP_V4 (+EXT_D32) + * | | + * | ARCH_NEON_VFP_V4 (+EXT_NEON+EXT_NEON_FMA) + * | + * ARCH_VFP_V3 (+EXT_D32) + * | + * +-------------------+ + * | | + * | ARCH_VFP_V3_FP16 (+EXT_FP16) + * | + * ARCH_VFP_V3_PLUS_NEON_V1 (+EXT_NEON) + * | + * ARCH_NEON_FP16 (+EXT_FP16) + * + */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.h new file mode 100644 index 0000000000000000000000000000000000000000..ffa39bfc2fca5b2686cfdd377ad8f471d095ec2d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/cpufeatures/cpu-features.h @@ -0,0 +1,324 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +#ifndef CPU_FEATURES_H +#define CPU_FEATURES_H + +#include +#include + +__BEGIN_DECLS + +/* A list of valid values returned by android_getCpuFamily(). + * They describe the CPU Architecture of the current process. + */ +typedef enum +{ + ANDROID_CPU_FAMILY_UNKNOWN = 0, + ANDROID_CPU_FAMILY_ARM, + ANDROID_CPU_FAMILY_X86, + ANDROID_CPU_FAMILY_MIPS, + ANDROID_CPU_FAMILY_ARM64, + ANDROID_CPU_FAMILY_X86_64, + ANDROID_CPU_FAMILY_MIPS64, + + ANDROID_CPU_FAMILY_MAX /* do not remove */ + +} AndroidCpuFamily; + +/* Return the CPU family of the current process. + * + * Note that this matches the bitness of the current process. I.e. when + * running a 32-bit binary on a 64-bit capable CPU, this will return the + * 32-bit CPU family value. + */ +extern AndroidCpuFamily android_getCpuFamily(void); + +/* Return a bitmap describing a set of optional CPU features that are + * supported by the current device's CPU. The exact bit-flags returned + * depend on the value returned by android_getCpuFamily(). See the + * documentation for the ANDROID_CPU_*_FEATURE_* flags below for details. + */ +extern uint64_t android_getCpuFeatures(void); + +/* The list of feature flags for ANDROID_CPU_FAMILY_ARM that can be + * recognized by the library (see note below for 64-bit ARM). Value details + * are: + * + * VFPv2: + * CPU supports the VFPv2 instruction set. Many, but not all, ARMv6 CPUs + * support these instructions. VFPv2 is a subset of VFPv3 so this will + * be set whenever VFPv3 is set too. + * + * ARMv7: + * CPU supports the ARMv7-A basic instruction set. + * This feature is mandated by the 'armeabi-v7a' ABI. + * + * VFPv3: + * CPU supports the VFPv3-D16 instruction set, providing hardware FPU + * support for single and double precision floating point registers. + * Note that only 16 FPU registers are available by default, unless + * the D32 bit is set too. This feature is also mandated by the + * 'armeabi-v7a' ABI. + * + * VFP_D32: + * CPU VFP optional extension that provides 32 FPU registers, + * instead of 16. Note that ARM mandates this feature is the 'NEON' + * feature is implemented by the CPU. + * + * NEON: + * CPU FPU supports "ARM Advanced SIMD" instructions, also known as + * NEON. Note that this mandates the VFP_D32 feature as well, per the + * ARM Architecture specification. + * + * VFP_FP16: + * Half-width floating precision VFP extension. If set, the CPU + * supports instructions to perform floating-point operations on + * 16-bit registers. This is part of the VFPv4 specification, but + * not mandated by any Android ABI. + * + * VFP_FMA: + * Fused multiply-accumulate VFP instructions extension. Also part of + * the VFPv4 specification, but not mandated by any Android ABI. + * + * NEON_FMA: + * Fused multiply-accumulate NEON instructions extension. Optional + * extension from the VFPv4 specification, but not mandated by any + * Android ABI. + * + * IDIV_ARM: + * Integer division available in ARM mode. Only available + * on recent CPUs (e.g. Cortex-A15). + * + * IDIV_THUMB2: + * Integer division available in Thumb-2 mode. Only available + * on recent CPUs (e.g. Cortex-A15). + * + * iWMMXt: + * Optional extension that adds MMX registers and operations to an + * ARM CPU. This is only available on a few XScale-based CPU designs + * sold by Marvell. Pretty rare in practice. + * + * AES: + * CPU supports AES instructions. These instructions are only + * available for 32-bit applications running on ARMv8 CPU. + * + * CRC32: + * CPU supports CRC32 instructions. These instructions are only + * available for 32-bit applications running on ARMv8 CPU. + * + * SHA2: + * CPU supports SHA2 instructions. These instructions are only + * available for 32-bit applications running on ARMv8 CPU. + * + * SHA1: + * CPU supports SHA1 instructions. These instructions are only + * available for 32-bit applications running on ARMv8 CPU. + * + * PMULL: + * CPU supports 64-bit PMULL and PMULL2 instructions. These + * instructions are only available for 32-bit applications + * running on ARMv8 CPU. + * + * If you want to tell the compiler to generate code that targets one of + * the feature set above, you should probably use one of the following + * flags (for more details, see technical note at the end of this file): + * + * -mfpu=vfp + * -mfpu=vfpv2 + * These are equivalent and tell GCC to use VFPv2 instructions for + * floating-point operations. Use this if you want your code to + * run on *some* ARMv6 devices, and any ARMv7-A device supported + * by Android. + * + * Generated code requires VFPv2 feature. + * + * -mfpu=vfpv3-d16 + * Tell GCC to use VFPv3 instructions (using only 16 FPU registers). + * This should be generic code that runs on any CPU that supports the + * 'armeabi-v7a' Android ABI. Note that no ARMv6 CPU supports this. + * + * Generated code requires VFPv3 feature. + * + * -mfpu=vfpv3 + * Tell GCC to use VFPv3 instructions with 32 FPU registers. + * Generated code requires VFPv3|VFP_D32 features. + * + * -mfpu=neon + * Tell GCC to use VFPv3 instructions with 32 FPU registers, and + * also support NEON intrinsics (see ). + * Generated code requires VFPv3|VFP_D32|NEON features. + * + * -mfpu=vfpv4-d16 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA features. + * + * -mfpu=vfpv4 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32 features. + * + * -mfpu=neon-vfpv4 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32|NEON|NEON_FMA + * features. + * + * -mcpu=cortex-a7 + * -mcpu=cortex-a15 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32| + * NEON|NEON_FMA|IDIV_ARM|IDIV_THUMB2 + * This flag implies -mfpu=neon-vfpv4. + * + * -mcpu=iwmmxt + * Allows the use of iWMMXt intrinsics with GCC. + * + * IMPORTANT NOTE: These flags should only be tested when + * android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM, i.e. this is a + * 32-bit process. + * + * When running a 64-bit ARM process on an ARMv8 CPU, + * android_getCpuFeatures() will return a different set of bitflags + */ +enum +{ + ANDROID_CPU_ARM_FEATURE_ARMv7 = (1 << 0), + ANDROID_CPU_ARM_FEATURE_VFPv3 = (1 << 1), + ANDROID_CPU_ARM_FEATURE_NEON = (1 << 2), + ANDROID_CPU_ARM_FEATURE_LDREX_STREX = (1 << 3), + ANDROID_CPU_ARM_FEATURE_VFPv2 = (1 << 4), + ANDROID_CPU_ARM_FEATURE_VFP_D32 = (1 << 5), + ANDROID_CPU_ARM_FEATURE_VFP_FP16 = (1 << 6), + ANDROID_CPU_ARM_FEATURE_VFP_FMA = (1 << 7), + ANDROID_CPU_ARM_FEATURE_NEON_FMA = (1 << 8), + ANDROID_CPU_ARM_FEATURE_IDIV_ARM = (1 << 9), + ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 = (1 << 10), + ANDROID_CPU_ARM_FEATURE_iWMMXt = (1 << 11), + ANDROID_CPU_ARM_FEATURE_AES = (1 << 12), + ANDROID_CPU_ARM_FEATURE_PMULL = (1 << 13), + ANDROID_CPU_ARM_FEATURE_SHA1 = (1 << 14), + ANDROID_CPU_ARM_FEATURE_SHA2 = (1 << 15), + ANDROID_CPU_ARM_FEATURE_CRC32 = (1 << 16), +}; + +/* The bit flags corresponding to the output of android_getCpuFeatures() + * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM64. Value details + * are: + * + * FP: + * CPU has Floating-point unit. + * + * ASIMD: + * CPU has Advanced SIMD unit. + * + * AES: + * CPU supports AES instructions. + * + * CRC32: + * CPU supports CRC32 instructions. + * + * SHA2: + * CPU supports SHA2 instructions. + * + * SHA1: + * CPU supports SHA1 instructions. + * + * PMULL: + * CPU supports 64-bit PMULL and PMULL2 instructions. + */ +enum +{ + ANDROID_CPU_ARM64_FEATURE_FP = (1 << 0), + ANDROID_CPU_ARM64_FEATURE_ASIMD = (1 << 1), + ANDROID_CPU_ARM64_FEATURE_AES = (1 << 2), + ANDROID_CPU_ARM64_FEATURE_PMULL = (1 << 3), + ANDROID_CPU_ARM64_FEATURE_SHA1 = (1 << 4), + ANDROID_CPU_ARM64_FEATURE_SHA2 = (1 << 5), + ANDROID_CPU_ARM64_FEATURE_CRC32 = (1 << 6), +}; + +/* The bit flags corresponding to the output of android_getCpuFeatures() + * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_X86 or + * ANDROID_CPU_FAMILY_X86_64. + */ +enum +{ + ANDROID_CPU_X86_FEATURE_SSSE3 = (1 << 0), + ANDROID_CPU_X86_FEATURE_POPCNT = (1 << 1), + ANDROID_CPU_X86_FEATURE_MOVBE = (1 << 2), + ANDROID_CPU_X86_FEATURE_SSE4_1 = (1 << 3), + ANDROID_CPU_X86_FEATURE_SSE4_2 = (1 << 4), + ANDROID_CPU_X86_FEATURE_AES_NI = (1 << 5), + ANDROID_CPU_X86_FEATURE_AVX = (1 << 6), + ANDROID_CPU_X86_FEATURE_RDRAND = (1 << 7), + ANDROID_CPU_X86_FEATURE_AVX2 = (1 << 8), + ANDROID_CPU_X86_FEATURE_SHA_NI = (1 << 9), +}; + +/* The bit flags corresponding to the output of android_getCpuFeatures() + * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_MIPS + * or ANDROID_CPU_FAMILY_MIPS64. Values are: + * + * R6: + * CPU executes MIPS Release 6 instructions natively, and + * supports obsoleted R1..R5 instructions only via kernel traps. + * + * MSA: + * CPU supports Mips SIMD Architecture instructions. + */ +enum +{ + ANDROID_CPU_MIPS_FEATURE_R6 = (1 << 0), + ANDROID_CPU_MIPS_FEATURE_MSA = (1 << 1), +}; + +/* Return the number of CPU cores detected on this device. */ +extern int android_getCpuCount(void); + +/* The following is used to force the CPU count and features + * mask in sandboxed processes. Under 4.1 and higher, these processes + * cannot access /proc, which is the only way to get information from + * the kernel about the current hardware (at least on ARM). + * + * It _must_ be called only once, and before any android_getCpuXXX + * function, any other case will fail. + * + * This function return 1 on success, and 0 on failure. + */ +extern int android_setCpu(int cpu_count, uint64_t cpu_features); + +#ifdef __arm__ +/* Retrieve the ARM 32-bit CPUID value from the kernel. + * Note that this cannot work on sandboxed processes under 4.1 and + * higher, unless you called android_setCpuArm() before. + */ +extern uint32_t android_getCpuIdArm(void); + +/* An ARM-specific variant of android_setCpu() that also allows you + * to set the ARM CPUID field. + */ +extern int android_setCpuArm(int cpu_count, uint64_t cpu_features, uint32_t cpu_id); +#endif + +__END_DECLS + +#endif /* CPU_FEATURES_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/sysinfo.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/sysinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..2a3d3474460b9fab2c0245dfa6e62e31eae031ea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/sysinfo.c @@ -0,0 +1,1230 @@ +/** + * WinPR: Windows Portable Runtime + * System Information + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2013 Bernhard Miklautz + * + * 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 + +#include +#include +#include + +#if defined(ANDROID) +#include "cpufeatures/cpu-features.h" +#endif + +#if defined(__linux__) +#include +#include +#include +#endif + +#if !defined(_WIN32) +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 199309L) +#include +#elif !defined(__APPLE__) +#include +#include +#endif +#endif + +#include "../log.h" +#define TAG WINPR_TAG("sysinfo") + +#define FILETIME_TO_UNIX_OFFSET_S 11644473600UL + +#if defined(__MACH__) && defined(__APPLE__) + +#include + +static UINT64 scaleHighPrecision(UINT64 i, UINT32 numer, UINT32 denom) +{ + UINT64 high = (i >> 32) * numer; + UINT64 low = (i & 0xffffffffull) * numer / denom; + UINT64 highRem = ((high % denom) << 32) / denom; + high /= denom; + return (high << 32) + highRem + low; +} + +static UINT64 mac_get_time_ns(void) +{ + mach_timebase_info_data_t timebase = { 0 }; + mach_timebase_info(&timebase); + UINT64 t = mach_absolute_time(); + return scaleHighPrecision(t, timebase.numer, timebase.denom); +} + +#endif + +/** + * api-ms-win-core-sysinfo-l1-1-1.dll: + * + * EnumSystemFirmwareTables + * GetSystemFirmwareTable + * GetLogicalProcessorInformation + * GetLogicalProcessorInformationEx + * GetProductInfo + * GetSystemDirectoryA + * GetSystemDirectoryW + * GetSystemTimeAdjustment + * GetSystemWindowsDirectoryA + * GetSystemWindowsDirectoryW + * GetWindowsDirectoryA + * GetWindowsDirectoryW + * GlobalMemoryStatusEx + * SetComputerNameExW + * VerSetConditionMask + */ + +#ifndef _WIN32 + +#include +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include +#include + +#if defined(__MACOSX__) || defined(__IOS__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) || defined(__DragonFly__) +#include +#endif + +static WORD GetProcessorArchitecture(void) +{ + WORD cpuArch = PROCESSOR_ARCHITECTURE_UNKNOWN; +#if defined(ANDROID) + AndroidCpuFamily family = android_getCpuFamily(); + + switch (family) + { + case ANDROID_CPU_FAMILY_ARM: + return PROCESSOR_ARCHITECTURE_ARM; + + case ANDROID_CPU_FAMILY_X86: + return PROCESSOR_ARCHITECTURE_INTEL; + + case ANDROID_CPU_FAMILY_MIPS: + return PROCESSOR_ARCHITECTURE_MIPS; + + case ANDROID_CPU_FAMILY_ARM64: + return PROCESSOR_ARCHITECTURE_ARM64; + + case ANDROID_CPU_FAMILY_X86_64: + return PROCESSOR_ARCHITECTURE_AMD64; + + case ANDROID_CPU_FAMILY_MIPS64: + return PROCESSOR_ARCHITECTURE_MIPS64; + + default: + return PROCESSOR_ARCHITECTURE_UNKNOWN; + } + +#elif defined(_M_ARM) + cpuArch = PROCESSOR_ARCHITECTURE_ARM; +#elif defined(_M_IX86) + cpuArch = PROCESSOR_ARCHITECTURE_INTEL; +#elif defined(_M_MIPS64) + /* Needs to be before __mips__ since the compiler defines both */ + cpuArch = PROCESSOR_ARCHITECTURE_MIPS64; +#elif defined(_M_MIPS) + cpuArch = PROCESSOR_ARCHITECTURE_MIPS; +#elif defined(_M_ARM64) + cpuArch = PROCESSOR_ARCHITECTURE_ARM64; +#elif defined(_M_AMD64) + cpuArch = PROCESSOR_ARCHITECTURE_AMD64; +#elif defined(_M_PPC) + cpuArch = PROCESSOR_ARCHITECTURE_PPC; +#elif defined(_M_ALPHA) + cpuArch = PROCESSOR_ARCHITECTURE_ALPHA; +#elif defined(_M_E2K) + cpuArch = PROCESSOR_ARCHITECTURE_E2K; +#endif + return cpuArch; +} + +static DWORD GetNumberOfProcessors(void) +{ + DWORD numCPUs = 1; +#if defined(ANDROID) + return android_getCpuCount(); + /* TODO: iOS */ +#elif defined(__linux__) || defined(__sun) || defined(_AIX) + numCPUs = (DWORD)sysconf(_SC_NPROCESSORS_ONLN); +#elif defined(__MACOSX__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) || defined(__DragonFly__) + { + int mib[4]; + size_t length = sizeof(numCPUs); + mib[0] = CTL_HW; +#if defined(__FreeBSD__) || defined(__OpenBSD__) + mib[1] = HW_NCPU; +#else + mib[1] = HW_AVAILCPU; +#endif + sysctl(mib, 2, &numCPUs, &length, NULL, 0); + + if (numCPUs < 1) + { + mib[1] = HW_NCPU; + sysctl(mib, 2, &numCPUs, &length, NULL, 0); + + if (numCPUs < 1) + numCPUs = 1; + } + } +#elif defined(__hpux) + numCPUs = (DWORD)mpctl(MPC_GETNUMSPUS, NULL, NULL); +#elif defined(__sgi) + numCPUs = (DWORD)sysconf(_SC_NPROC_ONLN); +#endif + return numCPUs; +} + +static DWORD GetSystemPageSize(void) +{ + DWORD dwPageSize = 0; + long sc_page_size = -1; +#if defined(_SC_PAGESIZE) + + if (sc_page_size < 0) + sc_page_size = sysconf(_SC_PAGESIZE); + +#endif +#if defined(_SC_PAGE_SIZE) + + if (sc_page_size < 0) + sc_page_size = sysconf(_SC_PAGE_SIZE); + +#endif + + if (sc_page_size > 0) + dwPageSize = (DWORD)sc_page_size; + + if (dwPageSize < 4096) + dwPageSize = 4096; + + return dwPageSize; +} + +void GetSystemInfo(LPSYSTEM_INFO lpSystemInfo) +{ + const SYSTEM_INFO empty = { 0 }; + WINPR_ASSERT(lpSystemInfo); + + *lpSystemInfo = empty; + lpSystemInfo->DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture = + GetProcessorArchitecture(); + lpSystemInfo->dwPageSize = GetSystemPageSize(); + lpSystemInfo->dwNumberOfProcessors = GetNumberOfProcessors(); +} + +void GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo) +{ + GetSystemInfo(lpSystemInfo); +} + +void GetSystemTime(LPSYSTEMTIME lpSystemTime) +{ + time_t ct = 0; + struct tm tres; + struct tm* stm = NULL; + WORD wMilliseconds = 0; + ct = time(NULL); + wMilliseconds = (WORD)(GetTickCount() % 1000); + stm = gmtime_r(&ct, &tres); + ZeroMemory(lpSystemTime, sizeof(SYSTEMTIME)); + + if (stm) + { + lpSystemTime->wYear = (WORD)(stm->tm_year + 1900); + lpSystemTime->wMonth = (WORD)(stm->tm_mon + 1); + lpSystemTime->wDayOfWeek = (WORD)stm->tm_wday; + lpSystemTime->wDay = (WORD)stm->tm_mday; + lpSystemTime->wHour = (WORD)stm->tm_hour; + lpSystemTime->wMinute = (WORD)stm->tm_min; + lpSystemTime->wSecond = (WORD)stm->tm_sec; + lpSystemTime->wMilliseconds = wMilliseconds; + } +} + +BOOL SetSystemTime(CONST SYSTEMTIME* lpSystemTime) +{ + /* TODO: Implement */ + return FALSE; +} + +VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) +{ + time_t ct = 0; + struct tm tres; + struct tm* ltm = NULL; + WORD wMilliseconds = 0; + ct = time(NULL); + wMilliseconds = (WORD)(GetTickCount() % 1000); + ltm = localtime_r(&ct, &tres); + ZeroMemory(lpSystemTime, sizeof(SYSTEMTIME)); + + if (ltm) + { + lpSystemTime->wYear = (WORD)(ltm->tm_year + 1900); + lpSystemTime->wMonth = (WORD)(ltm->tm_mon + 1); + lpSystemTime->wDayOfWeek = (WORD)ltm->tm_wday; + lpSystemTime->wDay = (WORD)ltm->tm_mday; + lpSystemTime->wHour = (WORD)ltm->tm_hour; + lpSystemTime->wMinute = (WORD)ltm->tm_min; + lpSystemTime->wSecond = (WORD)ltm->tm_sec; + lpSystemTime->wMilliseconds = wMilliseconds; + } +} + +BOOL SetLocalTime(CONST SYSTEMTIME* lpSystemTime) +{ + /* TODO: Implement */ + return FALSE; +} + +VOID GetSystemTimeAsFileTime(LPFILETIME lpSystemTimeAsFileTime) +{ + union + { + UINT64 u64; + FILETIME ft; + } t; + + t.u64 = (winpr_GetUnixTimeNS() / 100ull) + FILETIME_TO_UNIX_OFFSET_S * 10000000ull; + *lpSystemTimeAsFileTime = t.ft; +} + +BOOL GetSystemTimeAdjustment(PDWORD lpTimeAdjustment, PDWORD lpTimeIncrement, + PBOOL lpTimeAdjustmentDisabled) +{ + /* TODO: Implement */ + return FALSE; +} + +#ifndef CLOCK_MONOTONIC_RAW +#define CLOCK_MONOTONIC_RAW 4 +#endif + +DWORD GetTickCount(void) +{ + return (DWORD)GetTickCount64(); +} +#endif // _WIN32 + +#if !defined(_WIN32) || defined(_UWP) + +#if defined(WITH_WINPR_DEPRECATED) +/* OSVERSIONINFOEX Structure: + * http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833 + */ + +BOOL GetVersionExA(LPOSVERSIONINFOA lpVersionInformation) +{ +#ifdef _UWP + + /* Windows 10 Version Info */ + if ((lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOA)) || + (lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOEXA))) + { + lpVersionInformation->dwMajorVersion = 10; + lpVersionInformation->dwMinorVersion = 0; + lpVersionInformation->dwBuildNumber = 0; + lpVersionInformation->dwPlatformId = VER_PLATFORM_WIN32_NT; + ZeroMemory(lpVersionInformation->szCSDVersion, sizeof(lpVersionInformation->szCSDVersion)); + + if (lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOEXA)) + { + LPOSVERSIONINFOEXA lpVersionInformationEx = (LPOSVERSIONINFOEXA)lpVersionInformation; + lpVersionInformationEx->wServicePackMajor = 0; + lpVersionInformationEx->wServicePackMinor = 0; + lpVersionInformationEx->wSuiteMask = 0; + lpVersionInformationEx->wProductType = VER_NT_WORKSTATION; + lpVersionInformationEx->wReserved = 0; + } + + return TRUE; + } + +#else + + /* Windows 7 SP1 Version Info */ + if ((lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOA)) || + (lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOEXA))) + { + lpVersionInformation->dwMajorVersion = 6; + lpVersionInformation->dwMinorVersion = 1; + lpVersionInformation->dwBuildNumber = 7601; + lpVersionInformation->dwPlatformId = VER_PLATFORM_WIN32_NT; + ZeroMemory(lpVersionInformation->szCSDVersion, sizeof(lpVersionInformation->szCSDVersion)); + + if (lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOEXA)) + { + LPOSVERSIONINFOEXA lpVersionInformationEx = (LPOSVERSIONINFOEXA)lpVersionInformation; + lpVersionInformationEx->wServicePackMajor = 1; + lpVersionInformationEx->wServicePackMinor = 0; + lpVersionInformationEx->wSuiteMask = 0; + lpVersionInformationEx->wProductType = VER_NT_WORKSTATION; + lpVersionInformationEx->wReserved = 0; + } + + return TRUE; + } + +#endif + return FALSE; +} + +BOOL GetVersionExW(LPOSVERSIONINFOW lpVersionInformation) +{ + ZeroMemory(lpVersionInformation->szCSDVersion, sizeof(lpVersionInformation->szCSDVersion)); + return GetVersionExA((LPOSVERSIONINFOA)lpVersionInformation); +} + +#endif + +#endif + +#if !defined(_WIN32) || defined(_UWP) + +BOOL GetComputerNameW(LPWSTR lpBuffer, LPDWORD lpnSize) +{ + BOOL rc = 0; + LPSTR buffer = NULL; + if (!lpnSize || (*lpnSize > INT_MAX)) + return FALSE; + + if (*lpnSize > 0) + { + buffer = malloc(*lpnSize); + if (!buffer) + return FALSE; + } + rc = GetComputerNameA(buffer, lpnSize); + + if (rc && (*lpnSize > 0)) + { + const SSIZE_T res = ConvertUtf8NToWChar(buffer, *lpnSize, lpBuffer, *lpnSize); + rc = res > 0; + } + + free(buffer); + + return rc; +} + +BOOL GetComputerNameA(LPSTR lpBuffer, LPDWORD lpnSize) +{ + if (!lpnSize) + { + SetLastError(ERROR_BAD_ARGUMENTS); + return FALSE; + } + + char hostname[256 + 1] = { 0 }; + if (gethostname(hostname, ARRAYSIZE(hostname) - 1) == -1) + return FALSE; + + size_t length = strnlen(hostname, MAX_COMPUTERNAME_LENGTH); + const char* dot = strchr(hostname, '.'); + if (dot) + { + const size_t dotlen = WINPR_ASSERTING_INT_CAST(size_t, (dot - hostname)); + if (dotlen < length) + length = dotlen; + } + + if ((*lpnSize <= (DWORD)length) || !lpBuffer) + { + SetLastError(ERROR_BUFFER_OVERFLOW); + *lpnSize = (DWORD)(length + 1); + return FALSE; + } + + strncpy(lpBuffer, hostname, length); + lpBuffer[length] = '\0'; + *lpnSize = (DWORD)length; + return TRUE; +} + +BOOL GetComputerNameExA(COMPUTER_NAME_FORMAT NameType, LPSTR lpBuffer, LPDWORD lpnSize) +{ + size_t length = 0; + char hostname[256] = { 0 }; + + if (!lpnSize) + { + SetLastError(ERROR_BAD_ARGUMENTS); + return FALSE; + } + + if ((NameType == ComputerNameNetBIOS) || (NameType == ComputerNamePhysicalNetBIOS)) + { + BOOL rc = GetComputerNameA(lpBuffer, lpnSize); + + if (!rc) + { + if (GetLastError() == ERROR_BUFFER_OVERFLOW) + SetLastError(ERROR_MORE_DATA); + } + + return rc; + } + + if (gethostname(hostname, sizeof(hostname)) == -1) + return FALSE; + + length = strnlen(hostname, sizeof(hostname)); + + switch (NameType) + { + case ComputerNameDnsHostname: + case ComputerNameDnsDomain: + case ComputerNameDnsFullyQualified: + case ComputerNamePhysicalDnsHostname: + case ComputerNamePhysicalDnsDomain: + case ComputerNamePhysicalDnsFullyQualified: + if ((*lpnSize <= (DWORD)length) || !lpBuffer) + { + *lpnSize = (DWORD)(length + 1); + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + CopyMemory(lpBuffer, hostname, length); + lpBuffer[length] = '\0'; + *lpnSize = (DWORD)length; + break; + + default: + return FALSE; + } + + return TRUE; +} + +BOOL GetComputerNameExW(COMPUTER_NAME_FORMAT NameType, LPWSTR lpBuffer, LPDWORD lpnSize) +{ + BOOL rc = 0; + LPSTR lpABuffer = NULL; + + if (!lpnSize) + { + SetLastError(ERROR_BAD_ARGUMENTS); + return FALSE; + } + + if (*lpnSize > 0) + { + lpABuffer = calloc(*lpnSize, sizeof(CHAR)); + + if (!lpABuffer) + return FALSE; + } + + rc = GetComputerNameExA(NameType, lpABuffer, lpnSize); + + if (rc && (*lpnSize > 0)) + { + const SSIZE_T res = ConvertUtf8NToWChar(lpABuffer, *lpnSize, lpBuffer, *lpnSize); + rc = res > 0; + } + + free(lpABuffer); + return rc; +} + +#endif + +#if defined(_UWP) + +DWORD GetTickCount(void) +{ + return (DWORD)GetTickCount64(); +} + +#endif + +#if (!defined(_WIN32)) || (defined(_WIN32) && (_WIN32_WINNT < 0x0600)) + +ULONGLONG winpr_GetTickCount64(void) +{ + const UINT64 ns = winpr_GetTickCount64NS(); + return WINPR_TIME_NS_TO_MS(ns); +} + +#endif + +UINT64 winpr_GetTickCount64NS(void) +{ + UINT64 ticks = 0; +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 199309L) + struct timespec ts = { 0 }; + + if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) + ticks = (WINPR_ASSERTING_INT_CAST(uint64_t, ts.tv_sec) * 1000000000ull) + + WINPR_ASSERTING_INT_CAST(uint64_t, ts.tv_nsec); +#elif defined(__MACH__) && defined(__APPLE__) + ticks = mac_get_time_ns(); +#elif defined(_WIN32) + LARGE_INTEGER li = { 0 }; + LARGE_INTEGER freq = { 0 }; + if (QueryPerformanceFrequency(&freq) && QueryPerformanceCounter(&li)) + ticks = li.QuadPart * 1000000000ull / freq.QuadPart; +#else + struct timeval tv = { 0 }; + + if (gettimeofday(&tv, NULL) == 0) + ticks = (tv.tv_sec * 1000000000ull) + (tv.tv_usec * 1000ull); + + /* We need to trick here: + * this function should return the system uptime, but we need higher resolution. + * so on first call get the actual timestamp along with the system uptime. + * + * return the uptime measured from now on (e.g. current measure - first measure + uptime at + * first measure) + */ + static UINT64 first = 0; + static UINT64 uptime = 0; + if (first == 0) + { + struct sysinfo info = { 0 }; + if (sysinfo(&info) == 0) + { + first = ticks; + uptime = 1000000000ull * info.uptime; + } + } + + ticks = ticks - first + uptime; +#endif + return ticks; +} + +UINT64 winpr_GetUnixTimeNS(void) +{ +#if defined(_WIN32) + + union + { + UINT64 u64; + FILETIME ft; + } t = { 0 }; + GetSystemTimeAsFileTime(&t.ft); + return (t.u64 - FILETIME_TO_UNIX_OFFSET_S * 10000000ull) * 100ull; +#elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 199309L) + struct timespec ts = { 0 }; + if (clock_gettime(CLOCK_REALTIME, &ts) != 0) + return 0; + return WINPR_ASSERTING_INT_CAST(uint64_t, ts.tv_sec) * 1000000000ull + + WINPR_ASSERTING_INT_CAST(uint64_t, ts.tv_nsec); +#else + struct timeval tv = { 0 }; + if (gettimeofday(&tv, NULL) != 0) + return 0; + return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000ull; +#endif +} + +/* If x86 */ +#ifdef _M_IX86_AMD64 + +#if defined(__GNUC__) +#define xgetbv(_func_, _lo_, _hi_) \ + __asm__ __volatile__("xgetbv" : "=a"(_lo_), "=d"(_hi_) : "c"(_func_)) +#elif defined(_MSC_VER) +#define xgetbv(_func_, _lo_, _hi_) \ + { \ + unsigned __int64 val = _xgetbv(_func_); \ + _lo_ = val & 0xFFFFFFFF; \ + _hi_ = (val >> 32); \ + } +#endif + +#define B_BIT_AVX2 (1 << 5) +#define B_BIT_AVX512F (1 << 16) +#define D_BIT_MMX (1 << 23) +#define D_BIT_SSE (1 << 25) +#define D_BIT_SSE2 (1 << 26) +#define D_BIT_3DN (1 << 30) +#define C_BIT_SSE3 (1 << 0) +#define C_BIT_PCLMULQDQ (1 << 1) +#define C81_BIT_LZCNT (1 << 5) +#define C_BIT_3DNP (1 << 8) +#define C_BIT_3DNP (1 << 8) +#define C_BIT_SSSE3 (1 << 9) +#define C_BIT_SSE41 (1 << 19) +#define C_BIT_SSE42 (1 << 20) +#define C_BIT_FMA (1 << 12) +#define C_BIT_AES (1 << 25) +#define C_BIT_XGETBV (1 << 27) +#define C_BIT_AVX (1 << 28) +#define E_BIT_XMM (1 << 1) +#define E_BIT_YMM (1 << 2) +#define E_BITS_AVX (E_BIT_XMM | E_BIT_YMM) + +static void cpuid(unsigned info, unsigned* eax, unsigned* ebx, unsigned* ecx, unsigned* edx) +{ +#ifdef __GNUC__ + *eax = *ebx = *ecx = *edx = 0; + __asm volatile( + /* The EBX (or RBX register on x86_64) is used for the PIC base address + * and must not be corrupted by our inline assembly. + */ +#ifdef _M_IX86 + "mov %%ebx, %%esi;" + "cpuid;" + "xchg %%ebx, %%esi;" +#else + "mov %%rbx, %%rsi;" + "cpuid;" + "xchg %%rbx, %%rsi;" +#endif + : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx) + : "a"(info), "c"(0)); +#elif defined(_MSC_VER) + int a[4]; + __cpuid(a, info); + *eax = a[0]; + *ebx = a[1]; + *ecx = a[2]; + *edx = a[3]; +#endif +} +#elif defined(_M_ARM) || defined(_M_ARM64) +#if defined(__linux__) +// HWCAP flags from linux kernel - uapi/asm/hwcap.h +#define HWCAP_SWP (1 << 0) +#define HWCAP_HALF (1 << 1) +#define HWCAP_THUMB (1 << 2) +#define HWCAP_26BIT (1 << 3) /* Play it safe */ +#define HWCAP_FAST_MULT (1 << 4) +#define HWCAP_FPA (1 << 5) +#define HWCAP_VFP (1 << 6) +#define HWCAP_EDSP (1 << 7) +#define HWCAP_JAVA (1 << 8) +#define HWCAP_IWMMXT (1 << 9) +#define HWCAP_CRUNCH (1 << 10) +#define HWCAP_THUMBEE (1 << 11) +#define HWCAP_NEON (1 << 12) +#define HWCAP_VFPv3 (1 << 13) +#define HWCAP_VFPv3D16 (1 << 14) /* also set for VFPv4-D16 */ +#define HWCAP_TLS (1 << 15) +#define HWCAP_VFPv4 (1 << 16) +#define HWCAP_IDIVA (1 << 17) +#define HWCAP_IDIVT (1 << 18) +#define HWCAP_VFPD32 (1 << 19) /* set if VFP has 32 regs (not 16) */ +#define HWCAP_IDIV (HWCAP_IDIVA | HWCAP_IDIVT) + +// From linux kernel uapi/linux/auxvec.h +#define AT_HWCAP 16 + +static unsigned GetARMCPUCaps(void) +{ + unsigned caps = 0; + int fd = open("/proc/self/auxv", O_RDONLY); + + if (fd == -1) + return 0; + + static struct + { + unsigned a_type; /* Entry type */ + unsigned a_val; /* Integer value */ + } auxvec; + + while (1) + { + int num; + num = read(fd, (char*)&auxvec, sizeof(auxvec)); + + if (num < 1 || (auxvec.a_type == 0 && auxvec.a_val == 0)) + break; + + if (auxvec.a_type == AT_HWCAP) + { + caps = auxvec.a_val; + } + } + + close(fd); + return caps; +} + +#endif // defined(__linux__) +#endif // _M_IX86_AMD64 + +#ifndef _WIN32 + +#if defined(_M_ARM) || defined(_M_ARM64) +#ifdef __linux__ +#include +#endif +#endif + +BOOL IsProcessorFeaturePresent(DWORD ProcessorFeature) +{ + BOOL ret = FALSE; +#if defined(ANDROID) + const uint64_t features = android_getCpuFeatures(); + + switch (ProcessorFeature) + { + case PF_ARM_NEON_INSTRUCTIONS_AVAILABLE: + case PF_ARM_NEON: + return features & ANDROID_CPU_ARM_FEATURE_NEON; + + default: + WLog_WARN(TAG, "feature 0x%08" PRIx32 " check not implemented", ProcessorFeature); + return FALSE; + } + +#elif defined(_M_ARM) || defined(_M_ARM64) +#ifdef __linux__ + const unsigned long caps = getauxval(AT_HWCAP); + + switch (ProcessorFeature) + { + case PF_ARM_NEON_INSTRUCTIONS_AVAILABLE: + case PF_ARM_NEON: + + if (caps & HWCAP_NEON) + ret = TRUE; + + break; + + case PF_ARM_THUMB: + if (caps & HWCAP_THUMB) + ret = TRUE; + + case PF_ARM_VFP_32_REGISTERS_AVAILABLE: + if (caps & HWCAP_VFPD32) + ret = TRUE; + + case PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE: + if ((caps & HWCAP_IDIVA) || (caps & HWCAP_IDIVT)) + ret = TRUE; + + case PF_ARM_VFP3: + if (caps & HWCAP_VFPv3) + ret = TRUE; + + break; + + case PF_ARM_JAZELLE: + if (caps & HWCAP_JAVA) + ret = TRUE; + + break; + + case PF_ARM_DSP: + if (caps & HWCAP_EDSP) + ret = TRUE; + + break; + + case PF_ARM_MPU: + if (caps & HWCAP_EDSP) + ret = TRUE; + + break; + + case PF_ARM_THUMB2: + if ((caps & HWCAP_IDIVT) || (caps & HWCAP_VFPv4)) + ret = TRUE; + + break; + + case PF_ARM_T2EE: + if (caps & HWCAP_THUMBEE) + ret = TRUE; + + break; + + case PF_ARM_INTEL_WMMX: + if (caps & HWCAP_IWMMXT) + ret = TRUE; + + break; + case PF_ARM_V8_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V83_JSCVT_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V83_LRCPC_INSTRUCTIONS_AVAILABLE: + default: + WLog_WARN(TAG, "feature 0x%08" PRIx32 " check not implemented", ProcessorFeature); + break; + } + +#else // __linux__ + + switch (ProcessorFeature) + { + case PF_ARM_NEON_INSTRUCTIONS_AVAILABLE: + case PF_ARM_NEON: +#ifdef __ARM_NEON + ret = TRUE; +#endif + break; + case PF_ARM_V8_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V83_JSCVT_INSTRUCTIONS_AVAILABLE: + case PF_ARM_V83_LRCPC_INSTRUCTIONS_AVAILABLE: + default: + WLog_WARN(TAG, "feature 0x%08" PRIx32 " check not implemented", ProcessorFeature); + break; + } + +#endif // __linux__ +#endif + +#if defined(_M_IX86_AMD64) +#ifdef __GNUC__ + unsigned a = 0; + unsigned b = 0; + unsigned c = 0; + unsigned d = 0; + cpuid(1, &a, &b, &c, &d); + + switch (ProcessorFeature) + { + case PF_MMX_INSTRUCTIONS_AVAILABLE: + if (d & D_BIT_MMX) + ret = TRUE; + + break; + + case PF_XMMI_INSTRUCTIONS_AVAILABLE: + if (d & D_BIT_SSE) + ret = TRUE; + + break; + + case PF_XMMI64_INSTRUCTIONS_AVAILABLE: + if (d & D_BIT_SSE2) + ret = TRUE; + + break; + + case PF_3DNOW_INSTRUCTIONS_AVAILABLE: + if (d & D_BIT_3DN) + ret = TRUE; + + break; + + case PF_SSE3_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("sse3"); + break; + + case PF_SSSE3_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("ssse3"); + break; + case PF_SSE4_1_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("sse4.1"); + break; + case PF_SSE4_2_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("sse4.2"); + break; + case PF_AVX_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("avx"); + break; + case PF_AVX2_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("avx2"); + break; + case PF_AVX512F_INSTRUCTIONS_AVAILABLE: + ret = __builtin_cpu_supports("avx512f"); + break; + default: + WLog_WARN(TAG, "feature 0x%08" PRIx32 " check not implemented", ProcessorFeature); + break; + } + +#endif // __GNUC__ +#endif + +#if defined(_M_E2K) + /* compiler flags on e2k arch determine CPU features */ + switch (ProcessorFeature) + { + case PF_MMX_INSTRUCTIONS_AVAILABLE: +#ifdef __MMX__ + ret = TRUE; +#endif + break; + + case PF_3DNOW_INSTRUCTIONS_AVAILABLE: +#ifdef __3dNOW__ + ret = TRUE; +#endif + break; + + case PF_SSE3_INSTRUCTIONS_AVAILABLE: +#ifdef __SSE3__ + ret = TRUE; +#endif + break; + + default: + break; + } + +#endif + return ret; +} + +#endif //_WIN32 + +DWORD GetTickCountPrecise(void) +{ +#ifdef _WIN32 + LARGE_INTEGER freq = { 0 }; + LARGE_INTEGER current = { 0 }; + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(¤t); + return (DWORD)(current.QuadPart * 1000LL / freq.QuadPart); +#else + return GetTickCount(); +#endif +} + +BOOL IsProcessorFeaturePresentEx(DWORD ProcessorFeature) +{ + BOOL ret = FALSE; +#if defined(_M_ARM) || defined(_M_ARM64) +#ifdef __linux__ + unsigned caps; + caps = GetARMCPUCaps(); + + switch (ProcessorFeature) + { + case PF_EX_ARM_VFP1: + if (caps & HWCAP_VFP) + ret = TRUE; + + break; + + case PF_EX_ARM_VFP3D16: + if (caps & HWCAP_VFPv3D16) + ret = TRUE; + + break; + + case PF_EX_ARM_VFP4: + if (caps & HWCAP_VFPv4) + ret = TRUE; + + break; + + case PF_EX_ARM_IDIVA: + if (caps & HWCAP_IDIVA) + ret = TRUE; + + break; + + case PF_EX_ARM_IDIVT: + if (caps & HWCAP_IDIVT) + ret = TRUE; + + break; + } + +#endif // __linux__ +#elif defined(_M_IX86_AMD64) + unsigned a = 0; + unsigned b = 0; + unsigned c = 0; + unsigned d = 0; + cpuid(1, &a, &b, &c, &d); + + switch (ProcessorFeature) + { + case PF_EX_LZCNT: + { + unsigned a81 = 0; + unsigned b81 = 0; + unsigned c81 = 0; + unsigned d81 = 0; + cpuid(0x80000001, &a81, &b81, &c81, &d81); + + if (c81 & C81_BIT_LZCNT) + ret = TRUE; + } + break; + + case PF_EX_3DNOW_PREFETCH: + if (c & C_BIT_3DNP) + ret = TRUE; + + break; + + case PF_EX_SSSE3: + if (c & C_BIT_SSSE3) + ret = TRUE; + + break; + + case PF_EX_SSE41: + if (c & C_BIT_SSE41) + ret = TRUE; + + break; + + case PF_EX_SSE42: + if (c & C_BIT_SSE42) + ret = TRUE; + + break; +#if defined(__GNUC__) || defined(_MSC_VER) + + case PF_EX_AVX: + case PF_EX_AVX2: + case PF_EX_AVX512F: + case PF_EX_FMA: + case PF_EX_AVX_AES: + case PF_EX_AVX_PCLMULQDQ: + { + /* Check for general AVX support */ + if (!(c & C_BIT_AVX)) + break; + + /* Check for xgetbv support */ + if (!(c & C_BIT_XGETBV)) + break; + + int e = 0; + int f = 0; + xgetbv(0, e, f); + + /* XGETBV enabled for applications and XMM/YMM states enabled */ + if ((e & E_BITS_AVX) == E_BITS_AVX) + { + switch (ProcessorFeature) + { + case PF_EX_AVX: + ret = TRUE; + break; + + case PF_EX_AVX2: + case PF_EX_AVX512F: + cpuid(7, &a, &b, &c, &d); + switch (ProcessorFeature) + { + case PF_EX_AVX2: + if (b & B_BIT_AVX2) + ret = TRUE; + break; + + case PF_EX_AVX512F: + if (b & B_BIT_AVX512F) + ret = TRUE; + break; + + default: + break; + } + break; + + case PF_EX_FMA: + if (c & C_BIT_FMA) + ret = TRUE; + + break; + + case PF_EX_AVX_AES: + if (c & C_BIT_AES) + ret = TRUE; + + break; + + case PF_EX_AVX_PCLMULQDQ: + if (c & C_BIT_PCLMULQDQ) + ret = TRUE; + + break; + default: + break; + } + } + } + break; +#endif // __GNUC__ || _MSC_VER + + default: + break; + } +#elif defined(_M_E2K) + /* compiler flags on e2k arch determine CPU features */ + switch (ProcessorFeature) + { + case PF_EX_LZCNT: +#ifdef __LZCNT__ + ret = TRUE; +#endif + break; + + case PF_EX_SSSE3: +#ifdef __SSSE3__ + ret = TRUE; +#endif + break; + + case PF_EX_SSE41: +#ifdef __SSE4_1__ + ret = TRUE; +#endif + break; + + case PF_EX_SSE42: +#ifdef __SSE4_2__ + ret = TRUE; +#endif + break; + + case PF_EX_AVX: +#ifdef __AVX__ + ret = TRUE; +#endif + break; + + case PF_EX_AVX2: +#ifdef __AVX2__ + ret = TRUE; +#endif + break; + + case PF_EX_FMA: +#ifdef __FMA__ + ret = TRUE; +#endif + break; + + default: + break; + } +#endif + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..423e59bde7d8a8241040ee22863f9395b1f33f03 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/CMakeLists.txt @@ -0,0 +1,25 @@ +set(MODULE_NAME "TestSysInfo") +set(MODULE_PREFIX "TEST_SYSINFO") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestGetNativeSystemInfo.c TestCPUFeatures.c TestGetComputerName.c TestSystemTime.c + TestLocalTime.c +) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestCPUFeatures.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestCPUFeatures.c new file mode 100644 index 0000000000000000000000000000000000000000..75903c5e7c7ab349b5d7f46f65d324ae8a2523f3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestCPUFeatures.c @@ -0,0 +1,65 @@ + +#include +#include +#include + +#define TEST_FEATURE(feature) \ + printf("\t" #feature ": %s\n", IsProcessorFeaturePresent(feature) ? "yes" : "no") +#define TEST_FEATURE_EX(feature) \ + printf("\t" #feature ": %s\n", IsProcessorFeaturePresentEx(feature) ? "yes" : "no") +int TestCPUFeatures(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + printf("Base CPU Flags:\n"); +#ifdef _M_IX86_AMD64 + TEST_FEATURE(PF_MMX_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_XMMI_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_XMMI64_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_3DNOW_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_SSE3_INSTRUCTIONS_AVAILABLE); + printf("\n"); + printf("Extended CPU Flags (not found in windows API):\n"); + TEST_FEATURE_EX(PF_EX_3DNOW_PREFETCH); + TEST_FEATURE_EX(PF_EX_SSSE3); + TEST_FEATURE_EX(PF_EX_SSE41); + TEST_FEATURE_EX(PF_EX_SSE42); + TEST_FEATURE_EX(PF_EX_AVX); + TEST_FEATURE_EX(PF_EX_FMA); + TEST_FEATURE_EX(PF_EX_AVX_AES); + TEST_FEATURE_EX(PF_EX_AVX_PCLMULQDQ); +#elif defined(_M_ARM) || defined(_M_ARM64) + TEST_FEATURE(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_ARM_THUMB); + TEST_FEATURE(PF_ARM_VFP_32_REGISTERS_AVAILABLE); + TEST_FEATURE(PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE); + TEST_FEATURE(PF_ARM_VFP3); + TEST_FEATURE(PF_ARM_THUMB); + TEST_FEATURE(PF_ARM_JAZELLE); + TEST_FEATURE(PF_ARM_DSP); + TEST_FEATURE(PF_ARM_THUMB2); + TEST_FEATURE(PF_ARM_T2EE); + TEST_FEATURE(PF_ARM_INTEL_WMMX); + printf("Extended CPU Flags (not found in windows API):\n"); + TEST_FEATURE_EX(PF_EX_ARM_VFP1); + TEST_FEATURE_EX(PF_EX_ARM_VFP3D16); + TEST_FEATURE_EX(PF_EX_ARM_VFP4); + TEST_FEATURE_EX(PF_EX_ARM_IDIVA); + TEST_FEATURE_EX(PF_EX_ARM_IDIVT); +#elif defined(_M_E2K) + TEST_FEATURE(PF_MMX_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_3DNOW_INSTRUCTIONS_AVAILABLE); + TEST_FEATURE(PF_SSE3_INSTRUCTIONS_AVAILABLE); + printf("\n"); + printf("Extended CPU Flags (not found in windows API):\n"); + TEST_FEATURE_EX(PF_EX_SSSE3); + TEST_FEATURE_EX(PF_EX_SSE41); + TEST_FEATURE_EX(PF_EX_SSE42); + TEST_FEATURE_EX(PF_EX_AVX); + TEST_FEATURE_EX(PF_EX_FMA); +#endif + printf("\n"); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetComputerName.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetComputerName.c new file mode 100644 index 0000000000000000000000000000000000000000..716f46aa22f9e7b429a3643bedce66981c0acf72 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetComputerName.c @@ -0,0 +1,372 @@ +#include +#include +#include +#include +#include + +static BOOL Test_GetComputerName(void) +{ + /** + * BOOL WINAPI GetComputerName(LPTSTR lpBuffer, LPDWORD lpnSize); + * + * GetComputerName retrieves the NetBIOS name of the local computer. + * + * lpBuffer [out] + * A pointer to a buffer that receives the computer name or the cluster virtual server name. + * The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters. + * + * lpnSize [in, out] + * On input, specifies the size of the buffer, in TCHARs. + * On output, the number of TCHARs copied to the destination buffer, not including the + * terminating null character. If the buffer is too small, the function fails and GetLastError + * returns ERROR_BUFFER_OVERFLOW. The lpnSize parameter specifies the size of the buffer + * required, including the terminating null character + * + */ + + CHAR netbiosName1[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; + CHAR netbiosName2[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; + const size_t netbiosBufferSize = ARRAYSIZE(netbiosName1); + DWORD dwSize = 0; + DWORD dwNameLength = 0; + DWORD dwError = 0; + + memset(netbiosName1, 0xAA, netbiosBufferSize); + memset(netbiosName2, 0xBB, netbiosBufferSize); + + /* test with null buffer and zero size (required if buffer is null) */ + dwSize = 0; + if (GetComputerNameA(NULL, &dwSize) == TRUE) + { + (void)fprintf(stderr, "%s: (1) GetComputerNameA unexpectedly succeeded with null buffer\n", + __func__); + return FALSE; + } + if ((dwError = GetLastError()) != ERROR_BUFFER_OVERFLOW) + { + (void)fprintf(stderr, + "%s: (2) GetLastError returned 0x%08" PRIX32 + " (expected ERROR_BUFFER_OVERFLOW)\n", + __func__, dwError); + return FALSE; + } + + /* test with valid buffer and zero size */ + dwSize = 0; + if (GetComputerNameA(netbiosName1, &dwSize) == TRUE) + { + (void)fprintf(stderr, + "%s: (3) GetComputerNameA unexpectedly succeeded with zero size parameter\n", + __func__); + return FALSE; + } + if ((dwError = GetLastError()) != ERROR_BUFFER_OVERFLOW) + { + (void)fprintf(stderr, + "%s: (4) GetLastError returned 0x%08" PRIX32 + " (expected ERROR_BUFFER_OVERFLOW)\n", + __func__, dwError); + return FALSE; + } + /* check if returned size is valid: must be the size of the buffer required, including the + * terminating null character in this case */ + if (dwSize < 2 || dwSize > netbiosBufferSize) + { + (void)fprintf(stderr, + "%s: (5) GetComputerNameA returned wrong size %" PRIu32 + " (expected something in the range from 2 to %" PRIu32 ")\n", + __func__, dwSize, netbiosBufferSize); + return FALSE; + } + dwNameLength = dwSize - 1; + + /* test with returned size */ + if (GetComputerNameA(netbiosName1, &dwSize) == FALSE) + { + (void)fprintf(stderr, "%s: (6) GetComputerNameA failed with error: 0x%08" PRIX32 "\n", + __func__, GetLastError()); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength) + { + (void)fprintf(stderr, + "%s: (7) GetComputerNameA returned wrong size %" PRIu32 " (expected %" PRIu32 + ")\n", + __func__, dwSize, dwNameLength); + return FALSE; + } + /* check if string is correctly terminated */ + if (netbiosName1[dwSize] != 0) + { + (void)fprintf(stderr, "%s: (8) string termination error\n", __func__); + return FALSE; + } + + /* test with real buffer size */ + dwSize = netbiosBufferSize; + if (GetComputerNameA(netbiosName2, &dwSize) == FALSE) + { + (void)fprintf(stderr, "%s: (9) GetComputerNameA failed with error: 0x%08" PRIX32 "\n", + __func__, GetLastError()); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength) + { + (void)fprintf(stderr, + "%s: (10) GetComputerNameA returned wrong size %" PRIu32 " (expected %" PRIu32 + ")\n", + __func__, dwSize, dwNameLength); + return FALSE; + } + /* check if string is correctly terminated */ + if (netbiosName2[dwSize] != 0) + { + (void)fprintf(stderr, "%s: (11) string termination error\n", __func__); + return FALSE; + } + + /* compare the results */ + if (strcmp(netbiosName1, netbiosName2) != 0) + { + (void)fprintf(stderr, "%s: (12) string compare mismatch\n", __func__); + return FALSE; + } + + /* test with off by one buffer size */ + dwSize = dwNameLength; + if (GetComputerNameA(netbiosName1, &dwSize) == TRUE) + { + (void)fprintf(stderr, + "%s: (13) GetComputerNameA unexpectedly succeeded with limited buffer size\n", + __func__); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength + 1) + { + (void)fprintf(stderr, + "%s: (14) GetComputerNameA returned wrong size %" PRIu32 " (expected %" PRIu32 + ")\n", + __func__, dwSize, dwNameLength + 1); + return FALSE; + } + + return TRUE; +} + +static BOOL Test_GetComputerNameEx_Format(COMPUTER_NAME_FORMAT format) +{ + /** + * BOOL WINAPI GetComputerNameEx(COMPUTER_NAME_FORMAT NameType, LPTSTR lpBuffer, LPDWORD + * lpnSize); + * + * Retrieves a NetBIOS or DNS name associated with the local computer. + * + * NameType [in] + * ComputerNameNetBIOS + * ComputerNameDnsHostname + * ComputerNameDnsDomain + * ComputerNameDnsFullyQualified + * ComputerNamePhysicalNetBIOS + * ComputerNamePhysicalDnsHostname + * ComputerNamePhysicalDnsDomain + * ComputerNamePhysicalDnsFullyQualified + * + * lpBuffer [out] + * A pointer to a buffer that receives the computer name or the cluster virtual server name. + * The length of the name may be greater than MAX_COMPUTERNAME_LENGTH characters because DNS + * allows longer names. To ensure that this buffer is large enough, set this parameter to NULL + * and use the required buffer size returned in the lpnSize parameter. + * + * lpnSize [in, out] + * On input, specifies the size of the buffer, in TCHARs. + * On output, receives the number of TCHARs copied to the destination buffer, not including the + * terminating null character. If the buffer is too small, the function fails and GetLastError + * returns ERROR_MORE_DATA. This parameter receives the size of the buffer required, including + * the terminating null character. If lpBuffer is NULL, this parameter must be zero. + * + */ + + CHAR computerName1[255 + 1]; + CHAR computerName2[255 + 1]; + + const DWORD nameBufferSize = sizeof(computerName1) / sizeof(CHAR); + DWORD dwSize = 0; + DWORD dwMinSize = 0; + DWORD dwNameLength = 0; + DWORD dwError = 0; + + memset(computerName1, 0xAA, nameBufferSize); + memset(computerName2, 0xBB, nameBufferSize); + + if (format == ComputerNameDnsDomain || format == ComputerNamePhysicalDnsDomain) + { + /* domain names may be empty, terminating null only */ + dwMinSize = 1; + } + else + { + /* computer names must be at least 1 character */ + dwMinSize = 2; + } + + /* test with null buffer and zero size (required if buffer is null) */ + dwSize = 0; + if (GetComputerNameExA(format, NULL, &dwSize) == TRUE) + { + (void)fprintf(stderr, + "%s: (1/%d) GetComputerNameExA unexpectedly succeeded with null buffer\n", + __func__, format); + return FALSE; + } + if ((dwError = GetLastError()) != ERROR_MORE_DATA) + { + (void)fprintf( + stderr, "%s: (2/%d) GetLastError returned 0x%08" PRIX32 " (expected ERROR_MORE_DATA)\n", + __func__, format, dwError); + return FALSE; + } + + /* test with valid buffer and zero size */ + dwSize = 0; + if (GetComputerNameExA(format, computerName1, &dwSize) == TRUE) + { + (void)fprintf( + stderr, + "%s: (3/%d) GetComputerNameExA unexpectedly succeeded with zero size parameter\n", + __func__, format); + return FALSE; + } + if ((dwError = GetLastError()) != ERROR_MORE_DATA) + { + (void)fprintf( + stderr, "%s: (4/%d) GetLastError returned 0x%08" PRIX32 " (expected ERROR_MORE_DATA)\n", + __func__, format, dwError); + return FALSE; + } + /* check if returned size is valid: must be the size of the buffer required, including the + * terminating null character in this case */ + if (dwSize < dwMinSize || dwSize > nameBufferSize) + { + (void)fprintf(stderr, + "%s: (5/%d) GetComputerNameExA returned wrong size %" PRIu32 + " (expected something in the range from %" PRIu32 " to %" PRIu32 ")\n", + __func__, format, dwSize, dwMinSize, nameBufferSize); + return FALSE; + } + dwNameLength = dwSize - 1; + + /* test with returned size */ + if (GetComputerNameExA(format, computerName1, &dwSize) == FALSE) + { + (void)fprintf(stderr, "%s: (6/%d) GetComputerNameExA failed with error: 0x%08" PRIX32 "\n", + __func__, format, GetLastError()); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength) + { + (void)fprintf(stderr, + "%s: (7/%d) GetComputerNameExA returned wrong size %" PRIu32 + " (expected %" PRIu32 ")\n", + __func__, format, dwSize, dwNameLength); + return FALSE; + } + /* check if string is correctly terminated */ + if (computerName1[dwSize] != 0) + { + (void)fprintf(stderr, "%s: (8/%d) string termination error\n", __func__, format); + return FALSE; + } + + /* test with real buffer size */ + dwSize = nameBufferSize; + if (GetComputerNameExA(format, computerName2, &dwSize) == FALSE) + { + (void)fprintf(stderr, "%s: (9/%d) GetComputerNameExA failed with error: 0x%08" PRIX32 "\n", + __func__, format, GetLastError()); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength) + { + (void)fprintf(stderr, + "%s: (10/%d) GetComputerNameExA returned wrong size %" PRIu32 + " (expected %" PRIu32 ")\n", + __func__, format, dwSize, dwNameLength); + return FALSE; + } + /* check if string is correctly terminated */ + if (computerName2[dwSize] != 0) + { + (void)fprintf(stderr, "%s: (11/%d) string termination error\n", __func__, format); + return FALSE; + } + + /* compare the results */ + if (strcmp(computerName1, computerName2) != 0) + { + (void)fprintf(stderr, "%s: (12/%d) string compare mismatch\n", __func__, format); + return FALSE; + } + + /* test with off by one buffer size */ + dwSize = dwNameLength; + if (GetComputerNameExA(format, computerName1, &dwSize) == TRUE) + { + (void)fprintf( + stderr, + "%s: (13/%d) GetComputerNameExA unexpectedly succeeded with limited buffer size\n", + __func__, format); + return FALSE; + } + /* check if returned size is valid */ + if (dwSize != dwNameLength + 1) + { + (void)fprintf(stderr, + "%s: (14/%d) GetComputerNameExA returned wrong size %" PRIu32 + " (expected %" PRIu32 ")\n", + __func__, format, dwSize, dwNameLength + 1); + return FALSE; + } + + return TRUE; +} + +int TestGetComputerName(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!Test_GetComputerName()) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNameNetBIOS)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNameDnsHostname)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNameDnsDomain)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNameDnsFullyQualified)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNamePhysicalNetBIOS)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNamePhysicalDnsHostname)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNamePhysicalDnsDomain)) + return -1; + + if (!Test_GetComputerNameEx_Format(ComputerNamePhysicalDnsFullyQualified)) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetNativeSystemInfo.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetNativeSystemInfo.c new file mode 100644 index 0000000000000000000000000000000000000000..cb059d6da6b14d91e2780a53904e5fb1eba53e15 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestGetNativeSystemInfo.c @@ -0,0 +1,33 @@ + +#include +#include + +int TestGetNativeSystemInfo(int argc, char* argv[]) +{ + SYSTEM_INFO sysinfo = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + GetNativeSystemInfo(&sysinfo); + + const UINT16 wProcessorArchitecture = + sysinfo.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture; + const UINT16 wReserved = sysinfo.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wReserved; + + printf("SystemInfo:\n"); + printf("\twProcessorArchitecture: %" PRIu16 "\n", wProcessorArchitecture); + printf("\twReserved: %" PRIu16 "\n", wReserved); + printf("\tdwPageSize: 0x%08" PRIX32 "\n", sysinfo.dwPageSize); + printf("\tlpMinimumApplicationAddress: %p\n", sysinfo.lpMinimumApplicationAddress); + printf("\tlpMaximumApplicationAddress: %p\n", sysinfo.lpMaximumApplicationAddress); + printf("\tdwActiveProcessorMask: %p\n", (void*)sysinfo.dwActiveProcessorMask); + printf("\tdwNumberOfProcessors: %" PRIu32 "\n", sysinfo.dwNumberOfProcessors); + printf("\tdwProcessorType: %" PRIu32 "\n", sysinfo.dwProcessorType); + printf("\tdwAllocationGranularity: %" PRIu32 "\n", sysinfo.dwAllocationGranularity); + printf("\twProcessorLevel: %" PRIu16 "\n", sysinfo.wProcessorLevel); + printf("\twProcessorRevision: %" PRIu16 "\n", sysinfo.wProcessorRevision); + printf("\n"); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestLocalTime.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestLocalTime.c new file mode 100644 index 0000000000000000000000000000000000000000..6ff5bf043ef5ec033d0ae769c37cac1b16f5755a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestLocalTime.c @@ -0,0 +1,21 @@ + +#include +#include + +int TestLocalTime(int argc, char* argv[]) +{ + SYSTEMTIME lTime; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + GetLocalTime(&lTime); + + printf("GetLocalTime: wYear: %" PRIu16 " wMonth: %" PRIu16 " wDayOfWeek: %" PRIu16 + " wDay: %" PRIu16 " wHour: %" PRIu16 " wMinute: %" PRIu16 " wSecond: %" PRIu16 + " wMilliseconds: %" PRIu16 "\n", + lTime.wYear, lTime.wMonth, lTime.wDayOfWeek, lTime.wDay, lTime.wHour, lTime.wMinute, + lTime.wSecond, lTime.wMilliseconds); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestSystemTime.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestSystemTime.c new file mode 100644 index 0000000000000000000000000000000000000000..2a2b69ea774663547bdfad39a3a156305f2fa024 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/sysinfo/test/TestSystemTime.c @@ -0,0 +1,21 @@ + +#include +#include + +int TestSystemTime(int argc, char* argv[]) +{ + SYSTEMTIME sTime; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + GetSystemTime(&sTime); + + printf("GetSystemTime: wYear: %" PRIu16 " wMonth: %" PRIu16 " wDayOfWeek: %" PRIu16 + " wDay: %" PRIu16 " wHour: %" PRIu16 " wMinute: %" PRIu16 " wSecond: %" PRIu16 + " wMilliseconds: %" PRIu16 "\n", + sTime.wYear, sTime.wMonth, sTime.wDayOfWeek, sTime.wDay, sTime.wHour, sTime.wMinute, + sTime.wSecond, sTime.wMilliseconds); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..500bf2b8735137c2c26f6b7eea6da61196320f43 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/CMakeLists.txt @@ -0,0 +1,31 @@ +# WinPR: Windows Portable Runtime +# libwinpr-thread cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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( + apc.h + apc.c + argv.c + process.c + processor.c + thread.c + thread.h + tls.c +) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..1bbf6c8b48556d691f748d674846414ced6ca5ae --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "1") +set(MINWIN_GROUP "core") +set(MINWIN_MAJOR_VERSION "1") +set(MINWIN_MINOR_VERSION "1") +set(MINWIN_SHORT_NAME "processthreads") +set(MINWIN_LONG_NAME "Process and Thread Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.c new file mode 100644 index 0000000000000000000000000000000000000000..b775f23ccfc63348d4d16ecd4a4f9e4f80504691 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.c @@ -0,0 +1,272 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * APC implementation + * + * Copyright 2021 David Fort + * + * 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 _WIN32 + +#include "apc.h" +#include "thread.h" +#include "../log.h" +#include "../synch/pollset.h" +#include + +#define TAG WINPR_TAG("apc") + +BOOL apc_init(APC_QUEUE* apc) +{ + pthread_mutexattr_t attr; + BOOL ret = FALSE; + + WINPR_ASSERT(apc); + + pthread_mutexattr_init(&attr); + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) + { + WLog_ERR(TAG, "failed to initialize mutex attributes to recursive"); + return FALSE; + } + + memset(apc, 0, sizeof(*apc)); + + if (pthread_mutex_init(&apc->mutex, &attr) != 0) + { + WLog_ERR(TAG, "failed to initialize main thread APC mutex"); + goto out; + } + + ret = TRUE; +out: + pthread_mutexattr_destroy(&attr); + return ret; +} + +BOOL apc_uninit(APC_QUEUE* apc) +{ + WINPR_ASSERT(apc); + return pthread_mutex_destroy(&apc->mutex) == 0; +} + +void apc_register(WINPR_THREAD* thread, WINPR_APC_ITEM* addItem) +{ + WINPR_APC_ITEM** nextp = NULL; + APC_QUEUE* apc = NULL; + + WINPR_ASSERT(thread); + WINPR_ASSERT(addItem); + + apc = &thread->apc; + WINPR_ASSERT(apc); + + pthread_mutex_lock(&apc->mutex); + if (apc->tail) + { + nextp = &apc->tail->next; + addItem->last = apc->tail; + } + else + { + nextp = &apc->head; + } + + *nextp = addItem; + apc->tail = addItem; + apc->length++; + + addItem->markedForRemove = FALSE; + addItem->boundThread = GetCurrentThreadId(); + addItem->linked = TRUE; + pthread_mutex_unlock(&apc->mutex); +} + +static INLINE void apc_item_remove(APC_QUEUE* apc, WINPR_APC_ITEM* item) +{ + WINPR_ASSERT(apc); + WINPR_ASSERT(item); + + if (!item->last) + apc->head = item->next; + else + item->last->next = item->next; + + if (!item->next) + apc->tail = item->last; + else + item->next->last = item->last; + + apc->length--; +} + +APC_REMOVE_RESULT apc_remove(WINPR_APC_ITEM* item) +{ + WINPR_THREAD* thread = winpr_GetCurrentThread(); + APC_QUEUE* apc = NULL; + APC_REMOVE_RESULT ret = APC_REMOVE_OK; + + WINPR_ASSERT(item); + + if (!item->linked) + return APC_REMOVE_OK; + + if (item->boundThread != GetCurrentThreadId()) + { + WLog_ERR(TAG, "removing an APC entry should be done in the creating thread"); + return APC_REMOVE_ERROR; + } + + if (!thread) + { + WLog_ERR(TAG, "unable to retrieve current thread"); + return APC_REMOVE_ERROR; + } + + apc = &thread->apc; + WINPR_ASSERT(apc); + + pthread_mutex_lock(&apc->mutex); + if (apc->treatingCompletions) + { + item->markedForRemove = TRUE; + ret = APC_REMOVE_DELAY_FREE; + goto out; + } + + apc_item_remove(apc, item); + +out: + pthread_mutex_unlock(&apc->mutex); + item->boundThread = 0xFFFFFFFF; + item->linked = FALSE; + return ret; +} + +BOOL apc_collectFds(WINPR_THREAD* thread, WINPR_POLL_SET* set, BOOL* haveAutoSignaled) +{ + WINPR_APC_ITEM* item = NULL; + BOOL ret = FALSE; + APC_QUEUE* apc = NULL; + + WINPR_ASSERT(thread); + WINPR_ASSERT(haveAutoSignaled); + + apc = &thread->apc; + WINPR_ASSERT(apc); + + *haveAutoSignaled = FALSE; + pthread_mutex_lock(&apc->mutex); + item = apc->head; + for (; item; item = item->next) + { + if (item->alwaysSignaled) + { + *haveAutoSignaled = TRUE; + } + else if (!pollset_add(set, item->pollFd, item->pollMode)) + goto out; + } + + ret = TRUE; +out: + pthread_mutex_unlock(&apc->mutex); + return ret; +} + +int apc_executeCompletions(WINPR_THREAD* thread, WINPR_POLL_SET* set, size_t startIndex) +{ + APC_QUEUE* apc = NULL; + WINPR_APC_ITEM* nextItem = NULL; + size_t idx = startIndex; + int ret = 0; + + WINPR_ASSERT(thread); + + apc = &thread->apc; + WINPR_ASSERT(apc); + + pthread_mutex_lock(&apc->mutex); + apc->treatingCompletions = TRUE; + + /* first pass to compute signaled items */ + for (WINPR_APC_ITEM* item = apc->head; item; item = item->next) + { + item->isSignaled = item->alwaysSignaled || pollset_isSignaled(set, idx); + if (!item->alwaysSignaled) + idx++; + } + + /* second pass: run completions */ + for (WINPR_APC_ITEM* item = apc->head; item; item = nextItem) + { + if (item->isSignaled) + { + if (item->completion && !item->markedForRemove) + item->completion(item->completionArgs); + ret++; + } + + nextItem = item->next; + } + + /* third pass: to do final cleanup */ + for (WINPR_APC_ITEM* item = apc->head; item; item = nextItem) + { + nextItem = item->next; + + if (item->markedForRemove) + { + apc_item_remove(apc, item); + if (item->markedForFree) + free(item); + } + } + + apc->treatingCompletions = FALSE; + pthread_mutex_unlock(&apc->mutex); + + return ret; +} + +void apc_cleanupThread(WINPR_THREAD* thread) +{ + WINPR_APC_ITEM* item = NULL; + WINPR_APC_ITEM* nextItem = NULL; + APC_QUEUE* apc = NULL; + + WINPR_ASSERT(thread); + + apc = &thread->apc; + WINPR_ASSERT(apc); + + pthread_mutex_lock(&apc->mutex); + item = apc->head; + for (; item; item = nextItem) + { + nextItem = item->next; + + if (item->type == APC_TYPE_HANDLE_FREE) + item->completion(item->completionArgs); + + item->last = item->next = NULL; + item->linked = FALSE; + if (item->markedForFree) + free(item); + } + + apc->head = apc->tail = NULL; + pthread_mutex_unlock(&apc->mutex); +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.h new file mode 100644 index 0000000000000000000000000000000000000000..c69920d5dcf2c21190321da6c23ef7c7dc00f243 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/apc.h @@ -0,0 +1,85 @@ +/** + * WinPR: Windows Portable Runtime + * APC implementation + * + * Copyright 2021 David Fort + * + * 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_APC_H +#define WINPR_APC_H + +#include +#include + +#ifndef _WIN32 + +#include + +typedef struct winpr_thread WINPR_THREAD; +typedef struct winpr_APC_item WINPR_APC_ITEM; +typedef struct winpr_poll_set WINPR_POLL_SET; + +typedef void (*apc_treatment)(LPVOID arg); + +typedef enum +{ + APC_TYPE_USER, + APC_TYPE_TIMER, + APC_TYPE_HANDLE_FREE +} ApcType; + +struct winpr_APC_item +{ + ApcType type; + int pollFd; + DWORD pollMode; + apc_treatment completion; + LPVOID completionArgs; + BOOL markedForFree; + + /* private fields used by the APC */ + BOOL alwaysSignaled; + BOOL isSignaled; + DWORD boundThread; + BOOL linked; + BOOL markedForRemove; + WINPR_APC_ITEM *last, *next; +}; + +typedef enum +{ + APC_REMOVE_OK, + APC_REMOVE_ERROR, + APC_REMOVE_DELAY_FREE +} APC_REMOVE_RESULT; + +typedef struct +{ + pthread_mutex_t mutex; + DWORD length; + WINPR_APC_ITEM *head, *tail; + BOOL treatingCompletions; +} APC_QUEUE; + +BOOL apc_init(APC_QUEUE* apc); +BOOL apc_uninit(APC_QUEUE* apc); +void apc_register(WINPR_THREAD* thread, WINPR_APC_ITEM* addItem); +APC_REMOVE_RESULT apc_remove(WINPR_APC_ITEM* item); +BOOL apc_collectFds(WINPR_THREAD* thread, WINPR_POLL_SET* set, BOOL* haveAutoSignaled); +int apc_executeCompletions(WINPR_THREAD* thread, WINPR_POLL_SET* set, size_t startIndex); +void apc_cleanupThread(WINPR_THREAD* thread); +#endif + +#endif /* WINPR_APC_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/argv.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/argv.c new file mode 100644 index 0000000000000000000000000000000000000000..6f4d1318c2de5a2f90f6a40b0ac70aeba21ee14b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/argv.c @@ -0,0 +1,279 @@ +/** + * WinPR: Windows Portable Runtime + * Process Argument Vector Functions + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#include "../log.h" +#define TAG WINPR_TAG("thread") + +/** + * CommandLineToArgvW function: + * http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391/ + * + * CommandLineToArgvW has a special interpretation of backslash characters + * when they are followed by a quotation mark character ("), as follows: + * + * 2n backslashes followed by a quotation mark produce n backslashes followed by a quotation mark. + * (2n) + 1 backslashes followed by a quotation mark again produce n backslashes followed by a + * quotation mark. n backslashes not followed by a quotation mark simply produce n backslashes. + * + * The address returned by CommandLineToArgvW is the address of the first element in an array of + * LPWSTR values; the number of pointers in this array is indicated by pNumArgs. Each pointer to a + * null-terminated Unicode string represents an individual argument found on the command line. + * + * CommandLineToArgvW allocates a block of contiguous memory for pointers to the argument strings, + * and for the argument strings themselves; the calling application must free the memory used by the + * argument list when it is no longer needed. To free the memory, use a single call to the LocalFree + * function. + */ + +/** + * Parsing C++ Command-Line Arguments: + * http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft + * + * Microsoft C/C++ startup code uses the following rules when + * interpreting arguments given on the operating system command line: + * + * Arguments are delimited by white space, which is either a space or a tab. + * + * The caret character (^) is not recognized as an escape character or delimiter. + * The character is handled completely by the command-line parser in the operating + * system before being passed to the argv array in the program. + * + * A string surrounded by double quotation marks ("string") is interpreted as a + * single argument, regardless of white space contained within. A quoted string + * can be embedded in an argument. + * + * A double quotation mark preceded by a backslash (\") is interpreted as a + * literal double quotation mark character ("). + * + * Backslashes are interpreted literally, unless they immediately + * precede a double quotation mark. + * + * If an even number of backslashes is followed by a double quotation mark, + * one backslash is placed in the argv array for every pair of backslashes, + * and the double quotation mark is interpreted as a string delimiter. + * + * If an odd number of backslashes is followed by a double quotation mark, + * one backslash is placed in the argv array for every pair of backslashes, + * and the double quotation mark is "escaped" by the remaining backslash, + * causing a literal double quotation mark (") to be placed in argv. + * + */ + +LPSTR* CommandLineToArgvA(LPCSTR lpCmdLine, int* pNumArgs) +{ + const char* p = NULL; + size_t length = 0; + const char* pBeg = NULL; + const char* pEnd = NULL; + char* buffer = NULL; + char* pOutput = NULL; + int numArgs = 0; + LPSTR* pArgs = NULL; + size_t maxNumArgs = 0; + size_t maxBufferSize = 0; + size_t cmdLineLength = 0; + BOOL* lpEscapedChars = NULL; + LPSTR lpEscapedCmdLine = NULL; + + if (!lpCmdLine) + return NULL; + + if (!pNumArgs) + return NULL; + + pArgs = NULL; + lpEscapedCmdLine = NULL; + cmdLineLength = strlen(lpCmdLine); + lpEscapedChars = (BOOL*)calloc(cmdLineLength + 1, sizeof(BOOL)); + + if (!lpEscapedChars) + return NULL; + + if (strstr(lpCmdLine, "\\\"")) + { + size_t n = 0; + const char* pLastEnd = NULL; + lpEscapedCmdLine = (char*)calloc(cmdLineLength + 1, sizeof(char)); + + if (!lpEscapedCmdLine) + { + free(lpEscapedChars); + return NULL; + } + + p = (const char*)lpCmdLine; + pLastEnd = (const char*)lpCmdLine; + pOutput = (char*)lpEscapedCmdLine; + + while (p < &lpCmdLine[cmdLineLength]) + { + pBeg = strstr(p, "\\\""); + + if (!pBeg) + { + length = strlen(p); + CopyMemory(pOutput, p, length); + pOutput += length; + break; + } + + pEnd = pBeg + 2; + + while (pBeg >= lpCmdLine) + { + if (*pBeg != '\\') + { + pBeg++; + break; + } + + pBeg--; + } + + n = WINPR_ASSERTING_INT_CAST(size_t, ((pEnd - pBeg) - 1)); + length = WINPR_ASSERTING_INT_CAST(size_t, (pBeg - pLastEnd)); + CopyMemory(pOutput, p, length); + pOutput += length; + p += length; + + for (size_t i = 0; i < (n / 2); i++) + *pOutput++ = '\\'; + + p += n + 1; + + if ((n % 2) != 0) + lpEscapedChars[pOutput - lpEscapedCmdLine] = TRUE; + + *pOutput++ = '"'; + pLastEnd = p; + } + + *pOutput++ = '\0'; + lpCmdLine = (LPCSTR)lpEscapedCmdLine; + cmdLineLength = strlen(lpCmdLine); + } + + maxNumArgs = 2; + p = (const char*)lpCmdLine; + + while (p < lpCmdLine + cmdLineLength) + { + p += strcspn(p, " \t"); + p += strspn(p, " \t"); + maxNumArgs++; + } + + maxBufferSize = (maxNumArgs * (sizeof(char*))) + (cmdLineLength + 1); + buffer = calloc(maxBufferSize, sizeof(char)); + + if (!buffer) + { + free(lpEscapedCmdLine); + free(lpEscapedChars); + return NULL; + } + + pArgs = (LPSTR*)buffer; + pOutput = &buffer[maxNumArgs * (sizeof(char*))]; + p = (const char*)lpCmdLine; + + while (p < lpCmdLine + cmdLineLength) + { + pBeg = p; + + while (1) + { + p += strcspn(p, " \t\"\0"); + + if ((*p != '"') || !lpEscapedChars[p - lpCmdLine]) + break; + + p++; + } + + if (*p != '"') + { + /* no whitespace escaped with double quotes */ + length = WINPR_ASSERTING_INT_CAST(size_t, (p - pBeg)); + CopyMemory(pOutput, pBeg, length); + pOutput[length] = '\0'; + pArgs[numArgs++] = pOutput; + pOutput += (length + 1); + } + else + { + p++; + + while (1) + { + p += strcspn(p, "\"\0"); + + if ((*p != '"') || !lpEscapedChars[p - lpCmdLine]) + break; + + p++; + } + + if (*p != '"') + WLog_ERR(TAG, "parsing error: uneven number of unescaped double quotes!"); + + if (p[0] && p[1]) + p += 1 + strcspn(&p[1], " \t\0"); + + pArgs[numArgs++] = pOutput; + + while (pBeg < p) + { + if (*pBeg != '"') + *pOutput++ = *pBeg; + + pBeg++; + } + + *pOutput++ = '\0'; + } + + p += strspn(p, " \t"); + } + + free(lpEscapedCmdLine); + free(lpEscapedChars); + *pNumArgs = numArgs; + return pArgs; +} + +#ifndef _WIN32 + +LPWSTR* CommandLineToArgvW(LPCWSTR lpCmdLine, int* pNumArgs) +{ + return NULL; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/process.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/process.c new file mode 100644 index 0000000000000000000000000000000000000000..dc2ed7f5aa78465a27a193be3c7a6c805e2ea8f5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/process.c @@ -0,0 +1,606 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 DI (FH) Martin Haimberger + * + * 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 + +#include +#include "../handle/nonehandle.h" + +#include + +/** + * CreateProcessA + * CreateProcessW + * CreateProcessAsUserA + * CreateProcessAsUserW + * ExitProcess + * GetCurrentProcess + * GetCurrentProcessId + * GetExitCodeProcess + * GetProcessHandleCount + * GetProcessId + * GetProcessIdOfThread + * GetProcessMitigationPolicy + * GetProcessTimes + * GetProcessVersion + * OpenProcess + * OpenProcessToken + * ProcessIdToSessionId + * SetProcessAffinityUpdateMode + * SetProcessMitigationPolicy + * SetProcessShutdownParameters + * TerminateProcess + */ + +#ifndef _WIN32 + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#ifdef __linux__ +#include +#include +#include +#endif /* __linux__ */ + +#include "thread.h" + +#include "../security/security.h" + +#ifndef NSIG +#ifdef SIGMAX +#define NSIG SIGMAX +#else +#define NSIG 64 +#endif +#endif + +/** + * If the file name does not contain a directory path, the system searches for the executable file + * in the following sequence: + * + * 1) The directory from which the application loaded. + * 2) The current directory for the parent process. + * 3) The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of + * this directory. 4) The 16-bit Windows system directory. There is no function that obtains the + * path of this directory, but it is searched. The name of this directory is System. 5) The Windows + * directory. Use the GetWindowsDirectory function to get the path of this directory. 6) The + * directories that are listed in the PATH environment variable. Note that this function does not + * search the per-application path specified by the App Paths registry key. To include this + * per-application path in the search sequence, use the ShellExecute function. + */ + +static char* FindApplicationPath(char* application) +{ + LPCSTR pathName = "PATH"; + char* path = NULL; + char* save = NULL; + DWORD nSize = 0; + LPSTR lpSystemPath = NULL; + char* filename = NULL; + + if (!application) + return NULL; + + if (application[0] == '/') + return _strdup(application); + + nSize = GetEnvironmentVariableA(pathName, NULL, 0); + + if (!nSize) + return _strdup(application); + + lpSystemPath = (LPSTR)malloc(nSize); + + if (!lpSystemPath) + return NULL; + + if (GetEnvironmentVariableA(pathName, lpSystemPath, nSize) != nSize - 1) + { + free(lpSystemPath); + return NULL; + } + + save = NULL; + path = strtok_s(lpSystemPath, ":", &save); + + while (path) + { + filename = GetCombinedPath(path, application); + + if (winpr_PathFileExists(filename)) + { + break; + } + + free(filename); + filename = NULL; + path = strtok_s(NULL, ":", &save); + } + + free(lpSystemPath); + return filename; +} + +static HANDLE CreateProcessHandle(pid_t pid); +static BOOL ProcessHandleCloseHandle(HANDLE handle); + +static BOOL CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, LPCSTR lpApplicationName, + LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, + DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, + LPSTARTUPINFOA lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation) +{ + pid_t pid = 0; + int numArgs = 0; + LPSTR* pArgs = NULL; + char** envp = NULL; + char* filename = NULL; + HANDLE thread = NULL; + HANDLE process = NULL; + WINPR_ACCESS_TOKEN* token = NULL; + LPTCH lpszEnvironmentBlock = NULL; + BOOL ret = FALSE; + sigset_t oldSigMask; + sigset_t newSigMask; + BOOL restoreSigMask = FALSE; + numArgs = 0; + lpszEnvironmentBlock = NULL; + /* https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa + */ + if (lpCommandLine) + pArgs = CommandLineToArgvA(lpCommandLine, &numArgs); + else + pArgs = CommandLineToArgvA(lpApplicationName, &numArgs); + + if (!pArgs) + return FALSE; + + token = (WINPR_ACCESS_TOKEN*)hToken; + + if (lpEnvironment) + { + envp = EnvironmentBlockToEnvpA(lpEnvironment); + } + else + { + lpszEnvironmentBlock = GetEnvironmentStrings(); + + if (!lpszEnvironmentBlock) + goto finish; + + envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock); + } + + if (!envp) + goto finish; + + filename = FindApplicationPath(pArgs[0]); + + if (NULL == filename) + goto finish; + + /* block all signals so that the child can safely reset the caller's handlers */ + sigfillset(&newSigMask); + restoreSigMask = !pthread_sigmask(SIG_SETMASK, &newSigMask, &oldSigMask); + /* fork and exec */ + pid = fork(); + + if (pid < 0) + { + /* fork failure */ + goto finish; + } + + if (pid == 0) + { + /* child process */ +#ifndef __sun + int maxfd = 0; +#endif + sigset_t set = { 0 }; + struct sigaction act = { 0 }; + /* set default signal handlers */ + act.sa_handler = SIG_DFL; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + + for (int sig = 1; sig < NSIG; sig++) + sigaction(sig, &act, NULL); + + /* unblock all signals */ + sigfillset(&set); + pthread_sigmask(SIG_UNBLOCK, &set, NULL); + + if (lpStartupInfo) + { + int handle_fd = 0; + handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdOutput); + + if (handle_fd != -1) + dup2(handle_fd, STDOUT_FILENO); + + handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdError); + + if (handle_fd != -1) + dup2(handle_fd, STDERR_FILENO); + + handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdInput); + + if (handle_fd != -1) + dup2(handle_fd, STDIN_FILENO); + } + +#ifdef __sun + closefrom(3); +#else +#ifdef F_MAXFD // on some BSD derivates + maxfd = fcntl(0, F_MAXFD); +#else + { + const long rc = sysconf(_SC_OPEN_MAX); + if ((rc < INT32_MIN) || (rc > INT32_MAX)) + goto finish; + maxfd = (int)rc; + } +#endif + + for (int fd = 3; fd < maxfd; fd++) + close(fd); + +#endif // __sun + + if (token) + { + if (token->GroupId) + { + int rc = setgid((gid_t)token->GroupId); + + if (rc < 0) + { + } + else + { + initgroups(token->Username, (gid_t)token->GroupId); + } + } + + if (token->UserId) + { + int rc = setuid((uid_t)token->UserId); + if (rc != 0) + goto finish; + } + } + + /* TODO: add better cwd handling and error checking */ + if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0) + { + int rc = chdir(lpCurrentDirectory); + if (rc != 0) + goto finish; + } + + if (execve(filename, pArgs, envp) < 0) + { + /* execve failed - end the process */ + _exit(1); + } + } + else + { + /* parent process */ + } + + process = CreateProcessHandle(pid); + + if (!process) + { + goto finish; + } + + thread = CreateNoneHandle(); + + if (!thread) + { + ProcessHandleCloseHandle(process); + goto finish; + } + + lpProcessInformation->hProcess = process; + lpProcessInformation->hThread = thread; + lpProcessInformation->dwProcessId = (DWORD)pid; + lpProcessInformation->dwThreadId = (DWORD)pid; + ret = TRUE; +finish: + + /* restore caller's original signal mask */ + if (restoreSigMask) + pthread_sigmask(SIG_SETMASK, &oldSigMask, NULL); + + free(filename); + free((void*)pArgs); + + if (lpszEnvironmentBlock) + FreeEnvironmentStrings(lpszEnvironmentBlock); + + if (envp) + { + int i = 0; + + while (envp[i]) + { + free(envp[i]); + i++; + } + + free((void*)envp); + } + + return ret; +} + +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) +{ + return CreateProcessExA(NULL, 0, lpApplicationName, lpCommandLine, lpProcessAttributes, + lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, + lpCurrentDirectory, lpStartupInfo, lpProcessInformation); +} + +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) +{ + return FALSE; +} + +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) +{ + return CreateProcessExA(hToken, 0, lpApplicationName, lpCommandLine, lpProcessAttributes, + lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, + lpCurrentDirectory, lpStartupInfo, lpProcessInformation); +} + +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) +{ + return FALSE; +} + +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) +{ + return FALSE; +} + +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) +{ + return FALSE; +} + +BOOL CreateProcessWithTokenA(HANDLE hToken, DWORD dwLogonFlags, LPCSTR lpApplicationName, + LPSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, + LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation) +{ + return CreateProcessExA(NULL, 0, lpApplicationName, lpCommandLine, NULL, NULL, FALSE, + dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, + lpProcessInformation); +} + +BOOL CreateProcessWithTokenW(HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, + LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, + LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation) +{ + return FALSE; +} + +VOID ExitProcess(UINT uExitCode) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + exit((int)uExitCode); +} + +BOOL GetExitCodeProcess(HANDLE hProcess, LPDWORD lpExitCode) +{ + WINPR_PROCESS* process = NULL; + + if (!hProcess) + return FALSE; + + if (!lpExitCode) + return FALSE; + + process = (WINPR_PROCESS*)hProcess; + *lpExitCode = process->dwExitCode; + return TRUE; +} + +HANDLE _GetCurrentProcess(VOID) +{ + return NULL; +} + +DWORD GetCurrentProcessId(VOID) +{ + return ((DWORD)getpid()); +} + +BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode) +{ + WINPR_PROCESS* process = NULL; + process = (WINPR_PROCESS*)hProcess; + + if (!process || (process->pid <= 0)) + return FALSE; + + if (kill(process->pid, SIGTERM)) + return FALSE; + + return TRUE; +} + +static BOOL ProcessHandleCloseHandle(HANDLE handle) +{ + WINPR_PROCESS* process = (WINPR_PROCESS*)handle; + WINPR_ASSERT(process); + if (process->fd >= 0) + { + close(process->fd); + process->fd = -1; + } + free(process); + return TRUE; +} + +static BOOL ProcessHandleIsHandle(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_PROCESS, FALSE); +} + +static int ProcessGetFd(HANDLE handle) +{ + WINPR_PROCESS* process = (WINPR_PROCESS*)handle; + + if (!ProcessHandleIsHandle(handle)) + return -1; + + return process->fd; +} + +static DWORD ProcessCleanupHandle(HANDLE handle) +{ + WINPR_PROCESS* process = (WINPR_PROCESS*)handle; + + WINPR_ASSERT(process); + if (process->fd > 0) + { + if (waitpid(process->pid, &process->status, WNOHANG) == process->pid) + process->dwExitCode = (DWORD)process->status; + } + return WAIT_OBJECT_0; +} + +static HANDLE_OPS ops = { ProcessHandleIsHandle, + ProcessHandleCloseHandle, + ProcessGetFd, + ProcessCleanupHandle, /* CleanupHandle */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +static int pidfd_open(pid_t pid) +{ +#ifdef __linux__ +#if !defined(__NR_pidfd_open) +#define __NR_pidfd_open 434 +#endif /* __NR_pidfd_open */ + +#ifndef PIDFD_NONBLOCK +#define PIDFD_NONBLOCK O_NONBLOCK +#endif /* PIDFD_NONBLOCK */ + + long fd = syscall(__NR_pidfd_open, pid, PIDFD_NONBLOCK); + if (fd < 0 && errno == EINVAL) + { + /* possibly PIDFD_NONBLOCK is not supported, let's try to create a pidfd and set it + * non blocking afterward */ + int flags = 0; + fd = syscall(__NR_pidfd_open, pid, 0); + if ((fd < 0) || (fd > INT32_MAX)) + return -1; + + flags = fcntl((int)fd, F_GETFL); + if ((flags < 0) || fcntl((int)fd, F_SETFL, flags | O_NONBLOCK) < 0) + { + close((int)fd); + fd = -1; + } + } + if ((fd < 0) || (fd > INT32_MAX)) + return -1; + return (int)fd; +#else + return -1; +#endif +} + +HANDLE CreateProcessHandle(pid_t pid) +{ + WINPR_PROCESS* process = NULL; + process = (WINPR_PROCESS*)calloc(1, sizeof(WINPR_PROCESS)); + + if (!process) + return NULL; + + process->pid = pid; + process->common.Type = HANDLE_TYPE_PROCESS; + process->common.ops = &ops; + process->fd = pidfd_open(pid); + if (process->fd >= 0) + process->common.Mode = WINPR_FD_READ; + return (HANDLE)process; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/processor.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/processor.c new file mode 100644 index 0000000000000000000000000000000000000000..ed3df551a6c9d6be5d1b862d19a4d264b169993b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/processor.c @@ -0,0 +1,41 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +/** + * GetCurrentProcessorNumber + * GetCurrentProcessorNumberEx + * GetThreadIdealProcessorEx + * SetThreadIdealProcessorEx + * IsProcessorFeaturePresent + */ + +#ifndef _WIN32 + +DWORD GetCurrentProcessorNumber(VOID) +{ + return 0; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b65536d0407d7ba826db5a21af564708c62596a7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestThread") +set(MODULE_PREFIX "TEST_THREAD") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestThreadCommandLineToArgv.c TestThreadCreateProcess.c TestThreadExitThread.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCommandLineToArgv.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCommandLineToArgv.c new file mode 100644 index 0000000000000000000000000000000000000000..91017b8981c89584b194389533d6332ff6a70777 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCommandLineToArgv.c @@ -0,0 +1,109 @@ + +#include +#include +#include + +static const char* test_args_line_1 = "app.exe abc d e"; + +static const char* test_args_list_1[] = { "app.exe", "abc", "d", "e" }; + +static const char* test_args_line_2 = "app.exe abc \t def"; + +static const char* test_args_list_2[] = { "app.exe", "abc", "def" }; + +static const char* test_args_line_3 = "app.exe \"abc\" d e"; + +static const char* test_args_list_3[] = { "app.exe", "abc", "d", "e" }; + +static const char* test_args_line_4 = "app.exe a\\\\b d\"e f\"g h"; + +static const char* test_args_list_4[] = { "app.exe", "a\\\\b", "de fg", "h" }; + +static const char* test_args_line_5 = "app.exe a\\\\\\\"b c d"; + +static const char* test_args_list_5[] = { "app.exe", "a\\\"b", "c", "d" }; + +static const char* test_args_line_6 = "app.exe a\\\\\\\\\"b c\" d e"; + +static const char* test_args_list_6[] = { "app.exe", "a\\\\b c", "d", "e" }; + +static const char* test_args_line_7 = "app.exe a\\\\\\\\\"b c\" d e f\\\\\\\\\"g h\" i j"; + +static const char* test_args_list_7[] = { "app.exe", "a\\\\b c", "d", "e", "f\\\\g h", "i", "j" }; + +static BOOL test_command_line_parsing_case(const char* line, const char** list, size_t expect) +{ + BOOL rc = FALSE; + int numArgs = 0; + + printf("Parsing: %s\n", line); + + LPSTR* pArgs = CommandLineToArgvA(line, &numArgs); + if (numArgs < 0) + { + (void)fprintf(stderr, "expected %" PRIuz " arguments, got %d return\n", expect, numArgs); + goto fail; + } + if (numArgs != expect) + { + (void)fprintf(stderr, "expected %" PRIuz " arguments, got %d from '%s'\n", expect, numArgs, + line); + goto fail; + } + + if ((numArgs > 0) && !pArgs) + { + (void)fprintf(stderr, "expected %d arguments, got NULL return\n", numArgs); + goto fail; + } + + printf("pNumArgs: %d\n", numArgs); + + for (int i = 0; i < numArgs; i++) + { + printf("argv[%d] = %s\n", i, pArgs[i]); + if (strcmp(pArgs[i], list[i]) != 0) + { + (void)fprintf(stderr, "failed at argument %d: got '%s' but expected '%s'\n", i, + pArgs[i], list[i]); + goto fail; + } + } + + rc = TRUE; +fail: + free((void*)pArgs); + + return rc; +} + +int TestThreadCommandLineToArgv(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_command_line_parsing_case(test_args_line_1, test_args_list_1, + ARRAYSIZE(test_args_list_1))) + return -1; + if (!test_command_line_parsing_case(test_args_line_2, test_args_list_2, + ARRAYSIZE(test_args_list_2))) + return -1; + if (!test_command_line_parsing_case(test_args_line_3, test_args_list_3, + ARRAYSIZE(test_args_list_3))) + return -1; + if (!test_command_line_parsing_case(test_args_line_4, test_args_list_4, + ARRAYSIZE(test_args_list_4))) + return -1; + if (!test_command_line_parsing_case(test_args_line_5, test_args_list_5, + ARRAYSIZE(test_args_list_5))) + return -1; + if (!test_command_line_parsing_case(test_args_line_6, test_args_list_6, + ARRAYSIZE(test_args_list_6))) + return -1; + if (!test_command_line_parsing_case(test_args_line_7, test_args_list_7, + ARRAYSIZE(test_args_list_7))) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCreateProcess.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCreateProcess.c new file mode 100644 index 0000000000000000000000000000000000000000..7fa458babd453a2373df6b3e9a5b9c30d9775a37 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadCreateProcess.c @@ -0,0 +1,156 @@ + +#include +#include +#include +#include +#include +#include +#include + +#define TESTENV_A "HELLO=WORLD" +#define TESTENV_T _T(TESTENV_A) + +int TestThreadCreateProcess(int argc, char* argv[]) +{ + BOOL status = 0; + DWORD exitCode = 0; + LPCTSTR lpApplicationName = NULL; + +#ifdef _WIN32 + TCHAR lpCommandLine[200] = _T("cmd /C set"); +#else + TCHAR lpCommandLine[200] = _T("printenv"); +#endif + + // LPTSTR lpCommandLine; + LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL; + LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL; + BOOL bInheritHandles = 0; + DWORD dwCreationFlags = 0; + LPVOID lpEnvironment = NULL; + LPCTSTR lpCurrentDirectory = NULL; + STARTUPINFO StartupInfo = { 0 }; + PROCESS_INFORMATION ProcessInformation = { 0 }; + LPTCH lpszEnvironmentBlock = NULL; + HANDLE pipe_read = NULL; + HANDLE pipe_write = NULL; + char buf[1024] = { 0 }; + DWORD read_bytes = 0; + int ret = 0; + SECURITY_ATTRIBUTES saAttr; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + lpszEnvironmentBlock = GetEnvironmentStrings(); + + lpApplicationName = NULL; + + lpProcessAttributes = NULL; + lpThreadAttributes = NULL; + bInheritHandles = FALSE; + dwCreationFlags = 0; +#ifdef _UNICODE + dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; +#endif + lpEnvironment = lpszEnvironmentBlock; + lpCurrentDirectory = NULL; + StartupInfo.cb = sizeof(STARTUPINFO); + + status = CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, + lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, + lpCurrentDirectory, &StartupInfo, &ProcessInformation); + + if (!status) + { + printf("CreateProcess failed. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + + if (WaitForSingleObject(ProcessInformation.hProcess, 5000) != WAIT_OBJECT_0) + { + printf("Failed to wait for first process. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + + exitCode = 0; + status = GetExitCodeProcess(ProcessInformation.hProcess, &exitCode); + + printf("GetExitCodeProcess status: %" PRId32 "\n", status); + printf("Process exited with code: 0x%08" PRIX32 "\n", exitCode); + + (void)CloseHandle(ProcessInformation.hProcess); + (void)CloseHandle(ProcessInformation.hThread); + FreeEnvironmentStrings(lpszEnvironmentBlock); + + /* Test stdin,stdout,stderr redirection */ + + saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); + saAttr.bInheritHandle = TRUE; + saAttr.lpSecurityDescriptor = NULL; + + if (!CreatePipe(&pipe_read, &pipe_write, &saAttr, 0)) + { + printf("Pipe creation failed. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + + bInheritHandles = TRUE; + + ZeroMemory(&StartupInfo, sizeof(STARTUPINFO)); + StartupInfo.cb = sizeof(STARTUPINFO); + StartupInfo.hStdOutput = pipe_write; + StartupInfo.hStdError = pipe_write; + StartupInfo.dwFlags = STARTF_USESTDHANDLES; + + ZeroMemory(&ProcessInformation, sizeof(PROCESS_INFORMATION)); + + if (!(lpEnvironment = calloc(1, sizeof(TESTENV_T) + sizeof(TCHAR)))) + { + printf("Failed to allocate environment buffer. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + memcpy(lpEnvironment, (void*)TESTENV_T, sizeof(TESTENV_T)); + + status = CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, + lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, + lpCurrentDirectory, &StartupInfo, &ProcessInformation); + + free(lpEnvironment); + + if (!status) + { + (void)CloseHandle(pipe_read); + (void)CloseHandle(pipe_write); + printf("CreateProcess failed. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + + if (WaitForSingleObject(ProcessInformation.hProcess, 5000) != WAIT_OBJECT_0) + { + printf("Failed to wait for second process. error=%" PRIu32 "\n", GetLastError()); + return 1; + } + + ZeroMemory(buf, sizeof(buf)); + ReadFile(pipe_read, buf, sizeof(buf) - 1, &read_bytes, NULL); + if (!strstr((const char*)buf, TESTENV_A)) + { + printf("No or unexpected data read from pipe\n"); + ret = 1; + } + + (void)CloseHandle(pipe_read); + (void)CloseHandle(pipe_write); + + exitCode = 0; + status = GetExitCodeProcess(ProcessInformation.hProcess, &exitCode); + + printf("GetExitCodeProcess status: %" PRId32 "\n", status); + printf("Process exited with code: 0x%08" PRIX32 "\n", exitCode); + + (void)CloseHandle(ProcessInformation.hProcess); + (void)CloseHandle(ProcessInformation.hThread); + + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadExitThread.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadExitThread.c new file mode 100644 index 0000000000000000000000000000000000000000..ca7104f7e9d2326a284c519de29ed23a94e575ad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/test/TestThreadExitThread.c @@ -0,0 +1,53 @@ +// Copyright © 2015 Hewlett-Packard Development Company, L.P. + +#include +#include +#include + +static DWORD WINAPI thread_func(LPVOID arg) +{ + WINPR_UNUSED(arg); + + /* exists of the thread the quickest as possible */ + ExitThread(0); + return 0; +} + +int TestThreadExitThread(int argc, char* argv[]) +{ + HANDLE thread = NULL; + DWORD waitResult = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* FIXME: create some noise to better guaranty the test validity and + * decrease the number of loops */ + for (int i = 0; i < 100; i++) + { + thread = CreateThread(NULL, 0, thread_func, NULL, 0, NULL); + + if (thread == INVALID_HANDLE_VALUE) + { + (void)fprintf(stderr, "Got an invalid thread!\n"); + return -1; + } + + waitResult = WaitForSingleObject(thread, 300); + if (waitResult != WAIT_OBJECT_0) + { + /* When the thread exits before the internal thread_list + * was updated, ExitThread() is not able to retrieve the + * related WINPR_THREAD object and is not able to signal + * the end of the thread. Therefore WaitForSingleObject + * never get the signal. + */ + (void)fprintf( + stderr, "300ms should have been enough for the thread to be in a signaled state\n"); + return -1; + } + + (void)CloseHandle(thread); + } + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.c new file mode 100644 index 0000000000000000000000000000000000000000..28d516febeb774479dd84c172d70008e51ce1803 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.c @@ -0,0 +1,1118 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Hewlett-Packard Development Company, L.P. + * Copyright 2021 David Fort + * + * + * 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 + +#include +#include + +#include + +#include + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +#ifndef MAX +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + +/** + * api-ms-win-core-processthreads-l1-1-1.dll + * + * CreateRemoteThread + * CreateRemoteThreadEx + * CreateThread + * DeleteProcThreadAttributeList + * ExitThread + * FlushInstructionCache + * FlushProcessWriteBuffers + * GetCurrentThread + * GetCurrentThreadId + * GetCurrentThreadStackLimits + * GetExitCodeThread + * GetPriorityClass + * GetStartupInfoW + * GetThreadContext + * GetThreadId + * GetThreadIdealProcessorEx + * GetThreadPriority + * GetThreadPriorityBoost + * GetThreadTimes + * InitializeProcThreadAttributeList + * OpenThread + * OpenThreadToken + * QueryProcessAffinityUpdateMode + * QueueUserAPC + * ResumeThread + * SetPriorityClass + * SetThreadContext + * SetThreadPriority + * SetThreadPriorityBoost + * SetThreadStackGuarantee + * SetThreadToken + * SuspendThread + * SwitchToThread + * TerminateThread + * UpdateProcThreadAttribute + */ + +#ifndef _WIN32 + +#include +#include + +#include +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#ifdef WINPR_HAVE_SYS_EVENTFD_H +#include +#endif + +#include + +#include +#include + +#include + +#include "thread.h" +#include "apc.h" + +#include "../handle/handle.h" +#include "../log.h" +#define TAG WINPR_TAG("thread") + +static WINPR_THREAD mainThread; + +#if defined(WITH_THREAD_LIST) +static wListDictionary* thread_list = NULL; +#endif + +static BOOL ThreadCloseHandle(HANDLE handle); +static void cleanup_handle(void* obj); + +static BOOL ThreadIsHandled(HANDLE handle) +{ + return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_THREAD, FALSE); +} + +static int ThreadGetFd(HANDLE handle) +{ + WINPR_THREAD* pThread = (WINPR_THREAD*)handle; + + if (!ThreadIsHandled(handle)) + return -1; + + return pThread->event.fds[0]; +} + +#define run_mutex_init(fkt, mux, arg) run_mutex_init_(fkt, #fkt, mux, arg) +static BOOL run_mutex_init_(int (*fkt)(pthread_mutex_t*, const pthread_mutexattr_t*), + const char* name, pthread_mutex_t* mutex, + const pthread_mutexattr_t* mutexattr) +{ + int rc = 0; + + WINPR_ASSERT(fkt); + WINPR_ASSERT(mutex); + + rc = fkt(mutex, mutexattr); + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer))); + } + return rc == 0; +} + +#define run_mutex_fkt(fkt, mux) run_mutex_fkt_(fkt, #fkt, mux) +static BOOL run_mutex_fkt_(int (*fkt)(pthread_mutex_t* mux), const char* name, + pthread_mutex_t* mutex) +{ + int rc = 0; + + WINPR_ASSERT(fkt); + WINPR_ASSERT(mutex); + + rc = fkt(mutex); + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer))); + } + return rc == 0; +} + +#define run_cond_init(fkt, cond, arg) run_cond_init_(fkt, #fkt, cond, arg) +static BOOL run_cond_init_(int (*fkt)(pthread_cond_t*, const pthread_condattr_t*), const char* name, + pthread_cond_t* condition, const pthread_condattr_t* conditionattr) +{ + int rc = 0; + + WINPR_ASSERT(fkt); + WINPR_ASSERT(condition); + + rc = fkt(condition, conditionattr); + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer))); + } + return rc == 0; +} + +#define run_cond_fkt(fkt, cond) run_cond_fkt_(fkt, #fkt, cond) +static BOOL run_cond_fkt_(int (*fkt)(pthread_cond_t* mux), const char* name, + pthread_cond_t* condition) +{ + int rc = 0; + + WINPR_ASSERT(fkt); + WINPR_ASSERT(condition); + + rc = fkt(condition); + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer))); + } + return rc == 0; +} + +static int pthread_mutex_checked_unlock(pthread_mutex_t* mutex) +{ + WINPR_ASSERT(mutex); + WINPR_ASSERT(pthread_mutex_trylock(mutex) == EBUSY); + return pthread_mutex_unlock(mutex); +} + +static BOOL mux_condition_bundle_init(mux_condition_bundle* bundle) +{ + WINPR_ASSERT(bundle); + + bundle->val = FALSE; + if (!run_mutex_init(pthread_mutex_init, &bundle->mux, NULL)) + return FALSE; + + if (!run_cond_init(pthread_cond_init, &bundle->cond, NULL)) + return FALSE; + return TRUE; +} + +static void mux_condition_bundle_uninit(mux_condition_bundle* bundle) +{ + mux_condition_bundle empty = { 0 }; + + WINPR_ASSERT(bundle); + + run_cond_fkt(pthread_cond_destroy, &bundle->cond); + run_mutex_fkt(pthread_mutex_destroy, &bundle->mux); + *bundle = empty; +} + +static BOOL mux_condition_bundle_signal(mux_condition_bundle* bundle) +{ + BOOL rc = TRUE; + WINPR_ASSERT(bundle); + + if (!run_mutex_fkt(pthread_mutex_lock, &bundle->mux)) + return FALSE; + bundle->val = TRUE; + if (!run_cond_fkt(pthread_cond_signal, &bundle->cond)) + rc = FALSE; + if (!run_mutex_fkt(pthread_mutex_checked_unlock, &bundle->mux)) + rc = FALSE; + return rc; +} + +static BOOL mux_condition_bundle_lock(mux_condition_bundle* bundle) +{ + WINPR_ASSERT(bundle); + return run_mutex_fkt(pthread_mutex_lock, &bundle->mux); +} + +static BOOL mux_condition_bundle_unlock(mux_condition_bundle* bundle) +{ + WINPR_ASSERT(bundle); + return run_mutex_fkt(pthread_mutex_checked_unlock, &bundle->mux); +} + +static BOOL mux_condition_bundle_wait(mux_condition_bundle* bundle, const char* name) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(bundle); + WINPR_ASSERT(name); + WINPR_ASSERT(pthread_mutex_trylock(&bundle->mux) == EBUSY); + + while (!bundle->val) + { + int r = pthread_cond_wait(&bundle->cond, &bundle->mux); + if (r != 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "failed to wait for %s [%s]", name, + winpr_strerror(r, ebuffer, sizeof(ebuffer))); + switch (r) + { + case ENOTRECOVERABLE: + case EPERM: + case ETIMEDOUT: + case EINVAL: + goto fail; + + default: + break; + } + } + } + + rc = bundle->val; + +fail: + return rc; +} + +static BOOL signal_thread_ready(WINPR_THREAD* thread) +{ + WINPR_ASSERT(thread); + + return mux_condition_bundle_signal(&thread->isCreated); +} + +static BOOL signal_thread_is_running(WINPR_THREAD* thread) +{ + WINPR_ASSERT(thread); + + return mux_condition_bundle_signal(&thread->isRunning); +} + +static DWORD ThreadCleanupHandle(HANDLE handle) +{ + DWORD status = WAIT_FAILED; + WINPR_THREAD* thread = (WINPR_THREAD*)handle; + + if (!ThreadIsHandled(handle)) + return WAIT_FAILED; + + if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex)) + return WAIT_FAILED; + + if (!thread->joined) + { + int rc = pthread_join(thread->thread, NULL); + + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pthread_join failure: [%d] %s", rc, + winpr_strerror(rc, ebuffer, sizeof(ebuffer))); + goto fail; + } + else + thread->joined = TRUE; + } + + status = WAIT_OBJECT_0; + +fail: + if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex)) + return WAIT_FAILED; + + return status; +} + +static HANDLE_OPS ops = { ThreadIsHandled, + ThreadCloseHandle, + ThreadGetFd, + ThreadCleanupHandle, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL }; + +static void dump_thread(WINPR_THREAD* thread) +{ +#if defined(WITH_DEBUG_THREADS) + void* stack = winpr_backtrace(20); + char** msg = NULL; + size_t used = 0; + WLog_DBG(TAG, "Called from:"); + msg = winpr_backtrace_symbols(stack, &used); + + for (size_t i = 0; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); + winpr_backtrace_free(stack); + WLog_DBG(TAG, "Thread handle created still not closed!"); + msg = winpr_backtrace_symbols(thread->create_stack, &used); + + for (size_t i = 0; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); + + if (thread->started) + { + WLog_DBG(TAG, "Thread still running!"); + } + else if (!thread->exit_stack) + { + WLog_DBG(TAG, "Thread suspended."); + } + else + { + WLog_DBG(TAG, "Thread exited at:"); + msg = winpr_backtrace_symbols(thread->exit_stack, &used); + + for (size_t i = 0; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); + } +#else + WINPR_UNUSED(thread); +#endif +} + +/** + * TODO: implement thread suspend/resume using pthreads + * http://stackoverflow.com/questions/3140867/suspend-pthreads-without-using-condition + */ +static BOOL set_event(WINPR_THREAD* thread) +{ + return winpr_event_set(&thread->event); +} + +static BOOL reset_event(WINPR_THREAD* thread) +{ + return winpr_event_reset(&thread->event); +} + +#if defined(WITH_THREAD_LIST) +static BOOL thread_compare(const void* a, const void* b) +{ + const pthread_t* p1 = a; + const pthread_t* p2 = b; + BOOL rc = pthread_equal(*p1, *p2); + return rc; +} +#endif + +static INIT_ONCE threads_InitOnce = INIT_ONCE_STATIC_INIT; +static pthread_t mainThreadId; +static DWORD currentThreadTlsIndex = TLS_OUT_OF_INDEXES; + +static BOOL initializeThreads(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context) +{ + if (!apc_init(&mainThread.apc)) + { + WLog_ERR(TAG, "failed to initialize APC"); + goto out; + } + + mainThread.common.Type = HANDLE_TYPE_THREAD; + mainThreadId = pthread_self(); + + currentThreadTlsIndex = TlsAlloc(); + if (currentThreadTlsIndex == TLS_OUT_OF_INDEXES) + { + WLog_ERR(TAG, "Major bug, unable to allocate a TLS value for currentThread"); + } + +#if defined(WITH_THREAD_LIST) + thread_list = ListDictionary_New(TRUE); + + if (!thread_list) + { + WLog_ERR(TAG, "Couldn't create global thread list"); + goto error_thread_list; + } + + thread_list->objectKey.fnObjectEquals = thread_compare; +#endif + +out: + return TRUE; +} + +static BOOL signal_and_wait_for_ready(WINPR_THREAD* thread) +{ + BOOL res = FALSE; + + WINPR_ASSERT(thread); + + if (!mux_condition_bundle_lock(&thread->isRunning)) + return FALSE; + + if (!signal_thread_ready(thread)) + goto fail; + + if (!mux_condition_bundle_wait(&thread->isRunning, "threadIsRunning")) + goto fail; + +#if defined(WITH_THREAD_LIST) + if (!ListDictionary_Contains(thread_list, &thread->thread)) + { + WLog_ERR(TAG, "Thread not in thread_list, startup failed!"); + goto fail; + } +#endif + + res = TRUE; + +fail: + if (!mux_condition_bundle_unlock(&thread->isRunning)) + return FALSE; + + return res; +} + +/* Thread launcher function responsible for registering + * cleanup handlers and calling pthread_exit, if not done + * in thread function. */ +static void* thread_launcher(void* arg) +{ + DWORD rc = 0; + WINPR_THREAD* thread = (WINPR_THREAD*)arg; + LPTHREAD_START_ROUTINE fkt = NULL; + + if (!thread) + { + WLog_ERR(TAG, "Called with invalid argument %p", arg); + goto exit; + } + + if (!TlsSetValue(currentThreadTlsIndex, thread)) + { + WLog_ERR(TAG, "thread %d, unable to set current thread value", pthread_self()); + goto exit; + } + + if (!(fkt = thread->lpStartAddress)) + { + union + { + LPTHREAD_START_ROUTINE fkt; + void* pv; + } cnv; + cnv.fkt = fkt; + WLog_ERR(TAG, "Thread function argument is %p", cnv.pv); + goto exit; + } + + if (!signal_and_wait_for_ready(thread)) + goto exit; + + rc = fkt(thread->lpParameter); +exit: + + if (thread) + { + apc_cleanupThread(thread); + + if (!thread->exited) + thread->dwExitCode = rc; + + set_event(thread); + + (void)signal_thread_ready(thread); + + if (thread->detached || !thread->started) + cleanup_handle(thread); + } + + return NULL; +} + +static BOOL winpr_StartThread(WINPR_THREAD* thread) +{ + BOOL rc = FALSE; + BOOL locked = FALSE; + pthread_attr_t attr = { 0 }; + + if (!mux_condition_bundle_lock(&thread->isCreated)) + return FALSE; + locked = TRUE; + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + + if (thread->dwStackSize > 0) + pthread_attr_setstacksize(&attr, thread->dwStackSize); + + thread->started = TRUE; + reset_event(thread); + +#if defined(WITH_THREAD_LIST) + if (!ListDictionary_Add(thread_list, &thread->thread, thread)) + { + WLog_ERR(TAG, "failed to add the thread to the thread list"); + goto error; + } +#endif + + if (pthread_create(&thread->thread, &attr, thread_launcher, thread)) + goto error; + + if (!mux_condition_bundle_wait(&thread->isCreated, "threadIsCreated")) + goto error; + + locked = FALSE; + if (!mux_condition_bundle_unlock(&thread->isCreated)) + goto error; + + if (!signal_thread_is_running(thread)) + { + WLog_ERR(TAG, "failed to signal the thread was ready"); + goto error; + } + + rc = TRUE; +error: + if (locked) + { + if (!mux_condition_bundle_unlock(&thread->isCreated)) + rc = FALSE; + } + + pthread_attr_destroy(&attr); + + if (rc) + dump_thread(thread); + + return rc; +} + +BOOL SetThreadPriority(HANDLE hThread, int nPriority) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + + if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD) + return FALSE; + + const int min = 19; + const int max = 0; + const int diff = (max - min); + const int normal = min + diff / 2; + const int off = MIN(1, diff / 4); + int sched_priority = -1; + + switch (nPriority & ~(THREAD_MODE_BACKGROUND_BEGIN | THREAD_MODE_BACKGROUND_END)) + { + case THREAD_PRIORITY_ABOVE_NORMAL: + sched_priority = MIN(normal + off, max); + break; + case THREAD_PRIORITY_BELOW_NORMAL: + sched_priority = MAX(normal - off, min); + break; + case THREAD_PRIORITY_HIGHEST: + sched_priority = max; + break; + case THREAD_PRIORITY_IDLE: + sched_priority = min; + break; + case THREAD_PRIORITY_LOWEST: + sched_priority = min; + break; + case THREAD_PRIORITY_TIME_CRITICAL: + sched_priority = max; + break; + default: + case THREAD_PRIORITY_NORMAL: + sched_priority = normal; + break; + } +#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) && defined(PTHREAD_SETSCHEDPRIO) + WINPR_THREAD* thread = (WINPR_THREAD*)Object; + const int rc = pthread_setschedprio(thread->thread, sched_priority); + if (rc != 0) + { + char buffer[256] = { 0 }; + WLog_ERR(TAG, "pthread_setschedprio(%d) %s [%d]", sched_priority, + winpr_strerror(rc, buffer, sizeof(buffer)), rc); + } + return rc == 0; +#else + WLog_WARN(TAG, "pthread_setschedprio(%d) not implemented, requires POSIX 2008 or later", + sched_priority); + return TRUE; +#endif +} + +HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, size_t dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, + DWORD dwCreationFlags, LPDWORD lpThreadId) +{ + HANDLE handle = NULL; + WINPR_THREAD* thread = (WINPR_THREAD*)calloc(1, sizeof(WINPR_THREAD)); + + if (!thread) + return NULL; + + thread->dwStackSize = dwStackSize; + thread->lpParameter = lpParameter; + thread->lpStartAddress = lpStartAddress; + thread->lpThreadAttributes = lpThreadAttributes; + thread->common.ops = &ops; +#if defined(WITH_DEBUG_THREADS) + thread->create_stack = winpr_backtrace(20); + dump_thread(thread); +#endif + + if (!winpr_event_init(&thread->event)) + { + WLog_ERR(TAG, "failed to create event"); + goto fail; + } + + if (!run_mutex_init(pthread_mutex_init, &thread->mutex, NULL)) + { + WLog_ERR(TAG, "failed to initialize thread mutex"); + goto fail; + } + + if (!apc_init(&thread->apc)) + { + WLog_ERR(TAG, "failed to initialize APC"); + goto fail; + } + + if (!mux_condition_bundle_init(&thread->isCreated)) + goto fail; + if (!mux_condition_bundle_init(&thread->isRunning)) + goto fail; + + WINPR_HANDLE_SET_TYPE_AND_MODE(thread, HANDLE_TYPE_THREAD, WINPR_FD_READ); + handle = (HANDLE)thread; + + InitOnceExecuteOnce(&threads_InitOnce, initializeThreads, NULL, NULL); + + if (!(dwCreationFlags & CREATE_SUSPENDED)) + { + if (!winpr_StartThread(thread)) + goto fail; + } + else + { + if (!set_event(thread)) + goto fail; + } + + return handle; +fail: + cleanup_handle(thread); + return NULL; +} + +void cleanup_handle(void* obj) +{ + WINPR_THREAD* thread = (WINPR_THREAD*)obj; + if (!thread) + return; + + if (!apc_uninit(&thread->apc)) + WLog_ERR(TAG, "failed to destroy APC"); + + mux_condition_bundle_uninit(&thread->isCreated); + mux_condition_bundle_uninit(&thread->isRunning); + run_mutex_fkt(pthread_mutex_destroy, &thread->mutex); + + winpr_event_uninit(&thread->event); + +#if defined(WITH_THREAD_LIST) + ListDictionary_Remove(thread_list, &thread->thread); +#endif +#if defined(WITH_DEBUG_THREADS) + + if (thread->create_stack) + winpr_backtrace_free(thread->create_stack); + + if (thread->exit_stack) + winpr_backtrace_free(thread->exit_stack); + +#endif + free(thread); +} + +BOOL ThreadCloseHandle(HANDLE handle) +{ + WINPR_THREAD* thread = (WINPR_THREAD*)handle; + +#if defined(WITH_THREAD_LIST) + if (!thread_list) + { + WLog_ERR(TAG, "Thread list does not exist, check call!"); + dump_thread(thread); + } + else if (!ListDictionary_Contains(thread_list, &thread->thread)) + { + WLog_ERR(TAG, "Thread list does not contain this thread! check call!"); + dump_thread(thread); + } + else + { + ListDictionary_Lock(thread_list); +#endif + dump_thread(thread); + + if ((thread->started) && (WaitForSingleObject(thread, 0) != WAIT_OBJECT_0)) + { + WLog_DBG(TAG, "Thread running, setting to detached state!"); + thread->detached = TRUE; + pthread_detach(thread->thread); + } + else + { + cleanup_handle(thread); + } + +#if defined(WITH_THREAD_LIST) + ListDictionary_Unlock(thread_list); + } +#endif + + return TRUE; +} + +HANDLE CreateRemoteThread(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, + size_t dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) +{ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return NULL; +} + +VOID ExitThread(DWORD dwExitCode) +{ +#if defined(WITH_THREAD_LIST) + DWORD rc; + pthread_t tid = pthread_self(); + + if (!thread_list) + { + WLog_ERR(TAG, "function called without existing thread list!"); +#if defined(WITH_DEBUG_THREADS) + DumpThreadHandles(); +#endif + pthread_exit(0); + } + else if (!ListDictionary_Contains(thread_list, &tid)) + { + WLog_ERR(TAG, "function called, but no matching entry in thread list!"); +#if defined(WITH_DEBUG_THREADS) + DumpThreadHandles(); +#endif + pthread_exit(0); + } + else + { + WINPR_THREAD* thread; + ListDictionary_Lock(thread_list); + thread = ListDictionary_GetItemValue(thread_list, &tid); + WINPR_ASSERT(thread); + thread->exited = TRUE; + thread->dwExitCode = dwExitCode; +#if defined(WITH_DEBUG_THREADS) + thread->exit_stack = winpr_backtrace(20); +#endif + ListDictionary_Unlock(thread_list); + set_event(thread); + rc = thread->dwExitCode; + + if (thread->detached || !thread->started) + cleanup_handle(thread); + + pthread_exit((void*)(size_t)rc); + } +#else + WINPR_UNUSED(dwExitCode); +#endif +} + +BOOL GetExitCodeThread(HANDLE hThread, LPDWORD lpExitCode) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_THREAD* thread = NULL; + + if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD) + { + WLog_ERR(TAG, "hThread is not a thread"); + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + thread = (WINPR_THREAD*)Object; + *lpExitCode = thread->dwExitCode; + return TRUE; +} + +WINPR_THREAD* winpr_GetCurrentThread(VOID) +{ + WINPR_THREAD* ret = NULL; + + InitOnceExecuteOnce(&threads_InitOnce, initializeThreads, NULL, NULL); + if (mainThreadId == pthread_self()) + return (HANDLE)&mainThread; + + ret = TlsGetValue(currentThreadTlsIndex); + return ret; +} + +HANDLE _GetCurrentThread(VOID) +{ + return (HANDLE)winpr_GetCurrentThread(); +} + +DWORD GetCurrentThreadId(VOID) +{ + pthread_t tid = pthread_self(); + /* Since pthread_t can be 64-bits on some systems, take just the */ + /* lower 32-bits of it for the thread ID returned by this function. */ + uintptr_t ptid = WINPR_REINTERPRET_CAST(tid, pthread_t, uintptr_t); + return ptid & UINT32_MAX; +} + +typedef struct +{ + WINPR_APC_ITEM apc; + PAPCFUNC completion; + ULONG_PTR completionArg; +} UserApcItem; + +static void userAPC(LPVOID arg) +{ + UserApcItem* userApc = (UserApcItem*)arg; + + userApc->completion(userApc->completionArg); + + userApc->apc.markedForRemove = TRUE; +} + +DWORD QueueUserAPC(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_APC_ITEM* apc = NULL; + UserApcItem* apcItem = NULL; + + if (!pfnAPC) + return 1; + + if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD) + { + WLog_ERR(TAG, "hThread is not a thread"); + SetLastError(ERROR_INVALID_PARAMETER); + return (DWORD)0; + } + + apcItem = calloc(1, sizeof(*apcItem)); + if (!apcItem) + { + SetLastError(ERROR_INVALID_PARAMETER); + return (DWORD)0; + } + + apc = &apcItem->apc; + apc->type = APC_TYPE_USER; + apc->markedForFree = TRUE; + apc->alwaysSignaled = TRUE; + apc->completion = userAPC; + apc->completionArgs = apc; + apcItem->completion = pfnAPC; + apcItem->completionArg = dwData; + apc_register(hThread, apc); + return 1; +} + +DWORD ResumeThread(HANDLE hThread) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_THREAD* thread = NULL; + + if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD) + { + WLog_ERR(TAG, "hThread is not a thread"); + SetLastError(ERROR_INVALID_PARAMETER); + return (DWORD)-1; + } + + thread = (WINPR_THREAD*)Object; + + if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex)) + return (DWORD)-1; + + if (!thread->started) + { + if (!winpr_StartThread(thread)) + { + run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex); + return (DWORD)-1; + } + } + else + WLog_WARN(TAG, "Thread already started!"); + + if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex)) + return (DWORD)-1; + + return 0; +} + +DWORD SuspendThread(HANDLE hThread) +{ + WLog_ERR(TAG, "not implemented"); + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + return (DWORD)-1; +} + +BOOL SwitchToThread(VOID) +{ + /** + * Note: on some operating systems sched_yield is a stub returning -1. + * usleep should at least trigger a context switch if any thread is waiting. + */ + if (sched_yield() != 0) + usleep(1); + + return TRUE; +} + +BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode) +{ + ULONG Type = 0; + WINPR_HANDLE* Object = NULL; + WINPR_THREAD* thread = NULL; + + if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD) + return FALSE; + + thread = (WINPR_THREAD*)Object; + thread->exited = TRUE; + thread->dwExitCode = dwExitCode; + + if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex)) + return FALSE; + +#ifndef ANDROID + pthread_cancel(thread->thread); +#else + WLog_ERR(TAG, "Function not supported on this platform!"); +#endif + + if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex)) + return FALSE; + + set_event(thread); + return TRUE; +} + +VOID DumpThreadHandles(void) +{ +#if defined(WITH_DEBUG_THREADS) + char** msg = NULL; + size_t used = 0; + void* stack = winpr_backtrace(20); + WLog_DBG(TAG, "---------------- Called from ----------------------------"); + msg = winpr_backtrace_symbols(stack, &used); + + for (size_t i = 0; i < used; i++) + { + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + } + + free(msg); + winpr_backtrace_free(stack); + WLog_DBG(TAG, "---------------- Start Dumping thread handles -----------"); + +#if defined(WITH_THREAD_LIST) + if (!thread_list) + { + WLog_DBG(TAG, "All threads properly shut down and disposed of."); + } + else + { + ULONG_PTR* keys = NULL; + ListDictionary_Lock(thread_list); + int x, count = ListDictionary_GetKeys(thread_list, &keys); + WLog_DBG(TAG, "Dumping %d elements", count); + + for (size_t x = 0; x < count; x++) + { + WINPR_THREAD* thread = ListDictionary_GetItemValue(thread_list, (void*)keys[x]); + WLog_DBG(TAG, "Thread [%d] handle created still not closed!", x); + msg = winpr_backtrace_symbols(thread->create_stack, &used); + + for (size_t i = 0; i < used; i++) + { + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + } + + free(msg); + + if (thread->started) + { + WLog_DBG(TAG, "Thread [%d] still running!", x); + } + else + { + WLog_DBG(TAG, "Thread [%d] exited at:", x); + msg = winpr_backtrace_symbols(thread->exit_stack, &used); + + for (size_t i = 0; i < used; i++) + WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]); + + free(msg); + } + } + + free(keys); + ListDictionary_Unlock(thread_list); + } +#endif + + WLog_DBG(TAG, "---------------- End Dumping thread handles -------------"); +#endif +} +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.h new file mode 100644 index 0000000000000000000000000000000000000000..d6a9009c3a91b2e03ca69ad5ab3b8e5c448a924a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/thread.h @@ -0,0 +1,85 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2015 Hewlett-Packard Development Company, L.P. + * Copyright 2021 David Fort + * + * 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_PRIVATE_H +#define WINPR_THREAD_PRIVATE_H + +#ifndef _WIN32 + +#include + +#include + +#include "../handle/handle.h" +#include "../synch/event.h" +#include "apc.h" + +typedef void* (*pthread_start_routine)(void*); +typedef struct winpr_APC_item WINPR_APC_ITEM; + +typedef struct +{ + WINPR_ALIGN64 pthread_mutex_t mux; + WINPR_ALIGN64 pthread_cond_t cond; + WINPR_ALIGN64 BOOL val; +} mux_condition_bundle; + +struct winpr_thread +{ + WINPR_HANDLE common; + + WINPR_ALIGN64 BOOL started; + WINPR_ALIGN64 WINPR_EVENT_IMPL event; + WINPR_ALIGN64 BOOL mainProcess; + WINPR_ALIGN64 BOOL detached; + WINPR_ALIGN64 BOOL joined; + WINPR_ALIGN64 BOOL exited; + WINPR_ALIGN64 DWORD dwExitCode; + WINPR_ALIGN64 pthread_t thread; + WINPR_ALIGN64 size_t dwStackSize; + WINPR_ALIGN64 LPVOID lpParameter; + WINPR_ALIGN64 pthread_mutex_t mutex; + mux_condition_bundle isRunning; + mux_condition_bundle isCreated; + WINPR_ALIGN64 LPTHREAD_START_ROUTINE lpStartAddress; + WINPR_ALIGN64 LPSECURITY_ATTRIBUTES lpThreadAttributes; + WINPR_ALIGN64 APC_QUEUE apc; +#if defined(WITH_DEBUG_THREADS) + WINPR_ALIGN64 void* create_stack; + WINPR_ALIGN64 void* exit_stack; +#endif +}; + +WINPR_THREAD* winpr_GetCurrentThread(VOID); + +typedef struct +{ + WINPR_HANDLE common; + + pid_t pid; + int status; + DWORD dwExitCode; + int fd; +} WINPR_PROCESS; + +#endif + +#endif /* WINPR_THREAD_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/tls.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/tls.c new file mode 100644 index 0000000000000000000000000000000000000000..977d47d2a7180d627e8d32310bfeee3c1fb16e76 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/thread/tls.c @@ -0,0 +1,72 @@ +/** + * WinPR: Windows Portable Runtime + * Process Thread Functions + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +/** + * TlsAlloc + * TlsFree + * TlsGetValue + * TlsSetValue + */ + +#ifndef _WIN32 + +#include + +DWORD TlsAlloc(void) +{ + pthread_key_t key = 0; + + if (pthread_key_create(&key, NULL) != 0) + return TLS_OUT_OF_INDEXES; + + return key; +} + +LPVOID TlsGetValue(DWORD dwTlsIndex) +{ + LPVOID value = NULL; + pthread_key_t key = 0; + key = (pthread_key_t)dwTlsIndex; + value = (LPVOID)pthread_getspecific(key); + return value; +} + +BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) +{ + pthread_key_t key = 0; + key = (pthread_key_t)dwTlsIndex; + pthread_setspecific(key, lpTlsValue); + return TRUE; +} + +BOOL TlsFree(DWORD dwTlsIndex) +{ + pthread_key_t key = 0; + key = (pthread_key_t)dwTlsIndex; + pthread_key_delete(key); + return TRUE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7012b95bf63f61c3280dca38d2e9c74ea2a5d629 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/CMakeLists.txt @@ -0,0 +1,59 @@ +# WinPR: Windows Portable Runtime +# libwinpr-timezone cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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. + +option(WITH_TIMEZONE_COMPILED "Use compiled in timezone definitions" ON) +if(WITH_TIMEZONE_COMPILED) + winpr_definition_add(WITH_TIMEZONE_COMPILED) +endif() + +include(CMakeDependentOption) +cmake_dependent_option(WITH_TIMEZONE_FROM_FILE "Use timezone definitions from JSON file" OFF WITH_WINPR_JSON OFF) +if(WITH_TIMEZONE_FROM_FILE) + + winpr_definition_add(WINPR_RESOURCE_ROOT="${WINPR_RESOURCE_ROOT}") + winpr_definition_add(WITH_TIMEZONE_FROM_FILE) + + install(FILES TimeZoneNameMap.json DESTINATION ${WINPR_RESOURCE_ROOT}) +endif() + +set(SRCS TimeZoneNameMapUtils.c TimeZoneNameMap.h timezone.c timezone.h) +if(WITH_TIMEZONE_COMPILED) + list(APPEND SRCS TimeZoneNameMap_static.h) +endif() + +if(NOT WIN32) + list(APPEND SRCS TimeZoneIanaAbbrevMap.c TimeZoneIanaAbbrevMap.h) +endif() + +option(WITH_TIMEZONE_ICU "Use ICU for improved timezone mapping" OFF) +if(WITH_TIMEZONE_ICU) + find_package(ICU COMPONENTS i18n uc REQUIRED) + winpr_system_include_directory_add(${ICU_INCLUDE_DIRS}) + winpr_library_add_private(${ICU_LIBRARIES}) + winpr_definition_add(WITH_TIMEZONE_ICU) +else() + list(APPEND SRCS WindowsZones.c WindowsZones.h) +endif() + +winpr_module_add(${SRCS}) + +if(WIN32) + option(WITH_TIMEZONE_UPDATER "Build C# tzextract" OFF) + if(WITH_TIMEZONE_UPDATER) + add_subdirectory(utils) + endif() +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..b6f1aed2e6817f053ccde6736797868abc6cf50b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/ModuleOptions.cmake @@ -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 "timezone") +set(MINWIN_LONG_NAME "Time Zone Functions") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.c new file mode 100644 index 0000000000000000000000000000000000000000..3346c3ad08c3a406a82ee3c90537549a62f5de80 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.c @@ -0,0 +1,260 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone + * + * Copyright 2024 Armin Novak + * 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 "TimeZoneIanaAbbrevMap.h" + +#include +#include +#include +#include +#include + +#include +#include "timezone.h" + +typedef struct +{ + char* Iana; + char* Abbrev; +} TimeZoneInanaAbbrevMapEntry; + +const static char* zonepath = "/usr/share/zoneinfo"; + +static TimeZoneInanaAbbrevMapEntry* TimeZoneIanaAbbrevMap = NULL; +static size_t TimeZoneIanaAbbrevMapSize = 0; + +static void append(const char* iana, const char* sname) +{ + const size_t size = TimeZoneIanaAbbrevMapSize + 1; + + TimeZoneInanaAbbrevMapEntry* tmp = + realloc(TimeZoneIanaAbbrevMap, size * sizeof(TimeZoneInanaAbbrevMapEntry)); + if (!tmp) + return; + TimeZoneIanaAbbrevMap = tmp; + TimeZoneIanaAbbrevMapSize = size; + + TimeZoneInanaAbbrevMapEntry* cur = &TimeZoneIanaAbbrevMap[size - 1]; + cur->Abbrev = _strdup(sname); + cur->Iana = _strdup(iana); +} + +static void append_timezone(const char* dir, const char* name) +{ + char* tz = NULL; + if (!dir && !name) + return; + if (!dir) + { + size_t len = 0; + winpr_asprintf(&tz, &len, "%s", name); + } + else + { + size_t len = 0; + winpr_asprintf(&tz, &len, "%s/%s", dir, name); + } + if (!tz) + return; + + char* oldtz = setNewAndSaveOldTZ(tz); + + const time_t t = time(NULL); + struct tm lt = { 0 }; + (void)localtime_r(&t, <); + append(tz, lt.tm_zone); + restoreSavedTZ(oldtz); + free(tz); +} + +static void handle_link(const char* base, const char* dir, const char* name); + +static char* topath(const char* base, const char* bname, const char* name) +{ + size_t plen = 0; + char* path = NULL; + + if (!base && !bname && !name) + return NULL; + + if (!base && !name) + return _strdup(bname); + + if (!bname && !name) + return _strdup(base); + + if (!base && !bname) + return _strdup(name); + + if (!base) + winpr_asprintf(&path, &plen, "%s/%s", bname, name); + else if (!bname) + winpr_asprintf(&path, &plen, "%s/%s", base, name); + else if (!name) + winpr_asprintf(&path, &plen, "%s/%s", base, bname); + else + winpr_asprintf(&path, &plen, "%s/%s/%s", base, bname, name); + return path; +} + +static void iterate_subdir_recursive(const char* base, const char* bname, const char* name) +{ + char* path = topath(base, bname, name); + if (!path) + return; + + DIR* d = opendir(path); + if (d) + { + struct dirent* dp = NULL; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + while ((dp = readdir(d)) != NULL) + { + switch (dp->d_type) + { + case DT_DIR: + { + if (strcmp(dp->d_name, ".") == 0) + continue; + if (strcmp(dp->d_name, "..") == 0) + continue; + iterate_subdir_recursive(path, dp->d_name, NULL); + } + break; + case DT_LNK: + handle_link(base, bname, dp->d_name); + break; + case DT_REG: + append_timezone(bname, dp->d_name); + break; + default: + break; + } + } + closedir(d); + } + free(path); +} + +static char* get_link_target(const char* base, const char* dir, const char* name) +{ + char* apath = NULL; + char* path = topath(base, dir, name); + if (!path) + return NULL; + + SSIZE_T rc = -1; + size_t size = 0; + char* target = NULL; + do + { + size += 64; + char* tmp = realloc(target, size + 1); + if (!tmp) + goto fail; + + target = tmp; + + memset(target, 0, size + 1); + rc = readlink(path, target, size); + if (rc < 0) + goto fail; + } while ((size_t)rc >= size); + + apath = topath(base, dir, target); +fail: + free(target); + free(path); + return apath; +} + +void handle_link(const char* base, const char* dir, const char* name) +{ + int isDir = -1; + + char* target = get_link_target(base, dir, name); + if (target) + { + struct stat s = { 0 }; + const int rc3 = stat(target, &s); + if (rc3 == 0) + isDir = S_ISDIR(s.st_mode); + + free(target); + } + + switch (isDir) + { + case 1: + iterate_subdir_recursive(base, dir, name); + break; + case 0: + append_timezone(dir, name); + break; + default: + break; + } +} + +static void TimeZoneIanaAbbrevCleanup(void) +{ + if (!TimeZoneIanaAbbrevMap) + return; + + for (size_t x = 0; x < TimeZoneIanaAbbrevMapSize; x++) + { + TimeZoneInanaAbbrevMapEntry* entry = &TimeZoneIanaAbbrevMap[x]; + free(entry->Iana); + free(entry->Abbrev); + } + free(TimeZoneIanaAbbrevMap); + TimeZoneIanaAbbrevMap = NULL; + TimeZoneIanaAbbrevMapSize = 0; +} + +static void TimeZoneIanaAbbrevInitialize(void) +{ + static BOOL initialized = FALSE; + if (initialized) + return; + + iterate_subdir_recursive(zonepath, NULL, NULL); + (void)atexit(TimeZoneIanaAbbrevCleanup); + initialized = TRUE; +} + +size_t TimeZoneIanaAbbrevGet(const char* abbrev, const char** list, size_t listsize) +{ + TimeZoneIanaAbbrevInitialize(); + + size_t rc = 0; + for (size_t x = 0; x < TimeZoneIanaAbbrevMapSize; x++) + { + const TimeZoneInanaAbbrevMapEntry* entry = &TimeZoneIanaAbbrevMap[x]; + if (strcmp(abbrev, entry->Abbrev) == 0) + { + if (listsize > rc) + list[rc] = entry->Iana; + rc++; + } + } + + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.h new file mode 100644 index 0000000000000000000000000000000000000000..c331d1aa15403d037943dd8396d570e8882e9e18 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneIanaAbbrevMap.h @@ -0,0 +1,36 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone + * + * Copyright 2024 Armin Novak + * 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_TIMEZONE_IANA_ABBREV +#define WINPR_TIMEZONE_IANA_ABBREV + +#include + +/**! \brief returns a list of IANA names for a short timezone name + * + * \param abbrev The short name to look for + * \param list The list to hold the const IANA names + * \param listsize The size of the \b list. Set to 0 to only get the required size. + * + * \return The number of mappings found + */ +size_t TimeZoneIanaAbbrevGet(const char* abbrev, const char** list, size_t listsize); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap.h new file mode 100644 index 0000000000000000000000000000000000000000..60841ad9095ebd390ac5a9a0d3da9a9ec8acf06a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap.h @@ -0,0 +1,47 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone Name Map + * + * Copyright 2024 Armin Novak + * 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_TIME_NAME_MAP_H_ +#define WINPR_TIME_NAME_MAP_H_ + +#include + +typedef enum +{ + TIME_ZONE_NAME_ID, + TIME_ZONE_NAME_STANDARD, + TIME_ZONE_NAME_DISPLAY, + TIME_ZONE_NAME_DAYLIGHT, + TIME_ZONE_NAME_IANA, +} TimeZoneNameType; + +typedef struct +{ + char* Id; + char* StandardName; + char* DisplayName; + char* DaylightName; + char* Iana; +} TimeZoneNameMapEntry; + +const TimeZoneNameMapEntry* TimeZoneGetAt(size_t index); +const char* TimeZoneIanaToWindows(const char* iana, TimeZoneNameType type); + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMapUtils.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMapUtils.c new file mode 100644 index 0000000000000000000000000000000000000000..beddc595584eccd0fd75b0a19473b86e0c6c9031 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMapUtils.c @@ -0,0 +1,452 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone Name Map Utils + * + * Copyright 2024 Armin Novak + * 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 +#include +#include +#include +#include +#include +#include + +#include "../log.h" + +#include + +#define TAG WINPR_TAG("timezone.utils") + +#if defined(WITH_TIMEZONE_ICU) +#include +#else +#include "WindowsZones.h" +#endif + +#include "TimeZoneNameMap.h" + +#if defined(WITH_TIMEZONE_COMPILED) +#include "TimeZoneNameMap_static.h" +#endif + +typedef struct +{ + size_t count; + TimeZoneNameMapEntry* entries; +} TimeZoneNameMapContext; + +static TimeZoneNameMapContext tz_context = { 0 }; + +static void tz_entry_free(TimeZoneNameMapEntry* entry) +{ + if (!entry) + return; + free(entry->DaylightName); + free(entry->DisplayName); + free(entry->Iana); + free(entry->Id); + free(entry->StandardName); + + const TimeZoneNameMapEntry empty = { 0 }; + *entry = empty; +} + +static TimeZoneNameMapEntry tz_entry_clone(const TimeZoneNameMapEntry* entry) +{ + TimeZoneNameMapEntry clone = { 0 }; + if (!entry) + return clone; + + if (entry->DaylightName) + clone.DaylightName = _strdup(entry->DaylightName); + if (entry->DisplayName) + clone.DisplayName = _strdup(entry->DisplayName); + if (entry->Iana) + clone.Iana = _strdup(entry->Iana); + if (entry->Id) + clone.Id = _strdup(entry->Id); + if (entry->StandardName) + clone.StandardName = _strdup(entry->StandardName); + return clone; +} + +static void tz_context_free(void) +{ + for (size_t x = 0; x < tz_context.count; x++) + tz_entry_free(&tz_context.entries[x]); + free(tz_context.entries); + tz_context.count = 0; + tz_context.entries = NULL; +} + +#if defined(WITH_TIMEZONE_FROM_FILE) && defined(WITH_WINPR_JSON) +static char* tz_get_object_str(WINPR_JSON* json, size_t pos, const char* name) +{ + WINPR_ASSERT(json); + if (!WINPR_JSON_IsObject(json) || !WINPR_JSON_HasObjectItem(json, name)) + { + WLog_WARN(TAG, "Invalid JSON entry at entry %" PRIuz ", missing an Object named '%s'", pos, + name); + return NULL; + } + WINPR_JSON* obj = WINPR_JSON_GetObjectItem(json, name); + WINPR_ASSERT(obj); + if (!WINPR_JSON_IsString(obj)) + { + WLog_WARN(TAG, + "Invalid JSON entry at entry %" PRIuz ", Object named '%s': Not of type string", + pos, name); + return NULL; + } + + const char* str = WINPR_JSON_GetStringValue(obj); + if (!str) + { + WLog_WARN(TAG, "Invalid JSON entry at entry %" PRIuz ", Object named '%s': NULL string", + pos, name); + return NULL; + } + + return _strdup(str); +} + +static BOOL tz_parse_json_entry(WINPR_JSON* json, size_t pos, TimeZoneNameMapEntry* entry) +{ + WINPR_ASSERT(entry); + if (!json || !WINPR_JSON_IsObject(json)) + { + WLog_WARN(TAG, "Invalid JSON entry at entry %" PRIuz ", expected an array", pos); + return FALSE; + } + + entry->Id = tz_get_object_str(json, pos, "Id"); + entry->StandardName = tz_get_object_str(json, pos, "StandardName"); + entry->DisplayName = tz_get_object_str(json, pos, "DisplayName"); + entry->DaylightName = tz_get_object_str(json, pos, "DaylightName"); + entry->Iana = tz_get_object_str(json, pos, "Iana"); + if (!entry->Id || !entry->StandardName || !entry->DisplayName || !entry->DaylightName || + !entry->Iana) + { + tz_entry_free(entry); + return FALSE; + } + return TRUE; +} + +static WINPR_JSON* load_timezones_from_file(const char* filename) +{ + INT64 jstrlen = 0; + char* jstr = NULL; + WINPR_JSON* json = NULL; + FILE* fp = winpr_fopen(filename, "r"); + if (!fp) + { + WLog_WARN(TAG, "Timezone resource file '%s' does not exist or is not readable", filename); + return NULL; + } + + if (_fseeki64(fp, 0, SEEK_END) < 0) + { + WLog_WARN(TAG, "Timezone resource file '%s' seek failed", filename); + goto end; + } + jstrlen = _ftelli64(fp); + if (jstrlen < 0) + { + WLog_WARN(TAG, "Timezone resource file '%s' invalid length %" PRId64, filename, jstrlen); + goto end; + } + if (_fseeki64(fp, 0, SEEK_SET) < 0) + { + WLog_WARN(TAG, "Timezone resource file '%s' seek failed", filename); + goto end; + } + + jstr = calloc(WINPR_ASSERTING_INT_CAST(size_t, jstrlen + 1), sizeof(char)); + if (!jstr) + { + WLog_WARN(TAG, "Timezone resource file '%s' failed to allocate buffer of size %" PRId64, + filename, jstrlen); + goto end; + } + + if (fread(jstr, WINPR_ASSERTING_INT_CAST(size_t, jstrlen), sizeof(char), fp) != 1) + { + WLog_WARN(TAG, "Timezone resource file '%s' failed to read buffer of size %" PRId64, + filename, jstrlen); + goto end; + } + + json = WINPR_JSON_ParseWithLength(jstr, WINPR_ASSERTING_INT_CAST(size_t, jstrlen)); + if (!json) + WLog_WARN(TAG, "Timezone resource file '%s' is not a valid JSON file", filename); +end: + fclose(fp); + free(jstr); + return json; +} +#endif + +static BOOL reallocate_context(TimeZoneNameMapContext* context, size_t size_to_add) +{ + { + TimeZoneNameMapEntry* tmp = realloc(context->entries, (context->count + size_to_add) * + sizeof(TimeZoneNameMapEntry)); + if (!tmp) + { + WLog_WARN(TAG, + "Failed to reallocate TimeZoneNameMapEntry::entries to %" PRIuz " elements", + context->count + size_to_add); + return FALSE; + } + const size_t offset = context->count; + context->entries = tmp; + context->count += size_to_add; + + memset(&context->entries[offset], 0, size_to_add * sizeof(TimeZoneNameMapEntry)); + } + return TRUE; +} + +static BOOL CALLBACK load_timezones(PINIT_ONCE once, PVOID param, PVOID* pvcontext) +{ + TimeZoneNameMapContext* context = param; + WINPR_ASSERT(context); + WINPR_UNUSED(pvcontext); + WINPR_UNUSED(once); + + const TimeZoneNameMapContext empty = { 0 }; + *context = empty; + +#if defined(WITH_TIMEZONE_FROM_FILE) && defined(WITH_WINPR_JSON) + { + WINPR_JSON* json = NULL; + char* filename = GetCombinedPath(WINPR_RESOURCE_ROOT, "TimeZoneNameMap.json"); + if (!filename) + { + WLog_WARN(TAG, "Could not create WinPR timezone resource filename"); + goto end; + } + + json = load_timezones_from_file(filename); + if (!json) + goto end; + + if (!WINPR_JSON_IsObject(json)) + { + WLog_WARN(TAG, "Invalid top level JSON type in file %s, expected an array", filename); + goto end; + } + + WINPR_JSON* obj = WINPR_JSON_GetObjectItem(json, "TimeZoneNameMap"); + if (!WINPR_JSON_IsArray(obj)) + { + WLog_WARN(TAG, "Invalid top level JSON type in file %s, expected an array", filename); + goto end; + } + const size_t count = WINPR_JSON_GetArraySize(obj); + const size_t offset = context->count; + if (!reallocate_context(context, count)) + goto end; + for (size_t x = 0; x < count; x++) + { + WINPR_JSON* entry = WINPR_JSON_GetArrayItem(obj, x); + if (!tz_parse_json_entry(entry, x, &context->entries[offset + x])) + goto end; + } + + end: + free(filename); + WINPR_JSON_Delete(json); + } +#endif + +#if defined(WITH_TIMEZONE_COMPILED) + { + const size_t offset = context->count; + if (!reallocate_context(context, TimeZoneNameMapSize)) + return FALSE; + for (size_t x = 0; x < TimeZoneNameMapSize; x++) + context->entries[offset + x] = tz_entry_clone(&TimeZoneNameMap[x]); + } +#endif + + (void)atexit(tz_context_free); + return TRUE; +} + +const TimeZoneNameMapEntry* TimeZoneGetAt(size_t index) +{ + static INIT_ONCE init_guard = INIT_ONCE_STATIC_INIT; + + InitOnceExecuteOnce(&init_guard, load_timezones, &tz_context, NULL); + if (index >= tz_context.count) + return NULL; + return &tz_context.entries[index]; +} + +static const char* return_type(const TimeZoneNameMapEntry* entry, TimeZoneNameType type) +{ + WINPR_ASSERT(entry); + switch (type) + { + case TIME_ZONE_NAME_IANA: + return entry->Iana; + case TIME_ZONE_NAME_ID: + return entry->Id; + case TIME_ZONE_NAME_STANDARD: + return entry->StandardName; + case TIME_ZONE_NAME_DISPLAY: + return entry->DisplayName; + case TIME_ZONE_NAME_DAYLIGHT: + return entry->DaylightName; + default: + return NULL; + } +} + +static BOOL iana_cmp(const TimeZoneNameMapEntry* entry, const char* iana) +{ + if (!entry || !iana || !entry->Iana) + return FALSE; + return strcmp(iana, entry->Iana) == 0; +} + +static BOOL id_cmp(const TimeZoneNameMapEntry* entry, const char* id) +{ + if (!entry || !id || !entry->Id) + return FALSE; + return strcmp(id, entry->Id) == 0; +} + +static const char* get_for_type(const char* val, TimeZoneNameType type, + BOOL (*cmp)(const TimeZoneNameMapEntry*, const char*)) +{ + WINPR_ASSERT(val); + WINPR_ASSERT(cmp); + + size_t index = 0; + while (TRUE) + { + const TimeZoneNameMapEntry* entry = TimeZoneGetAt(index++); + if (!entry) + return NULL; + if (cmp(entry, val)) + return return_type(entry, type); + } +} + +#if defined(WITH_TIMEZONE_ICU) +static char* get_wzid_icu(const UChar* utzid, size_t utzid_len) +{ + char* res = NULL; + UErrorCode error = U_ZERO_ERROR; + + int32_t rc = ucal_getWindowsTimeZoneID(utzid, WINPR_ASSERTING_INT_CAST(int32_t, utzid_len), + NULL, 0, &error); + if ((error == U_BUFFER_OVERFLOW_ERROR) && (rc > 0)) + { + rc++; // make space for '\0' + UChar* wzid = calloc((size_t)rc + 1, sizeof(UChar)); + if (wzid) + { + UErrorCode error2 = U_ZERO_ERROR; + int32_t rc2 = ucal_getWindowsTimeZoneID( + utzid, WINPR_ASSERTING_INT_CAST(int32_t, utzid_len), wzid, rc, &error2); + if (U_SUCCESS(error2) && (rc2 > 0)) + res = ConvertWCharNToUtf8Alloc(wzid, (size_t)rc, NULL); + free(wzid); + } + } + return res; +} + +static char* get(const char* iana) +{ + size_t utzid_len = 0; + UChar* utzid = ConvertUtf8ToWCharAlloc(iana, &utzid_len); + if (!utzid) + return NULL; + + char* wzid = get_wzid_icu(utzid, utzid_len); + free(utzid); + return wzid; +} + +static const char* map_fallback(const char* iana, TimeZoneNameType type) +{ + char* wzid = get(iana); + if (!wzid) + return NULL; + + const char* res = get_for_type(wzid, type, id_cmp); + free(wzid); + return res; +} +#else +static const char* map_fallback(const char* iana, TimeZoneNameType type) +{ + if (!iana) + return NULL; + + for (size_t x = 0; x < WindowsZonesNrElements; x++) + { + const WINDOWS_TZID_ENTRY* const entry = &WindowsZones[x]; + if (strchr(entry->tzid, ' ')) + { + const char* res = NULL; + char* tzid = _strdup(entry->tzid); + char* ctzid = tzid; + while (tzid) + { + char* space = strchr(tzid, ' '); + if (space) + *space++ = '\0'; + if (strcmp(tzid, iana) == 0) + { + res = entry->windows; + break; + } + tzid = space; + } + free(ctzid); + if (res) + return res; + } + else if (strcmp(entry->tzid, iana) == 0) + return entry->windows; + } + + return NULL; +} +#endif + +const char* TimeZoneIanaToWindows(const char* iana, TimeZoneNameType type) +{ + if (!iana) + return NULL; + + const char* val = get_for_type(iana, type, iana_cmp); + if (val) + return val; + + const char* wzid = map_fallback(iana, type); + if (!wzid) + return NULL; + + return get_for_type(wzid, type, id_cmp); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap_static.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap_static.h new file mode 100644 index 0000000000000000000000000000000000000000..b355baeb8e90c19b280588cfce50dcf8a7dfbc23 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/TimeZoneNameMap_static.h @@ -0,0 +1,292 @@ +/* Automatically generated by tzextract */ + +#include "TimeZoneNameMap.h" + +static const TimeZoneNameMapEntry TimeZoneNameMap[] = { + { "Dateline Standard Time", "Dateline Standard Time", + "(UTC-12:00) International Date Line West", "Dateline Daylight Time", "Etc/GMT+12" }, + { "UTC-11", "UTC-11", "(UTC-11:00) Coordinated Universal Time-11", "UTC-11", "Etc/GMT+11" }, + { "Aleutian Standard Time", "Aleutian Standard Time", "(UTC-10:00) Aleutian Islands", + "Aleutian Daylight Time", "America/Adak" }, + { "Hawaiian Standard Time", "Hawaiian Standard Time", "(UTC-10:00) Hawaii", + "Hawaiian Daylight Time", "Pacific/Honolulu" }, + { "Marquesas Standard Time", "Marquesas Standard Time", "(UTC-09:30) Marquesas Islands", + "Marquesas Daylight Time", "Pacific/Marquesas" }, + { "Alaskan Standard Time", "Alaskan Standard Time", "(UTC-09:00) Alaska", + "Alaskan Daylight Time", "America/Anchorage" }, + { "UTC-09", "UTC-09", "(UTC-09:00) Coordinated Universal Time-09", "UTC-09", "Etc/GMT+9" }, + { "Pacific Standard Time (Mexico)", "Pacific Standard Time (Mexico)", + "(UTC-08:00) Baja California", "Pacific Daylight Time (Mexico)", "America/Tijuana" }, + { "UTC-08", "UTC-08", "(UTC-08:00) Coordinated Universal Time-08", "UTC-08", "Etc/GMT+8" }, + { "Pacific Standard Time", "Pacific Standard Time", "(UTC-08:00) Pacific Time (US & Canada)", + "Pacific Daylight Time", "America/Los_Angeles" }, + { "US Mountain Standard Time", "US Mountain Standard Time", "(UTC-07:00) Arizona", + "US Mountain Daylight Time", "America/Phoenix" }, + { "Mountain Standard Time (Mexico)", "Mountain Standard Time (Mexico)", + "(UTC-07:00) La Paz, Mazatlan", "Mountain Daylight Time (Mexico)", "America/Chihuahua" }, + { "Mountain Standard Time", "Mountain Standard Time", "(UTC-07:00) Mountain Time (US & Canada)", + "Mountain Daylight Time", "America/Denver" }, + { "Yukon Standard Time", "Yukon Standard Time", "(UTC-07:00) Yukon", "Yukon Daylight Time", + "America/Whitehorse" }, + { "Central America Standard Time", "Central America Standard Time", + "(UTC-06:00) Central America", "Central America Daylight Time", "America/Guatemala" }, + { "Central Standard Time", "Central Standard Time", "(UTC-06:00) Central Time (US & Canada)", + "Central Daylight Time", "America/Chicago" }, + { "Easter Island Standard Time", "Easter Island Standard Time", "(UTC-06:00) Easter Island", + "Easter Island Daylight Time", "Pacific/Easter" }, + { "Central Standard Time (Mexico)", "Central Standard Time (Mexico)", + "(UTC-06:00) Guadalajara, Mexico City, Monterrey", "Central Daylight Time (Mexico)", + "America/Mexico_City" }, + { "Canada Central Standard Time", "Canada Central Standard Time", "(UTC-06:00) Saskatchewan", + "Canada Central Daylight Time", "America/Regina" }, + { "SA Pacific Standard Time", "SA Pacific Standard Time", + "(UTC-05:00) Bogota, Lima, Quito, Rio Branco", "SA Pacific Daylight Time", "America/Bogota" }, + { "Eastern Standard Time (Mexico)", "Eastern Standard Time (Mexico)", "(UTC-05:00) Chetumal", + "Eastern Daylight Time (Mexico)", "America/Cancun" }, + { "Eastern Standard Time", "Eastern Standard Time", "(UTC-05:00) Eastern Time (US & Canada)", + "Eastern Daylight Time", "America/New_York" }, + { "Haiti Standard Time", "Haiti Standard Time", "(UTC-05:00) Haiti", "Haiti Daylight Time", + "America/Port-au-Prince" }, + { "Cuba Standard Time", "Cuba Standard Time", "(UTC-05:00) Havana", "Cuba Daylight Time", + "America/Havana" }, + { "US Eastern Standard Time", "US Eastern Standard Time", "(UTC-05:00) Indiana (East)", + "US Eastern Daylight Time", "America/Indianapolis" }, + { "Turks And Caicos Standard Time", "Turks and Caicos Standard Time", + "(UTC-05:00) Turks and Caicos", "Turks and Caicos Daylight Time", "America/Grand_Turk" }, + { "Paraguay Standard Time", "Paraguay Standard Time", "(UTC-04:00) Asuncion", + "Paraguay Daylight Time", "America/Asuncion" }, + { "Atlantic Standard Time", "Atlantic Standard Time", "(UTC-04:00) Atlantic Time (Canada)", + "Atlantic Daylight Time", "America/Halifax" }, + { "Venezuela Standard Time", "Venezuela Standard Time", "(UTC-04:00) Caracas", + "Venezuela Daylight Time", "America/Caracas" }, + { "Central Brazilian Standard Time", "Central Brazilian Standard Time", "(UTC-04:00) Cuiaba", + "Central Brazilian Daylight Time", "America/Cuiaba" }, + { "SA Western Standard Time", "SA Western Standard Time", + "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan", "SA Western Daylight Time", + "America/La_Paz" }, + { "Pacific SA Standard Time", "Pacific SA Standard Time", "(UTC-04:00) Santiago", + "Pacific SA Daylight Time", "America/Santiago" }, + { "Newfoundland Standard Time", "Newfoundland Standard Time", "(UTC-03:30) Newfoundland", + "Newfoundland Daylight Time", "America/St_Johns" }, + { "Tocantins Standard Time", "Tocantins Standard Time", "(UTC-03:00) Araguaina", + "Tocantins Daylight Time", "America/Araguaina" }, + { "E. South America Standard Time", "E. South America Standard Time", "(UTC-03:00) Brasilia", + "E. South America Daylight Time", "America/Sao_Paulo" }, + { "SA Eastern Standard Time", "SA Eastern Standard Time", "(UTC-03:00) Cayenne, Fortaleza", + "SA Eastern Daylight Time", "America/Cayenne" }, + { "Argentina Standard Time", "Argentina Standard Time", "(UTC-03:00) City of Buenos Aires", + "Argentina Daylight Time", "America/Buenos_Aires" }, + { "Montevideo Standard Time", "Montevideo Standard Time", "(UTC-03:00) Montevideo", + "Montevideo Daylight Time", "America/Montevideo" }, + { "Magallanes Standard Time", "Magallanes Standard Time", "(UTC-03:00) Punta Arenas", + "Magallanes Daylight Time", "America/Punta_Arenas" }, + { "Saint Pierre Standard Time", "Saint Pierre Standard Time", + "(UTC-03:00) Saint Pierre and Miquelon", "Saint Pierre Daylight Time", "America/Miquelon" }, + { "Bahia Standard Time", "Bahia Standard Time", "(UTC-03:00) Salvador", "Bahia Daylight Time", + "America/Bahia" }, + { "UTC-02", "UTC-02", "(UTC-02:00) Coordinated Universal Time-02", "UTC-02", "Etc/GMT+2" }, + { "Greenland Standard Time", "Greenland Standard Time", "(UTC-02:00) Greenland", + "Greenland Daylight Time", "America/Godthab" }, + { "Mid-Atlantic Standard Time", "Mid-Atlantic Standard Time", "(UTC-02:00) Mid-Atlantic - Old", + "Mid-Atlantic Daylight Time", "" }, + { "Azores Standard Time", "Azores Standard Time", "(UTC-01:00) Azores", "Azores Daylight Time", + "Atlantic/Azores" }, + { "Cape Verde Standard Time", "Cabo Verde Standard Time", "(UTC-01:00) Cabo Verde Is.", + "Cabo Verde Daylight Time", "Atlantic/Cape_Verde" }, + { "UTC", "Coordinated Universal Time", "(UTC) Coordinated Universal Time", + "Coordinated Universal Time", "Etc/UTC" }, + { "GMT Standard Time", "GMT Standard Time", "(UTC+00:00) Dublin, Edinburgh, Lisbon, London", + "GMT Daylight Time", "Europe/London" }, + { "Greenwich Standard Time", "Greenwich Standard Time", "(UTC+00:00) Monrovia, Reykjavik", + "Greenwich Daylight Time", "Atlantic/Reykjavik" }, + { "Sao Tome Standard Time", "Sao Tome Standard Time", "(UTC+00:00) Sao Tome", + "Sao Tome Daylight Time", "Africa/Sao_Tome" }, + { "Morocco Standard Time", "Morocco Standard Time", "(UTC+01:00) Casablanca", + "Morocco Daylight Time", "Africa/Casablanca" }, + { "W. Europe Standard Time", "W. Europe Standard Time", + "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", "W. Europe Daylight Time", + "Europe/Berlin" }, + { "Central Europe Standard Time", "Central Europe Standard Time", + "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", + "Central Europe Daylight Time", "Europe/Budapest" }, + { "Romance Standard Time", "Romance Standard Time", + "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris", "Romance Daylight Time", "Europe/Paris" }, + { "Central European Standard Time", "Central European Standard Time", + "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb", "Central European Daylight Time", + "Europe/Warsaw" }, + { "W. Central Africa Standard Time", "W. Central Africa Standard Time", + "(UTC+01:00) West Central Africa", "W. Central Africa Daylight Time", "Africa/Lagos" }, + { "GTB Standard Time", "GTB Standard Time", "(UTC+02:00) Athens, Bucharest", + "GTB Daylight Time", "Europe/Bucharest" }, + { "Middle East Standard Time", "Middle East Standard Time", "(UTC+02:00) Beirut", + "Middle East Daylight Time", "Asia/Beirut" }, + { "Egypt Standard Time", "Egypt Standard Time", "(UTC+02:00) Cairo", "Egypt Daylight Time", + "Africa/Cairo" }, + { "E. Europe Standard Time", "E. Europe Standard Time", "(UTC+02:00) Chisinau", + "E. Europe Daylight Time", "Europe/Chisinau" }, + { "West Bank Standard Time", "West Bank Gaza Standard Time", "(UTC+02:00) Gaza, Hebron", + "West Bank Gaza Daylight Time", "Asia/Hebron" }, + { "South Africa Standard Time", "South Africa Standard Time", "(UTC+02:00) Harare, Pretoria", + "South Africa Daylight Time", "Africa/Johannesburg" }, + { "FLE Standard Time", "FLE Standard Time", + "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", "FLE Daylight Time", + "Europe/Kiev" }, + { "Israel Standard Time", "Jerusalem Standard Time", "(UTC+02:00) Jerusalem", + "Jerusalem Daylight Time", "Asia/Jerusalem" }, + { "South Sudan Standard Time", "South Sudan Standard Time", "(UTC+02:00) Juba", + "South Sudan Daylight Time", "" }, + { "Kaliningrad Standard Time", "Russia TZ 1 Standard Time", "(UTC+02:00) Kaliningrad", + "Russia TZ 1 Daylight Time", "Europe/Kaliningrad" }, + { "Sudan Standard Time", "Sudan Standard Time", "(UTC+02:00) Khartoum", "Sudan Daylight Time", + "Africa/Khartoum" }, + { "Libya Standard Time", "Libya Standard Time", "(UTC+02:00) Tripoli", "Libya Daylight Time", + "Africa/Tripoli" }, + { "Namibia Standard Time", "Namibia Standard Time", "(UTC+02:00) Windhoek", + "Namibia Daylight Time", "Africa/Windhoek" }, + { "Jordan Standard Time", "Jordan Standard Time", "(UTC+03:00) Amman", "Jordan Daylight Time", + "Asia/Amman" }, + { "Arabic Standard Time", "Arabic Standard Time", "(UTC+03:00) Baghdad", "Arabic Daylight Time", + "Asia/Baghdad" }, + { "Syria Standard Time", "Syria Standard Time", "(UTC+03:00) Damascus", "Syria Daylight Time", + "Asia/Damascus" }, + { "Turkey Standard Time", "Turkey Standard Time", "(UTC+03:00) Istanbul", + "Turkey Daylight Time", "Europe/Istanbul" }, + { "Arab Standard Time", "Arab Standard Time", "(UTC+03:00) Kuwait, Riyadh", + "Arab Daylight Time", "Asia/Riyadh" }, + { "Belarus Standard Time", "Belarus Standard Time", "(UTC+03:00) Minsk", + "Belarus Daylight Time", "Europe/Minsk" }, + { "Russian Standard Time", "Russia TZ 2 Standard Time", "(UTC+03:00) Moscow, St. Petersburg", + "Russia TZ 2 Daylight Time", "Europe/Moscow" }, + { "E. Africa Standard Time", "E. Africa Standard Time", "(UTC+03:00) Nairobi", + "E. Africa Daylight Time", "Africa/Nairobi" }, + { "Volgograd Standard Time", "Volgograd Standard Time", "(UTC+03:00) Volgograd", + "Volgograd Daylight Time", "Europe/Volgograd" }, + { "Iran Standard Time", "Iran Standard Time", "(UTC+03:30) Tehran", "Iran Daylight Time", + "Asia/Tehran" }, + { "Arabian Standard Time", "Arabian Standard Time", "(UTC+04:00) Abu Dhabi, Muscat", + "Arabian Daylight Time", "Asia/Dubai" }, + { "Astrakhan Standard Time", "Astrakhan Standard Time", "(UTC+04:00) Astrakhan, Ulyanovsk", + "Astrakhan Daylight Time", "Europe/Astrakhan" }, + { "Azerbaijan Standard Time", "Azerbaijan Standard Time", "(UTC+04:00) Baku", + "Azerbaijan Daylight Time", "Asia/Baku" }, + { "Russia Time Zone 3", "Russia TZ 3 Standard Time", "(UTC+04:00) Izhevsk, Samara", + "Russia TZ 3 Daylight Time", "Europe/Samara" }, + { "Mauritius Standard Time", "Mauritius Standard Time", "(UTC+04:00) Port Louis", + "Mauritius Daylight Time", "Indian/Mauritius" }, + { "Saratov Standard Time", "Saratov Standard Time", "(UTC+04:00) Saratov", + "Saratov Daylight Time", "Europe/Saratov" }, + { "Georgian Standard Time", "Georgian Standard Time", "(UTC+04:00) Tbilisi", + "Georgian Daylight Time", "Asia/Tbilisi" }, + { "Caucasus Standard Time", "Caucasus Standard Time", "(UTC+04:00) Yerevan", + "Caucasus Daylight Time", "Asia/Yerevan" }, + { "Afghanistan Standard Time", "Afghanistan Standard Time", "(UTC+04:30) Kabul", + "Afghanistan Daylight Time", "Asia/Kabul" }, + { "West Asia Standard Time", "West Asia Standard Time", "(UTC+05:00) Ashgabat, Tashkent", + "West Asia Daylight Time", "Asia/Tashkent" }, + { "Qyzylorda Standard Time", "Qyzylorda Standard Time", "(UTC+05:00) Astana", + "Qyzylorda Daylight Time", "Asia/Qyzylorda" }, + { "Ekaterinburg Standard Time", "Russia TZ 4 Standard Time", "(UTC+05:00) Ekaterinburg", + "Russia TZ 4 Daylight Time", "Asia/Yekaterinburg" }, + { "Pakistan Standard Time", "Pakistan Standard Time", "(UTC+05:00) Islamabad, Karachi", + "Pakistan Daylight Time", "Asia/Karachi" }, + { "India Standard Time", "India Standard Time", + "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", "India Daylight Time", "Asia/Calcutta" }, + { "Sri Lanka Standard Time", "Sri Lanka Standard Time", "(UTC+05:30) Sri Jayawardenepura", + "Sri Lanka Daylight Time", "Asia/Colombo" }, + { "Nepal Standard Time", "Nepal Standard Time", "(UTC+05:45) Kathmandu", "Nepal Daylight Time", + "Asia/Katmandu" }, + { "Central Asia Standard Time", "Central Asia Standard Time", "(UTC+06:00) Bishkek", + "Central Asia Daylight Time", "Asia/Almaty" }, + { "Bangladesh Standard Time", "Bangladesh Standard Time", "(UTC+06:00) Dhaka", + "Bangladesh Daylight Time", "Asia/Dhaka" }, + { "Omsk Standard Time", "Omsk Standard Time", "(UTC+06:00) Omsk", "Omsk Daylight Time", + "Asia/Omsk" }, + { "Myanmar Standard Time", "Myanmar Standard Time", "(UTC+06:30) Yangon (Rangoon)", + "Myanmar Daylight Time", "Asia/Rangoon" }, + { "SE Asia Standard Time", "SE Asia Standard Time", "(UTC+07:00) Bangkok, Hanoi, Jakarta", + "SE Asia Daylight Time", "Asia/Bangkok" }, + { "Altai Standard Time", "Altai Standard Time", "(UTC+07:00) Barnaul, Gorno-Altaysk", + "Altai Daylight Time", "Asia/Barnaul" }, + { "W. Mongolia Standard Time", "W. Mongolia Standard Time", "(UTC+07:00) Hovd", + "W. Mongolia Daylight Time", "Asia/Hovd" }, + { "North Asia Standard Time", "Russia TZ 6 Standard Time", "(UTC+07:00) Krasnoyarsk", + "Russia TZ 6 Daylight Time", "Asia/Krasnoyarsk" }, + { "N. Central Asia Standard Time", "Novosibirsk Standard Time", "(UTC+07:00) Novosibirsk", + "Novosibirsk Daylight Time", "Asia/Novosibirsk" }, + { "Tomsk Standard Time", "Tomsk Standard Time", "(UTC+07:00) Tomsk", "Tomsk Daylight Time", + "Asia/Tomsk" }, + { "China Standard Time", "China Standard Time", + "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi", "China Daylight Time", "Asia/Shanghai" }, + { "North Asia East Standard Time", "Russia TZ 7 Standard Time", "(UTC+08:00) Irkutsk", + "Russia TZ 7 Daylight Time", "Asia/Irkutsk" }, + { "Singapore Standard Time", "Malay Peninsula Standard Time", + "(UTC+08:00) Kuala Lumpur, Singapore", "Malay Peninsula Daylight Time", "Asia/Singapore" }, + { "W. Australia Standard Time", "W. Australia Standard Time", "(UTC+08:00) Perth", + "W. Australia Daylight Time", "Australia/Perth" }, + { "Taipei Standard Time", "Taipei Standard Time", "(UTC+08:00) Taipei", "Taipei Daylight Time", + "Asia/Taipei" }, + { "Ulaanbaatar Standard Time", "Ulaanbaatar Standard Time", "(UTC+08:00) Ulaanbaatar", + "Ulaanbaatar Daylight Time", "Asia/Ulaanbaatar" }, + { "Aus Central W. Standard Time", "Aus Central W. Standard Time", "(UTC+08:45) Eucla", + "Aus Central W. Daylight Time", "Australia/Eucla" }, + { "Transbaikal Standard Time", "Transbaikal Standard Time", "(UTC+09:00) Chita", + "Transbaikal Daylight Time", "Asia/Chita" }, + { "Tokyo Standard Time", "Tokyo Standard Time", "(UTC+09:00) Osaka, Sapporo, Tokyo", + "Tokyo Daylight Time", "Asia/Tokyo" }, + { "North Korea Standard Time", "North Korea Standard Time", "(UTC+09:00) Pyongyang", + "North Korea Daylight Time", "Asia/Pyongyang" }, + { "Korea Standard Time", "Korea Standard Time", "(UTC+09:00) Seoul", "Korea Daylight Time", + "Asia/Seoul" }, + { "Yakutsk Standard Time", "Russia TZ 8 Standard Time", "(UTC+09:00) Yakutsk", + "Russia TZ 8 Daylight Time", "Asia/Yakutsk" }, + { "Cen. Australia Standard Time", "Cen. Australia Standard Time", "(UTC+09:30) Adelaide", + "Cen. Australia Daylight Time", "Australia/Adelaide" }, + { "AUS Central Standard Time", "AUS Central Standard Time", "(UTC+09:30) Darwin", + "AUS Central Daylight Time", "Australia/Darwin" }, + { "E. Australia Standard Time", "E. Australia Standard Time", "(UTC+10:00) Brisbane", + "E. Australia Daylight Time", "Australia/Brisbane" }, + { "AUS Eastern Standard Time", "AUS Eastern Standard Time", + "(UTC+10:00) Canberra, Melbourne, Sydney", "AUS Eastern Daylight Time", "Australia/Sydney" }, + { "West Pacific Standard Time", "West Pacific Standard Time", "(UTC+10:00) Guam, Port Moresby", + "West Pacific Daylight Time", "Pacific/Port_Moresby" }, + { "Tasmania Standard Time", "Tasmania Standard Time", "(UTC+10:00) Hobart", + "Tasmania Daylight Time", "Australia/Hobart" }, + { "Vladivostok Standard Time", "Russia TZ 9 Standard Time", "(UTC+10:00) Vladivostok", + "Russia TZ 9 Daylight Time", "Asia/Vladivostok" }, + { "Lord Howe Standard Time", "Lord Howe Standard Time", "(UTC+10:30) Lord Howe Island", + "Lord Howe Daylight Time", "Australia/Lord_Howe" }, + { "Bougainville Standard Time", "Bougainville Standard Time", "(UTC+11:00) Bougainville Island", + "Bougainville Daylight Time", "Pacific/Bougainville" }, + { "Russia Time Zone 10", "Russia TZ 10 Standard Time", "(UTC+11:00) Chokurdakh", + "Russia TZ 10 Daylight Time", "Asia/Srednekolymsk" }, + { "Magadan Standard Time", "Magadan Standard Time", "(UTC+11:00) Magadan", + "Magadan Daylight Time", "Asia/Magadan" }, + { "Norfolk Standard Time", "Norfolk Standard Time", "(UTC+11:00) Norfolk Island", + "Norfolk Daylight Time", "Pacific/Norfolk" }, + { "Sakhalin Standard Time", "Sakhalin Standard Time", "(UTC+11:00) Sakhalin", + "Sakhalin Daylight Time", "Asia/Sakhalin" }, + { "Central Pacific Standard Time", "Central Pacific Standard Time", + "(UTC+11:00) Solomon Is., New Caledonia", "Central Pacific Daylight Time", + "Pacific/Guadalcanal" }, + { "Russia Time Zone 11", "Russia TZ 11 Standard Time", + "(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky", "Russia TZ 11 Daylight Time", + "Asia/Kamchatka" }, + { "New Zealand Standard Time", "New Zealand Standard Time", "(UTC+12:00) Auckland, Wellington", + "New Zealand Daylight Time", "Pacific/Auckland" }, + { "UTC+12", "UTC+12", "(UTC+12:00) Coordinated Universal Time+12", "UTC+12", "Etc/GMT-12" }, + { "Fiji Standard Time", "Fiji Standard Time", "(UTC+12:00) Fiji", "Fiji Daylight Time", + "Pacific/Fiji" }, + { "Kamchatka Standard Time", "Kamchatka Standard Time", + "(UTC+12:00) Petropavlovsk-Kamchatsky - Old", "Kamchatka Daylight Time", "" }, + { "Chatham Islands Standard Time", "Chatham Islands Standard Time", + "(UTC+12:45) Chatham Islands", "Chatham Islands Daylight Time", "Pacific/Chatham" }, + { "UTC+13", "UTC+13", "(UTC+13:00) Coordinated Universal Time+13", "UTC+13", "Etc/GMT-13" }, + { "Tonga Standard Time", "Tonga Standard Time", "(UTC+13:00) Nuku'alofa", "Tonga Daylight Time", + "Pacific/Tongatapu" }, + { "Samoa Standard Time", "Samoa Standard Time", "(UTC+13:00) Samoa", "Samoa Daylight Time", + "Pacific/Apia" }, + { "Line Islands Standard Time", "Line Islands Standard Time", "(UTC+14:00) Kiritimati Island", + "Line Islands Daylight Time", "Pacific/Kiritimati" } +}; + +static const size_t TimeZoneNameMapSize = ARRAYSIZE(TimeZoneNameMap); diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.c new file mode 100644 index 0000000000000000000000000000000000000000..e78b60e0f5cd2e95ac6c5904bd06ff3757788b2c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.c @@ -0,0 +1,530 @@ +/* Automatically generated by tzextract + * + * url https://raw.githubusercontent.com/unicode-org/cldr/main/common/supplemental/windowsZones.xml + * version: $Revision$ + * mapTimezones: otherVersion: 7e11800, typeVersion: 2021a + */ + +#include "WindowsZones.h" + +const WINDOWS_TZID_ENTRY WindowsZones[] = { + { "Etc/GMT+12", "Dateline Standard Time" }, // 001 + { "Etc/GMT+12", "Dateline Standard Time" }, // ZZ + { "Etc/GMT+11", "UTC-11" }, // 001 + { "Pacific/Pago_Pago", "UTC-11" }, // AS + { "Pacific/Niue", "UTC-11" }, // NU + { "Pacific/Midway", "UTC-11" }, // UM + { "Etc/GMT+11", "UTC-11" }, // ZZ + { "America/Adak", "Aleutian Standard Time" }, // 001 + { "America/Adak", "Aleutian Standard Time" }, // US + { "Pacific/Honolulu", "Hawaiian Standard Time" }, // 001 + { "Pacific/Rarotonga", "Hawaiian Standard Time" }, // CK + { "Pacific/Tahiti", "Hawaiian Standard Time" }, // PF + { "Pacific/Honolulu", "Hawaiian Standard Time" }, // US + { "Etc/GMT+10", "Hawaiian Standard Time" }, // ZZ + { "Pacific/Marquesas", "Marquesas Standard Time" }, // 001 + { "Pacific/Marquesas", "Marquesas Standard Time" }, // PF + { "America/Anchorage", "Alaskan Standard Time" }, // 001 + { "America/Anchorage America/Juneau America/Metlakatla America/Nome America/Sitka " + "America/Yakutat", + "Alaskan Standard Time" }, // US + { "Etc/GMT+9", "UTC-09" }, // 001 + { "Pacific/Gambier", "UTC-09" }, // PF + { "Etc/GMT+9", "UTC-09" }, // ZZ + { "America/Tijuana", "Pacific Standard Time (Mexico)" }, // 001 + { "America/Tijuana", "Pacific Standard Time (Mexico)" }, // MX + { "Etc/GMT+8", "UTC-08" }, // 001 + { "Pacific/Pitcairn", "UTC-08" }, // PN + { "Etc/GMT+8", "UTC-08" }, // ZZ + { "America/Los_Angeles", "Pacific Standard Time" }, // 001 + { "America/Vancouver", "Pacific Standard Time" }, // CA + { "America/Los_Angeles", "Pacific Standard Time" }, // US + { "America/Phoenix", "US Mountain Standard Time" }, // 001 + { "America/Creston America/Dawson_Creek America/Fort_Nelson", + "US Mountain Standard Time" }, // CA + { "America/Hermosillo", "US Mountain Standard Time" }, // MX + { "America/Phoenix", "US Mountain Standard Time" }, // US + { "Etc/GMT+7", "US Mountain Standard Time" }, // ZZ + { "America/Mazatlan", "Mountain Standard Time (Mexico)" }, // 001 + { "America/Mazatlan", "Mountain Standard Time (Mexico)" }, // MX + { "America/Denver", "Mountain Standard Time" }, // 001 + { "America/Edmonton America/Cambridge_Bay America/Inuvik", "Mountain Standard Time" }, // CA + { "America/Ciudad_Juarez", "Mountain Standard Time" }, // MX + { "America/Denver America/Boise", "Mountain Standard Time" }, // US + { "America/Whitehorse", "Yukon Standard Time" }, // 001 + { "America/Whitehorse America/Dawson", "Yukon Standard Time" }, // CA + { "America/Guatemala", "Central America Standard Time" }, // 001 + { "America/Belize", "Central America Standard Time" }, // BZ + { "America/Costa_Rica", "Central America Standard Time" }, // CR + { "Pacific/Galapagos", "Central America Standard Time" }, // EC + { "America/Guatemala", "Central America Standard Time" }, // GT + { "America/Tegucigalpa", "Central America Standard Time" }, // HN + { "America/Managua", "Central America Standard Time" }, // NI + { "America/El_Salvador", "Central America Standard Time" }, // SV + { "Etc/GMT+6", "Central America Standard Time" }, // ZZ + { "America/Chicago", "Central Standard Time" }, // 001 + { "America/Winnipeg America/Rankin_Inlet America/Resolute", "Central Standard Time" }, // CA + { "America/Matamoros America/Ojinaga", "Central Standard Time" }, // MX + { "America/Chicago America/Indiana/Knox America/Indiana/Tell_City America/Menominee " + "America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem", + "Central Standard Time" }, // US + { "Pacific/Easter", "Easter Island Standard Time" }, // 001 + { "Pacific/Easter", "Easter Island Standard Time" }, // CL + { "America/Mexico_City", "Central Standard Time (Mexico)" }, // 001 + { "America/Mexico_City America/Bahia_Banderas America/Merida America/Monterrey " + "America/Chihuahua ", + "Central Standard Time (Mexico)" }, // MX + { "America/Regina", "Canada Central Standard Time" }, // 001 + { "America/Regina America/Swift_Current", "Canada Central Standard Time" }, // CA + { "America/Bogota", "SA Pacific Standard Time" }, // 001 + { "America/Rio_Branco America/Eirunepe", "SA Pacific Standard Time" }, // BR + { "America/Coral_Harbour", "SA Pacific Standard Time" }, // CA + { "America/Bogota", "SA Pacific Standard Time" }, // CO + { "America/Guayaquil", "SA Pacific Standard Time" }, // EC + { "America/Jamaica", "SA Pacific Standard Time" }, // JM + { "America/Cayman", "SA Pacific Standard Time" }, // KY + { "America/Panama", "SA Pacific Standard Time" }, // PA + { "America/Lima", "SA Pacific Standard Time" }, // PE + { "Etc/GMT+5", "SA Pacific Standard Time" }, // ZZ + { "America/Cancun", "Eastern Standard Time (Mexico)" }, // 001 + { "America/Cancun", "Eastern Standard Time (Mexico)" }, // MX + { "America/New_York", "Eastern Standard Time" }, // 001 + { "America/Nassau", "Eastern Standard Time" }, // BS + { "America/Toronto America/Iqaluit", "Eastern Standard Time" }, // CA + { "America/New_York America/Detroit America/Indiana/Petersburg America/Indiana/Vincennes " + "America/Indiana/Winamac America/Kentucky/Monticello America/Louisville", + "Eastern Standard Time" }, // US + { "America/Port-au-Prince", "Haiti Standard Time" }, // 001 + { "America/Port-au-Prince", "Haiti Standard Time" }, // HT + { "America/Havana", "Cuba Standard Time" }, // 001 + { "America/Havana", "Cuba Standard Time" }, // CU + { "America/Indianapolis", "US Eastern Standard Time" }, // 001 + { "America/Indianapolis America/Indiana/Marengo America/Indiana/Vevay", + "US Eastern Standard Time" }, // US + { "America/Grand_Turk", "Turks And Caicos Standard Time" }, // 001 + { "America/Grand_Turk", "Turks And Caicos Standard Time" }, // TC + { "America/Asuncion", "Paraguay Standard Time" }, // 001 + { "America/Asuncion", "Paraguay Standard Time" }, // PY + { "America/Halifax", "Atlantic Standard Time" }, // 001 + { "Atlantic/Bermuda", "Atlantic Standard Time" }, // BM + { "America/Halifax America/Glace_Bay America/Goose_Bay America/Moncton", + "Atlantic Standard Time" }, // CA + { "America/Thule", "Atlantic Standard Time" }, // GL + { "America/Caracas", "Venezuela Standard Time" }, // 001 + { "America/Caracas", "Venezuela Standard Time" }, // VE + { "America/Cuiaba", "Central Brazilian Standard Time" }, // 001 + { "America/Cuiaba America/Campo_Grande", "Central Brazilian Standard Time" }, // BR + { "America/La_Paz", "SA Western Standard Time" }, // 001 + { "America/Antigua", "SA Western Standard Time" }, // AG + { "America/Anguilla", "SA Western Standard Time" }, // AI + { "America/Aruba", "SA Western Standard Time" }, // AW + { "America/Barbados", "SA Western Standard Time" }, // BB + { "America/St_Barthelemy", "SA Western Standard Time" }, // BL + { "America/La_Paz", "SA Western Standard Time" }, // BO + { "America/Kralendijk", "SA Western Standard Time" }, // BQ + { "America/Manaus America/Boa_Vista America/Porto_Velho", "SA Western Standard Time" }, // BR + { "America/Blanc-Sablon", "SA Western Standard Time" }, // CA + { "America/Curacao", "SA Western Standard Time" }, // CW + { "America/Dominica", "SA Western Standard Time" }, // DM + { "America/Santo_Domingo", "SA Western Standard Time" }, // DO + { "America/Grenada", "SA Western Standard Time" }, // GD + { "America/Guadeloupe", "SA Western Standard Time" }, // GP + { "America/Guyana", "SA Western Standard Time" }, // GY + { "America/St_Kitts", "SA Western Standard Time" }, // KN + { "America/St_Lucia", "SA Western Standard Time" }, // LC + { "America/Marigot", "SA Western Standard Time" }, // MF + { "America/Martinique", "SA Western Standard Time" }, // MQ + { "America/Montserrat", "SA Western Standard Time" }, // MS + { "America/Puerto_Rico", "SA Western Standard Time" }, // PR + { "America/Lower_Princes", "SA Western Standard Time" }, // SX + { "America/Port_of_Spain", "SA Western Standard Time" }, // TT + { "America/St_Vincent", "SA Western Standard Time" }, // VC + { "America/Tortola", "SA Western Standard Time" }, // VG + { "America/St_Thomas", "SA Western Standard Time" }, // VI + { "Etc/GMT+4", "SA Western Standard Time" }, // ZZ + { "America/Santiago", "Pacific SA Standard Time" }, // 001 + { "America/Santiago", "Pacific SA Standard Time" }, // CL + { "America/St_Johns", "Newfoundland Standard Time" }, // 001 + { "America/St_Johns", "Newfoundland Standard Time" }, // CA + { "America/Araguaina", "Tocantins Standard Time" }, // 001 + { "America/Araguaina", "Tocantins Standard Time" }, // BR + { "America/Sao_Paulo", "E. South America Standard Time" }, // 001 + { "America/Sao_Paulo", "E. South America Standard Time" }, // BR + { "America/Cayenne", "SA Eastern Standard Time" }, // 001 + { "Antarctica/Rothera Antarctica/Palmer", "SA Eastern Standard Time" }, // AQ + { "America/Fortaleza America/Belem America/Maceio America/Recife America/Santarem", + "SA Eastern Standard Time" }, // BR + { "Atlantic/Stanley", "SA Eastern Standard Time" }, // FK + { "America/Cayenne", "SA Eastern Standard Time" }, // GF + { "America/Paramaribo", "SA Eastern Standard Time" }, // SR + { "Etc/GMT+3", "SA Eastern Standard Time" }, // ZZ + { "America/Buenos_Aires", "Argentina Standard Time" }, // 001 + { "America/Buenos_Aires America/Argentina/La_Rioja America/Argentina/Rio_Gallegos " + "America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis " + "America/Argentina/Tucuman America/Argentina/Ushuaia America/Catamarca America/Cordoba " + "America/Jujuy America/Mendoza", + "Argentina Standard Time" }, // AR + { "America/Godthab", "Greenland Standard Time" }, // 001 + { "America/Godthab", "Greenland Standard Time" }, // GL + { "America/Montevideo", "Montevideo Standard Time" }, // 001 + { "America/Montevideo", "Montevideo Standard Time" }, // UY + { "America/Punta_Arenas", "Magallanes Standard Time" }, // 001 + { "America/Punta_Arenas", "Magallanes Standard Time" }, // CL + { "America/Miquelon", "Saint Pierre Standard Time" }, // 001 + { "America/Miquelon", "Saint Pierre Standard Time" }, // PM + { "America/Bahia", "Bahia Standard Time" }, // 001 + { "America/Bahia", "Bahia Standard Time" }, // BR + { "Etc/GMT+2", "UTC-02" }, // 001 + { "America/Noronha", "UTC-02" }, // BR + { "Atlantic/South_Georgia", "UTC-02" }, // GS + { "Etc/GMT+2", "UTC-02" }, // ZZ + { "Atlantic/Azores", "Azores Standard Time" }, // 001 + { "America/Scoresbysund", "Azores Standard Time" }, // GL + { "Atlantic/Azores", "Azores Standard Time" }, // PT + { "Atlantic/Cape_Verde", "Cape Verde Standard Time" }, // 001 + { "Atlantic/Cape_Verde", "Cape Verde Standard Time" }, // CV + { "Etc/GMT+1", "Cape Verde Standard Time" }, // ZZ + { "Etc/UTC", "UTC" }, // 001 + { "Etc/UTC Etc/GMT", "UTC" }, // ZZ + { "Europe/London", "GMT Standard Time" }, // 001 + { "Atlantic/Canary", "GMT Standard Time" }, // ES + { "Atlantic/Faeroe", "GMT Standard Time" }, // FO + { "Europe/London", "GMT Standard Time" }, // GB + { "Europe/Guernsey", "GMT Standard Time" }, // GG + { "Europe/Dublin", "GMT Standard Time" }, // IE + { "Europe/Isle_of_Man", "GMT Standard Time" }, // IM + { "Europe/Jersey", "GMT Standard Time" }, // JE + { "Europe/Lisbon Atlantic/Madeira", "GMT Standard Time" }, // PT + { "Atlantic/Reykjavik", "Greenwich Standard Time" }, // 001 + { "Africa/Ouagadougou", "Greenwich Standard Time" }, // BF + { "Africa/Abidjan", "Greenwich Standard Time" }, // CI + { "Africa/Accra", "Greenwich Standard Time" }, // GH + { "America/Danmarkshavn", "Greenwich Standard Time" }, // GL + { "Africa/Banjul", "Greenwich Standard Time" }, // GM + { "Africa/Conakry", "Greenwich Standard Time" }, // GN + { "Africa/Bissau", "Greenwich Standard Time" }, // GW + { "Atlantic/Reykjavik", "Greenwich Standard Time" }, // IS + { "Africa/Monrovia", "Greenwich Standard Time" }, // LR + { "Africa/Bamako", "Greenwich Standard Time" }, // ML + { "Africa/Nouakchott", "Greenwich Standard Time" }, // MR + { "Atlantic/St_Helena", "Greenwich Standard Time" }, // SH + { "Africa/Freetown", "Greenwich Standard Time" }, // SL + { "Africa/Dakar", "Greenwich Standard Time" }, // SN + { "Africa/Lome", "Greenwich Standard Time" }, // TG + { "Africa/Sao_Tome", "Sao Tome Standard Time" }, // 001 + { "Africa/Sao_Tome", "Sao Tome Standard Time" }, // ST + { "Africa/Casablanca", "Morocco Standard Time" }, // 001 + { "Africa/El_Aaiun", "Morocco Standard Time" }, // EH + { "Africa/Casablanca", "Morocco Standard Time" }, // MA + { "Europe/Berlin", "W. Europe Standard Time" }, // 001 + { "Europe/Andorra", "W. Europe Standard Time" }, // AD + { "Europe/Vienna", "W. Europe Standard Time" }, // AT + { "Europe/Zurich", "W. Europe Standard Time" }, // CH + { "Europe/Berlin Europe/Busingen", "W. Europe Standard Time" }, // DE + { "Europe/Gibraltar", "W. Europe Standard Time" }, // GI + { "Europe/Rome", "W. Europe Standard Time" }, // IT + { "Europe/Vaduz", "W. Europe Standard Time" }, // LI + { "Europe/Luxembourg", "W. Europe Standard Time" }, // LU + { "Europe/Monaco", "W. Europe Standard Time" }, // MC + { "Europe/Malta", "W. Europe Standard Time" }, // MT + { "Europe/Amsterdam", "W. Europe Standard Time" }, // NL + { "Europe/Oslo", "W. Europe Standard Time" }, // NO + { "Europe/Stockholm", "W. Europe Standard Time" }, // SE + { "Arctic/Longyearbyen", "W. Europe Standard Time" }, // SJ + { "Europe/San_Marino", "W. Europe Standard Time" }, // SM + { "Europe/Vatican", "W. Europe Standard Time" }, // VA + { "Europe/Budapest", "Central Europe Standard Time" }, // 001 + { "Europe/Tirane", "Central Europe Standard Time" }, // AL + { "Europe/Prague", "Central Europe Standard Time" }, // CZ + { "Europe/Budapest", "Central Europe Standard Time" }, // HU + { "Europe/Podgorica", "Central Europe Standard Time" }, // ME + { "Europe/Belgrade", "Central Europe Standard Time" }, // RS + { "Europe/Ljubljana", "Central Europe Standard Time" }, // SI + { "Europe/Bratislava", "Central Europe Standard Time" }, // SK + { "Europe/Paris", "Romance Standard Time" }, // 001 + { "Europe/Brussels", "Romance Standard Time" }, // BE + { "Europe/Copenhagen", "Romance Standard Time" }, // DK + { "Europe/Madrid Africa/Ceuta", "Romance Standard Time" }, // ES + { "Europe/Paris", "Romance Standard Time" }, // FR + { "Europe/Warsaw", "Central European Standard Time" }, // 001 + { "Europe/Sarajevo", "Central European Standard Time" }, // BA + { "Europe/Zagreb", "Central European Standard Time" }, // HR + { "Europe/Skopje", "Central European Standard Time" }, // MK + { "Europe/Warsaw", "Central European Standard Time" }, // PL + { "Africa/Lagos", "W. Central Africa Standard Time" }, // 001 + { "Africa/Luanda", "W. Central Africa Standard Time" }, // AO + { "Africa/Porto-Novo", "W. Central Africa Standard Time" }, // BJ + { "Africa/Kinshasa", "W. Central Africa Standard Time" }, // CD + { "Africa/Bangui", "W. Central Africa Standard Time" }, // CF + { "Africa/Brazzaville", "W. Central Africa Standard Time" }, // CG + { "Africa/Douala", "W. Central Africa Standard Time" }, // CM + { "Africa/Algiers", "W. Central Africa Standard Time" }, // DZ + { "Africa/Libreville", "W. Central Africa Standard Time" }, // GA + { "Africa/Malabo", "W. Central Africa Standard Time" }, // GQ + { "Africa/Niamey", "W. Central Africa Standard Time" }, // NE + { "Africa/Lagos", "W. Central Africa Standard Time" }, // NG + { "Africa/Ndjamena", "W. Central Africa Standard Time" }, // TD + { "Africa/Tunis", "W. Central Africa Standard Time" }, // TN + { "Etc/GMT-1", "W. Central Africa Standard Time" }, // ZZ + { "Asia/Amman", "Jordan Standard Time" }, // 001 + { "Asia/Amman", "Jordan Standard Time" }, // JO + { "Europe/Bucharest", "GTB Standard Time" }, // 001 + { "Asia/Nicosia Asia/Famagusta", "GTB Standard Time" }, // CY + { "Europe/Athens", "GTB Standard Time" }, // GR + { "Europe/Bucharest", "GTB Standard Time" }, // RO + { "Asia/Beirut", "Middle East Standard Time" }, // 001 + { "Asia/Beirut", "Middle East Standard Time" }, // LB + { "Africa/Cairo", "Egypt Standard Time" }, // 001 + { "Africa/Cairo", "Egypt Standard Time" }, // EG + { "Europe/Chisinau", "E. Europe Standard Time" }, // 001 + { "Europe/Chisinau", "E. Europe Standard Time" }, // MD + { "Asia/Damascus", "Syria Standard Time" }, // 001 + { "Asia/Damascus", "Syria Standard Time" }, // SY + { "Asia/Hebron", "West Bank Standard Time" }, // 001 + { "Asia/Hebron Asia/Gaza", "West Bank Standard Time" }, // PS + { "Africa/Johannesburg", "South Africa Standard Time" }, // 001 + { "Africa/Bujumbura", "South Africa Standard Time" }, // BI + { "Africa/Gaborone", "South Africa Standard Time" }, // BW + { "Africa/Lubumbashi", "South Africa Standard Time" }, // CD + { "Africa/Maseru", "South Africa Standard Time" }, // LS + { "Africa/Blantyre", "South Africa Standard Time" }, // MW + { "Africa/Maputo", "South Africa Standard Time" }, // MZ + { "Africa/Kigali", "South Africa Standard Time" }, // RW + { "Africa/Mbabane", "South Africa Standard Time" }, // SZ + { "Africa/Johannesburg", "South Africa Standard Time" }, // ZA + { "Africa/Lusaka", "South Africa Standard Time" }, // ZM + { "Africa/Harare", "South Africa Standard Time" }, // ZW + { "Etc/GMT-2", "South Africa Standard Time" }, // ZZ + { "Europe/Kiev", "FLE Standard Time" }, // 001 + { "Europe/Mariehamn", "FLE Standard Time" }, // AX + { "Europe/Sofia", "FLE Standard Time" }, // BG + { "Europe/Tallinn", "FLE Standard Time" }, // EE + { "Europe/Helsinki", "FLE Standard Time" }, // FI + { "Europe/Vilnius", "FLE Standard Time" }, // LT + { "Europe/Riga", "FLE Standard Time" }, // LV + { "Europe/Kiev", "FLE Standard Time" }, // UA + { "Asia/Jerusalem", "Israel Standard Time" }, // 001 + { "Asia/Jerusalem", "Israel Standard Time" }, // IL + { "Africa/Juba", "South Sudan Standard Time" }, // 001 + { "Africa/Juba", "South Sudan Standard Time" }, // SS + { "Europe/Kaliningrad", "Kaliningrad Standard Time" }, // 001 + { "Europe/Kaliningrad", "Kaliningrad Standard Time" }, // RU + { "Africa/Khartoum", "Sudan Standard Time" }, // 001 + { "Africa/Khartoum", "Sudan Standard Time" }, // SD + { "Africa/Tripoli", "Libya Standard Time" }, // 001 + { "Africa/Tripoli", "Libya Standard Time" }, // LY + { "Africa/Windhoek", "Namibia Standard Time" }, // 001 + { "Africa/Windhoek", "Namibia Standard Time" }, // NA + { "Asia/Baghdad", "Arabic Standard Time" }, // 001 + { "Asia/Baghdad", "Arabic Standard Time" }, // IQ + { "Europe/Istanbul", "Turkey Standard Time" }, // 001 + { "Europe/Istanbul", "Turkey Standard Time" }, // TR + { "Asia/Riyadh", "Arab Standard Time" }, // 001 + { "Asia/Bahrain", "Arab Standard Time" }, // BH + { "Asia/Kuwait", "Arab Standard Time" }, // KW + { "Asia/Qatar", "Arab Standard Time" }, // QA + { "Asia/Riyadh", "Arab Standard Time" }, // SA + { "Asia/Aden", "Arab Standard Time" }, // YE + { "Europe/Minsk", "Belarus Standard Time" }, // 001 + { "Europe/Minsk", "Belarus Standard Time" }, // BY + { "Europe/Moscow", "Russian Standard Time" }, // 001 + { "Europe/Moscow Europe/Kirov", "Russian Standard Time" }, // RU + { "Europe/Simferopol", "Russian Standard Time" }, // UA + { "Africa/Nairobi", "E. Africa Standard Time" }, // 001 + { "Antarctica/Syowa", "E. Africa Standard Time" }, // AQ + { "Africa/Djibouti", "E. Africa Standard Time" }, // DJ + { "Africa/Asmera", "E. Africa Standard Time" }, // ER + { "Africa/Addis_Ababa", "E. Africa Standard Time" }, // ET + { "Africa/Nairobi", "E. Africa Standard Time" }, // KE + { "Indian/Comoro", "E. Africa Standard Time" }, // KM + { "Indian/Antananarivo", "E. Africa Standard Time" }, // MG + { "Africa/Mogadishu", "E. Africa Standard Time" }, // SO + { "Africa/Dar_es_Salaam", "E. Africa Standard Time" }, // TZ + { "Africa/Kampala", "E. Africa Standard Time" }, // UG + { "Indian/Mayotte", "E. Africa Standard Time" }, // YT + { "Etc/GMT-3", "E. Africa Standard Time" }, // ZZ + { "Asia/Tehran", "Iran Standard Time" }, // 001 + { "Asia/Tehran", "Iran Standard Time" }, // IR + { "Asia/Dubai", "Arabian Standard Time" }, // 001 + { "Asia/Dubai", "Arabian Standard Time" }, // AE + { "Asia/Muscat", "Arabian Standard Time" }, // OM + { "Etc/GMT-4", "Arabian Standard Time" }, // ZZ + { "Europe/Astrakhan", "Astrakhan Standard Time" }, // 001 + { "Europe/Astrakhan Europe/Ulyanovsk", "Astrakhan Standard Time" }, // RU + { "Asia/Baku", "Azerbaijan Standard Time" }, // 001 + { "Asia/Baku", "Azerbaijan Standard Time" }, // AZ + { "Europe/Samara", "Russia Time Zone 3" }, // 001 + { "Europe/Samara", "Russia Time Zone 3" }, // RU + { "Indian/Mauritius", "Mauritius Standard Time" }, // 001 + { "Indian/Mauritius", "Mauritius Standard Time" }, // MU + { "Indian/Reunion", "Mauritius Standard Time" }, // RE + { "Indian/Mahe", "Mauritius Standard Time" }, // SC + { "Europe/Saratov", "Saratov Standard Time" }, // 001 + { "Europe/Saratov", "Saratov Standard Time" }, // RU + { "Asia/Tbilisi", "Georgian Standard Time" }, // 001 + { "Asia/Tbilisi", "Georgian Standard Time" }, // GE + { "Europe/Volgograd", "Volgograd Standard Time" }, // 001 + { "Europe/Volgograd", "Volgograd Standard Time" }, // RU + { "Asia/Yerevan", "Caucasus Standard Time" }, // 001 + { "Asia/Yerevan", "Caucasus Standard Time" }, // AM + { "Asia/Kabul", "Afghanistan Standard Time" }, // 001 + { "Asia/Kabul", "Afghanistan Standard Time" }, // AF + { "Asia/Tashkent", "West Asia Standard Time" }, // 001 + { "Antarctica/Mawson", "West Asia Standard Time" }, // AQ + { "Asia/Oral Asia/Almaty Asia/Aqtau Asia/Aqtobe Asia/Atyrau Asia/Qostanay", + "West Asia Standard Time" }, // KZ + { "Indian/Maldives", "West Asia Standard Time" }, // MV + { "Indian/Kerguelen", "West Asia Standard Time" }, // TF + { "Asia/Dushanbe", "West Asia Standard Time" }, // TJ + { "Asia/Ashgabat", "West Asia Standard Time" }, // TM + { "Asia/Tashkent Asia/Samarkand", "West Asia Standard Time" }, // UZ + { "Etc/GMT-5", "West Asia Standard Time" }, // ZZ + { "Asia/Yekaterinburg", "Ekaterinburg Standard Time" }, // 001 + { "Asia/Yekaterinburg", "Ekaterinburg Standard Time" }, // RU + { "Asia/Karachi", "Pakistan Standard Time" }, // 001 + { "Asia/Karachi", "Pakistan Standard Time" }, // PK + { "Asia/Qyzylorda", "Qyzylorda Standard Time" }, // 001 + { "Asia/Qyzylorda", "Qyzylorda Standard Time" }, // KZ + { "Asia/Calcutta", "India Standard Time" }, // 001 + { "Asia/Calcutta", "India Standard Time" }, // IN + { "Asia/Colombo", "Sri Lanka Standard Time" }, // 001 + { "Asia/Colombo", "Sri Lanka Standard Time" }, // LK + { "Asia/Katmandu", "Nepal Standard Time" }, // 001 + { "Asia/Katmandu", "Nepal Standard Time" }, // NP + { "Asia/Bishkek", "Central Asia Standard Time" }, // 001 + { "Antarctica/Vostok", "Central Asia Standard Time" }, // AQ + { "Asia/Urumqi", "Central Asia Standard Time" }, // CN + { "Indian/Chagos", "Central Asia Standard Time" }, // IO + { "Asia/Bishkek", "Central Asia Standard Time" }, // KG + { "Etc/GMT-6", "Central Asia Standard Time" }, // ZZ + { "Asia/Dhaka", "Bangladesh Standard Time" }, // 001 + { "Asia/Dhaka", "Bangladesh Standard Time" }, // BD + { "Asia/Thimphu", "Bangladesh Standard Time" }, // BT + { "Asia/Omsk", "Omsk Standard Time" }, // 001 + { "Asia/Omsk", "Omsk Standard Time" }, // RU + { "Asia/Rangoon", "Myanmar Standard Time" }, // 001 + { "Indian/Cocos", "Myanmar Standard Time" }, // CC + { "Asia/Rangoon", "Myanmar Standard Time" }, // MM + { "Asia/Bangkok", "SE Asia Standard Time" }, // 001 + { "Antarctica/Davis", "SE Asia Standard Time" }, // AQ + { "Indian/Christmas", "SE Asia Standard Time" }, // CX + { "Asia/Jakarta Asia/Pontianak", "SE Asia Standard Time" }, // ID + { "Asia/Phnom_Penh", "SE Asia Standard Time" }, // KH + { "Asia/Vientiane", "SE Asia Standard Time" }, // LA + { "Asia/Bangkok", "SE Asia Standard Time" }, // TH + { "Asia/Saigon", "SE Asia Standard Time" }, // VN + { "Etc/GMT-7", "SE Asia Standard Time" }, // ZZ + { "Asia/Barnaul", "Altai Standard Time" }, // 001 + { "Asia/Barnaul", "Altai Standard Time" }, // RU + { "Asia/Hovd", "W. Mongolia Standard Time" }, // 001 + { "Asia/Hovd", "W. Mongolia Standard Time" }, // MN + { "Asia/Krasnoyarsk", "North Asia Standard Time" }, // 001 + { "Asia/Krasnoyarsk Asia/Novokuznetsk", "North Asia Standard Time" }, // RU + { "Asia/Novosibirsk", "N. Central Asia Standard Time" }, // 001 + { "Asia/Novosibirsk", "N. Central Asia Standard Time" }, // RU + { "Asia/Tomsk", "Tomsk Standard Time" }, // 001 + { "Asia/Tomsk", "Tomsk Standard Time" }, // RU + { "Asia/Shanghai", "China Standard Time" }, // 001 + { "Asia/Shanghai", "China Standard Time" }, // CN + { "Asia/Hong_Kong", "China Standard Time" }, // HK + { "Asia/Macau", "China Standard Time" }, // MO + { "Asia/Irkutsk", "North Asia East Standard Time" }, // 001 + { "Asia/Irkutsk", "North Asia East Standard Time" }, // RU + { "Asia/Singapore", "Singapore Standard Time" }, // 001 + { "Asia/Brunei", "Singapore Standard Time" }, // BN + { "Asia/Makassar", "Singapore Standard Time" }, // ID + { "Asia/Kuala_Lumpur Asia/Kuching", "Singapore Standard Time" }, // MY + { "Asia/Manila", "Singapore Standard Time" }, // PH + { "Asia/Singapore", "Singapore Standard Time" }, // SG + { "Etc/GMT-8", "Singapore Standard Time" }, // ZZ + { "Australia/Perth", "W. Australia Standard Time" }, // 001 + { "Australia/Perth", "W. Australia Standard Time" }, // AU + { "Asia/Taipei", "Taipei Standard Time" }, // 001 + { "Asia/Taipei", "Taipei Standard Time" }, // TW + { "Asia/Ulaanbaatar", "Ulaanbaatar Standard Time" }, // 001 + { "Asia/Ulaanbaatar", "Ulaanbaatar Standard Time" }, // MN + { "Australia/Eucla", "Aus Central W. Standard Time" }, // 001 + { "Australia/Eucla", "Aus Central W. Standard Time" }, // AU + { "Asia/Chita", "Transbaikal Standard Time" }, // 001 + { "Asia/Chita", "Transbaikal Standard Time" }, // RU + { "Asia/Tokyo", "Tokyo Standard Time" }, // 001 + { "Asia/Jayapura", "Tokyo Standard Time" }, // ID + { "Asia/Tokyo", "Tokyo Standard Time" }, // JP + { "Pacific/Palau", "Tokyo Standard Time" }, // PW + { "Asia/Dili", "Tokyo Standard Time" }, // TL + { "Etc/GMT-9", "Tokyo Standard Time" }, // ZZ + { "Asia/Pyongyang", "North Korea Standard Time" }, // 001 + { "Asia/Pyongyang", "North Korea Standard Time" }, // KP + { "Asia/Seoul", "Korea Standard Time" }, // 001 + { "Asia/Seoul", "Korea Standard Time" }, // KR + { "Asia/Yakutsk", "Yakutsk Standard Time" }, // 001 + { "Asia/Yakutsk Asia/Khandyga", "Yakutsk Standard Time" }, // RU + { "Australia/Adelaide", "Cen. Australia Standard Time" }, // 001 + { "Australia/Adelaide Australia/Broken_Hill", "Cen. Australia Standard Time" }, // AU + { "Australia/Darwin", "AUS Central Standard Time" }, // 001 + { "Australia/Darwin", "AUS Central Standard Time" }, // AU + { "Australia/Brisbane", "E. Australia Standard Time" }, // 001 + { "Australia/Brisbane Australia/Lindeman", "E. Australia Standard Time" }, // AU + { "Australia/Sydney", "AUS Eastern Standard Time" }, // 001 + { "Australia/Sydney Australia/Melbourne", "AUS Eastern Standard Time" }, // AU + { "Pacific/Port_Moresby", "West Pacific Standard Time" }, // 001 + { "Antarctica/DumontDUrville", "West Pacific Standard Time" }, // AQ + { "Pacific/Truk", "West Pacific Standard Time" }, // FM + { "Pacific/Guam", "West Pacific Standard Time" }, // GU + { "Pacific/Saipan", "West Pacific Standard Time" }, // MP + { "Pacific/Port_Moresby", "West Pacific Standard Time" }, // PG + { "Etc/GMT-10", "West Pacific Standard Time" }, // ZZ + { "Australia/Hobart", "Tasmania Standard Time" }, // 001 + { "Australia/Hobart Antarctica/Macquarie", "Tasmania Standard Time" }, // AU + { "Asia/Vladivostok", "Vladivostok Standard Time" }, // 001 + { "Asia/Vladivostok Asia/Ust-Nera", "Vladivostok Standard Time" }, // RU + { "Australia/Lord_Howe", "Lord Howe Standard Time" }, // 001 + { "Australia/Lord_Howe", "Lord Howe Standard Time" }, // AU + { "Pacific/Bougainville", "Bougainville Standard Time" }, // 001 + { "Pacific/Bougainville", "Bougainville Standard Time" }, // PG + { "Asia/Srednekolymsk", "Russia Time Zone 10" }, // 001 + { "Asia/Srednekolymsk", "Russia Time Zone 10" }, // RU + { "Asia/Magadan", "Magadan Standard Time" }, // 001 + { "Asia/Magadan", "Magadan Standard Time" }, // RU + { "Pacific/Norfolk", "Norfolk Standard Time" }, // 001 + { "Pacific/Norfolk", "Norfolk Standard Time" }, // NF + { "Asia/Sakhalin", "Sakhalin Standard Time" }, // 001 + { "Asia/Sakhalin", "Sakhalin Standard Time" }, // RU + { "Pacific/Guadalcanal", "Central Pacific Standard Time" }, // 001 + { "Antarctica/Casey", "Central Pacific Standard Time" }, // AQ + { "Pacific/Ponape Pacific/Kosrae", "Central Pacific Standard Time" }, // FM + { "Pacific/Noumea", "Central Pacific Standard Time" }, // NC + { "Pacific/Guadalcanal", "Central Pacific Standard Time" }, // SB + { "Pacific/Efate", "Central Pacific Standard Time" }, // VU + { "Etc/GMT-11", "Central Pacific Standard Time" }, // ZZ + { "Asia/Kamchatka", "Russia Time Zone 11" }, // 001 + { "Asia/Kamchatka Asia/Anadyr", "Russia Time Zone 11" }, // RU + { "Pacific/Auckland", "New Zealand Standard Time" }, // 001 + { "Antarctica/McMurdo", "New Zealand Standard Time" }, // AQ + { "Pacific/Auckland", "New Zealand Standard Time" }, // NZ + { "Etc/GMT-12", "UTC+12" }, // 001 + { "Pacific/Tarawa", "UTC+12" }, // KI + { "Pacific/Majuro Pacific/Kwajalein", "UTC+12" }, // MH + { "Pacific/Nauru", "UTC+12" }, // NR + { "Pacific/Funafuti", "UTC+12" }, // TV + { "Pacific/Wake", "UTC+12" }, // UM + { "Pacific/Wallis", "UTC+12" }, // WF + { "Etc/GMT-12", "UTC+12" }, // ZZ + { "Pacific/Fiji", "Fiji Standard Time" }, // 001 + { "Pacific/Fiji", "Fiji Standard Time" }, // FJ + { "Pacific/Chatham", "Chatham Islands Standard Time" }, // 001 + { "Pacific/Chatham", "Chatham Islands Standard Time" }, // NZ + { "Etc/GMT-13", "UTC+13" }, // 001 + { "Pacific/Enderbury", "UTC+13" }, // KI + { "Pacific/Fakaofo", "UTC+13" }, // TK + { "Etc/GMT-13", "UTC+13" }, // ZZ + { "Pacific/Tongatapu", "Tonga Standard Time" }, // 001 + { "Pacific/Tongatapu", "Tonga Standard Time" }, // TO + { "Pacific/Apia", "Samoa Standard Time" }, // 001 + { "Pacific/Apia", "Samoa Standard Time" }, // WS + { "Pacific/Kiritimati", "Line Islands Standard Time" }, // 001 + { "Pacific/Kiritimati", "Line Islands Standard Time" }, // KI + { "Etc/GMT-14", "Line Islands Standard Time" }, // ZZ +}; + +const size_t WindowsZonesNrElements = ARRAYSIZE(WindowsZones); diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.h new file mode 100644 index 0000000000000000000000000000000000000000..691c14ff985154be2171ba1fbfa017103619f7ef --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/WindowsZones.h @@ -0,0 +1,18 @@ +/* + * Automatically generated with scripts/update-windows-zones.py + */ +#ifndef WINPR_WINDOWS_ZONES_H_ +#define WINPR_WINDOWS_ZONES_H_ + +#include + +typedef struct +{ + const char* tzid; + const char* windows; +} WINDOWS_TZID_ENTRY; + +extern const WINDOWS_TZID_ENTRY WindowsZones[]; +extern const size_t WindowsZonesNrElements; + +#endif /* WINPR_WINDOWS_ZONES_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.c new file mode 100644 index 0000000000000000000000000000000000000000..a0d8c235b2df5d6070732203bc3544bdf3787535 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.c @@ -0,0 +1,944 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2024 Armin Novak + * 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 + +#include +#include +#include +#include +#include +#include +#include "../log.h" +#include "timezone.h" + +#define TAG WINPR_TAG("timezone") + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +#include "TimeZoneNameMap.h" +#include "TimeZoneIanaAbbrevMap.h" + +#ifndef _WIN32 + +#include +#include + +#endif + +#if !defined(_WIN32) +static char* winpr_read_unix_timezone_identifier_from_file(FILE* fp) +{ + const INT CHUNK_SIZE = 32; + size_t rc = 0; + size_t read = 0; + size_t length = CHUNK_SIZE; + + char* tzid = malloc(length); + if (!tzid) + return NULL; + + do + { + rc = fread(tzid + read, 1, length - read - 1UL, fp); + if (rc > 0) + read += rc; + + if (read < (length - 1UL)) + break; + + if (read > length - 1UL) + { + free(tzid); + return NULL; + } + + length += CHUNK_SIZE; + char* tmp = (char*)realloc(tzid, length); + if (!tmp) + { + free(tzid); + return NULL; + } + + tzid = tmp; + } while (rc > 0); + + if (ferror(fp)) + { + free(tzid); + return NULL; + } + + tzid[read] = '\0'; + if (read > 0) + { + if (tzid[read - 1] == '\n') + tzid[read - 1] = '\0'; + } + + return tzid; +} + +static char* winpr_get_timezone_from_link(const char* links[], size_t count) +{ + const char* _links[] = { "/etc/localtime", "/etc/TZ" }; + + if (links == NULL) + { + links = _links; + count = ARRAYSIZE(_links); + } + + /* + * On linux distros such as Redhat or Archlinux, a symlink at /etc/localtime + * will point to /usr/share/zoneinfo/region/place where region/place could be + * America/Montreal for example. + * Some distributions do have to symlink at /etc/TZ. + */ + + for (size_t x = 0; x < count; x++) + { + char* tzid = NULL; + const char* link = links[x]; + char* buf = realpath(link, NULL); + + if (buf) + { + size_t sep = 0; + size_t alloc = 0; + size_t pos = 0; + size_t len = pos = strlen(buf); + + /* find the position of the 2nd to last "/" */ + for (size_t i = 1; i <= len; i++) + { + const size_t curpos = len - i; + const char cur = buf[curpos]; + + if (cur == '/') + sep++; + if (sep >= 2) + { + alloc = i; + pos = len - i + 1; + break; + } + } + + if ((len == 0) || (sep != 2)) + goto end; + + tzid = (char*)calloc(alloc + 1, sizeof(char)); + + if (!tzid) + goto end; + + strncpy(tzid, &buf[pos], alloc); + WLog_DBG(TAG, "tzid: %s", tzid); + goto end; + } + + end: + free(buf); + if (tzid) + return tzid; + } + + return NULL; +} + +#if defined(ANDROID) +#include "../utils/android.h" + +static char* winpr_get_android_timezone_identifier(void) +{ + char* tzid = NULL; + JNIEnv* jniEnv; + + /* Preferred: Try to get identifier from java TimeZone class */ + if (jniVm && ((*jniVm)->GetEnv(jniVm, (void**)&jniEnv, JNI_VERSION_1_6) == JNI_OK)) + { + const char* raw; + jclass jObjClass; + jobject jObj; + jmethodID jDefaultTimezone; + jmethodID jTimezoneIdentifier; + jstring tzJId; + jboolean attached = (*jniVm)->AttachCurrentThread(jniVm, &jniEnv, NULL); + jObjClass = (*jniEnv)->FindClass(jniEnv, "java/util/TimeZone"); + + if (!jObjClass) + goto fail; + + jDefaultTimezone = + (*jniEnv)->GetStaticMethodID(jniEnv, jObjClass, "getDefault", "()Ljava/util/TimeZone;"); + + if (!jDefaultTimezone) + goto fail; + + jObj = (*jniEnv)->CallStaticObjectMethod(jniEnv, jObjClass, jDefaultTimezone); + + if (!jObj) + goto fail; + + jTimezoneIdentifier = + (*jniEnv)->GetMethodID(jniEnv, jObjClass, "getID", "()Ljava/lang/String;"); + + if (!jTimezoneIdentifier) + goto fail; + + tzJId = (*jniEnv)->CallObjectMethod(jniEnv, jObj, jTimezoneIdentifier); + + if (!tzJId) + goto fail; + + raw = (*jniEnv)->GetStringUTFChars(jniEnv, tzJId, 0); + + if (raw) + tzid = _strdup(raw); + + (*jniEnv)->ReleaseStringUTFChars(jniEnv, tzJId, raw); + fail: + + if (attached) + (*jniVm)->DetachCurrentThread(jniVm); + } + + /* Fall back to property, might not be available. */ + if (!tzid) + { + FILE* fp = popen("getprop persist.sys.timezone", "r"); + + if (fp) + { + tzid = winpr_read_unix_timezone_identifier_from_file(fp); + pclose(fp); + } + } + + return tzid; +} +#endif + +static char* winpr_get_unix_timezone_identifier_from_file(void) +{ +#if defined(ANDROID) + return winpr_get_android_timezone_identifier(); +#else + FILE* fp = NULL; + char* tzid = NULL; +#if !defined(WINPR_TIMEZONE_FILE) +#error \ + "Please define WINPR_TIMEZONE_FILE with the path to your timezone file (e.g. /etc/timezone or similar)" +#else + fp = winpr_fopen(WINPR_TIMEZONE_FILE, "r"); +#endif + + if (NULL == fp) + return NULL; + + tzid = winpr_read_unix_timezone_identifier_from_file(fp); + (void)fclose(fp); + if (tzid != NULL) + WLog_DBG(TAG, "tzid: %s", tzid); + return tzid; +#endif +} + +static char* winpr_time_zone_from_env(void) +{ + LPCSTR tz = "TZ"; + char* tzid = NULL; + + DWORD nSize = GetEnvironmentVariableA(tz, NULL, 0); + if (nSize > 0) + { + tzid = (char*)calloc(nSize, sizeof(char)); + if (!tzid) + goto fail; + if (!GetEnvironmentVariableA(tz, tzid, nSize)) + goto fail; + else if (tzid[0] == ':') + { + /* Remove leading colon, see tzset(3) */ + memmove(tzid, tzid + 1, nSize - sizeof(char)); + } + } + + return tzid; + +fail: + free(tzid); + return NULL; +} + +static char* winpr_translate_time_zone(const char* tzid) +{ + const char* zipath = "/usr/share/zoneinfo/"; + char* buf = NULL; + const char* links[] = { buf }; + + if (!tzid) + return NULL; + + if (tzid[0] == '/') + { + /* Full path given in TZ */ + links[0] = tzid; + } + else + { + size_t bsize = 0; + winpr_asprintf(&buf, &bsize, "%s%s", zipath, tzid); + links[0] = buf; + } + + char* ntzid = winpr_get_timezone_from_link(links, 1); + free(buf); + return ntzid; +} + +static char* winpr_guess_time_zone(void) +{ + char* tzid = winpr_time_zone_from_env(); + if (tzid) + goto end; + tzid = winpr_get_unix_timezone_identifier_from_file(); + if (tzid) + goto end; + tzid = winpr_get_timezone_from_link(NULL, 0); + if (tzid) + goto end; + +end: +{ + char* ntzid = winpr_translate_time_zone(tzid); + if (ntzid) + { + free(tzid); + return ntzid; + } + return tzid; +} +} + +static SYSTEMTIME tm2systemtime(const struct tm* t) +{ + SYSTEMTIME st = { 0 }; + + if (t) + { + st.wYear = (WORD)(1900 + t->tm_year); + st.wMonth = (WORD)t->tm_mon + 1; + st.wDay = (WORD)t->tm_mday; + st.wDayOfWeek = (WORD)t->tm_wday; + st.wHour = (WORD)t->tm_hour; + st.wMinute = (WORD)t->tm_min; + st.wSecond = (WORD)t->tm_sec; + st.wMilliseconds = 0; + } + return st; +} + +static struct tm systemtime2tm(const SYSTEMTIME* st) +{ + struct tm t = { 0 }; + if (st) + { + if (st->wYear >= 1900) + t.tm_year = st->wYear - 1900; + if (st->wMonth > 0) + t.tm_mon = st->wMonth - 1; + t.tm_mday = st->wDay; + t.tm_wday = st->wDayOfWeek; + t.tm_hour = st->wHour; + t.tm_min = st->wMinute; + t.tm_sec = st->wSecond; + } + return t; +} + +static LONG get_gmtoff_min(const struct tm* t) +{ + WINPR_ASSERT(t); + return -(LONG)(t->tm_gmtoff / 60l); +} + +static struct tm next_day(const struct tm* start) +{ + struct tm cur = *start; + cur.tm_hour = 0; + cur.tm_min = 0; + cur.tm_sec = 0; + cur.tm_isdst = -1; + cur.tm_mday++; + const time_t t = mktime(&cur); + (void)localtime_r(&t, &cur); + return cur; +} + +static struct tm adjust_time(const struct tm* start, int hour, int minute) +{ + struct tm cur = *start; + cur.tm_hour = hour; + cur.tm_min = minute; + cur.tm_sec = 0; + cur.tm_isdst = -1; + const time_t t = mktime(&cur); + (void)localtime_r(&t, &cur); + return cur; +} + +/* [MS-RDPBCGR] 2.2.1.11.1.1.1.1.1 System Time (TS_SYSTEMTIME) */ +static WORD get_transition_weekday_occurrence(const SYSTEMTIME* st) +{ + WORD count = 0; + struct tm start = systemtime2tm(st); + + WORD last = 0; + struct tm next = start; + next.tm_mday = 1; + next.tm_isdst = -1; + do + { + + const time_t t = mktime(&next); + next.tm_mday++; + + struct tm cur = { 0 }; + (void)localtime_r(&t, &cur); + + if (cur.tm_mon + 1 != st->wMonth) + break; + + if (cur.tm_wday == st->wDayOfWeek) + { + if (cur.tm_mday <= st->wDay) + count++; + last++; + } + + } while (TRUE); + + if (count == last) + count = 5; + + return count; +} + +static SYSTEMTIME tm2transitiontime(const struct tm* cur) +{ + SYSTEMTIME t = tm2systemtime(cur); + if (cur) + { + t.wDay = get_transition_weekday_occurrence(&t); + t.wYear = 0; + } + + return t; +} + +static SYSTEMTIME get_transition_time(const struct tm* start, BOOL toDst) +{ + BOOL toggled = FALSE; + struct tm first = adjust_time(start, 0, 0); + for (int hour = 0; hour < 24; hour++) + { + struct tm cur = adjust_time(start, hour, 0); + if (cur.tm_isdst != first.tm_isdst) + toggled = TRUE; + + if (toggled) + { + if (toDst && (cur.tm_isdst > 0)) + return tm2transitiontime(&cur); + else if (!toDst && (cur.tm_isdst == 0)) + return tm2transitiontime(&cur); + } + } + return tm2transitiontime(start); +} + +static BOOL get_transition_date(const struct tm* start, BOOL toDst, SYSTEMTIME* pdate) +{ + WINPR_ASSERT(start); + WINPR_ASSERT(pdate); + + *pdate = tm2transitiontime(NULL); + + if (start->tm_isdst < 0) + return FALSE; + + BOOL val = start->tm_isdst > 0; // the year starts with DST or not + BOOL toggled = FALSE; + struct tm cur = *start; + struct tm last = cur; + for (int day = 1; day <= 365; day++) + { + last = cur; + cur = next_day(&cur); + const BOOL curDst = (cur.tm_isdst > 0); + if ((val != curDst) && !toggled) + toggled = TRUE; + + if (toggled) + { + if (toDst && curDst) + { + *pdate = get_transition_time(&last, toDst); + return TRUE; + } + if (!toDst && !curDst) + { + *pdate = get_transition_time(&last, toDst); + return TRUE; + } + } + } + return FALSE; +} + +static LONG get_bias(const struct tm* start, BOOL dstBias) +{ + if ((start->tm_isdst > 0) && dstBias) + return get_gmtoff_min(start); + if ((start->tm_isdst == 0) && !dstBias) + return get_gmtoff_min(start); + if (start->tm_isdst < 0) + return get_gmtoff_min(start); + + struct tm cur = *start; + for (int day = 1; day <= 365; day++) + { + cur = next_day(&cur); + if ((cur.tm_isdst > 0) && dstBias) + return get_gmtoff_min(&cur); + else if ((cur.tm_isdst == 0) && !dstBias) + return get_gmtoff_min(&cur); + } + return 0; +} + +static BOOL map_iana_id(const char* iana, LPDYNAMIC_TIME_ZONE_INFORMATION tz) +{ + const char* winId = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_ID); + const char* winStd = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_STANDARD); + const char* winDst = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_DAYLIGHT); + + if (winStd) + (void)ConvertUtf8ToWChar(winStd, tz->StandardName, ARRAYSIZE(tz->StandardName)); + if (winDst) + (void)ConvertUtf8ToWChar(winDst, tz->DaylightName, ARRAYSIZE(tz->DaylightName)); + if (winId) + (void)ConvertUtf8ToWChar(winId, tz->TimeZoneKeyName, ARRAYSIZE(tz->TimeZoneKeyName)); + + return winId != NULL; +} + +static const char* weekday2str(WORD wDayOfWeek) +{ + switch (wDayOfWeek) + { + case 0: + return "SUNDAY"; + case 1: + return "MONDAY"; + case 2: + return "TUESDAY"; + case 3: + return "WEDNESDAY"; + case 4: + return "THURSDAY"; + case 5: + return "FRIDAY"; + case 6: + return "SATURDAY"; + default: + return "DAY-OF-MAGIC"; + } +} + +static char* systemtime2str(const SYSTEMTIME* t, char* buffer, size_t len) +{ + const SYSTEMTIME empty = { 0 }; + + if (memcmp(t, &empty, sizeof(SYSTEMTIME)) == 0) + (void)_snprintf(buffer, len, "{ not set }"); + else + { + (void)_snprintf(buffer, len, + "{ %" PRIu16 "-%" PRIu16 "-%" PRIu16 " [%s] %" PRIu16 ":%" PRIu16 + ":%" PRIu16 ".%" PRIu16 "}", + t->wYear, t->wMonth, t->wDay, weekday2str(t->wDayOfWeek), t->wHour, + t->wMinute, t->wSecond, t->wMilliseconds); + } + return buffer; +} + +static void log_print(wLog* log, DWORD level, const char* file, const char* fkt, size_t line, ...) +{ + if (!WLog_IsLevelActive(log, level)) + return; + + va_list ap = { 0 }; + va_start(ap, line); + WLog_PrintMessageVA(log, WLOG_MESSAGE_TEXT, level, line, file, fkt, ap); + va_end(ap); +} + +#define log_timezone(tzif, result) log_timezone_((tzif), (result), __FILE__, __func__, __LINE__) +static void log_timezone_(const DYNAMIC_TIME_ZONE_INFORMATION* tzif, DWORD result, const char* file, + const char* fkt, size_t line) +{ + WINPR_ASSERT(tzif); + + char buffer[130] = { 0 }; + DWORD level = WLOG_TRACE; + wLog* log = WLog_Get(TAG); + log_print(log, level, file, fkt, line, "DYNAMIC_TIME_ZONE_INFORMATION {"); + + log_print(log, level, file, fkt, line, " Bias=%" PRIu32, tzif->Bias); + (void)ConvertWCharNToUtf8(tzif->StandardName, ARRAYSIZE(tzif->StandardName), buffer, + ARRAYSIZE(buffer)); + log_print(log, level, file, fkt, line, " StandardName=%s", buffer); + log_print(log, level, file, fkt, line, " StandardDate=%s", + systemtime2str(&tzif->StandardDate, buffer, sizeof(buffer))); + log_print(log, level, file, fkt, line, " StandardBias=%" PRIu32, tzif->StandardBias); + + (void)ConvertWCharNToUtf8(tzif->DaylightName, ARRAYSIZE(tzif->DaylightName), buffer, + ARRAYSIZE(buffer)); + log_print(log, level, file, fkt, line, " DaylightName=%s", buffer); + log_print(log, level, file, fkt, line, " DaylightDate=%s", + systemtime2str(&tzif->DaylightDate, buffer, sizeof(buffer))); + log_print(log, level, file, fkt, line, " DaylightBias=%" PRIu32, tzif->DaylightBias); + (void)ConvertWCharNToUtf8(tzif->TimeZoneKeyName, ARRAYSIZE(tzif->TimeZoneKeyName), buffer, + ARRAYSIZE(buffer)); + log_print(log, level, file, fkt, line, " TimeZoneKeyName=%s", buffer); + log_print(log, level, file, fkt, line, " DynamicDaylightTimeDisabled=DST-%s", + tzif->DynamicDaylightTimeDisabled ? "disabled" : "enabled"); + switch (result) + { + case TIME_ZONE_ID_DAYLIGHT: + log_print(log, level, file, fkt, line, " DaylightDate in use"); + break; + case TIME_ZONE_ID_STANDARD: + log_print(log, level, file, fkt, line, " StandardDate in use"); + break; + default: + log_print(log, level, file, fkt, line, " UnknownDate in use"); + break; + } + log_print(log, level, file, fkt, line, "}"); +} + +DWORD GetTimeZoneInformation(LPTIME_ZONE_INFORMATION lpTimeZoneInformation) +{ + DYNAMIC_TIME_ZONE_INFORMATION dyn = { 0 }; + DWORD rc = GetDynamicTimeZoneInformation(&dyn); + lpTimeZoneInformation->Bias = dyn.Bias; + lpTimeZoneInformation->DaylightBias = dyn.DaylightBias; + lpTimeZoneInformation->DaylightDate = dyn.DaylightDate; + lpTimeZoneInformation->StandardBias = dyn.StandardBias; + lpTimeZoneInformation->StandardDate = dyn.StandardDate; + memcpy(lpTimeZoneInformation->StandardName, dyn.StandardName, + sizeof(lpTimeZoneInformation->StandardName)); + memcpy(lpTimeZoneInformation->DaylightName, dyn.DaylightName, + sizeof(lpTimeZoneInformation->DaylightName)); + return rc; +} + +BOOL SetTimeZoneInformation(const TIME_ZONE_INFORMATION* lpTimeZoneInformation) +{ + WINPR_UNUSED(lpTimeZoneInformation); + return FALSE; +} + +BOOL SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, LPFILETIME lpFileTime) +{ + WINPR_UNUSED(lpSystemTime); + WINPR_UNUSED(lpFileTime); + return FALSE; +} + +BOOL FileTimeToSystemTime(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime) +{ + WINPR_UNUSED(lpFileTime); + WINPR_UNUSED(lpSystemTime); + return FALSE; +} + +BOOL SystemTimeToTzSpecificLocalTime(LPTIME_ZONE_INFORMATION lpTimeZone, + LPSYSTEMTIME lpUniversalTime, LPSYSTEMTIME lpLocalTime) +{ + WINPR_UNUSED(lpTimeZone); + WINPR_UNUSED(lpUniversalTime); + WINPR_UNUSED(lpLocalTime); + return FALSE; +} + +BOOL TzSpecificLocalTimeToSystemTime(LPTIME_ZONE_INFORMATION lpTimeZoneInformation, + LPSYSTEMTIME lpLocalTime, LPSYSTEMTIME lpUniversalTime) +{ + WINPR_UNUSED(lpTimeZoneInformation); + WINPR_UNUSED(lpLocalTime); + WINPR_UNUSED(lpUniversalTime); + return FALSE; +} + +#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 */ + +typedef enum +{ + HAVE_TRANSITION_DATES = 0, + HAVE_NO_STANDARD_TRANSITION_DATE = 1, + HAVE_NO_DAYLIGHT_TRANSITION_DATE = 2 +} dyn_transition_result; + +static int dynamic_time_zone_from_localtime(const struct tm* local_time, + PDYNAMIC_TIME_ZONE_INFORMATION tz) +{ + WINPR_ASSERT(local_time); + WINPR_ASSERT(tz); + int rc = HAVE_TRANSITION_DATES; + + tz->Bias = get_bias(local_time, FALSE); + + /* If the current time has (or had) DST */ + if (local_time->tm_isdst >= 0) + { + /* DST bias is the difference between standard time and DST in minutes */ + const LONG d = get_bias(local_time, TRUE); + tz->DaylightBias = -1 * (tz->Bias - d); + if (!get_transition_date(local_time, FALSE, &tz->StandardDate)) + { + rc |= HAVE_NO_STANDARD_TRANSITION_DATE; + tz->StandardBias = 0; + } + if (!get_transition_date(local_time, TRUE, &tz->DaylightDate)) + { + rc |= HAVE_NO_DAYLIGHT_TRANSITION_DATE; + tz->DaylightBias = 0; + } + } + return rc; +} + +DWORD GetDynamicTimeZoneInformation(PDYNAMIC_TIME_ZONE_INFORMATION pTimeZoneInformation) +{ + const char** list = NULL; + char* tzid = NULL; + const char* defaultName = "Client Local Time"; + DWORD res = TIME_ZONE_ID_UNKNOWN; + const DYNAMIC_TIME_ZONE_INFORMATION empty = { 0 }; + + WINPR_ASSERT(pTimeZoneInformation); + + *pTimeZoneInformation = empty; + (void)ConvertUtf8ToWChar(defaultName, pTimeZoneInformation->StandardName, + ARRAYSIZE(pTimeZoneInformation->StandardName)); + + const time_t t = time(NULL); + struct tm tres = { 0 }; + struct tm* local_time = localtime_r(&t, &tres); + if (!local_time) + goto out_error; + + pTimeZoneInformation->Bias = get_bias(local_time, FALSE); + if (local_time->tm_isdst >= 0) + dynamic_time_zone_from_localtime(local_time, pTimeZoneInformation); + + tzid = winpr_guess_time_zone(); + if (!map_iana_id(tzid, pTimeZoneInformation)) + { + const size_t len = TimeZoneIanaAbbrevGet(local_time->tm_zone, NULL, 0); + list = (const char**)calloc(len, sizeof(const char*)); + if (!list) + goto out_error; + const size_t size = TimeZoneIanaAbbrevGet(local_time->tm_zone, list, len); + for (size_t x = 0; x < size; x++) + { + const char* id = list[x]; + if (map_iana_id(id, pTimeZoneInformation)) + { + res = (local_time->tm_isdst) ? TIME_ZONE_ID_DAYLIGHT : TIME_ZONE_ID_STANDARD; + break; + } + } + } + else + res = (local_time->tm_isdst) ? TIME_ZONE_ID_DAYLIGHT : TIME_ZONE_ID_STANDARD; + +out_error: + free(tzid); + free((void*)list); + + log_timezone(pTimeZoneInformation, res); + return res; +} + +BOOL SetDynamicTimeZoneInformation(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation) +{ + WINPR_UNUSED(lpTimeZoneInformation); + return FALSE; +} + +BOOL GetTimeZoneInformationForYear(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, + LPTIME_ZONE_INFORMATION ptzi) +{ + WINPR_UNUSED(wYear); + WINPR_UNUSED(pdtzi); + WINPR_UNUSED(ptzi); + return FALSE; +} + +#endif + +#if !defined(_WIN32) || (defined(_WIN32) && (_WIN32_WINNT < 0x0601)) /* Windows 7 */ + +BOOL SystemTimeToTzSpecificLocalTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, + const SYSTEMTIME* lpUniversalTime, LPSYSTEMTIME lpLocalTime) +{ + WINPR_UNUSED(lpTimeZoneInformation); + WINPR_UNUSED(lpUniversalTime); + WINPR_UNUSED(lpLocalTime); + return FALSE; +} + +BOOL TzSpecificLocalTimeToSystemTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, + const SYSTEMTIME* lpLocalTime, LPSYSTEMTIME lpUniversalTime) +{ + WINPR_UNUSED(lpTimeZoneInformation); + WINPR_UNUSED(lpLocalTime); + WINPR_UNUSED(lpUniversalTime); + return FALSE; +} + +#endif + +#if !defined(_WIN32) + +DWORD EnumDynamicTimeZoneInformation(const DWORD dwIndex, + PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation) +{ + if (!lpTimeZoneInformation) + return ERROR_INVALID_PARAMETER; + const DYNAMIC_TIME_ZONE_INFORMATION empty = { 0 }; + *lpTimeZoneInformation = empty; + + const TimeZoneNameMapEntry* entry = TimeZoneGetAt(dwIndex); + if (!entry) + return ERROR_NO_MORE_ITEMS; + + if (entry->DaylightName) + (void)ConvertUtf8ToWChar(entry->DaylightName, lpTimeZoneInformation->DaylightName, + ARRAYSIZE(lpTimeZoneInformation->DaylightName)); + if (entry->StandardName) + (void)ConvertUtf8ToWChar(entry->StandardName, lpTimeZoneInformation->StandardName, + ARRAYSIZE(lpTimeZoneInformation->StandardName)); + if (entry->Id) + (void)ConvertUtf8ToWChar(entry->Id, lpTimeZoneInformation->TimeZoneKeyName, + ARRAYSIZE(lpTimeZoneInformation->TimeZoneKeyName)); + + const time_t t = time(NULL); + struct tm tres = { 0 }; + + char* tzcopy = entry->Iana ? setNewAndSaveOldTZ(entry->Iana) : NULL; + + struct tm* local_time = localtime_r(&t, &tres); + + if (local_time) + dynamic_time_zone_from_localtime(local_time, lpTimeZoneInformation); + + if (entry->Iana) + restoreSavedTZ(tzcopy); + + return ERROR_SUCCESS; +} + +// NOLINTBEGIN(readability-non-const-parameter) +DWORD GetDynamicTimeZoneInformationEffectiveYears( + const PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation, LPDWORD FirstYear, LPDWORD LastYear) +// NOLINTEND(readability-non-const-parameter) +{ + WINPR_UNUSED(lpTimeZoneInformation); + WINPR_UNUSED(FirstYear); + WINPR_UNUSED(LastYear); + return ERROR_FILE_NOT_FOUND; +} + +#elif _WIN32_WINNT < 0x0602 /* Windows 8 */ +DWORD EnumDynamicTimeZoneInformation(const DWORD dwIndex, + PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation) +{ + WINPR_UNUSED(dwIndex); + WINPR_UNUSED(lpTimeZoneInformation); + return ERROR_NO_MORE_ITEMS; +} + +DWORD GetDynamicTimeZoneInformationEffectiveYears( + const PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation, LPDWORD FirstYear, LPDWORD LastYear) +{ + WINPR_UNUSED(lpTimeZoneInformation); + WINPR_UNUSED(FirstYear); + WINPR_UNUSED(LastYear); + return ERROR_FILE_NOT_FOUND; +} +#endif + +#if !defined(_WIN32) +char* setNewAndSaveOldTZ(const char* val) +{ + // NOLINTBEGIN(concurrency-mt-unsafe) + const char* otz = getenv("TZ"); + char* oldtz = NULL; + if (otz) + oldtz = _strdup(otz); + setenv("TZ", val, 1); + tzset(); + // NOLINTEND(concurrency-mt-unsafe) + return oldtz; +} + +void restoreSavedTZ(char* saved) +{ + // NOLINTBEGIN(concurrency-mt-unsafe) + if (saved) + { + setenv("TZ", saved, 1); + free(saved); + } + else + unsetenv("TZ"); + tzset(); + // NOLINTEND(concurrency-mt-unsafe) +} +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.h new file mode 100644 index 0000000000000000000000000000000000000000..bb656e8e2336c2bd32d10f2524c50f8047419b0e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/timezone.h @@ -0,0 +1,26 @@ +/** + * WinPR: Windows Portable Runtime + * Time Zone + * + * Copyright 2025 Armin Novak + * Copyright 2025 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 + +#if !defined(_WIN32) +char* setNewAndSaveOldTZ(const char* val); +void restoreSavedTZ(char* saved); +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0edf04b13770a0db5a30ef13387f8de79e13a87b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() + +project(tzextract VERSION 1.0.0 LANGUAGES CSharp) + +set(CMAKE_CSharp_FLAGS "/langversion:10") +set(CMAKE_DOTNET_TARGET_FRAMEWORK "net6.0") +set(CMAKE_DOTNET_SDK "Microsoft.NET.Sdk") + +add_executable(${PROJECT_NAME} tzextract.cs) + +set_property(TARGET ${PROJECT_NAME} PROPERTY WIN32_EXECUTABLE FALSE) + +set_property( + TARGET ${PROJECT_NAME} + PROPERTY VS_DOTNET_REFERENCES + "System" + "System.Collections.Generic" + "System.IO" + "System.Net.Http" + "System.Linq" + "System.Threading" + "System.Threading.Tasks" +) +install(TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBRARY_DIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBRARY_DIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINARY_DIR} INCLUDES + DESTINATION ${CMAKE_INSTALL_INCLUDE_DIR} +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/tzextract.cs b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/tzextract.cs new file mode 100644 index 0000000000000000000000000000000000000000..457d0ca945f316a71be10850acced92c344fdf5a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/timezone/utils/tzextract.cs @@ -0,0 +1,220 @@ +using System; +using System.IO; +using System.Net; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using System.Xml.Schema; + +internal class Program +{ + private static string app = AppDomain.CurrentDomain.FriendlyName; + private static TextWriter stderr = Console.Error; + private static TextWriter stdout = Console.Out; + + private static void usage() + { + stderr.WriteLine("Usage:"); + stderr.WriteLine(app + " "); + Environment.Exit(1); + } + + private static bool writeZoneMapC(string path) + { + string fname = "TimeZoneNameMap"; + string fpath = Path.Combine(path, fname + "_static.h"); + + using (StreamWriter fs = new StreamWriter(fpath)) + { + fs.WriteLine("/* Automatically generated by " + app + " */"); + fs.WriteLine(""); + fs.WriteLine("#include \"" + fname + ".h\""); + fs.WriteLine(""); + fs.WriteLine("static const " + fname + "Entry " + fname + "[] ={"); + + bool first = true; + foreach (System.TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones()) + { + string iana; + System.TimeZoneInfo.TryConvertWindowsIdToIanaId(tz.Id, out iana); + + StringBuilder sb = new StringBuilder(); + if (!first) + sb.Append(","); + first = false; + sb.Append("{ \""); + sb.Append(tz.Id); + sb.Append("\", \""); + sb.Append(tz.StandardName); + sb.Append("\", \""); + sb.Append(tz.DisplayName); + sb.Append("\", \""); + sb.Append(tz.DaylightName); + sb.Append("\", \""); + sb.Append(iana); + sb.Append("\" }"); + fs.WriteLine(sb.ToString()); + } + + fs.WriteLine("};"); + fs.WriteLine(""); + fs.WriteLine("static const size_t " + fname + "Size = ARRAYSIZE(" + fname + ");"); + } + return true; + } + + private static bool writeZoneMapJSON(string path) + { + string fname = "TimeZoneNameMap"; + string fpath = Path.Combine(path, fname + ".json"); + + using (StreamWriter fs = new StreamWriter(fpath)) + { + fs.WriteLine("{"); + fs.WriteLine("\"TimeZoneNameMap\": ["); + + bool first = true; + foreach (System.TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones()) + { + string iana; + System.TimeZoneInfo.TryConvertWindowsIdToIanaId(tz.Id, out iana); + + StringBuilder sb = new StringBuilder(); + if (!first) + sb.Append(","); + first = false; + sb.Append("{ "); + sb.Append("\"Id\": \""); + sb.Append(tz.Id); + sb.Append("\", \"StandardName\": \""); + sb.Append(tz.StandardName); + sb.Append("\", \"DisplayName\": \""); + sb.Append(tz.DisplayName); + sb.Append("\", \"DaylightName\": \""); + sb.Append(tz.DaylightName); + sb.Append("\", \"Iana\": \""); + sb.Append(iana); + sb.Append("\" }"); + fs.WriteLine(sb.ToString()); + } + + fs.WriteLine("]"); + fs.WriteLine("}"); + } + return true; + } + + private static bool writeZoneMap(string path) + { + if (!writeZoneMapC(path)) + return false; + if (!writeZoneMapJSON(path)) + return false; + return true; + } + + private static void onValidation(object sender, ValidationEventArgs e) + { + switch (e.Severity) + { + case XmlSeverityType.Warning: + case XmlSeverityType.Error: + stderr.WriteLine(e.ToString()); + break; + default: + break; + } + } + private static bool updateWindowsIanaMap(string path) + { + string url = + "https://raw.githubusercontent.com/unicode-org/cldr/main/common/supplemental/windowsZones.xml"; + string fname = "WindowsZones"; + string fpath = Path.Combine(path, fname + ".c"); + + XmlDocument doc = new XmlDocument(); + doc.Load(url); + + stdout.WriteLine("Downloaded and parsed XML from '" + url + "'"); + + ValidationEventHandler handler = new ValidationEventHandler(onValidation); + // doc.Validate(handler); + + XmlNodeList versions = doc.SelectNodes("//supplementalData/version"); + XmlNodeList zones = doc.SelectNodes("//supplementalData/windowsZones/mapTimezones"); + XmlNodeList mzones = + doc.SelectNodes("//supplementalData/windowsZones/mapTimezones/mapZone"); + + using (StreamWriter fs = new StreamWriter(fpath)) + { + fs.WriteLine("/* Automatically generated by " + app); + fs.WriteLine(" *"); + fs.WriteLine(" * url " + url); + + foreach (XmlNode version in versions) + { + XmlNode nr = version.Attributes.GetNamedItem("number"); + fs.WriteLine(" * version: " + nr.InnerText); + } + + foreach (XmlNode node in zones) + { + XmlNode over = node.Attributes.GetNamedItem("otherVersion"); + XmlNode tver = node.Attributes.GetNamedItem("typeVersion"); + fs.WriteLine(" * mapTimezones: otherVersion: " + over.InnerText + + ", typeVersion: " + tver.InnerText); + } + + fs.WriteLine(" */"); + fs.WriteLine(""); + fs.WriteLine("#include \"" + fname + ".h\""); + fs.WriteLine(""); + fs.WriteLine("const WINDOWS_TZID_ENTRY " + fname + "[] = {"); + + foreach (XmlNode mzone in mzones) + { + XmlAttributeCollection attrs = mzone.Attributes; + XmlNode wzid = attrs.GetNamedItem("other"); + XmlNode territory = attrs.GetNamedItem("territory"); + XmlNode iana = attrs.GetNamedItem("type"); + fs.WriteLine("\t{ \"" + iana.InnerText + "\", \"" + wzid.InnerText + "\" }, // " + + territory.InnerText); + } + + fs.WriteLine("};"); + fs.WriteLine(""); + fs.WriteLine("const size_t " + fname + "NrElements = ARRAYSIZE(" + fname + ");"); + } + stdout.WriteLine("Finished update"); + return true; + } + + private static void Main(string[] args) + { + try + { + if (args.Length == 0) + { + stderr.WriteLine("Missing arguments!"); + usage(); + } + + DirectoryInfo info = new DirectoryInfo(args[0]); + if (!info.Exists) + { + stderr.WriteLine("Path '" + info.FullName + "' does not exist"); + usage(); + } + + if (!writeZoneMap(info.FullName)) + return; + + updateWindowsIanaMap(info.FullName); + } + catch (Exception e) + { + stderr.WriteLine(e.ToString()); + Environment.Exit(-23); + } + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7e3d1b83fd7929b063bd77c83c88982613684885 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/CMakeLists.txt @@ -0,0 +1,230 @@ +# WinPR: Windows Portable Runtime +# libwinpr-utils cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(CMakeDependentOption) + +winpr_include_directory_add(${CMAKE_CURRENT_SOURCE_DIR}) + +option(WITH_STREAMPOOL_DEBUG "build with extensive streampool logging" OFF) +if(WITH_STREAMPOOL_DEBUG) + winpr_definition_add(-DWITH_STREAMPOOL_DEBUG) +endif() + +option(WITH_LODEPNG "build WinPR with PNG support" OFF) +if(WITH_LODEPNG) + find_package(lodepng REQUIRED) + + winpr_definition_add(WITH_LODEPNG) + set(WINPR_WITH_PNG ON CACHE BOOL "build cache") + + winpr_system_include_directory_add(${lodepng_INCLUDE_DIRS}) + winpr_library_add_private(${lodepng_LIBRARIES}) +endif() + +option(WINPR_UTILS_IMAGE_PNG "Add PNG <--> BMP conversion support to clipboard" OFF) +if(WINPR_UTILS_IMAGE_PNG) + find_package(PNG REQUIRED) + + set(WINPR_WITH_PNG ON CACHE BOOL "build cache") + winpr_system_include_directory_add(${PNG_INCLUDE_DIRS}) + winpr_library_add_private(${PNG_LIBRARIES}) +endif() + +option(WINPR_UTILS_IMAGE_WEBP "Add WebP <--> BMP conversion support to clipboard" OFF) +if(WINPR_UTILS_IMAGE_WEBP) + find_package(PkgConfig REQUIRED) + pkg_check_modules(WEBP libwebp REQUIRED) + + winpr_system_include_directory_add(${WEBP_INCLUDE_DIRS}) + winpr_library_add_private(${WEBP_LIBRARIES}) +endif() + +option(WINPR_UTILS_IMAGE_JPEG "Add Jpeg <--> BMP conversion support to clipboard" OFF) +if(WINPR_UTILS_IMAGE_JPEG) + find_package(PkgConfig REQUIRED) + pkg_check_modules(JPEG libjpeg REQUIRED) + + winpr_system_include_directory_add(${JPEG_INCLUDE_DIRS}) + winpr_library_add_private(${JPEG_LIBRARIES}) +endif() + +set(COLLECTIONS_SRCS + collections/Object.c + collections/Queue.c + collections/Stack.c + collections/PubSub.c + collections/BitStream.c + collections/ArrayList.c + collections/LinkedList.c + collections/HashTable.c + collections/ListDictionary.c + collections/CountdownEvent.c + collections/BufferPool.c + collections/ObjectPool.c + collections/StreamPool.c + collections/MessageQueue.c + collections/MessagePipe.c +) + +if(WINPR_HAVE_SYSLOG_H) + set(SYSLOG_SRCS wlog/SyslogAppender.c wlog/SyslogAppender.h) +endif() + +find_package(libsystemd) +option(WITH_SYSTEMD "allows to export wLog to systemd journal" ${libsystemd_FOUND}) +if(WITH_LIBSYSTEMD) + find_package(libsystemd REQUIRED) + set(WINPR_HAVE_JOURNALD_H TRUE) + set(JOURNALD_SRCS wlog/JournaldAppender.c wlog/JournaldAppender.h) + winpr_system_include_directory_add(${LIBSYSTEMD_INCLUDE_DIR}) + winpr_library_add_private(${LIBSYSTEMD_LIBRARY}) +else() + unset(WINPR_HAVE_JOURNALD_H) +endif() + +set(WLOG_SRCS + wlog/wlog.c + wlog/wlog.h + wlog/Layout.c + wlog/Layout.h + wlog/Message.c + wlog/Message.h + wlog/DataMessage.c + wlog/DataMessage.h + wlog/ImageMessage.c + wlog/ImageMessage.h + wlog/PacketMessage.c + wlog/PacketMessage.h + wlog/Appender.c + wlog/Appender.h + wlog/FileAppender.c + wlog/FileAppender.h + wlog/BinaryAppender.c + wlog/BinaryAppender.h + wlog/CallbackAppender.c + wlog/CallbackAppender.h + wlog/ConsoleAppender.c + wlog/ConsoleAppender.h + wlog/UdpAppender.c + wlog/UdpAppender.h + ${SYSLOG_SRCS} + ${JOURNALD_SRCS} +) + +set(ASN1_SRCS asn1/asn1.c) + +set(SRCS + ini.c + sam.c + ntlm.c + image.c + print.c + stream.h + stream.c + strlst.c + debug.c + winpr.c + cmdline.c + ssl.c +) + +if(ANDROID) + list(APPEND SRCS android.h android.c) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + if(NOT WINPR_HAVE_UNWIND_H) + message("[backtrace] android NDK without unwind.h, falling back to corkscrew") + set(WINPR_HAVE_CORKSCREW 1) + endif() +endif() + +if(WINPR_HAVE_CORKSCREW) + list(APPEND SRCS corkscrew/debug.c corkscrew/debug.h) +endif() + +if(WIN32) + list(APPEND SRCS windows/debug.c windows/debug.h) +endif() + +if(WINPR_HAVE_EXECINFO_H) + option(USE_EXECINFO "Use execinfo.h to generate backtraces" ON) + if(USE_EXECINFO) + winpr_definition_add(USE_EXECINFO) + list(APPEND SRCS execinfo/debug.c execinfo/debug.h) + endif() +endif() + +if(WINPR_HAVE_UNWIND_H) + option(USE_UNWIND "Use unwind.h to generate backtraces" ON) + if(USE_UNWIND) + winpr_definition_add(USE_UNWIND) + list(APPEND SRCS unwind/debug.c unwind/debug.h) + endif() +endif() + +include(JsonDetect) +if(NOT WITH_JSON_DISABLED) + if(JSONC_FOUND AND NOT WITH_CJSON_REQUIRED) + winpr_library_add_private(${JSONC_LIBRARIES}) + winpr_system_include_directory_add(${JSONC_INCLUDE_DIRS}) + winpr_definition_add(WITH_JSONC) + set(WITH_WINPR_JSON ON CACHE INTERNAL "internal") + elseif(CJSON_FOUND) + winpr_library_add_private(${CJSON_LIBRARIES}) + winpr_system_include_directory_add(${CJSON_INCLUDE_DIRS}) + winpr_definition_add(WITH_CJSON) + set(WITH_WINPR_JSON ON CACHE INTERNAL "internal") + endif() +endif() + +winpr_module_add(json/json.c) + +winpr_module_add(${SRCS} ${COLLECTIONS_SRCS} ${WLOG_SRCS} ${ASN1_SRCS}) + +winpr_include_directory_add(".") + +if(OPENSSL_FOUND) + winpr_system_include_directory_add(${OPENSSL_INCLUDE_DIR}) + winpr_library_add_private(${OPENSSL_LIBRARIES}) +endif() + +if(MBEDTLS_FOUND) + winpr_system_include_directory_add(${MBEDTLS_INCLUDE_DIR}) + winpr_library_add_private(${MBEDTLS_LIBRARIES}) +endif() + +if(UNIX) + winpr_library_add_private(m) + + set(CMAKE_REQUIRED_INCLUDES backtrace.h) + check_function_exists(backtrace BACKTRACE) + if(NOT BACKTRACE) + set(CMAKE_REQUIRED_LIBRARIES execinfo) + check_function_exists(backtrace EXECINFO) + if(EXECINFO) + winpr_library_add_private(execinfo) + endif() + endif() +endif() + +if(WIN32) + winpr_library_add_public(dbghelp) +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..cc0d0ed449fd15882478bea5f4e5e74b7bb195f1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ModuleOptions.cmake @@ -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 "utils") +set(MINWIN_LONG_NAME "WinPR Utils") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.c new file mode 100644 index 0000000000000000000000000000000000000000..2918cc717ae4c5f475205c980f110be6af3ccb52 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.c @@ -0,0 +1,77 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Winpr android helpers + * + * Copyright 2022 Armin Novak + * + * 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 "android.h" +#include + +#include +#include + +#include "../log.h" + +#define TAG WINPR_TAG("android") + +JavaVM* jniVm = NULL; + +WINPR_API jint JNI_OnLoad(JavaVM* vm, void* reserved) +{ + WLog_INFO(TAG, "Setting up JNI environment..."); + + jniVm = vm; + return JNI_VERSION_1_6; +} + +WINPR_API void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) +{ + JNIEnv* env = NULL; + WLog_INFO(TAG, "Tearing down JNI environment..."); + + if ((*jniVm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) + { + WLog_FATAL(TAG, "Failed to get the environment"); + return; + } +} + +jboolean winpr_jni_attach_thread(JNIEnv** env) +{ + WINPR_ASSERT(jniVm); + + if ((*jniVm)->GetEnv(jniVm, (void**)env, JNI_VERSION_1_4) != JNI_OK) + { + WLog_INFO(TAG, "android_java_callback: attaching current thread"); + (*jniVm)->AttachCurrentThread(jniVm, env, NULL); + + if ((*jniVm)->GetEnv(jniVm, (void**)env, JNI_VERSION_1_4) != JNI_OK) + { + WLog_ERR(TAG, "android_java_callback: failed to obtain current JNI environment"); + } + + return JNI_TRUE; + } + + return JNI_FALSE; +} + +/* attach current thread to JVM */ +void winpr_jni_detach_thread(void) +{ + WINPR_ASSERT(jniVm); + (*jniVm)->DetachCurrentThread(jniVm); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.h new file mode 100644 index 0000000000000000000000000000000000000000..30b264b53acc8e7a4b11f695f1159cd9c8631dd0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/android.h @@ -0,0 +1,30 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Winpr android helpers + * + * Copyright 2022 Armin Novak + * + * 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_ANDROID_PRIV_H +#define WINPR_UTILS_ANDROID_PRIV_H + +#include + +extern JavaVM* jniVm; + +jboolean winpr_jni_attach_thread(JNIEnv** env); +void winpr_jni_detach_thread(void); + +#endif /* WINPR_UTILS_ANDROID_PRIV_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/asn1/asn1.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/asn1/asn1.c new file mode 100644 index 0000000000000000000000000000000000000000..c91484bac31d79a42981266fc74d472441e2e356 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/asn1/asn1.c @@ -0,0 +1,1505 @@ +/** + * WinPR: Windows Portable Runtime + * ASN1 routines + * + * Copyright 2022 David Fort + * + * 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 + +#include +#include +#include + +#include "../../log.h" +#define TAG WINPR_TAG("asn1") + +typedef struct +{ + size_t poolOffset; + size_t capacity; + size_t used; +} Asn1Chunk; + +#define MAX_STATIC_ITEMS 50 + +/** @brief type of encoder container */ +typedef enum +{ + ASN1_CONTAINER_SEQ, + ASN1_CONTAINER_SET, + ASN1_CONTAINER_APP, + ASN1_CONTAINER_CONTEXT_ONLY, + ASN1_CONTAINER_OCTETSTRING, +} ContainerType; + +typedef struct WinPrAsn1EncContainer WinPrAsn1EncContainer; +/** @brief a container in the ASN1 stream (sequence, set, app or contextual) */ +struct WinPrAsn1EncContainer +{ + size_t headerChunkId; + BOOL contextual; + WinPrAsn1_tag tag; + ContainerType containerType; +}; + +/** @brief the encoder internal state */ +struct WinPrAsn1Encoder +{ + WinPrAsn1EncodingRule encoding; + wStream* pool; + + Asn1Chunk* chunks; + Asn1Chunk staticChunks[MAX_STATIC_ITEMS]; + size_t freeChunkId; + size_t chunksCapacity; + + WinPrAsn1EncContainer* containers; + WinPrAsn1EncContainer staticContainers[MAX_STATIC_ITEMS]; + size_t freeContainerIndex; + size_t containerCapacity; +}; + +#define WINPR_ASSERT_VALID_TAG(t) WINPR_ASSERT((t) < 64) + +void WinPrAsn1FreeOID(WinPrAsn1_OID* poid) +{ + WINPR_ASSERT(poid); + free(poid->data); + poid->data = NULL; + poid->len = 0; +} + +void WinPrAsn1FreeOctetString(WinPrAsn1_OctetString* octets) +{ + WinPrAsn1FreeOID(octets); +} + +/** + * The encoder is implemented with the goals to: + * * have an API which is convenient to use (avoid computing inner elements size) + * * hide the BER/DER encoding details + * * avoid multiple copies and memory moves when building the content + * + * To achieve this, the encoder contains a big memory block (encoder->pool), and various chunks + * (encoder->chunks) pointing to that memory block. The idea is to reserve some space in the pool + * for the container headers when we start a new container element. For example when a sequence is + * started we reserve 6 bytes which is the maximum size: byte0 + length. Then fill the content of + * the sequence in further chunks. When a container is closed, we compute the inner size (by adding + * the size of inner chunks), we write the headers bytes, and we adjust the chunk size accordingly. + * + * For example to encode: + * SEQ + * IASTRING(test1) + * INTEGER(200) + * + * with this code: + * + * WinPrAsn1EncSeqContainer(enc); + * WinPrAsn1EncIA5String(enc, "test1"); + * WinPrAsn1EncInteger(enc, 200); + * + * Memory pool and chunks would look like: + * + * [ reserved for seq][string|5|"test1"][integer|0x81|200] + * (6 bytes) + * |-----------------||----------------------------------| + * ^ ^ + * | | + * chunk0 chunk1 + * + * As we try to compact chunks as much as we can, we managed to encode the ia5string and the + * integer using the same chunk. + * + * When the sequence is closed with: + * + * WinPrAsn1EncEndContainer(enc); + * + * The final pool and chunks will look like: + * + * XXXXXX[seq headers][string|5|"test1"][integer|0x81|200] + * + * |-----------||----------------------------------| + * ^ ^ + * | | + * chunk0 chunk1 + * + * The generated content can be retrieved using: + * + * WinPrAsn1EncToStream(enc, targetStream); + * + * It will sequentially write all the chunks in the given target stream. + */ + +WinPrAsn1Encoder* WinPrAsn1Encoder_New(WinPrAsn1EncodingRule encoding) +{ + WinPrAsn1Encoder* enc = calloc(1, sizeof(*enc)); + if (!enc) + return NULL; + + enc->encoding = encoding; + enc->pool = Stream_New(NULL, 1024); + if (!enc->pool) + { + free(enc); + return NULL; + } + + enc->containers = &enc->staticContainers[0]; + enc->chunks = &enc->staticChunks[0]; + enc->chunksCapacity = MAX_STATIC_ITEMS; + enc->freeContainerIndex = 0; + return enc; +} + +void WinPrAsn1Encoder_Reset(WinPrAsn1Encoder* enc) +{ + WINPR_ASSERT(enc); + + enc->freeContainerIndex = 0; + enc->freeChunkId = 0; + + ZeroMemory(enc->chunks, sizeof(*enc->chunks) * enc->chunksCapacity); +} + +void WinPrAsn1Encoder_Free(WinPrAsn1Encoder** penc) +{ + WinPrAsn1Encoder* enc = NULL; + + WINPR_ASSERT(penc); + enc = *penc; + if (enc) + { + if (enc->containers != &enc->staticContainers[0]) + free(enc->containers); + + if (enc->chunks != &enc->staticChunks[0]) + free(enc->chunks); + + Stream_Free(enc->pool, TRUE); + free(enc); + } + *penc = NULL; +} + +static Asn1Chunk* asn1enc_get_free_chunk(WinPrAsn1Encoder* enc, size_t chunkSz, BOOL commit, + size_t* id) +{ + Asn1Chunk* ret = NULL; + WINPR_ASSERT(enc); + WINPR_ASSERT(chunkSz); + + if (commit) + { + /* if it's not a reservation let's see if the last chunk is not a reservation and can be + * expanded */ + size_t lastChunk = enc->freeChunkId ? enc->freeChunkId - 1 : 0; + ret = &enc->chunks[lastChunk]; + if (ret->capacity && ret->capacity == ret->used) + { + if (!Stream_EnsureRemainingCapacity(enc->pool, chunkSz)) + return NULL; + + Stream_Seek(enc->pool, chunkSz); + ret->capacity += chunkSz; + ret->used += chunkSz; + if (id) + *id = lastChunk; + return ret; + } + } + + if (enc->freeChunkId == enc->chunksCapacity) + { + /* chunks need a resize */ + Asn1Chunk* src = (enc->chunks != &enc->staticChunks[0]) ? enc->chunks : NULL; + Asn1Chunk* tmp = realloc(src, (enc->chunksCapacity + 10) * sizeof(*src)); + if (!tmp) + return NULL; + + if (enc->chunks == &enc->staticChunks[0]) + memcpy(tmp, &enc->staticChunks[0], enc->chunksCapacity * sizeof(*src)); + else + memset(tmp + enc->freeChunkId, 0, sizeof(*tmp) * 10); + + enc->chunks = tmp; + enc->chunksCapacity += 10; + } + if (enc->freeChunkId == enc->chunksCapacity) + return NULL; + + if (!Stream_EnsureRemainingCapacity(enc->pool, chunkSz)) + return NULL; + + ret = &enc->chunks[enc->freeChunkId]; + ret->poolOffset = Stream_GetPosition(enc->pool); + ret->capacity = chunkSz; + ret->used = commit ? chunkSz : 0; + if (id) + *id = enc->freeChunkId; + + enc->freeChunkId++; + Stream_Seek(enc->pool, chunkSz); + return ret; +} + +static WinPrAsn1EncContainer* asn1enc_get_free_container(WinPrAsn1Encoder* enc, size_t* id) +{ + WinPrAsn1EncContainer* ret = NULL; + WINPR_ASSERT(enc); + + if (enc->freeContainerIndex == enc->containerCapacity) + { + /* containers need a resize (or switch from static to dynamic) */ + WinPrAsn1EncContainer* src = + (enc->containers != &enc->staticContainers[0]) ? enc->containers : NULL; + WinPrAsn1EncContainer* tmp = realloc(src, (enc->containerCapacity + 10) * sizeof(*src)); + if (!tmp) + return NULL; + + if (enc->containers == &enc->staticContainers[0]) + memcpy(tmp, &enc->staticContainers[0], enc->containerCapacity * sizeof(*src)); + + enc->containers = tmp; + enc->containerCapacity += 10; + } + if (enc->freeContainerIndex == enc->containerCapacity) + return NULL; + + ret = &enc->containers[enc->freeContainerIndex]; + *id = enc->freeContainerIndex; + + enc->freeContainerIndex++; + return ret; +} + +static size_t lenBytes(size_t len) +{ + if (len < 128) + return 1; + if (len < (1 << 8)) + return 2; + if (len < (1 << 16)) + return 3; + if (len < (1 << 24)) + return 4; + + return 5; +} + +static void asn1WriteLen(wStream* s, size_t len) +{ + if (len < 128) + { + Stream_Write_UINT8(s, (UINT8)len); + } + else if (len < (1 << 8)) + { + Stream_Write_UINT8(s, 0x81); + Stream_Write_UINT8(s, (UINT8)len); + } + else if (len < (1 << 16)) + { + Stream_Write_UINT8(s, 0x82); + Stream_Write_UINT16_BE(s, (UINT16)len); + } + else if (len < (1 << 24)) + { + Stream_Write_UINT8(s, 0x83); + Stream_Write_UINT24_BE(s, (UINT32)len); + } + else + { + WINPR_ASSERT(len <= UINT32_MAX); + Stream_Write_UINT8(s, 0x84); + Stream_Write_UINT32_BE(s, (UINT32)len); + } +} + +static WinPrAsn1EncContainer* getAsn1Container(WinPrAsn1Encoder* enc, ContainerType ctype, + WinPrAsn1_tag tag, BOOL contextual, size_t maxLen) +{ + size_t ret = 0; + size_t chunkId = 0; + WinPrAsn1EncContainer* container = NULL; + + Asn1Chunk* chunk = asn1enc_get_free_chunk(enc, maxLen, FALSE, &chunkId); + if (!chunk) + return NULL; + + container = asn1enc_get_free_container(enc, &ret); + container->containerType = ctype; + container->tag = tag; + container->contextual = contextual; + container->headerChunkId = chunkId; + return container; +} + +BOOL WinPrAsn1EncAppContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId) +{ + WINPR_ASSERT_VALID_TAG(tagId); + return getAsn1Container(enc, ASN1_CONTAINER_APP, tagId, FALSE, 6) != NULL; +} + +BOOL WinPrAsn1EncSeqContainer(WinPrAsn1Encoder* enc) +{ + return getAsn1Container(enc, ASN1_CONTAINER_SEQ, 0, FALSE, 6) != NULL; +} + +BOOL WinPrAsn1EncSetContainer(WinPrAsn1Encoder* enc) +{ + return getAsn1Container(enc, ASN1_CONTAINER_SET, 0, FALSE, 6) != NULL; +} + +BOOL WinPrAsn1EncContextualSeqContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId) +{ + return getAsn1Container(enc, ASN1_CONTAINER_SEQ, tagId, TRUE, 6 + 6) != NULL; +} + +BOOL WinPrAsn1EncContextualSetContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId) +{ + return getAsn1Container(enc, ASN1_CONTAINER_SET, tagId, TRUE, 6 + 6) != NULL; +} + +BOOL WinPrAsn1EncContextualContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId) +{ + return getAsn1Container(enc, ASN1_CONTAINER_CONTEXT_ONLY, tagId, TRUE, 6) != NULL; +} + +BOOL WinPrAsn1EncOctetStringContainer(WinPrAsn1Encoder* enc) +{ + return getAsn1Container(enc, ASN1_CONTAINER_OCTETSTRING, 0, FALSE, 6) != NULL; +} + +BOOL WinPrAsn1EncContextualOctetStringContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId) +{ + return getAsn1Container(enc, ASN1_CONTAINER_OCTETSTRING, tagId, TRUE, 6 + 6) != NULL; +} + +size_t WinPrAsn1EncEndContainer(WinPrAsn1Encoder* enc) +{ + size_t innerLen = 0; + size_t unused = 0; + size_t innerHeaderBytes = 0; + size_t outerHeaderBytes = 0; + BYTE containerByte = 0; + WinPrAsn1EncContainer* container = NULL; + Asn1Chunk* chunk = NULL; + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT(enc->freeContainerIndex); + + /* compute inner length */ + container = &enc->containers[enc->freeContainerIndex - 1]; + innerLen = 0; + for (size_t i = container->headerChunkId + 1; i < enc->freeChunkId; i++) + innerLen += enc->chunks[i].used; + + /* compute effective headerLength */ + switch (container->containerType) + { + case ASN1_CONTAINER_SEQ: + containerByte = ER_TAG_SEQUENCE; + innerHeaderBytes = 1 + lenBytes(innerLen); + break; + case ASN1_CONTAINER_SET: + containerByte = ER_TAG_SET; + innerHeaderBytes = 1 + lenBytes(innerLen); + break; + case ASN1_CONTAINER_OCTETSTRING: + containerByte = ER_TAG_OCTET_STRING; + innerHeaderBytes = 1 + lenBytes(innerLen); + break; + case ASN1_CONTAINER_APP: + containerByte = ER_TAG_APP | container->tag; + innerHeaderBytes = 1 + lenBytes(innerLen); + break; + case ASN1_CONTAINER_CONTEXT_ONLY: + innerHeaderBytes = 0; + break; + default: + WLog_ERR(TAG, "invalid containerType"); + return 0; + } + + outerHeaderBytes = innerHeaderBytes; + if (container->contextual) + { + outerHeaderBytes = 1 + lenBytes(innerHeaderBytes + innerLen) + innerHeaderBytes; + } + + /* we write the headers at the end of the reserved space and we adjust + * the chunk to be a non reserved chunk */ + chunk = &enc->chunks[container->headerChunkId]; + unused = chunk->capacity - outerHeaderBytes; + chunk->poolOffset += unused; + chunk->capacity = chunk->used = outerHeaderBytes; + + Stream_StaticInit(s, Stream_Buffer(enc->pool) + chunk->poolOffset, outerHeaderBytes); + if (container->contextual) + { + Stream_Write_UINT8(s, ER_TAG_CONTEXTUAL | container->tag); + asn1WriteLen(s, innerHeaderBytes + innerLen); + } + + switch (container->containerType) + { + case ASN1_CONTAINER_SEQ: + case ASN1_CONTAINER_SET: + case ASN1_CONTAINER_OCTETSTRING: + case ASN1_CONTAINER_APP: + Stream_Write_UINT8(s, containerByte); + asn1WriteLen(s, innerLen); + break; + case ASN1_CONTAINER_CONTEXT_ONLY: + break; + default: + WLog_ERR(TAG, "invalid containerType"); + return 0; + } + + /* TODO: here there is place for packing chunks */ + enc->freeContainerIndex--; + return outerHeaderBytes + innerLen; +} + +static BOOL asn1_getWriteStream(WinPrAsn1Encoder* enc, size_t len, wStream* s) +{ + BYTE* dest = NULL; + Asn1Chunk* chunk = asn1enc_get_free_chunk(enc, len, TRUE, NULL); + if (!chunk) + return FALSE; + + dest = Stream_Buffer(enc->pool) + chunk->poolOffset + chunk->capacity - len; + Stream_StaticInit(s, dest, len); + return TRUE; +} + +size_t WinPrAsn1EncRawContent(WinPrAsn1Encoder* enc, const WinPrAsn1_MemoryChunk* c) +{ + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT(c); + + if (!asn1_getWriteStream(enc, c->len, s)) + return 0; + + Stream_Write(s, c->data, c->len); + return c->len; +} + +size_t WinPrAsn1EncContextualRawContent(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + const WinPrAsn1_MemoryChunk* c) +{ + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT(c); + WINPR_ASSERT_VALID_TAG(tagId); + + size_t len = 1 + lenBytes(c->len) + c->len; + if (!asn1_getWriteStream(enc, len, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_CONTEXTUAL | tagId); + asn1WriteLen(s, c->len); + + Stream_Write(s, c->data, c->len); + return len; +} + +static size_t asn1IntegerLen(WinPrAsn1_INTEGER value) +{ + if (value <= 127 && value >= -128) + return 2; + else if (value <= 32767 && value >= -32768) + return 3; + else + return 5; +} + +static size_t WinPrAsn1EncIntegerLike(WinPrAsn1Encoder* enc, WinPrAsn1_tag b, + WinPrAsn1_INTEGER value) +{ + wStream staticS = { 0 }; + wStream* s = &staticS; + + const size_t len = asn1IntegerLen(value); + if (!asn1_getWriteStream(enc, 1 + len, s)) + return 0; + + Stream_Write_UINT8(s, b); + switch (len) + { + case 2: + Stream_Write_UINT8(s, 1); + Stream_Write_INT8(s, (INT8)value); + break; + case 3: + Stream_Write_UINT8(s, 2); + Stream_Write_INT16_BE(s, (INT16)value); + break; + case 5: + Stream_Write_UINT8(s, 4); + Stream_Write_INT32_BE(s, (INT32)value); + break; + default: + return 0; + } + return 1 + len; +} + +size_t WinPrAsn1EncInteger(WinPrAsn1Encoder* enc, WinPrAsn1_INTEGER integer) +{ + return WinPrAsn1EncIntegerLike(enc, ER_TAG_INTEGER, integer); +} + +size_t WinPrAsn1EncEnumerated(WinPrAsn1Encoder* enc, WinPrAsn1_ENUMERATED value) +{ + return WinPrAsn1EncIntegerLike(enc, ER_TAG_ENUMERATED, value); +} + +static size_t WinPrAsn1EncContextualIntegerLike(WinPrAsn1Encoder* enc, WinPrAsn1_tag tag, + WinPrAsn1_tagId tagId, WinPrAsn1_INTEGER value) +{ + wStream staticS = { 0 }; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT_VALID_TAG(tagId); + + const size_t len = asn1IntegerLen(value); + const size_t outLen = 1 + lenBytes(1 + len) + (1 + len); + if (!asn1_getWriteStream(enc, outLen, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_CONTEXTUAL | tagId); + asn1WriteLen(s, 1 + len); + + Stream_Write_UINT8(s, tag); + switch (len) + { + case 2: + Stream_Write_UINT8(s, 1); + Stream_Write_INT8(s, (INT8)value); + break; + case 3: + Stream_Write_UINT8(s, 2); + Stream_Write_INT16_BE(s, (INT16)value); + break; + case 5: + Stream_Write_UINT8(s, 4); + Stream_Write_INT32_BE(s, value); + break; + default: + return 0; + } + return outLen; +} + +size_t WinPrAsn1EncContextualInteger(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + WinPrAsn1_INTEGER integer) +{ + return WinPrAsn1EncContextualIntegerLike(enc, ER_TAG_INTEGER, tagId, integer); +} + +size_t WinPrAsn1EncContextualEnumerated(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + WinPrAsn1_ENUMERATED value) +{ + return WinPrAsn1EncContextualIntegerLike(enc, ER_TAG_ENUMERATED, tagId, value); +} + +size_t WinPrAsn1EncBoolean(WinPrAsn1Encoder* enc, WinPrAsn1_BOOL b) +{ + wStream staticS; + wStream* s = &staticS; + + if (!asn1_getWriteStream(enc, 3, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_BOOLEAN); + Stream_Write_UINT8(s, 1); + Stream_Write_UINT8(s, b ? 0xff : 0); + + return 3; +} + +size_t WinPrAsn1EncContextualBoolean(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, WinPrAsn1_BOOL b) +{ + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT_VALID_TAG(tagId); + + if (!asn1_getWriteStream(enc, 5, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_CONTEXTUAL | tagId); + Stream_Write_UINT8(s, 3); + + Stream_Write_UINT8(s, ER_TAG_BOOLEAN); + Stream_Write_UINT8(s, 1); + Stream_Write_UINT8(s, b ? 0xff : 0); + + return 5; +} + +static size_t WinPrAsn1EncMemoryChunk(WinPrAsn1Encoder* enc, BYTE wireType, + const WinPrAsn1_MemoryChunk* mchunk) +{ + wStream s; + size_t len = 0; + + WINPR_ASSERT(enc); + WINPR_ASSERT(mchunk); + len = 1 + lenBytes(mchunk->len) + mchunk->len; + + if (!asn1_getWriteStream(enc, len, &s)) + return 0; + + Stream_Write_UINT8(&s, wireType); + asn1WriteLen(&s, mchunk->len); + Stream_Write(&s, mchunk->data, mchunk->len); + return len; +} + +size_t WinPrAsn1EncOID(WinPrAsn1Encoder* enc, const WinPrAsn1_OID* oid) +{ + return WinPrAsn1EncMemoryChunk(enc, ER_TAG_OBJECT_IDENTIFIER, oid); +} + +size_t WinPrAsn1EncOctetString(WinPrAsn1Encoder* enc, const WinPrAsn1_OctetString* octetstring) +{ + return WinPrAsn1EncMemoryChunk(enc, ER_TAG_OCTET_STRING, octetstring); +} + +size_t WinPrAsn1EncIA5String(WinPrAsn1Encoder* enc, WinPrAsn1_IA5STRING ia5) +{ + WinPrAsn1_MemoryChunk chunk; + WINPR_ASSERT(ia5); + chunk.data = (BYTE*)ia5; + chunk.len = strlen(ia5); + return WinPrAsn1EncMemoryChunk(enc, ER_TAG_IA5STRING, &chunk); +} + +size_t WinPrAsn1EncGeneralString(WinPrAsn1Encoder* enc, WinPrAsn1_STRING str) +{ + WinPrAsn1_MemoryChunk chunk; + WINPR_ASSERT(str); + chunk.data = (BYTE*)str; + chunk.len = strlen(str); + return WinPrAsn1EncMemoryChunk(enc, ER_TAG_GENERAL_STRING, &chunk); +} + +static size_t WinPrAsn1EncContextualMemoryChunk(WinPrAsn1Encoder* enc, BYTE wireType, + WinPrAsn1_tagId tagId, + const WinPrAsn1_MemoryChunk* mchunk) +{ + wStream s; + size_t len = 0; + size_t outLen = 0; + + WINPR_ASSERT(enc); + WINPR_ASSERT_VALID_TAG(tagId); + WINPR_ASSERT(mchunk); + len = 1 + lenBytes(mchunk->len) + mchunk->len; + + outLen = 1 + lenBytes(len) + len; + if (!asn1_getWriteStream(enc, outLen, &s)) + return 0; + + Stream_Write_UINT8(&s, ER_TAG_CONTEXTUAL | tagId); + asn1WriteLen(&s, len); + + Stream_Write_UINT8(&s, wireType); + asn1WriteLen(&s, mchunk->len); + Stream_Write(&s, mchunk->data, mchunk->len); + return outLen; +} + +size_t WinPrAsn1EncContextualOID(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + const WinPrAsn1_OID* oid) +{ + return WinPrAsn1EncContextualMemoryChunk(enc, ER_TAG_OBJECT_IDENTIFIER, tagId, oid); +} + +size_t WinPrAsn1EncContextualOctetString(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + const WinPrAsn1_OctetString* octetstring) +{ + return WinPrAsn1EncContextualMemoryChunk(enc, ER_TAG_OCTET_STRING, tagId, octetstring); +} + +size_t WinPrAsn1EncContextualIA5String(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + WinPrAsn1_IA5STRING ia5) +{ + WinPrAsn1_MemoryChunk chunk; + WINPR_ASSERT(ia5); + chunk.data = (BYTE*)ia5; + chunk.len = strlen(ia5); + + return WinPrAsn1EncContextualMemoryChunk(enc, ER_TAG_IA5STRING, tagId, &chunk); +} + +static void write2digit(wStream* s, UINT8 v) +{ + Stream_Write_UINT8(s, '0' + (v / 10)); + Stream_Write_UINT8(s, '0' + (v % 10)); +} + +size_t WinPrAsn1EncUtcTime(WinPrAsn1Encoder* enc, const WinPrAsn1_UTCTIME* utc) +{ + wStream staticS = { 0 }; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT(utc); + WINPR_ASSERT(utc->year >= 2000); + + if (!asn1_getWriteStream(enc, 15, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_UTCTIME); + Stream_Write_UINT8(s, 13); + + write2digit(s, (UINT8)(utc->year - 2000)); + write2digit(s, utc->month); + write2digit(s, utc->day); + write2digit(s, utc->hour); + write2digit(s, utc->minute); + write2digit(s, utc->second); + Stream_Write_INT8(s, utc->tz); + return 15; +} + +size_t WinPrAsn1EncContextualUtcTime(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId, + const WinPrAsn1_UTCTIME* utc) +{ + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(enc); + WINPR_ASSERT_VALID_TAG(tagId); + WINPR_ASSERT(utc); + WINPR_ASSERT(utc->year >= 2000); + WINPR_ASSERT(utc->year < 2256); + + if (!asn1_getWriteStream(enc, 17, s)) + return 0; + + Stream_Write_UINT8(s, ER_TAG_CONTEXTUAL | tagId); + Stream_Write_UINT8(s, 15); + + Stream_Write_UINT8(s, ER_TAG_UTCTIME); + Stream_Write_UINT8(s, 13); + + write2digit(s, (UINT8)(utc->year - 2000)); + write2digit(s, utc->month); + write2digit(s, utc->day); + write2digit(s, utc->hour); + write2digit(s, utc->minute); + write2digit(s, utc->second); + Stream_Write_INT8(s, utc->tz); + + return 17; +} + +BOOL WinPrAsn1EncStreamSize(WinPrAsn1Encoder* enc, size_t* s) +{ + size_t finalSize = 0; + + WINPR_ASSERT(enc); + WINPR_ASSERT(s); + + if (enc->freeContainerIndex != 0) + { + WLog_ERR(TAG, "some container have not been closed"); + return FALSE; + } + + for (size_t i = 0; i < enc->freeChunkId; i++) + finalSize += enc->chunks[i].used; + *s = finalSize; + return TRUE; +} + +BOOL WinPrAsn1EncToStream(WinPrAsn1Encoder* enc, wStream* s) +{ + size_t finalSize = 0; + + WINPR_ASSERT(enc); + WINPR_ASSERT(s); + + if (!WinPrAsn1EncStreamSize(enc, &finalSize)) + return FALSE; + + if (!Stream_EnsureRemainingCapacity(s, finalSize)) + return FALSE; + + for (size_t i = 0; i < enc->freeChunkId; i++) + { + BYTE* src = Stream_Buffer(enc->pool) + enc->chunks[i].poolOffset; + Stream_Write(s, src, enc->chunks[i].used); + } + + return TRUE; +} + +void WinPrAsn1Decoder_Init(WinPrAsn1Decoder* decoder, WinPrAsn1EncodingRule encoding, + wStream* source) +{ + WINPR_ASSERT(decoder); + WINPR_ASSERT(source); + + decoder->encoding = encoding; + memcpy(&decoder->source, source, sizeof(*source)); +} + +void WinPrAsn1Decoder_InitMem(WinPrAsn1Decoder* decoder, WinPrAsn1EncodingRule encoding, + const BYTE* source, size_t len) +{ + WINPR_ASSERT(decoder); + WINPR_ASSERT(source); + + decoder->encoding = encoding; + Stream_StaticConstInit(&decoder->source, source, len); +} + +BOOL WinPrAsn1DecPeekTag(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag) +{ + WINPR_ASSERT(dec); + WINPR_ASSERT(tag); + + if (Stream_GetRemainingLength(&dec->source) < 1) + return FALSE; + Stream_Peek(&dec->source, tag, 1); + return TRUE; +} + +static size_t readLen(wStream* s, size_t* len, BOOL derCheck) +{ + size_t retLen = 0; + size_t ret = 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, 1)) + return 0; + + Stream_Read_UINT8(s, retLen); + ret++; + if (retLen & 0x80) + { + BYTE tmp = 0; + size_t nBytes = (retLen & 0x7f); + + if (!Stream_CheckAndLogRequiredLength(TAG, s, nBytes)) + return 0; + + ret += nBytes; + for (retLen = 0; nBytes; nBytes--) + { + Stream_Read_UINT8(s, tmp); + retLen = (retLen << 8) + tmp; + } + + if (derCheck) + { + /* check that the DER rule is respected, and that length encoding is optimal */ + if (ret > 1 && retLen < 128) + return 0; + } + } + + *len = retLen; + return ret; +} + +static size_t readTagAndLen(WinPrAsn1Decoder* dec, wStream* s, WinPrAsn1_tag* tag, size_t* len) +{ + size_t lenBytes = 0; + + if (Stream_GetRemainingLength(s) < 1) + return 0; + + Stream_Read(s, tag, 1); + lenBytes = readLen(s, len, (dec->encoding == WINPR_ASN1_DER)); + if (lenBytes == 0) + return 0; + + return 1 + lenBytes; +} + +size_t WinPrAsn1DecReadTagAndLen(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag, size_t* len) +{ + WINPR_ASSERT(dec); + WINPR_ASSERT(tag); + WINPR_ASSERT(len); + + return readTagAndLen(dec, &dec->source, tag, len); +} + +size_t WinPrAsn1DecPeekTagAndLen(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag, size_t* len) +{ + wStream staticS; + wStream* s = &staticS; + + WINPR_ASSERT(dec); + + Stream_StaticConstInit(s, Stream_ConstPointer(&dec->source), + Stream_GetRemainingLength(&dec->source)); + return readTagAndLen(dec, s, tag, len); +} + +size_t WinPrAsn1DecReadTagLenValue(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag, size_t* len, + WinPrAsn1Decoder* value) +{ + size_t ret = 0; + WINPR_ASSERT(dec); + WINPR_ASSERT(tag); + WINPR_ASSERT(len); + WINPR_ASSERT(value); + + ret = readTagAndLen(dec, &dec->source, tag, len); + if (!ret) + return 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, &dec->source, *len)) + return 0; + + value->encoding = dec->encoding; + Stream_StaticInit(&value->source, Stream_Pointer(&dec->source), *len); + Stream_Seek(&dec->source, *len); + return ret + *len; +} + +size_t WinPrAsn1DecReadBoolean(WinPrAsn1Decoder* dec, WinPrAsn1_BOOL* target) +{ + BYTE v = 0; + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != ER_TAG_BOOLEAN) + return 0; + if (Stream_GetRemainingLength(&dec->source) < len || len != 1) + return 0; + + Stream_Read_UINT8(&dec->source, v); + *target = !!v; + return ret; +} + +static size_t WinPrAsn1DecReadIntegerLike(WinPrAsn1Decoder* dec, WinPrAsn1_tag expectedTag, + WinPrAsn1_INTEGER* target) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + size_t ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || (tag != expectedTag)) + return 0; + if (len == 0 || Stream_GetRemainingLength(&dec->source) < len || (len > 4)) + return 0; + + UINT32 uval = 0; + UINT8 v = 0; + + Stream_Read_UINT8(&dec->source, v); + + /* extract sign from first byte. + * the ASN integer might be smaller than 32bit so we need to set the initial + * value to FF for all unused bytes (e.g. all except the lowest one we just read) + */ + BOOL isNegative = (v & 0x80); + if (isNegative) + uval = 0xFFFFFF00; + uval |= v; + + for (size_t x = 1; x < len; x++) + { + Stream_Read_UINT8(&dec->source, v); + uval <<= 8; + uval |= v; + } + + *target = (WinPrAsn1_INTEGER)uval; + ret += len; + + /* TODO: check ber/der rules */ + return ret; +} + +size_t WinPrAsn1DecReadInteger(WinPrAsn1Decoder* dec, WinPrAsn1_INTEGER* target) +{ + return WinPrAsn1DecReadIntegerLike(dec, ER_TAG_INTEGER, target); +} + +size_t WinPrAsn1DecReadEnumerated(WinPrAsn1Decoder* dec, WinPrAsn1_ENUMERATED* target) +{ + return WinPrAsn1DecReadIntegerLike(dec, ER_TAG_ENUMERATED, target); +} + +static size_t WinPrAsn1DecReadMemoryChunkLike(WinPrAsn1Decoder* dec, WinPrAsn1_tag expectedTag, + WinPrAsn1_MemoryChunk* target, BOOL allocate) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != expectedTag) + return 0; + if (!Stream_CheckAndLogRequiredLength(TAG, &dec->source, len)) + return 0; + + ret += len; + + target->len = len; + if (allocate && (len > 0)) + { + target->data = malloc(len); + if (!target->data) + return 0; + Stream_Read(&dec->source, target->data, len); + } + else + { + target->data = Stream_Pointer(&dec->source); + Stream_Seek(&dec->source, len); + } + + return ret; +} + +size_t WinPrAsn1DecReadOID(WinPrAsn1Decoder* dec, WinPrAsn1_OID* target, BOOL allocate) +{ + return WinPrAsn1DecReadMemoryChunkLike(dec, ER_TAG_OBJECT_IDENTIFIER, + (WinPrAsn1_MemoryChunk*)target, allocate); +} + +size_t WinPrAsn1DecReadOctetString(WinPrAsn1Decoder* dec, WinPrAsn1_OctetString* target, + BOOL allocate) +{ + return WinPrAsn1DecReadMemoryChunkLike(dec, ER_TAG_OCTET_STRING, target, allocate); +} + +size_t WinPrAsn1DecReadIA5String(WinPrAsn1Decoder* dec, WinPrAsn1_IA5STRING* target) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + WinPrAsn1_IA5STRING s = NULL; + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != ER_TAG_IA5STRING) + return 0; + if (!Stream_CheckAndLogRequiredLength(TAG, &dec->source, len)) + return 0; + + ret += len; + + s = malloc(len + 1); + if (!s) + return 0; + Stream_Read(&dec->source, s, len); + s[len] = 0; + *target = s; + return ret; +} + +size_t WinPrAsn1DecReadGeneralString(WinPrAsn1Decoder* dec, WinPrAsn1_STRING* target) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + WinPrAsn1_IA5STRING s = NULL; + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != ER_TAG_GENERAL_STRING) + return 0; + if (!Stream_CheckAndLogRequiredLength(TAG, &dec->source, len)) + return 0; + + ret += len; + + s = malloc(len + 1); + if (!s) + return 0; + Stream_Read(&dec->source, s, len); + s[len] = 0; + *target = s; + return ret; +} + +static int read2digits(wStream* s) +{ + int ret = 0; + char c = 0; + + Stream_Read_INT8(s, c); + if (c < '0' || c > '9') + return -1; + + ret = (c - '0') * 10; + + Stream_Read_INT8(s, c); + if (c < '0' || c > '9') + return -1; + + ret += (c - '0'); + return ret; +} + +size_t WinPrAsn1DecReadUtcTime(WinPrAsn1Decoder* dec, WinPrAsn1_UTCTIME* target) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + int v = 0; + wStream sub; + wStream* s = ⊂ + + WINPR_ASSERT(dec); + WINPR_ASSERT(target); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != ER_TAG_UTCTIME) + return 0; + if (!Stream_CheckAndLogRequiredLength(TAG, &dec->source, len) || len < 12) + return 0; + + Stream_StaticConstInit(s, Stream_ConstPointer(&dec->source), len); + + v = read2digits(s); + if ((v <= 0) || (v >= UINT16_MAX - 2000)) + return 0; + target->year = (UINT16)(2000 + v); + + v = read2digits(s); + if ((v <= 0) || (v > UINT8_MAX)) + return 0; + target->month = (UINT8)v; + + v = read2digits(s); + if ((v <= 0) || (v > UINT8_MAX)) + return 0; + target->day = (UINT8)v; + + v = read2digits(s); + if ((v <= 0) || (v > UINT8_MAX)) + return 0; + target->hour = (UINT8)v; + + v = read2digits(s); + if ((v <= 0) || (v > UINT8_MAX)) + return 0; + target->minute = (UINT8)v; + + v = read2digits(s); + if ((v <= 0) || (v > UINT8_MAX)) + return 0; + target->second = (UINT8)v; + + if (Stream_GetRemainingLength(s) >= 1) + { + Stream_Read_INT8(s, target->tz); + } + + Stream_Seek(&dec->source, len); + ret += len; + + return ret; +} + +size_t WinPrAsn1DecReadNull(WinPrAsn1Decoder* dec) +{ + WinPrAsn1_tag tag = 0; + size_t len = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + + ret = readTagAndLen(dec, &dec->source, &tag, &len); + if (!ret || tag != ER_TAG_NULL || len) + return 0; + + return ret; +} + +static size_t readConstructed(WinPrAsn1Decoder* dec, wStream* s, WinPrAsn1_tag* tag, + WinPrAsn1Decoder* target) +{ + size_t len = 0; + size_t ret = 0; + + ret = readTagAndLen(dec, s, tag, &len); + if (!ret || !Stream_CheckAndLogRequiredLength(TAG, s, len)) + return 0; + + target->encoding = dec->encoding; + Stream_StaticConstInit(&target->source, Stream_ConstPointer(s), len); + Stream_Seek(s, len); + return ret + len; +} + +size_t WinPrAsn1DecReadApp(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId, WinPrAsn1Decoder* setDec) +{ + WinPrAsn1_tag tag = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(setDec); + + ret = readConstructed(dec, &dec->source, &tag, setDec); + if ((tag & ER_TAG_APP) != ER_TAG_APP) + return 0; + + *tagId = (tag & ER_TAG_MASK); + return ret; +} + +size_t WinPrAsn1DecReadSequence(WinPrAsn1Decoder* dec, WinPrAsn1Decoder* seqDec) +{ + WinPrAsn1_tag tag = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(seqDec); + + ret = readConstructed(dec, &dec->source, &tag, seqDec); + if (tag != ER_TAG_SEQUENCE) + return 0; + + return ret; +} + +size_t WinPrAsn1DecReadSet(WinPrAsn1Decoder* dec, WinPrAsn1Decoder* setDec) +{ + WinPrAsn1_tag tag = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(setDec); + + ret = readConstructed(dec, &dec->source, &tag, setDec); + if (tag != ER_TAG_SET) + return 0; + + return ret; +} + +static size_t readContextualTag(WinPrAsn1Decoder* dec, wStream* s, WinPrAsn1_tagId* tagId, + WinPrAsn1Decoder* ctxtDec) +{ + size_t ret = 0; + WinPrAsn1_tag ftag = 0; + + ret = readConstructed(dec, s, &ftag, ctxtDec); + if (!ret) + return 0; + + if ((ftag & ER_TAG_CONTEXTUAL) != ER_TAG_CONTEXTUAL) + return 0; + + *tagId = (ftag & ER_TAG_MASK); + return ret; +} + +size_t WinPrAsn1DecReadContextualTag(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId, + WinPrAsn1Decoder* ctxtDec) +{ + WINPR_ASSERT(dec); + WINPR_ASSERT(tagId); + WINPR_ASSERT(ctxtDec); + + return readContextualTag(dec, &dec->source, tagId, ctxtDec); +} + +size_t WinPrAsn1DecPeekContextualTag(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId, + WinPrAsn1Decoder* ctxtDec) +{ + wStream staticS; + WINPR_ASSERT(dec); + + Stream_StaticConstInit(&staticS, Stream_ConstPointer(&dec->source), + Stream_GetRemainingLength(&dec->source)); + return readContextualTag(dec, &staticS, tagId, ctxtDec); +} + +static size_t readContextualHeader(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, BOOL* error, + WinPrAsn1Decoder* content) +{ + WinPrAsn1_tag ftag = 0; + size_t ret = 0; + + WINPR_ASSERT(dec); + WINPR_ASSERT(error); + WINPR_ASSERT(content); + + *error = TRUE; + ret = WinPrAsn1DecPeekContextualTag(dec, &ftag, content); + if (!ret) + return 0; + + if (ftag != tagId) + { + *error = FALSE; + return 0; + } + + *error = FALSE; + return ret; +} + +size_t WinPrAsn1DecReadContextualBool(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, BOOL* error, + WinPrAsn1_BOOL* target) +{ + size_t ret = 0; + size_t ret2 = 0; + WinPrAsn1Decoder content; + + ret = readContextualHeader(dec, tagId, error, &content); + if (!ret) + return 0; + + ret2 = WinPrAsn1DecReadBoolean(&content, target); + if (!ret2) + { + *error = TRUE; + return 0; + } + + Stream_Seek(&dec->source, ret); + return ret; +} + +size_t WinPrAsn1DecReadContextualInteger(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, BOOL* error, + WinPrAsn1_INTEGER* target) +{ + size_t ret = 0; + size_t ret2 = 0; + WinPrAsn1Decoder content; + + ret = readContextualHeader(dec, tagId, error, &content); + if (!ret) + return 0; + + ret2 = WinPrAsn1DecReadInteger(&content, target); + if (!ret2) + { + *error = TRUE; + return 0; + } + + Stream_Seek(&dec->source, ret); + return ret; +} + +size_t WinPrAsn1DecReadContextualOID(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, BOOL* error, + WinPrAsn1_OID* target, BOOL allocate) +{ + size_t ret = 0; + size_t ret2 = 0; + WinPrAsn1Decoder content; + + ret = readContextualHeader(dec, tagId, error, &content); + if (!ret) + return 0; + + ret2 = WinPrAsn1DecReadOID(&content, target, allocate); + if (!ret2) + { + *error = TRUE; + return 0; + } + + Stream_Seek(&dec->source, ret); + return ret; +} + +size_t WinPrAsn1DecReadContextualOctetString(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, + BOOL* error, WinPrAsn1_OctetString* target, + BOOL allocate) +{ + size_t ret = 0; + size_t ret2 = 0; + WinPrAsn1Decoder content; + + ret = readContextualHeader(dec, tagId, error, &content); + if (!ret) + return 0; + + ret2 = WinPrAsn1DecReadOctetString(&content, target, allocate); + if (!ret2) + { + *error = TRUE; + return 0; + } + + Stream_Seek(&dec->source, ret); + return ret; +} + +size_t WinPrAsn1DecReadContextualSequence(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId, BOOL* error, + WinPrAsn1Decoder* target) +{ + size_t ret = 0; + size_t ret2 = 0; + WinPrAsn1Decoder content; + + ret = readContextualHeader(dec, tagId, error, &content); + if (!ret) + return 0; + + ret2 = WinPrAsn1DecReadSequence(&content, target); + if (!ret2) + { + *error = TRUE; + return 0; + } + + Stream_Seek(&dec->source, ret); + return ret; +} + +wStream WinPrAsn1DecGetStream(WinPrAsn1Decoder* dec) +{ + wStream s = { 0 }; + WINPR_ASSERT(dec); + + Stream_StaticConstInit(&s, Stream_ConstPointer(&dec->source), + Stream_GetRemainingLength(&dec->source)); + return s; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/cmdline.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/cmdline.c new file mode 100644 index 0000000000000000000000000000000000000000..99d439189144f34185cb566c7dd1906464bc1067 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/cmdline.c @@ -0,0 +1,859 @@ +/** + * WinPR: Windows Portable Runtime + * Command-Line Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "../log.h" + +#define TAG WINPR_TAG("commandline") + +/** + * Command-line syntax: some basic concepts: + * https://pythonconquerstheuniverse.wordpress.com/2010/07/25/command-line-syntax-some-basic-concepts/ + */ + +/** + * Command-Line Syntax: + * + * + * + * : '/' or '-' or ('+' | '-') + * + * : option, named argument, flag + * + * : ':' or '=' + * + * : argument value + * + */ + +static void log_error(DWORD flags, LPCSTR message, int index, LPCSTR argv) +{ + if ((flags & COMMAND_LINE_SILENCE_PARSER) == 0) + WLog_ERR(TAG, message, index, argv); +} + +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) +{ + int status = 0; + int count = 0; + BOOL notescaped = FALSE; + const char* sigil = NULL; + size_t sigil_length = 0; + char* keyword = NULL; + size_t keyword_index = 0; + char* separator = NULL; + char* value = NULL; + int toggle = 0; + + if (!argv) + return status; + + if (argc == 1) + { + if (flags & COMMAND_LINE_IGN_UNKNOWN_KEYWORD) + status = 0; + else + status = COMMAND_LINE_STATUS_PRINT_HELP; + + return status; + } + + for (int i = 1; i < argc; i++) + { + size_t keyword_length = 0; + BOOL found = FALSE; + BOOL escaped = TRUE; + + if (preFilter) + { + count = preFilter(context, i, argc, argv); + + if (count < 0) + { + log_error(flags, "Failed for index %d [%s]: PreFilter rule could not be applied", i, + argv[i]); + status = COMMAND_LINE_ERROR; + return status; + } + + if (count > 0) + { + i += (count - 1); + continue; + } + } + + sigil = argv[i]; + size_t length = strlen(argv[i]); + + if ((sigil[0] == '/') && (flags & COMMAND_LINE_SIGIL_SLASH)) + { + sigil_length = 1; + } + else if ((sigil[0] == '-') && (flags & COMMAND_LINE_SIGIL_DASH)) + { + sigil_length = 1; + + if (length > 2) + { + if ((sigil[1] == '-') && (flags & COMMAND_LINE_SIGIL_DOUBLE_DASH)) + sigil_length = 2; + } + } + else if ((sigil[0] == '+') && (flags & COMMAND_LINE_SIGIL_PLUS_MINUS)) + { + sigil_length = 1; + } + else if ((sigil[0] == '-') && (flags & COMMAND_LINE_SIGIL_PLUS_MINUS)) + { + sigil_length = 1; + } + else if (flags & COMMAND_LINE_SIGIL_NONE) + { + sigil_length = 0; + } + else if (flags & COMMAND_LINE_SIGIL_NOT_ESCAPED) + { + if (notescaped) + { + log_error(flags, "Failed at index %d [%s]: Unescaped sigil", i, argv[i]); + return COMMAND_LINE_ERROR; + } + + sigil_length = 0; + escaped = FALSE; + notescaped = TRUE; + } + else + { + log_error(flags, "Failed at index %d [%s]: Invalid sigil", i, argv[i]); + return COMMAND_LINE_ERROR; + } + + if ((sigil_length > 0) || (flags & COMMAND_LINE_SIGIL_NONE) || + (flags & COMMAND_LINE_SIGIL_NOT_ESCAPED)) + { + if (length < (sigil_length + 1)) + { + if ((flags & COMMAND_LINE_IGN_UNKNOWN_KEYWORD)) + continue; + + return COMMAND_LINE_ERROR_NO_KEYWORD; + } + + keyword_index = sigil_length; + keyword = &argv[i][keyword_index]; + toggle = -1; + + if (flags & COMMAND_LINE_SIGIL_ENABLE_DISABLE) + { + if (strncmp(keyword, "enable-", 7) == 0) + { + toggle = TRUE; + keyword_index += 7; + keyword = &argv[i][keyword_index]; + } + else if (strncmp(keyword, "disable-", 8) == 0) + { + toggle = FALSE; + keyword_index += 8; + keyword = &argv[i][keyword_index]; + } + } + + separator = NULL; + + if ((flags & COMMAND_LINE_SEPARATOR_COLON) && (!separator)) + separator = strchr(keyword, ':'); + + if ((flags & COMMAND_LINE_SEPARATOR_EQUAL) && (!separator)) + separator = strchr(keyword, '='); + + if (separator) + { + SSIZE_T separator_index = (separator - argv[i]); + SSIZE_T value_index = separator_index + 1; + keyword_length = WINPR_ASSERTING_INT_CAST(size_t, (separator - keyword)); + value = &argv[i][value_index]; + } + else + { + if (length < keyword_index) + { + log_error(flags, "Failed at index %d [%s]: Argument required", i, argv[i]); + return COMMAND_LINE_ERROR; + } + + keyword_length = length - keyword_index; + value = NULL; + } + + if (!escaped) + continue; + + for (size_t j = 0; options[j].Name != NULL; j++) + { + COMMAND_LINE_ARGUMENT_A* cur = &options[j]; + BOOL match = FALSE; + + if (strncmp(cur->Name, keyword, keyword_length) == 0) + { + if (strlen(cur->Name) == keyword_length) + match = TRUE; + } + + if ((!match) && (cur->Alias != NULL)) + { + if (strncmp(cur->Alias, keyword, keyword_length) == 0) + { + if (strlen(cur->Alias) == keyword_length) + match = TRUE; + } + } + + if (!match) + continue; + + found = match; + cur->Index = i; + + if ((flags & COMMAND_LINE_SEPARATOR_SPACE) && ((i + 1) < argc)) + { + BOOL argument = 0; + int value_present = 1; + + if (flags & COMMAND_LINE_SIGIL_DASH) + { + if (strncmp(argv[i + 1], "-", 1) == 0) + value_present = 0; + } + + if (flags & COMMAND_LINE_SIGIL_DOUBLE_DASH) + { + if (strncmp(argv[i + 1], "--", 2) == 0) + value_present = 0; + } + + if (flags & COMMAND_LINE_SIGIL_SLASH) + { + if (strncmp(argv[i + 1], "/", 1) == 0) + value_present = 0; + } + + if ((cur->Flags & COMMAND_LINE_VALUE_REQUIRED) || + (cur->Flags & COMMAND_LINE_VALUE_OPTIONAL)) + argument = TRUE; + else + argument = FALSE; + + if (value_present && argument) + { + i++; + value = argv[i]; + } + else if (!value_present && (cur->Flags & COMMAND_LINE_VALUE_OPTIONAL)) + { + value = NULL; + } + else if (!value_present && argument) + { + log_error(flags, "Failed at index %d [%s]: Argument required", i, argv[i]); + return COMMAND_LINE_ERROR; + } + } + + if (!(flags & COMMAND_LINE_SEPARATOR_SPACE)) + { + if (value && (cur->Flags & COMMAND_LINE_VALUE_FLAG)) + { + log_error(flags, "Failed at index %d [%s]: Unexpected value", i, argv[i]); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + else + { + if (value && (cur->Flags & COMMAND_LINE_VALUE_FLAG)) + { + i--; + value = NULL; + } + } + + if (!value && (cur->Flags & COMMAND_LINE_VALUE_REQUIRED)) + { + log_error(flags, "Failed at index %d [%s]: Missing value", i, argv[i]); + status = COMMAND_LINE_ERROR_MISSING_VALUE; + return status; + } + + cur->Flags |= COMMAND_LINE_ARGUMENT_PRESENT; + + if (value) + { + if (!(cur->Flags & (COMMAND_LINE_VALUE_OPTIONAL | COMMAND_LINE_VALUE_REQUIRED))) + { + log_error(flags, "Failed at index %d [%s]: Unexpected value", i, argv[i]); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + cur->Value = value; + cur->Flags |= COMMAND_LINE_VALUE_PRESENT; + } + else + { + if (cur->Flags & COMMAND_LINE_VALUE_FLAG) + { + cur->Value = (LPSTR)1; + cur->Flags |= COMMAND_LINE_VALUE_PRESENT; + } + else if (cur->Flags & COMMAND_LINE_VALUE_BOOL) + { + if (flags & COMMAND_LINE_SIGIL_ENABLE_DISABLE) + { + if (toggle == -1) + cur->Value = BoolValueTrue; + else if (!toggle) + cur->Value = BoolValueFalse; + else + cur->Value = BoolValueTrue; + } + else + { + if (sigil[0] == '+') + cur->Value = BoolValueTrue; + else if (sigil[0] == '-') + cur->Value = BoolValueFalse; + else + cur->Value = BoolValueTrue; + } + + cur->Flags |= COMMAND_LINE_VALUE_PRESENT; + } + } + + if (postFilter) + { + count = postFilter(context, &options[j]); + + if (count < 0) + { + log_error(flags, + "Failed at index %d [%s]: PostFilter rule could not be applied", + i, argv[i]); + status = COMMAND_LINE_ERROR; + return status; + } + } + + if (cur->Flags & COMMAND_LINE_PRINT) + return COMMAND_LINE_STATUS_PRINT; + else if (cur->Flags & COMMAND_LINE_PRINT_HELP) + return COMMAND_LINE_STATUS_PRINT_HELP; + else if (cur->Flags & COMMAND_LINE_PRINT_VERSION) + return COMMAND_LINE_STATUS_PRINT_VERSION; + else if (cur->Flags & COMMAND_LINE_PRINT_BUILDCONFIG) + return COMMAND_LINE_STATUS_PRINT_BUILDCONFIG; + } + + if (!found && (flags & COMMAND_LINE_IGN_UNKNOWN_KEYWORD) == 0) + { + log_error(flags, "Failed at index %d [%s]: Unexpected keyword", i, argv[i]); + return COMMAND_LINE_ERROR_NO_KEYWORD; + } + } + } + + return status; +} + +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) +{ + return 0; +} + +int CommandLineClearArgumentsA(COMMAND_LINE_ARGUMENT_A* options) +{ + for (size_t i = 0; options[i].Name != NULL; i++) + { + options[i].Flags &= COMMAND_LINE_INPUT_FLAG_MASK; + options[i].Value = NULL; + } + + return 0; +} + +int CommandLineClearArgumentsW(COMMAND_LINE_ARGUMENT_W* options) +{ + for (int i = 0; options[i].Name != NULL; i++) + { + options[i].Flags &= COMMAND_LINE_INPUT_FLAG_MASK; + options[i].Value = NULL; + } + + return 0; +} + +const COMMAND_LINE_ARGUMENT_A* CommandLineFindArgumentA(const COMMAND_LINE_ARGUMENT_A* options, + LPCSTR Name) +{ + WINPR_ASSERT(options); + WINPR_ASSERT(Name); + + for (size_t i = 0; options[i].Name != NULL; i++) + { + if (strcmp(options[i].Name, Name) == 0) + return &options[i]; + + if (options[i].Alias != NULL) + { + if (strcmp(options[i].Alias, Name) == 0) + return &options[i]; + } + } + + return NULL; +} + +const COMMAND_LINE_ARGUMENT_W* CommandLineFindArgumentW(const COMMAND_LINE_ARGUMENT_W* options, + LPCWSTR Name) +{ + WINPR_ASSERT(options); + WINPR_ASSERT(Name); + + for (size_t i = 0; options[i].Name != NULL; i++) + { + if (_wcscmp(options[i].Name, Name) == 0) + return &options[i]; + + if (options[i].Alias != NULL) + { + if (_wcscmp(options[i].Alias, Name) == 0) + return &options[i]; + } + } + + return NULL; +} + +const COMMAND_LINE_ARGUMENT_A* CommandLineFindNextArgumentA(const COMMAND_LINE_ARGUMENT_A* argument) +{ + const COMMAND_LINE_ARGUMENT_A* nextArgument = NULL; + + if (!argument || !argument->Name) + return NULL; + + nextArgument = &argument[1]; + + if (nextArgument->Name == NULL) + return NULL; + + return nextArgument; +} + +static int is_quoted(char c) +{ + switch (c) + { + case '"': + return 1; + case '\'': + return -1; + default: + return 0; + } +} + +static size_t get_element_count(const char* list, BOOL* failed, BOOL fullquoted) +{ + size_t count = 0; + int quoted = 0; + BOOL finished = FALSE; + BOOL first = TRUE; + const char* it = list; + + if (!list) + return 0; + if (strlen(list) == 0) + return 0; + + while (!finished) + { + BOOL nextFirst = FALSE; + switch (*it) + { + case '\0': + if (quoted != 0) + { + WLog_ERR(TAG, "Invalid argument (missing closing quote) '%s'", list); + *failed = TRUE; + return 0; + } + finished = TRUE; + break; + case '\'': + case '"': + if (!fullquoted) + { + int now = is_quoted(*it); + if (now == quoted) + quoted = 0; + else if (quoted == 0) + quoted = now; + } + break; + case ',': + if (first) + { + WLog_ERR(TAG, "Invalid argument (empty list elements) '%s'", list); + *failed = TRUE; + return 0; + } + if (quoted == 0) + { + nextFirst = TRUE; + count++; + } + break; + default: + break; + } + + first = nextFirst; + it++; + } + return count + 1; +} + +static char* get_next_comma(char* string, BOOL fullquoted) +{ + const char* log = string; + int quoted = 0; + BOOL first = TRUE; + + WINPR_ASSERT(string); + + while (TRUE) + { + switch (*string) + { + case '\0': + if (quoted != 0) + WLog_ERR(TAG, "Invalid quoted argument '%s'", log); + return NULL; + + case '\'': + case '"': + if (!fullquoted) + { + int now = is_quoted(*string); + if ((quoted == 0) && !first) + { + WLog_ERR(TAG, "Invalid quoted argument '%s'", log); + return NULL; + } + if (now == quoted) + quoted = 0; + else if (quoted == 0) + quoted = now; + } + break; + + case ',': + if (first) + { + WLog_ERR(TAG, "Invalid argument (empty list elements) '%s'", log); + return NULL; + } + if (quoted == 0) + return string; + break; + + default: + break; + } + first = FALSE; + string++; + } + + return NULL; +} + +static BOOL is_valid_fullquoted(const char* string) +{ + char cur = '\0'; + char last = '\0'; + const char quote = *string++; + + /* We did not start with a quote. */ + if (is_quoted(quote) == 0) + return FALSE; + + while ((cur = *string++) != '\0') + { + /* A quote is found. */ + if (cur == quote) + { + /* If the quote was escaped, it is valid. */ + if (last != '\\') + { + /* Only allow unescaped quote as last character in string. */ + if (*string != '\0') + return FALSE; + } + /* If the last quote in the string is escaped, it is wrong. */ + else if (*string != '\0') + return FALSE; + } + last = cur; + } + + /* The string did not terminate with the same quote as it started. */ + if (last != quote) + return FALSE; + return TRUE; +} + +char** CommandLineParseCommaSeparatedValuesEx(const char* name, const char* list, size_t* count) +{ + char** p = NULL; + char* str = NULL; + size_t nArgs = 0; + size_t prefix = 0; + size_t len = 0; + size_t namelen = 0; + BOOL failed = FALSE; + char* copy = NULL; + char* unquoted = NULL; + BOOL fullquoted = FALSE; + + BOOL success = FALSE; + if (count == NULL) + goto fail; + + *count = 0; + if (list) + { + int start = 0; + int end = 0; + unquoted = copy = _strdup(list); + if (!copy) + goto fail; + + len = strlen(unquoted); + if (len > 0) + { + start = is_quoted(unquoted[0]); + end = is_quoted(unquoted[len - 1]); + + if ((start != 0) && (end != 0)) + { + if (start != end) + { + WLog_ERR(TAG, "invalid argument (quote mismatch) '%s'", list); + goto fail; + } + if (!is_valid_fullquoted(unquoted)) + goto fail; + unquoted[len - 1] = '\0'; + unquoted++; + len -= 2; + fullquoted = TRUE; + } + } + } + + *count = get_element_count(unquoted, &failed, fullquoted); + if (failed) + goto fail; + + if (*count == 0) + { + if (!name) + goto fail; + else + { + size_t clen = strlen(name); + p = (char**)calloc(2UL + clen, sizeof(char*)); + + if (p) + { + char* dst = (char*)&p[1]; + p[0] = dst; + (void)sprintf_s(dst, clen + 1, "%s", name); + *count = 1; + success = TRUE; + goto fail; + } + } + } + + nArgs = *count; + + if (name) + nArgs++; + + prefix = (nArgs + 1UL) * sizeof(char*); + if (name) + namelen = strlen(name); + p = (char**)calloc(len + prefix + 1 + namelen + 1, sizeof(char*)); + + if (!p) + goto fail; + + str = &((char*)p)[prefix]; + memcpy(str, unquoted, len); + + if (name) + { + char* namestr = &((char*)p)[prefix + len + 1]; + memcpy(namestr, name, namelen); + + p[0] = namestr; + } + + for (size_t index = name ? 1 : 0; index < nArgs; index++) + { + char* ptr = str; + const int quote = is_quoted(*ptr); + char* comma = get_next_comma(str, fullquoted); + + if ((quote != 0) && !fullquoted) + ptr++; + + p[index] = ptr; + + if (comma) + { + char* last = comma - 1; + const int lastQuote = is_quoted(*last); + + if (!fullquoted) + { + if (lastQuote != quote) + { + WLog_ERR(TAG, "invalid argument (quote mismatch) '%s'", list); + goto fail; + } + else if (lastQuote != 0) + *last = '\0'; + } + *comma = '\0'; + + str = comma + 1; + } + else if (quote) + { + char* end = strrchr(ptr, '"'); + if (!end) + goto fail; + *end = '\0'; + } + } + + *count = nArgs; + success = TRUE; +fail: + free(copy); + if (!success) + { + if (count) + *count = 0; + free((void*)p); + return NULL; + } + return p; +} + +char** CommandLineParseCommaSeparatedValues(const char* list, size_t* count) +{ + return CommandLineParseCommaSeparatedValuesEx(NULL, list, count); +} + +char* CommandLineToCommaSeparatedValues(int argc, char* argv[]) +{ + return CommandLineToCommaSeparatedValuesEx(argc, argv, NULL, 0); +} + +static const char* filtered(const char* arg, const char* filters[], size_t number) +{ + if (number == 0) + return arg; + for (size_t x = 0; x < number; x++) + { + const char* filter = filters[x]; + size_t len = strlen(filter); + if (_strnicmp(arg, filter, len) == 0) + return &arg[len]; + } + return NULL; +} + +char* CommandLineToCommaSeparatedValuesEx(int argc, char* argv[], const char* filters[], + size_t number) +{ + char* str = NULL; + size_t offset = 0; + size_t size = WINPR_ASSERTING_INT_CAST(size_t, argc) + 1; + if ((argc <= 0) || !argv) + return NULL; + + for (int x = 0; x < argc; x++) + size += strlen(argv[x]); + + str = calloc(size, sizeof(char)); + if (!str) + return NULL; + for (int x = 0; x < argc; x++) + { + int rc = 0; + const char* arg = filtered(argv[x], filters, number); + if (!arg) + continue; + rc = _snprintf(&str[offset], size - offset, "%s,", arg); + if (rc <= 0) + { + free(str); + return NULL; + } + offset += (size_t)rc; + } + if (offset > 0) + str[offset - 1] = '\0'; + return str; +} + +void CommandLineParserFree(char** ptr) +{ + union + { + char* p; + char** pp; + } uptr; + uptr.pp = ptr; + free(uptr.p); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ArrayList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ArrayList.c new file mode 100644 index 0000000000000000000000000000000000000000..63dc3aa4f4e03b79f0a02398b624a1a5917e6ce5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ArrayList.c @@ -0,0 +1,613 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.ArrayList + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include +#include +#include + +#if defined(_WIN32) && (_MSC_VER < 1800) && !defined(__MINGW32__) +#define va_copy(dest, src) (dest = src) +#endif + +struct s_wArrayList +{ + size_t capacity; + size_t growthFactor; + BOOL synchronized; + + size_t size; + void** array; + CRITICAL_SECTION lock; + + wObject object; +}; + +/** + * C equivalent of the C# ArrayList Class: + * http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx + */ + +/** + * Properties + */ + +/** + * Gets or sets the number of elements that the ArrayList can contain. + */ + +size_t ArrayList_Capacity(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return arrayList->capacity; +} + +/** + * Gets the number of elements actually contained in the ArrayList. + */ + +size_t ArrayList_Count(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return arrayList->size; +} + +/** + * Gets the internal list of items contained in the ArrayList. + */ + +size_t ArrayList_Items(wArrayList* arrayList, ULONG_PTR** ppItems) +{ + WINPR_ASSERT(arrayList); + *ppItems = (ULONG_PTR*)arrayList->array; + return arrayList->size; +} + +/** + * Gets a value indicating whether the ArrayList has a fixed size. + */ + +BOOL ArrayList_IsFixedSized(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return FALSE; +} + +/** + * Gets a value indicating whether the ArrayList is read-only. + */ + +BOOL ArrayList_IsReadOnly(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return FALSE; +} + +/** + * Gets a value indicating whether access to the ArrayList is synchronized (thread safe). + */ + +BOOL ArrayList_IsSynchronized(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return arrayList->synchronized; +} + +/** + * Lock access to the ArrayList + */ + +static void ArrayList_Lock_Conditional(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + if (arrayList->synchronized) + EnterCriticalSection(&arrayList->lock); +} + +void ArrayList_Lock(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + EnterCriticalSection(&arrayList->lock); +} + +/** + * Unlock access to the ArrayList + */ + +static void ArrayList_Unlock_Conditional(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + if (arrayList->synchronized) + LeaveCriticalSection(&arrayList->lock); +} + +void ArrayList_Unlock(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + LeaveCriticalSection(&arrayList->lock); +} + +/** + * Gets the element at the specified index. + */ + +void* ArrayList_GetItem(wArrayList* arrayList, size_t index) +{ + void* obj = NULL; + + WINPR_ASSERT(arrayList); + if (index < arrayList->size) + { + obj = arrayList->array[index]; + } + + return obj; +} + +/** + * Sets the element at the specified index. + */ + +BOOL ArrayList_SetItem(wArrayList* arrayList, size_t index, const void* obj) +{ + WINPR_ASSERT(arrayList); + if (index >= arrayList->size) + return FALSE; + + if (arrayList->object.fnObjectNew) + { + arrayList->array[index] = arrayList->object.fnObjectNew(obj); + if (obj && !arrayList->array[index]) + return FALSE; + } + else + { + union + { + const void* cpv; + void* pv; + } cnv; + cnv.cpv = obj; + arrayList->array[index] = cnv.pv; + } + return TRUE; +} + +/** + * Methods + */ +static BOOL ArrayList_EnsureCapacity(wArrayList* arrayList, size_t count) +{ + WINPR_ASSERT(arrayList); + WINPR_ASSERT(count > 0); + + if (arrayList->size + count > arrayList->capacity) + { + void** newArray = NULL; + size_t newCapacity = arrayList->capacity * arrayList->growthFactor; + if (newCapacity < arrayList->size + count) + newCapacity = arrayList->size + count; + + newArray = (void**)realloc((void*)arrayList->array, sizeof(void*) * newCapacity); + + if (!newArray) + return FALSE; + + arrayList->array = newArray; + arrayList->capacity = newCapacity; + } + + return TRUE; +} +/** + * Shift a section of the list. + */ + +static BOOL ArrayList_Shift(wArrayList* arrayList, size_t index, SSIZE_T count) +{ + WINPR_ASSERT(arrayList); + if (count > 0) + { + if (!ArrayList_EnsureCapacity(arrayList, (size_t)count)) + return FALSE; + + MoveMemory((void*)&arrayList->array[index + (size_t)count], (void*)&arrayList->array[index], + (arrayList->size - index) * sizeof(void*)); + arrayList->size += (size_t)count; + } + else if (count < 0) + { + const size_t scount = WINPR_ASSERTING_INT_CAST(size_t, -count); + const size_t off = index + scount; + if (off < arrayList->size) + { + const size_t chunk = arrayList->size - off; + MoveMemory((void*)&arrayList->array[index], (void*)&arrayList->array[off], + chunk * sizeof(void*)); + } + + arrayList->size -= scount; + } + + return TRUE; +} + +/** + * Removes all elements from the ArrayList. + */ + +void ArrayList_Clear(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + for (size_t index = 0; index < arrayList->size; index++) + { + if (arrayList->object.fnObjectFree) + arrayList->object.fnObjectFree(arrayList->array[index]); + + arrayList->array[index] = NULL; + } + + arrayList->size = 0; + + ArrayList_Unlock_Conditional(arrayList); +} + +/** + * Determines whether an element is in the ArrayList. + */ + +BOOL ArrayList_Contains(wArrayList* arrayList, const void* obj) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + for (size_t index = 0; index < arrayList->size; index++) + { + rc = arrayList->object.fnObjectEquals(arrayList->array[index], obj); + + if (rc) + break; + } + + ArrayList_Unlock_Conditional(arrayList); + + return rc; +} + +#if defined(WITH_WINPR_DEPRECATED) +int ArrayList_Add(wArrayList* arrayList, const void* obj) +{ + WINPR_ASSERT(arrayList); + if (!ArrayList_Append(arrayList, obj)) + return -1; + return (int)ArrayList_Count(arrayList) - 1; +} +#endif + +/** + * Adds an object to the end of the ArrayList. + */ + +BOOL ArrayList_Append(wArrayList* arrayList, const void* obj) +{ + size_t index = 0; + BOOL rc = FALSE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + if (!ArrayList_EnsureCapacity(arrayList, 1)) + goto out; + + index = arrayList->size++; + rc = ArrayList_SetItem(arrayList, index, obj); +out: + + ArrayList_Unlock_Conditional(arrayList); + + return rc; +} + +/* + * Inserts an element into the ArrayList at the specified index. + */ + +BOOL ArrayList_Insert(wArrayList* arrayList, size_t index, const void* obj) +{ + BOOL ret = TRUE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + if (index < arrayList->size) + { + if (!ArrayList_Shift(arrayList, index, 1)) + { + ret = FALSE; + } + else + { + ArrayList_SetItem(arrayList, index, obj); + } + } + + ArrayList_Unlock_Conditional(arrayList); + + return ret; +} + +/** + * Removes the first occurrence of a specific object from the ArrayList. + */ + +BOOL ArrayList_Remove(wArrayList* arrayList, const void* obj) +{ + BOOL found = FALSE; + BOOL ret = TRUE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + size_t index = 0; + for (; index < arrayList->size; index++) + { + if (arrayList->object.fnObjectEquals(arrayList->array[index], obj)) + { + found = TRUE; + break; + } + } + + if (found) + { + if (arrayList->object.fnObjectFree) + arrayList->object.fnObjectFree(arrayList->array[index]); + + ret = ArrayList_Shift(arrayList, index, -1); + } + + ArrayList_Unlock_Conditional(arrayList); + + return ret; +} + +/** + * Removes the element at the specified index of the ArrayList. + */ + +BOOL ArrayList_RemoveAt(wArrayList* arrayList, size_t index) +{ + BOOL ret = TRUE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + if (index < arrayList->size) + { + if (arrayList->object.fnObjectFree) + arrayList->object.fnObjectFree(arrayList->array[index]); + + ret = ArrayList_Shift(arrayList, index, -1); + } + + ArrayList_Unlock_Conditional(arrayList); + + return ret; +} + +/** + * Searches for the specified Object and returns the zero-based index of the first occurrence within + * the entire ArrayList. + * + * Searches for the specified Object and returns the zero-based index of the last occurrence within + * the range of elements in the ArrayList that extends from the first element to the specified + * index. + * + * Searches for the specified Object and returns the zero-based index of the last occurrence within + * the range of elements in the ArrayList that contains the specified number of elements and ends at + * the specified index. + */ + +SSIZE_T ArrayList_IndexOf(wArrayList* arrayList, const void* obj, SSIZE_T startIndex, SSIZE_T count) +{ + BOOL found = FALSE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + SSIZE_T sindex = startIndex; + if (startIndex < 0) + sindex = 0; + + SSIZE_T index = sindex; + SSIZE_T cindex = count; + if (count < 0) + { + if (arrayList->size > SSIZE_MAX) + goto fail; + cindex = (SSIZE_T)arrayList->size; + } + + for (; index < sindex + cindex; index++) + { + if (arrayList->object.fnObjectEquals(arrayList->array[index], obj)) + { + found = TRUE; + break; + } + } + +fail: + if (!found) + index = -1; + + ArrayList_Unlock_Conditional(arrayList); + + return index; +} + +/** + * Searches for the specified Object and returns the zero-based index of the last occurrence within + * the entire ArrayList. + * + * Searches for the specified Object and returns the zero-based index of the last occurrence within + * the range of elements in the ArrayList that extends from the first element to the specified + * index. + * + * Searches for the specified Object and returns the zero-based index of the last occurrence within + * the range of elements in the ArrayList that contains the specified number of elements and ends at + * the specified index. + */ + +SSIZE_T ArrayList_LastIndexOf(wArrayList* arrayList, const void* obj, SSIZE_T startIndex, + SSIZE_T count) +{ + SSIZE_T sindex = 0; + SSIZE_T cindex = 0; + BOOL found = FALSE; + + WINPR_ASSERT(arrayList); + ArrayList_Lock_Conditional(arrayList); + + sindex = startIndex; + if (startIndex < 0) + sindex = 0; + + cindex = count; + if (count < 0) + { + WINPR_ASSERT(arrayList->size <= SSIZE_MAX); + cindex = (SSIZE_T)arrayList->size; + } + + SSIZE_T index = sindex + cindex; + for (; index > sindex; index--) + { + if (arrayList->object.fnObjectEquals(arrayList->array[index - 1], obj)) + { + found = TRUE; + break; + } + } + + if (!found) + index = -1; + + ArrayList_Unlock_Conditional(arrayList); + + return index; +} + +static BOOL ArrayList_DefaultCompare(const void* objA, const void* objB) +{ + return objA == objB ? TRUE : FALSE; +} + +wObject* ArrayList_Object(wArrayList* arrayList) +{ + WINPR_ASSERT(arrayList); + return &arrayList->object; +} + +BOOL ArrayList_ForEach(wArrayList* arrayList, ArrayList_ForEachFkt fkt, ...) +{ + BOOL rc = 0; + va_list ap = { 0 }; + va_start(ap, fkt); + rc = ArrayList_ForEachAP(arrayList, fkt, ap); + va_end(ap); + + return rc; +} + +BOOL ArrayList_ForEachAP(wArrayList* arrayList, ArrayList_ForEachFkt fkt, va_list ap) +{ + BOOL rc = FALSE; + va_list cap; + + WINPR_ASSERT(arrayList); + WINPR_ASSERT(fkt); + + ArrayList_Lock_Conditional(arrayList); + size_t count = ArrayList_Count(arrayList); + for (size_t index = 0; index < count; index++) + { + BOOL rs = 0; + void* obj = ArrayList_GetItem(arrayList, index); + va_copy(cap, ap); + rs = fkt(obj, index, cap); + va_end(cap); + if (!rs) + goto fail; + } + rc = TRUE; +fail: + ArrayList_Unlock_Conditional(arrayList); + return rc; +} + +/** + * Construction, Destruction + */ + +wArrayList* ArrayList_New(BOOL synchronized) +{ + wObject* obj = NULL; + wArrayList* arrayList = NULL; + arrayList = (wArrayList*)calloc(1, sizeof(wArrayList)); + + if (!arrayList) + return NULL; + + arrayList->synchronized = synchronized; + arrayList->growthFactor = 2; + obj = ArrayList_Object(arrayList); + if (!obj) + goto fail; + obj->fnObjectEquals = ArrayList_DefaultCompare; + if (!ArrayList_EnsureCapacity(arrayList, 32)) + goto fail; + + InitializeCriticalSectionAndSpinCount(&arrayList->lock, 4000); + return arrayList; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + ArrayList_Free(arrayList); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void ArrayList_Free(wArrayList* arrayList) +{ + if (!arrayList) + return; + + ArrayList_Clear(arrayList); + DeleteCriticalSection(&arrayList->lock); + free((void*)arrayList->array); + free(arrayList); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BitStream.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BitStream.c new file mode 100644 index 0000000000000000000000000000000000000000..e7bcd5b4276bb21dbde91c92fe0cd1e6da6c57ea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BitStream.c @@ -0,0 +1,177 @@ +/** + * WinPR: Windows Portable Runtime + * BitStream + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include +#include + +static const char* BYTE_BIT_STRINGS_LSB[256] = { + "00000000", "00000001", "00000010", "00000011", "00000100", "00000101", "00000110", "00000111", + "00001000", "00001001", "00001010", "00001011", "00001100", "00001101", "00001110", "00001111", + "00010000", "00010001", "00010010", "00010011", "00010100", "00010101", "00010110", "00010111", + "00011000", "00011001", "00011010", "00011011", "00011100", "00011101", "00011110", "00011111", + "00100000", "00100001", "00100010", "00100011", "00100100", "00100101", "00100110", "00100111", + "00101000", "00101001", "00101010", "00101011", "00101100", "00101101", "00101110", "00101111", + "00110000", "00110001", "00110010", "00110011", "00110100", "00110101", "00110110", "00110111", + "00111000", "00111001", "00111010", "00111011", "00111100", "00111101", "00111110", "00111111", + "01000000", "01000001", "01000010", "01000011", "01000100", "01000101", "01000110", "01000111", + "01001000", "01001001", "01001010", "01001011", "01001100", "01001101", "01001110", "01001111", + "01010000", "01010001", "01010010", "01010011", "01010100", "01010101", "01010110", "01010111", + "01011000", "01011001", "01011010", "01011011", "01011100", "01011101", "01011110", "01011111", + "01100000", "01100001", "01100010", "01100011", "01100100", "01100101", "01100110", "01100111", + "01101000", "01101001", "01101010", "01101011", "01101100", "01101101", "01101110", "01101111", + "01110000", "01110001", "01110010", "01110011", "01110100", "01110101", "01110110", "01110111", + "01111000", "01111001", "01111010", "01111011", "01111100", "01111101", "01111110", "01111111", + "10000000", "10000001", "10000010", "10000011", "10000100", "10000101", "10000110", "10000111", + "10001000", "10001001", "10001010", "10001011", "10001100", "10001101", "10001110", "10001111", + "10010000", "10010001", "10010010", "10010011", "10010100", "10010101", "10010110", "10010111", + "10011000", "10011001", "10011010", "10011011", "10011100", "10011101", "10011110", "10011111", + "10100000", "10100001", "10100010", "10100011", "10100100", "10100101", "10100110", "10100111", + "10101000", "10101001", "10101010", "10101011", "10101100", "10101101", "10101110", "10101111", + "10110000", "10110001", "10110010", "10110011", "10110100", "10110101", "10110110", "10110111", + "10111000", "10111001", "10111010", "10111011", "10111100", "10111101", "10111110", "10111111", + "11000000", "11000001", "11000010", "11000011", "11000100", "11000101", "11000110", "11000111", + "11001000", "11001001", "11001010", "11001011", "11001100", "11001101", "11001110", "11001111", + "11010000", "11010001", "11010010", "11010011", "11010100", "11010101", "11010110", "11010111", + "11011000", "11011001", "11011010", "11011011", "11011100", "11011101", "11011110", "11011111", + "11100000", "11100001", "11100010", "11100011", "11100100", "11100101", "11100110", "11100111", + "11101000", "11101001", "11101010", "11101011", "11101100", "11101101", "11101110", "11101111", + "11110000", "11110001", "11110010", "11110011", "11110100", "11110101", "11110110", "11110111", + "11111000", "11111001", "11111010", "11111011", "11111100", "11111101", "11111110", "11111111" +}; + +static const char* BYTE_BIT_STRINGS_MSB[256] = { + "00000000", "10000000", "01000000", "11000000", "00100000", "10100000", "01100000", "11100000", + "00010000", "10010000", "01010000", "11010000", "00110000", "10110000", "01110000", "11110000", + "00001000", "10001000", "01001000", "11001000", "00101000", "10101000", "01101000", "11101000", + "00011000", "10011000", "01011000", "11011000", "00111000", "10111000", "01111000", "11111000", + "00000100", "10000100", "01000100", "11000100", "00100100", "10100100", "01100100", "11100100", + "00010100", "10010100", "01010100", "11010100", "00110100", "10110100", "01110100", "11110100", + "00001100", "10001100", "01001100", "11001100", "00101100", "10101100", "01101100", "11101100", + "00011100", "10011100", "01011100", "11011100", "00111100", "10111100", "01111100", "11111100", + "00000010", "10000010", "01000010", "11000010", "00100010", "10100010", "01100010", "11100010", + "00010010", "10010010", "01010010", "11010010", "00110010", "10110010", "01110010", "11110010", + "00001010", "10001010", "01001010", "11001010", "00101010", "10101010", "01101010", "11101010", + "00011010", "10011010", "01011010", "11011010", "00111010", "10111010", "01111010", "11111010", + "00000110", "10000110", "01000110", "11000110", "00100110", "10100110", "01100110", "11100110", + "00010110", "10010110", "01010110", "11010110", "00110110", "10110110", "01110110", "11110110", + "00001110", "10001110", "01001110", "11001110", "00101110", "10101110", "01101110", "11101110", + "00011110", "10011110", "01011110", "11011110", "00111110", "10111110", "01111110", "11111110", + "00000001", "10000001", "01000001", "11000001", "00100001", "10100001", "01100001", "11100001", + "00010001", "10010001", "01010001", "11010001", "00110001", "10110001", "01110001", "11110001", + "00001001", "10001001", "01001001", "11001001", "00101001", "10101001", "01101001", "11101001", + "00011001", "10011001", "01011001", "11011001", "00111001", "10111001", "01111001", "11111001", + "00000101", "10000101", "01000101", "11000101", "00100101", "10100101", "01100101", "11100101", + "00010101", "10010101", "01010101", "11010101", "00110101", "10110101", "01110101", "11110101", + "00001101", "10001101", "01001101", "11001101", "00101101", "10101101", "01101101", "11101101", + "00011101", "10011101", "01011101", "11011101", "00111101", "10111101", "01111101", "11111101", + "00000011", "10000011", "01000011", "11000011", "00100011", "10100011", "01100011", "11100011", + "00010011", "10010011", "01010011", "11010011", "00110011", "10110011", "01110011", "11110011", + "00001011", "10001011", "01001011", "11001011", "00101011", "10101011", "01101011", "11101011", + "00011011", "10011011", "01011011", "11011011", "00111011", "10111011", "01111011", "11111011", + "00000111", "10000111", "01000111", "11000111", "00100111", "10100111", "01100111", "11100111", + "00010111", "10010111", "01010111", "11010111", "00110111", "10110111", "01110111", "11110111", + "00001111", "10001111", "01001111", "11001111", "00101111", "10101111", "01101111", "11101111", + "00011111", "10011111", "01011111", "11011111", "00111111", "10111111", "01111111", "11111111" +}; + +void BitDump(const char* tag, UINT32 level, const BYTE* buffer, UINT32 length, UINT32 flags) +{ + const char** strs = (flags & BITDUMP_MSB_FIRST) ? BYTE_BIT_STRINGS_MSB : BYTE_BIT_STRINGS_LSB; + char pbuffer[64 * 8 + 1] = { 0 }; + size_t pos = 0; + + WINPR_ASSERT(tag); + WINPR_ASSERT(buffer || (length == 0)); + + DWORD i = 0; + for (; i < length; i += 8) + { + const char* str = strs[buffer[i / 8]]; + const DWORD nbits = (length - i) > 8 ? 8 : (length - i); + WINPR_ASSERT(nbits <= INT32_MAX); + const int rc = _snprintf(&pbuffer[pos], length - pos, "%.*s ", (int)nbits, str); + if (rc < 0) + return; + + pos += (size_t)rc; + if ((i % 64) == 0) + { + pos = 0; + WLog_LVL(tag, level, "%s", pbuffer); + } + } + + if (i) + WLog_LVL(tag, level, "%s ", pbuffer); +} + +UINT32 ReverseBits32(UINT32 bits, UINT32 nbits) +{ + UINT32 rbits = 0; + + do + { + rbits = (rbits | (bits & 1)) << 1; + bits >>= 1; + nbits--; + } while (nbits > 0); + + rbits >>= 1; + return rbits; +} + +void BitStream_Attach(wBitStream* bs, const BYTE* buffer, UINT32 capacity) +{ + union + { + const BYTE* cpv; + BYTE* pv; + } cnv; + + WINPR_ASSERT(bs); + WINPR_ASSERT(buffer); + + cnv.cpv = buffer; + + bs->position = 0; + bs->buffer = cnv.pv; + bs->offset = 0; + bs->accumulator = 0; + bs->pointer = cnv.pv; + bs->capacity = capacity; + bs->length = bs->capacity * 8; +} + +wBitStream* BitStream_New(void) +{ + wBitStream* bs = (wBitStream*)calloc(1, sizeof(wBitStream)); + + return bs; +} + +void BitStream_Free(wBitStream* bs) +{ + if (!bs) + return; + + free(bs); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BufferPool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BufferPool.c new file mode 100644 index 0000000000000000000000000000000000000000..de6682ad12ae897ffa157f3633377a7b010329c0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/BufferPool.c @@ -0,0 +1,581 @@ +/** + * WinPR: Windows Portable Runtime + * Buffer Pool + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +#define MAX(a, b) ((a) > (b)) ? (a) : (b) + +typedef struct +{ + SSIZE_T size; + void* buffer; +} wBufferPoolItem; + +struct s_wBufferPool +{ + SSIZE_T fixedSize; + DWORD alignment; + BOOL synchronized; + CRITICAL_SECTION lock; + + SSIZE_T size; + SSIZE_T capacity; + void** array; + + SSIZE_T aSize; + SSIZE_T aCapacity; + wBufferPoolItem* aArray; + + SSIZE_T uSize; + SSIZE_T uCapacity; + wBufferPoolItem* uArray; +}; + +static BOOL BufferPool_Lock(wBufferPool* pool) +{ + if (!pool) + return FALSE; + + if (pool->synchronized) + EnterCriticalSection(&pool->lock); + return TRUE; +} + +static BOOL BufferPool_Unlock(wBufferPool* pool) +{ + if (!pool) + return FALSE; + + if (pool->synchronized) + LeaveCriticalSection(&pool->lock); + return TRUE; +} + +/** + * C equivalent of the C# BufferManager Class: + * http://msdn.microsoft.com/en-us/library/ms405814.aspx + */ + +/** + * Methods + */ + +static BOOL BufferPool_ShiftAvailable(wBufferPool* pool, size_t index, int count) +{ + if (count > 0) + { + if (pool->aSize + count > pool->aCapacity) + { + wBufferPoolItem* newArray = NULL; + SSIZE_T newCapacity = pool->aSize + count; + newCapacity += (newCapacity + 2) / 2; + + WINPR_ASSERT(newCapacity > 0); + if (pool->alignment > 0) + newArray = (wBufferPoolItem*)winpr_aligned_realloc( + pool->aArray, + sizeof(wBufferPoolItem) * WINPR_ASSERTING_INT_CAST(size_t, newCapacity), + pool->alignment); + else + newArray = (wBufferPoolItem*)realloc( + pool->aArray, + sizeof(wBufferPoolItem) * WINPR_ASSERTING_INT_CAST(size_t, newCapacity)); + if (!newArray) + return FALSE; + pool->aArray = newArray; + pool->aCapacity = newCapacity; + } + + MoveMemory( + &pool->aArray[index + WINPR_ASSERTING_INT_CAST(size_t, count)], &pool->aArray[index], + (WINPR_ASSERTING_INT_CAST(size_t, pool->aSize) - index) * sizeof(wBufferPoolItem)); + pool->aSize += count; + } + else if (count < 0) + { + MoveMemory( + &pool->aArray[index], &pool->aArray[index + WINPR_ASSERTING_INT_CAST(size_t, -count)], + (WINPR_ASSERTING_INT_CAST(size_t, pool->aSize) - index) * sizeof(wBufferPoolItem)); + pool->aSize += count; + } + return TRUE; +} + +static BOOL BufferPool_ShiftUsed(wBufferPool* pool, SSIZE_T index, SSIZE_T count) +{ + if (count > 0) + { + if (pool->uSize + count > pool->uCapacity) + { + SSIZE_T newUCapacity = pool->uCapacity * 2; + wBufferPoolItem* newUArray = NULL; + if (pool->alignment > 0) + newUArray = (wBufferPoolItem*)winpr_aligned_realloc( + pool->uArray, + sizeof(wBufferPoolItem) * WINPR_ASSERTING_INT_CAST(size_t, newUCapacity), + pool->alignment); + else + newUArray = (wBufferPoolItem*)realloc( + pool->uArray, + sizeof(wBufferPoolItem) * WINPR_ASSERTING_INT_CAST(size_t, newUCapacity)); + if (!newUArray) + return FALSE; + pool->uCapacity = newUCapacity; + pool->uArray = newUArray; + } + + MoveMemory(&pool->uArray[index + count], &pool->uArray[index], + WINPR_ASSERTING_INT_CAST(size_t, pool->uSize - index) * sizeof(wBufferPoolItem)); + pool->uSize += count; + } + else if (count < 0) + { + MoveMemory(&pool->uArray[index], &pool->uArray[index - count], + WINPR_ASSERTING_INT_CAST(size_t, pool->uSize - index) * sizeof(wBufferPoolItem)); + pool->uSize += count; + } + return TRUE; +} + +/** + * Get the buffer pool size + */ + +SSIZE_T BufferPool_GetPoolSize(wBufferPool* pool) +{ + SSIZE_T size = 0; + + BufferPool_Lock(pool); + + if (pool->fixedSize) + { + /* fixed size buffers */ + size = pool->size; + } + else + { + /* variable size buffers */ + size = pool->uSize; + } + + BufferPool_Unlock(pool); + + return size; +} + +/** + * Get the size of a pooled buffer + */ + +SSIZE_T BufferPool_GetBufferSize(wBufferPool* pool, const void* buffer) +{ + SSIZE_T size = 0; + BOOL found = FALSE; + + BufferPool_Lock(pool); + + if (pool->fixedSize) + { + /* fixed size buffers */ + size = pool->fixedSize; + found = TRUE; + } + else + { + /* variable size buffers */ + + for (SSIZE_T index = 0; index < pool->uSize; index++) + { + if (pool->uArray[index].buffer == buffer) + { + size = pool->uArray[index].size; + found = TRUE; + break; + } + } + } + + BufferPool_Unlock(pool); + + return (found) ? size : -1; +} + +/** + * Gets a buffer of at least the specified size from the pool. + */ + +void* BufferPool_Take(wBufferPool* pool, SSIZE_T size) +{ + SSIZE_T maxSize = 0; + SSIZE_T maxIndex = 0; + SSIZE_T foundIndex = -1; + BOOL found = FALSE; + void* buffer = NULL; + + BufferPool_Lock(pool); + + if (pool->fixedSize) + { + /* fixed size buffers */ + + if (pool->size > 0) + buffer = pool->array[--(pool->size)]; + + if (!buffer) + { + if (pool->alignment) + buffer = winpr_aligned_malloc(WINPR_ASSERTING_INT_CAST(size_t, pool->fixedSize), + pool->alignment); + else + buffer = malloc(WINPR_ASSERTING_INT_CAST(size_t, pool->fixedSize)); + } + + if (!buffer) + goto out_error; + } + else + { + /* variable size buffers */ + + maxSize = 0; + maxIndex = 0; + + if (size < 1) + size = pool->fixedSize; + + for (SSIZE_T index = 0; index < pool->aSize; index++) + { + if (pool->aArray[index].size > maxSize) + { + maxIndex = index; + maxSize = pool->aArray[index].size; + } + + if (pool->aArray[index].size >= size) + { + foundIndex = index; + found = TRUE; + break; + } + } + + if (!found && maxSize) + { + foundIndex = maxIndex; + found = TRUE; + } + + if (!found) + { + if (!size) + buffer = NULL; + else + { + if (pool->alignment) + buffer = winpr_aligned_malloc(WINPR_ASSERTING_INT_CAST(size_t, size), + pool->alignment); + else + buffer = malloc(WINPR_ASSERTING_INT_CAST(size_t, size)); + + if (!buffer) + goto out_error; + } + } + else + { + buffer = pool->aArray[foundIndex].buffer; + + if (maxSize < size) + { + void* newBuffer = NULL; + if (pool->alignment) + newBuffer = winpr_aligned_realloc( + buffer, WINPR_ASSERTING_INT_CAST(size_t, size), pool->alignment); + else + newBuffer = realloc(buffer, WINPR_ASSERTING_INT_CAST(size_t, size)); + + if (!newBuffer) + goto out_error_no_free; + + buffer = newBuffer; + } + + if (!BufferPool_ShiftAvailable(pool, WINPR_ASSERTING_INT_CAST(size_t, foundIndex), -1)) + goto out_error; + } + + if (!buffer) + goto out_error; + + if (pool->uSize + 1 > pool->uCapacity) + { + size_t newUCapacity = WINPR_ASSERTING_INT_CAST(size_t, pool->uCapacity); + newUCapacity += (newUCapacity + 2) / 2; + if (newUCapacity > SSIZE_MAX) + goto out_error; + wBufferPoolItem* newUArray = + (wBufferPoolItem*)realloc(pool->uArray, sizeof(wBufferPoolItem) * newUCapacity); + if (!newUArray) + goto out_error; + + pool->uCapacity = (SSIZE_T)newUCapacity; + pool->uArray = newUArray; + } + + pool->uArray[pool->uSize].buffer = buffer; + pool->uArray[pool->uSize].size = size; + (pool->uSize)++; + } + + BufferPool_Unlock(pool); + + return buffer; + +out_error: + if (pool->alignment) + winpr_aligned_free(buffer); + else + free(buffer); +out_error_no_free: + BufferPool_Unlock(pool); + return NULL; +} + +/** + * Returns a buffer to the pool. + */ + +BOOL BufferPool_Return(wBufferPool* pool, void* buffer) +{ + BOOL rc = FALSE; + SSIZE_T size = 0; + BOOL found = FALSE; + + BufferPool_Lock(pool); + + if (pool->fixedSize) + { + /* fixed size buffers */ + + if ((pool->size + 1) >= pool->capacity) + { + SSIZE_T newCapacity = MAX(1, pool->size + (pool->size + 2) / 2 + 1); + void** newArray = (void**)realloc( + (void*)pool->array, sizeof(void*) * WINPR_ASSERTING_INT_CAST(size_t, newCapacity)); + if (!newArray) + goto out_error; + + pool->capacity = newCapacity; + pool->array = newArray; + } + + pool->array[(pool->size)++] = buffer; + } + else + { + /* variable size buffers */ + + SSIZE_T index = 0; + for (; index < pool->uSize; index++) + { + if (pool->uArray[index].buffer == buffer) + { + found = TRUE; + break; + } + } + + if (found) + { + size = pool->uArray[index].size; + if (!BufferPool_ShiftUsed(pool, index, -1)) + goto out_error; + } + + if (size) + { + if ((pool->aSize + 1) >= pool->aCapacity) + { + SSIZE_T newCapacity = MAX(1, pool->aSize + (pool->aSize + 2) / 2 + 1); + wBufferPoolItem* newArray = (wBufferPoolItem*)realloc( + pool->aArray, + sizeof(wBufferPoolItem) * WINPR_ASSERTING_INT_CAST(size_t, newCapacity)); + if (!newArray) + goto out_error; + + pool->aCapacity = newCapacity; + pool->aArray = newArray; + } + + pool->aArray[pool->aSize].buffer = buffer; + pool->aArray[pool->aSize].size = size; + (pool->aSize)++; + } + } + + rc = TRUE; +out_error: + BufferPool_Unlock(pool); + return rc; +} + +/** + * Releases the buffers currently cached in the pool. + */ + +void BufferPool_Clear(wBufferPool* pool) +{ + BufferPool_Lock(pool); + + if (pool->fixedSize) + { + /* fixed size buffers */ + + while (pool->size > 0) + { + (pool->size)--; + + if (pool->alignment) + winpr_aligned_free(pool->array[pool->size]); + else + free(pool->array[pool->size]); + } + } + else + { + /* variable size buffers */ + + while (pool->aSize > 0) + { + (pool->aSize)--; + + if (pool->alignment) + winpr_aligned_free(pool->aArray[pool->aSize].buffer); + else + free(pool->aArray[pool->aSize].buffer); + } + + while (pool->uSize > 0) + { + (pool->uSize)--; + + if (pool->alignment) + winpr_aligned_free(pool->uArray[pool->uSize].buffer); + else + free(pool->uArray[pool->uSize].buffer); + } + } + + BufferPool_Unlock(pool); +} + +/** + * Construction, Destruction + */ + +wBufferPool* BufferPool_New(BOOL synchronized, SSIZE_T fixedSize, DWORD alignment) +{ + wBufferPool* pool = NULL; + + pool = (wBufferPool*)calloc(1, sizeof(wBufferPool)); + + if (pool) + { + pool->fixedSize = fixedSize; + + if (pool->fixedSize < 0) + pool->fixedSize = 0; + + pool->alignment = alignment; + pool->synchronized = synchronized; + + if (pool->synchronized) + InitializeCriticalSectionAndSpinCount(&pool->lock, 4000); + + if (pool->fixedSize) + { + /* fixed size buffers */ + + pool->size = 0; + pool->capacity = 32; + pool->array = + (void**)calloc(WINPR_ASSERTING_INT_CAST(size_t, pool->capacity), sizeof(void*)); + if (!pool->array) + goto out_error; + } + else + { + /* variable size buffers */ + + pool->aSize = 0; + pool->aCapacity = 32; + pool->aArray = (wBufferPoolItem*)calloc( + WINPR_ASSERTING_INT_CAST(size_t, pool->aCapacity), sizeof(wBufferPoolItem)); + if (!pool->aArray) + goto out_error; + + pool->uSize = 0; + pool->uCapacity = 32; + pool->uArray = (wBufferPoolItem*)calloc( + WINPR_ASSERTING_INT_CAST(size_t, pool->uCapacity), sizeof(wBufferPoolItem)); + if (!pool->uArray) + goto out_error; + } + } + + return pool; + +out_error: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + BufferPool_Free(pool); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void BufferPool_Free(wBufferPool* pool) +{ + if (pool) + { + BufferPool_Clear(pool); + + if (pool->synchronized) + DeleteCriticalSection(&pool->lock); + + if (pool->fixedSize) + { + /* fixed size buffers */ + + free((void*)pool->array); + } + else + { + /* variable size buffers */ + + free(pool->aArray); + free(pool->uArray); + } + + free(pool); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/CountdownEvent.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/CountdownEvent.c new file mode 100644 index 0000000000000000000000000000000000000000..487f21e35e2ecb5709fd981a76837a20116517cb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/CountdownEvent.c @@ -0,0 +1,210 @@ +/** + * WinPR: Windows Portable Runtime + * Countdown Event + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include + +#include + +struct CountdownEvent +{ + size_t count; + CRITICAL_SECTION lock; + HANDLE event; + size_t initialCount; +}; + +/** + * C equivalent of the C# CountdownEvent Class + * http://msdn.microsoft.com/en-us/library/dd235708/ + */ + +/** + * Properties + */ + +/** + * Gets the number of remaining signals required to set the event. + */ + +size_t CountdownEvent_CurrentCount(wCountdownEvent* countdown) +{ + WINPR_ASSERT(countdown); + EnterCriticalSection(&countdown->lock); + const size_t rc = countdown->count; + LeaveCriticalSection(&countdown->lock); + return rc; +} + +/** + * Gets the numbers of signals initially required to set the event. + */ + +size_t CountdownEvent_InitialCount(wCountdownEvent* countdown) +{ + WINPR_ASSERT(countdown); + EnterCriticalSection(&countdown->lock); + const size_t rc = countdown->initialCount; + LeaveCriticalSection(&countdown->lock); + return rc; +} + +/** + * Determines whether the event is set. + */ + +BOOL CountdownEvent_IsSet(wCountdownEvent* countdown) +{ + BOOL status = FALSE; + + WINPR_ASSERT(countdown); + if (WaitForSingleObject(countdown->event, 0) == WAIT_OBJECT_0) + status = TRUE; + + return status; +} + +/** + * Gets a WaitHandle that is used to wait for the event to be set. + */ + +HANDLE CountdownEvent_WaitHandle(wCountdownEvent* countdown) +{ + WINPR_ASSERT(countdown); + return countdown->event; +} + +/** + * Methods + */ + +/** + * Increments the CountdownEvent's current count by a specified value. + */ + +void CountdownEvent_AddCount(wCountdownEvent* countdown, size_t signalCount) +{ + WINPR_ASSERT(countdown); + EnterCriticalSection(&countdown->lock); + + const BOOL signalSet = countdown->count == 0; + countdown->count += signalCount; + + if (signalSet) + (void)ResetEvent(countdown->event); + + LeaveCriticalSection(&countdown->lock); +} + +/** + * Registers multiple signals with the CountdownEvent, decrementing the value of CurrentCount by the + * specified amount. + */ + +BOOL CountdownEvent_Signal(wCountdownEvent* countdown, size_t signalCount) +{ + BOOL status = FALSE; + BOOL newStatus = FALSE; + BOOL oldStatus = FALSE; + + WINPR_ASSERT(countdown); + + EnterCriticalSection(&countdown->lock); + + if (WaitForSingleObject(countdown->event, 0) == WAIT_OBJECT_0) + oldStatus = TRUE; + + if (signalCount <= countdown->count) + countdown->count -= signalCount; + else + countdown->count = 0; + + if (countdown->count == 0) + newStatus = TRUE; + + if (newStatus && (!oldStatus)) + { + (void)SetEvent(countdown->event); + status = TRUE; + } + + LeaveCriticalSection(&countdown->lock); + + return status; +} + +/** + * Resets the InitialCount property to a specified value. + */ + +void CountdownEvent_Reset(wCountdownEvent* countdown, size_t count) +{ + WINPR_ASSERT(countdown); + countdown->initialCount = count; +} + +/** + * Construction, Destruction + */ + +wCountdownEvent* CountdownEvent_New(size_t initialCount) +{ + wCountdownEvent* countdown = (wCountdownEvent*)calloc(1, sizeof(wCountdownEvent)); + + if (!countdown) + return NULL; + + countdown->count = initialCount; + countdown->initialCount = initialCount; + + if (!InitializeCriticalSectionAndSpinCount(&countdown->lock, 4000)) + goto fail; + + countdown->event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!countdown->event) + goto fail; + + if (countdown->count == 0) + { + if (!SetEvent(countdown->event)) + goto fail; + } + + return countdown; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + CountdownEvent_Free(countdown); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void CountdownEvent_Free(wCountdownEvent* countdown) +{ + if (!countdown) + return; + + DeleteCriticalSection(&countdown->lock); + (void)CloseHandle(countdown->event); + + free(countdown); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/HashTable.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/HashTable.c new file mode 100644 index 0000000000000000000000000000000000000000..773a2320b1a267621adcf683361c92aa2e9c4453 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/HashTable.c @@ -0,0 +1,872 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.Hashtable + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +/** + * This implementation is based on the public domain + * hash table implementation made by Keith Pomakis: + * + * http://www.pomakis.com/hashtable/hashtable.c + * http://www.pomakis.com/hashtable/hashtable.h + */ + +typedef struct s_wKeyValuePair wKeyValuePair; + +struct s_wKeyValuePair +{ + void* key; + void* value; + + wKeyValuePair* next; + BOOL markedForRemove; +}; + +struct s_wHashTable +{ + BOOL synchronized; + CRITICAL_SECTION lock; + + size_t numOfBuckets; + size_t numOfElements; + float idealRatio; + float lowerRehashThreshold; + float upperRehashThreshold; + wKeyValuePair** bucketArray; + + HASH_TABLE_HASH_FN hash; + wObject key; + wObject value; + + DWORD foreachRecursionLevel; + DWORD pendingRemoves; +}; + +BOOL HashTable_PointerCompare(const void* pointer1, const void* pointer2) +{ + return (pointer1 == pointer2); +} + +UINT32 HashTable_PointerHash(const void* pointer) +{ + return ((UINT32)(UINT_PTR)pointer) >> 4; +} + +BOOL HashTable_StringCompare(const void* string1, const void* string2) +{ + if (!string1 || !string2) + return (string1 == string2); + + return (strcmp((const char*)string1, (const char*)string2) == 0); +} + +UINT32 HashTable_StringHash(const void* key) +{ + UINT32 c = 0; + UINT32 hash = 5381; + const BYTE* str = (const BYTE*)key; + + /* djb2 algorithm */ + while ((c = *str++) != '\0') + hash = (hash * 33) + c; + + return hash; +} + +void* HashTable_StringClone(const void* str) +{ + return winpr_ObjectStringClone(str); +} + +void HashTable_StringFree(void* str) +{ + winpr_ObjectStringFree(str); +} + +static INLINE BOOL HashTable_IsProbablePrime(size_t oddNumber) +{ + for (size_t i = 3; i < 51; i += 2) + { + if (oddNumber == i) + return TRUE; + else if (oddNumber % i == 0) + return FALSE; + } + + return TRUE; /* maybe */ +} + +static INLINE size_t HashTable_CalculateIdealNumOfBuckets(wHashTable* table) +{ + WINPR_ASSERT(table); + + const float numOfElements = (float)table->numOfElements; + const float tmp = (numOfElements / table->idealRatio); + size_t idealNumOfBuckets = (size_t)tmp; + + if (idealNumOfBuckets < 5) + idealNumOfBuckets = 5; + else + idealNumOfBuckets |= 0x01; + + while (!HashTable_IsProbablePrime(idealNumOfBuckets)) + idealNumOfBuckets += 2; + + return idealNumOfBuckets; +} + +static INLINE void HashTable_Rehash(wHashTable* table, size_t numOfBuckets) +{ + UINT32 hashValue = 0; + wKeyValuePair* nextPair = NULL; + wKeyValuePair** newBucketArray = NULL; + + WINPR_ASSERT(table); + if (numOfBuckets == 0) + numOfBuckets = HashTable_CalculateIdealNumOfBuckets(table); + + if (numOfBuckets == table->numOfBuckets) + return; /* already the right size! */ + + newBucketArray = (wKeyValuePair**)calloc(numOfBuckets, sizeof(wKeyValuePair*)); + + if (!newBucketArray) + { + /* + * Couldn't allocate memory for the new array. + * This isn't a fatal error; we just can't perform the rehash. + */ + return; + } + + for (size_t index = 0; index < table->numOfBuckets; index++) + { + wKeyValuePair* pair = table->bucketArray[index]; + + while (pair) + { + nextPair = pair->next; + hashValue = table->hash(pair->key) % numOfBuckets; + pair->next = newBucketArray[hashValue]; + newBucketArray[hashValue] = pair; + pair = nextPair; + } + } + + free((void*)table->bucketArray); + table->bucketArray = newBucketArray; + table->numOfBuckets = numOfBuckets; +} + +static INLINE BOOL HashTable_Equals(wHashTable* table, const wKeyValuePair* pair, const void* key) +{ + WINPR_ASSERT(table); + WINPR_ASSERT(pair); + WINPR_ASSERT(key); + return table->key.fnObjectEquals(key, pair->key); +} + +static INLINE wKeyValuePair* HashTable_Get(wHashTable* table, const void* key) +{ + UINT32 hashValue = 0; + wKeyValuePair* pair = NULL; + + WINPR_ASSERT(table); + if (!key) + return NULL; + + hashValue = table->hash(key) % table->numOfBuckets; + pair = table->bucketArray[hashValue]; + + while (pair && !HashTable_Equals(table, pair, key)) + pair = pair->next; + + return pair; +} + +static INLINE void disposeKey(wHashTable* table, void* key) +{ + WINPR_ASSERT(table); + if (table->key.fnObjectFree) + table->key.fnObjectFree(key); +} + +static INLINE void disposeValue(wHashTable* table, void* value) +{ + WINPR_ASSERT(table); + if (table->value.fnObjectFree) + table->value.fnObjectFree(value); +} + +static INLINE void disposePair(wHashTable* table, wKeyValuePair* pair) +{ + WINPR_ASSERT(table); + if (!pair) + return; + disposeKey(table, pair->key); + disposeValue(table, pair->value); + free(pair); +} + +static INLINE void setKey(wHashTable* table, wKeyValuePair* pair, const void* key) +{ + WINPR_ASSERT(table); + if (!pair) + return; + disposeKey(table, pair->key); + if (table->key.fnObjectNew) + pair->key = table->key.fnObjectNew(key); + else + { + union + { + const void* cpv; + void* pv; + } cnv; + cnv.cpv = key; + pair->key = cnv.pv; + } +} + +static INLINE void setValue(wHashTable* table, wKeyValuePair* pair, const void* value) +{ + WINPR_ASSERT(table); + if (!pair) + return; + disposeValue(table, pair->value); + if (table->value.fnObjectNew) + pair->value = table->value.fnObjectNew(value); + else + { + union + { + const void* cpv; + void* pv; + } cnv; + cnv.cpv = value; + pair->value = cnv.pv; + } +} + +/** + * C equivalent of the C# Hashtable Class: + * http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx + */ + +/** + * Properties + */ + +/** + * Gets the number of key/value pairs contained in the HashTable. + */ + +size_t HashTable_Count(wHashTable* table) +{ + WINPR_ASSERT(table); + return table->numOfElements; +} + +/** + * Methods + */ + +/** + * Adds an element with the specified key and value into the HashTable. + */ +#if defined(WITH_WINPR_DEPRECATED) +int HashTable_Add(wHashTable* table, const void* key, const void* value) +{ + if (!HashTable_Insert(table, key, value)) + return -1; + return 0; +} +#endif + +BOOL HashTable_Insert(wHashTable* table, const void* key, const void* value) +{ + BOOL rc = FALSE; + UINT32 hashValue = 0; + wKeyValuePair* pair = NULL; + wKeyValuePair* newPair = NULL; + + WINPR_ASSERT(table); + if (!key || !value) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + hashValue = table->hash(key) % table->numOfBuckets; + pair = table->bucketArray[hashValue]; + + while (pair && !HashTable_Equals(table, pair, key)) + pair = pair->next; + + if (pair) + { + if (pair->markedForRemove) + { + /* this entry was set to be removed but will be recycled instead */ + table->pendingRemoves--; + pair->markedForRemove = FALSE; + table->numOfElements++; + } + + if (pair->key != key) + { + setKey(table, pair, key); + } + + if (pair->value != value) + { + setValue(table, pair, value); + } + rc = TRUE; + } + else + { + newPair = (wKeyValuePair*)calloc(1, sizeof(wKeyValuePair)); + + if (newPair) + { + setKey(table, newPair, key); + setValue(table, newPair, value); + newPair->next = table->bucketArray[hashValue]; + newPair->markedForRemove = FALSE; + table->bucketArray[hashValue] = newPair; + table->numOfElements++; + + if (!table->foreachRecursionLevel && table->upperRehashThreshold > table->idealRatio) + { + float elementToBucketRatio = + (float)table->numOfElements / (float)table->numOfBuckets; + + if (elementToBucketRatio > table->upperRehashThreshold) + HashTable_Rehash(table, 0); + } + rc = TRUE; + } + } + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return rc; +} + +/** + * Removes the element with the specified key from the HashTable. + */ + +BOOL HashTable_Remove(wHashTable* table, const void* key) +{ + UINT32 hashValue = 0; + BOOL status = TRUE; + wKeyValuePair* pair = NULL; + wKeyValuePair* previousPair = NULL; + + WINPR_ASSERT(table); + if (!key) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + hashValue = table->hash(key) % table->numOfBuckets; + pair = table->bucketArray[hashValue]; + + while (pair && !HashTable_Equals(table, pair, key)) + { + previousPair = pair; + pair = pair->next; + } + + if (!pair) + { + status = FALSE; + goto out; + } + + if (table->foreachRecursionLevel) + { + /* if we are running a HashTable_Foreach, just mark the entry for removal */ + pair->markedForRemove = TRUE; + table->pendingRemoves++; + table->numOfElements--; + goto out; + } + + if (previousPair) + previousPair->next = pair->next; + else + table->bucketArray[hashValue] = pair->next; + + disposePair(table, pair); + table->numOfElements--; + + if (!table->foreachRecursionLevel && table->lowerRehashThreshold > 0.0f) + { + float elementToBucketRatio = (float)table->numOfElements / (float)table->numOfBuckets; + + if (elementToBucketRatio < table->lowerRehashThreshold) + HashTable_Rehash(table, 0); + } + +out: + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return status; +} + +/** + * Get an item value using key + */ + +void* HashTable_GetItemValue(wHashTable* table, const void* key) +{ + void* value = NULL; + wKeyValuePair* pair = NULL; + + WINPR_ASSERT(table); + if (!key) + return NULL; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + pair = HashTable_Get(table, key); + + if (pair && !pair->markedForRemove) + value = pair->value; + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return value; +} + +/** + * Set an item value using key + */ + +BOOL HashTable_SetItemValue(wHashTable* table, const void* key, const void* value) +{ + BOOL status = TRUE; + wKeyValuePair* pair = NULL; + + WINPR_ASSERT(table); + if (!key) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + pair = HashTable_Get(table, key); + + if (!pair || pair->markedForRemove) + status = FALSE; + else + { + setValue(table, pair, value); + } + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return status; +} + +/** + * Removes all elements from the HashTable. + */ + +void HashTable_Clear(wHashTable* table) +{ + wKeyValuePair* nextPair = NULL; + + WINPR_ASSERT(table); + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + for (size_t index = 0; index < table->numOfBuckets; index++) + { + wKeyValuePair* pair = table->bucketArray[index]; + + while (pair) + { + nextPair = pair->next; + + if (table->foreachRecursionLevel) + { + /* if we're in a foreach we just mark the entry for removal */ + pair->markedForRemove = TRUE; + table->pendingRemoves++; + } + else + { + disposePair(table, pair); + pair = nextPair; + } + } + + table->bucketArray[index] = NULL; + } + + table->numOfElements = 0; + if (table->foreachRecursionLevel == 0) + HashTable_Rehash(table, 5); + + if (table->synchronized) + LeaveCriticalSection(&table->lock); +} + +/** + * Gets the list of keys as an array + */ + +size_t HashTable_GetKeys(wHashTable* table, ULONG_PTR** ppKeys) +{ + size_t iKey = 0; + size_t count = 0; + ULONG_PTR* pKeys = NULL; + wKeyValuePair* nextPair = NULL; + + WINPR_ASSERT(table); + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + iKey = 0; + count = table->numOfElements; + if (ppKeys) + *ppKeys = NULL; + + if (count < 1) + { + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return 0; + } + + pKeys = (ULONG_PTR*)calloc(count, sizeof(ULONG_PTR)); + + if (!pKeys) + { + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return 0; + } + + for (size_t index = 0; index < table->numOfBuckets; index++) + { + wKeyValuePair* pair = table->bucketArray[index]; + + while (pair) + { + nextPair = pair->next; + if (!pair->markedForRemove) + pKeys[iKey++] = (ULONG_PTR)pair->key; + pair = nextPair; + } + } + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + if (ppKeys) + *ppKeys = pKeys; + else + free(pKeys); + return count; +} + +BOOL HashTable_Foreach(wHashTable* table, HASH_TABLE_FOREACH_FN fn, VOID* arg) +{ + BOOL ret = TRUE; + + WINPR_ASSERT(table); + WINPR_ASSERT(fn); + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + table->foreachRecursionLevel++; + for (size_t index = 0; index < table->numOfBuckets; index++) + { + for (wKeyValuePair* pair = table->bucketArray[index]; pair; pair = pair->next) + { + if (!pair->markedForRemove && !fn(pair->key, pair->value, arg)) + { + ret = FALSE; + goto out; + } + } + } + table->foreachRecursionLevel--; + + if (!table->foreachRecursionLevel && table->pendingRemoves) + { + /* if we're the last recursive foreach call, let's do the cleanup if needed */ + wKeyValuePair** prevPtr = NULL; + for (size_t index = 0; index < table->numOfBuckets; index++) + { + wKeyValuePair* nextPair = NULL; + prevPtr = &table->bucketArray[index]; + for (wKeyValuePair* pair = table->bucketArray[index]; pair;) + { + nextPair = pair->next; + + if (pair->markedForRemove) + { + disposePair(table, pair); + *prevPtr = nextPair; + } + else + { + prevPtr = &pair->next; + } + pair = nextPair; + } + } + table->pendingRemoves = 0; + } + +out: + if (table->synchronized) + LeaveCriticalSection(&table->lock); + return ret; +} + +/** + * Determines whether the HashTable contains a specific key. + */ + +BOOL HashTable_Contains(wHashTable* table, const void* key) +{ + BOOL status = 0; + wKeyValuePair* pair = NULL; + + WINPR_ASSERT(table); + if (!key) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + pair = HashTable_Get(table, key); + status = (pair && !pair->markedForRemove); + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return status; +} + +/** + * Determines whether the HashTable contains a specific key. + */ + +BOOL HashTable_ContainsKey(wHashTable* table, const void* key) +{ + BOOL status = 0; + wKeyValuePair* pair = NULL; + + WINPR_ASSERT(table); + if (!key) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + pair = HashTable_Get(table, key); + status = (pair && !pair->markedForRemove); + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return status; +} + +/** + * Determines whether the HashTable contains a specific value. + */ + +BOOL HashTable_ContainsValue(wHashTable* table, const void* value) +{ + BOOL status = FALSE; + + WINPR_ASSERT(table); + if (!value) + return FALSE; + + if (table->synchronized) + EnterCriticalSection(&table->lock); + + for (size_t index = 0; index < table->numOfBuckets; index++) + { + wKeyValuePair* pair = table->bucketArray[index]; + + while (pair) + { + if (!pair->markedForRemove && HashTable_Equals(table, pair, value)) + { + status = TRUE; + break; + } + + pair = pair->next; + } + + if (status) + break; + } + + if (table->synchronized) + LeaveCriticalSection(&table->lock); + + return status; +} + +/** + * Construction, Destruction + */ + +wHashTable* HashTable_New(BOOL synchronized) +{ + wHashTable* table = (wHashTable*)calloc(1, sizeof(wHashTable)); + + if (!table) + goto fail; + + table->synchronized = synchronized; + InitializeCriticalSectionAndSpinCount(&(table->lock), 4000); + table->numOfBuckets = 64; + table->numOfElements = 0; + table->bucketArray = (wKeyValuePair**)calloc(table->numOfBuckets, sizeof(wKeyValuePair*)); + + if (!table->bucketArray) + goto fail; + + table->idealRatio = 3.0f; + table->lowerRehashThreshold = 0.0f; + table->upperRehashThreshold = 15.0f; + table->hash = HashTable_PointerHash; + table->key.fnObjectEquals = HashTable_PointerCompare; + table->value.fnObjectEquals = HashTable_PointerCompare; + + return table; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + HashTable_Free(table); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void HashTable_Free(wHashTable* table) +{ + wKeyValuePair* pair = NULL; + wKeyValuePair* nextPair = NULL; + + if (!table) + return; + + if (table->bucketArray) + { + for (size_t index = 0; index < table->numOfBuckets; index++) + { + pair = table->bucketArray[index]; + + while (pair) + { + nextPair = pair->next; + + disposePair(table, pair); + pair = nextPair; + } + } + free((void*)table->bucketArray); + } + DeleteCriticalSection(&(table->lock)); + + free(table); +} + +void HashTable_Lock(wHashTable* table) +{ + WINPR_ASSERT(table); + EnterCriticalSection(&table->lock); +} + +void HashTable_Unlock(wHashTable* table) +{ + WINPR_ASSERT(table); + LeaveCriticalSection(&table->lock); +} + +wObject* HashTable_KeyObject(wHashTable* table) +{ + WINPR_ASSERT(table); + return &table->key; +} + +wObject* HashTable_ValueObject(wHashTable* table) +{ + WINPR_ASSERT(table); + return &table->value; +} + +BOOL HashTable_SetHashFunction(wHashTable* table, HASH_TABLE_HASH_FN fn) +{ + WINPR_ASSERT(table); + table->hash = fn; + return fn != NULL; +} + +BOOL HashTable_SetupForStringData(wHashTable* table, BOOL stringValues) +{ + wObject* obj = NULL; + + if (!HashTable_SetHashFunction(table, HashTable_StringHash)) + return FALSE; + + obj = HashTable_KeyObject(table); + obj->fnObjectEquals = HashTable_StringCompare; + obj->fnObjectNew = HashTable_StringClone; + obj->fnObjectFree = HashTable_StringFree; + + if (stringValues) + { + obj = HashTable_ValueObject(table); + obj->fnObjectEquals = HashTable_StringCompare; + obj->fnObjectNew = HashTable_StringClone; + obj->fnObjectFree = HashTable_StringFree; + } + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/LinkedList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/LinkedList.c new file mode 100644 index 0000000000000000000000000000000000000000..48d64d94e700bf7f27a01ca9157e00bd11bc07ac --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/LinkedList.c @@ -0,0 +1,385 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.Generic.LinkedList + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include +#include + +typedef struct s_wLinkedListItem wLinkedListNode; + +struct s_wLinkedListItem +{ + void* value; + wLinkedListNode* prev; + wLinkedListNode* next; +}; + +struct s_wLinkedList +{ + size_t count; + int initial; + wLinkedListNode* head; + wLinkedListNode* tail; + wLinkedListNode* current; + wObject object; +}; + +/** + * C equivalent of the C# LinkedList Class: + * http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx + * + * Internal implementation uses a doubly-linked list + */ + +/** + * Properties + */ + +/** + * Gets the number of nodes actually contained in the LinkedList. + */ + +size_t LinkedList_Count(wLinkedList* list) +{ + WINPR_ASSERT(list); + return list->count; +} + +/** + * Gets the first node of the LinkedList. + */ + +void* LinkedList_First(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->head) + return list->head->value; + else + return NULL; +} + +/** + * Gets the last node of the LinkedList. + */ + +void* LinkedList_Last(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->tail) + return list->tail->value; + else + return NULL; +} + +/** + * Methods + */ + +/** + * Determines whether the LinkedList contains a specific value. + */ + +BOOL LinkedList_Contains(wLinkedList* list, const void* value) +{ + wLinkedListNode* item = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + + WINPR_ASSERT(list); + if (!list->head) + return FALSE; + + item = list->head; + keyEquals = list->object.fnObjectEquals; + + while (item) + { + if (keyEquals(item->value, value)) + break; + + item = item->next; + } + + return (item) ? TRUE : FALSE; +} + +static wLinkedListNode* LinkedList_FreeNode(wLinkedList* list, wLinkedListNode* node) +{ + wLinkedListNode* next = NULL; + wLinkedListNode* prev = NULL; + + WINPR_ASSERT(list); + WINPR_ASSERT(node); + + next = node->next; + prev = node->prev; + if (prev) + prev->next = next; + + if (next) + next->prev = prev; + + if (node == list->head) + list->head = node->next; + + if (node == list->tail) + list->tail = node->prev; + + if (list->object.fnObjectUninit) + list->object.fnObjectUninit(node); + + if (list->object.fnObjectFree) + list->object.fnObjectFree(node); + + free(node); + list->count--; + return next; +} + +/** + * Removes all entries from the LinkedList. + */ + +void LinkedList_Clear(wLinkedList* list) +{ + wLinkedListNode* node = NULL; + WINPR_ASSERT(list); + if (!list->head) + return; + + node = list->head; + + while (node) + node = LinkedList_FreeNode(list, node); + + list->head = list->tail = NULL; + list->count = 0; +} + +static wLinkedListNode* LinkedList_Create(wLinkedList* list, const void* value) +{ + wLinkedListNode* node = NULL; + + WINPR_ASSERT(list); + node = (wLinkedListNode*)calloc(1, sizeof(wLinkedListNode)); + + if (!node) + return NULL; + + if (list->object.fnObjectNew) + node->value = list->object.fnObjectNew(value); + else + { + union + { + const void* cpv; + void* pv; + } cnv; + cnv.cpv = value; + node->value = cnv.pv; + } + + if (list->object.fnObjectInit) + list->object.fnObjectInit(node); + + return node; +} +/** + * Adds a new node containing the specified value at the start of the LinkedList. + */ + +BOOL LinkedList_AddFirst(wLinkedList* list, const void* value) +{ + wLinkedListNode* node = LinkedList_Create(list, value); + + if (!node) + return FALSE; + + if (!list->head) + { + list->tail = list->head = node; + } + else + { + list->head->prev = node; + node->next = list->head; + list->head = node; + } + + list->count++; + return TRUE; +} + +/** + * Adds a new node containing the specified value at the end of the LinkedList. + */ + +BOOL LinkedList_AddLast(wLinkedList* list, const void* value) +{ + wLinkedListNode* node = LinkedList_Create(list, value); + + if (!node) + return FALSE; + + if (!list->tail) + { + list->head = list->tail = node; + } + else + { + list->tail->next = node; + node->prev = list->tail; + list->tail = node; + } + + list->count++; + return TRUE; +} + +/** + * Removes the first occurrence of the specified value from the LinkedList. + */ + +BOOL LinkedList_Remove(wLinkedList* list, const void* value) +{ + wLinkedListNode* node = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + WINPR_ASSERT(list); + + keyEquals = list->object.fnObjectEquals; + node = list->head; + + while (node) + { + if (keyEquals(node->value, value)) + { + LinkedList_FreeNode(list, node); + return TRUE; + } + + node = node->next; + } + + return FALSE; +} + +/** + * Removes the node at the start of the LinkedList. + */ + +void LinkedList_RemoveFirst(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->head) + LinkedList_FreeNode(list, list->head); +} + +/** + * Removes the node at the end of the LinkedList. + */ + +void LinkedList_RemoveLast(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->tail) + LinkedList_FreeNode(list, list->tail); +} + +/** + * Sets the enumerator to its initial position, which is before the first element in the collection. + */ + +void LinkedList_Enumerator_Reset(wLinkedList* list) +{ + WINPR_ASSERT(list); + list->initial = 1; + list->current = list->head; +} + +/* + * Gets the element at the current position of the enumerator. + */ + +void* LinkedList_Enumerator_Current(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->initial) + return NULL; + + if (list->current) + return list->current->value; + else + return NULL; +} + +/* + * Advances the enumerator to the next element of the LinkedList. + */ + +BOOL LinkedList_Enumerator_MoveNext(wLinkedList* list) +{ + WINPR_ASSERT(list); + if (list->initial) + list->initial = 0; + else if (list->current) + list->current = list->current->next; + + if (!list->current) + return FALSE; + + return TRUE; +} + +static BOOL default_equal_function(const void* objA, const void* objB) +{ + return objA == objB; +} + +/** + * Construction, Destruction + */ + +wLinkedList* LinkedList_New(void) +{ + wLinkedList* list = NULL; + list = (wLinkedList*)calloc(1, sizeof(wLinkedList)); + + if (list) + { + list->object.fnObjectEquals = default_equal_function; + } + + return list; +} + +void LinkedList_Free(wLinkedList* list) +{ + if (list) + { + LinkedList_Clear(list); + free(list); + } +} + +wObject* LinkedList_Object(wLinkedList* list) +{ + WINPR_ASSERT(list); + + return &list->object; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ListDictionary.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ListDictionary.c new file mode 100644 index 0000000000000000000000000000000000000000..4e69a86786841b271b8768452061ab36889d8081 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ListDictionary.c @@ -0,0 +1,562 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.Specialized.ListDictionary + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include + +typedef struct s_wListDictionaryItem wListDictionaryItem; + +struct s_wListDictionaryItem +{ + void* key; + void* value; + + wListDictionaryItem* next; +}; + +struct s_wListDictionary +{ + BOOL synchronized; + CRITICAL_SECTION lock; + + wListDictionaryItem* head; + wObject objectKey; + wObject objectValue; +}; + +/** + * C equivalent of the C# ListDictionary Class: + * http://msdn.microsoft.com/en-us/library/system.collections.specialized.listdictionary.aspx + * + * Internal implementation uses a singly-linked list + */ + +WINPR_API wObject* ListDictionary_KeyObject(wListDictionary* listDictionary) +{ + WINPR_ASSERT(listDictionary); + return &listDictionary->objectKey; +} + +WINPR_API wObject* ListDictionary_ValueObject(wListDictionary* listDictionary) +{ + WINPR_ASSERT(listDictionary); + return &listDictionary->objectValue; +} + +/** + * Properties + */ + +/** + * Gets the number of key/value pairs contained in the ListDictionary. + */ + +size_t ListDictionary_Count(wListDictionary* listDictionary) +{ + size_t count = 0; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + if (listDictionary->head) + { + wListDictionaryItem* item = listDictionary->head; + + while (item) + { + count++; + item = item->next; + } + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return count; +} + +/** + * Lock access to the ListDictionary + */ + +void ListDictionary_Lock(wListDictionary* listDictionary) +{ + WINPR_ASSERT(listDictionary); + + EnterCriticalSection(&listDictionary->lock); +} + +/** + * Unlock access to the ListDictionary + */ + +void ListDictionary_Unlock(wListDictionary* listDictionary) +{ + WINPR_ASSERT(listDictionary); + + LeaveCriticalSection(&listDictionary->lock); +} + +/** + * Methods + */ + +/** + * Gets the list of keys as an array + */ + +size_t ListDictionary_GetKeys(wListDictionary* listDictionary, ULONG_PTR** ppKeys) +{ + ULONG_PTR* pKeys = NULL; + + WINPR_ASSERT(listDictionary); + if (!ppKeys) + return 0; + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + size_t count = 0; + + if (listDictionary->head) + { + wListDictionaryItem* item = listDictionary->head; + + while (item) + { + count++; + item = item->next; + } + } + + if (count > 0) + { + pKeys = (ULONG_PTR*)calloc(count, sizeof(ULONG_PTR)); + + if (!pKeys) + { + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return 0; + } + } + + size_t index = 0; + + if (listDictionary->head) + { + wListDictionaryItem* item = listDictionary->head; + + while (item) + { + pKeys[index++] = (ULONG_PTR)item->key; + item = item->next; + } + } + + *ppKeys = pKeys; + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return count; +} + +static void item_free(wListDictionary* listDictionary, wListDictionaryItem* item) +{ + WINPR_ASSERT(listDictionary); + + if (item) + { + if (listDictionary->objectKey.fnObjectFree) + listDictionary->objectKey.fnObjectFree(item->key); + if (listDictionary->objectValue.fnObjectFree) + listDictionary->objectValue.fnObjectFree(item->value); + } + free(item); +} + +static void item_set(wListDictionary* listDictionary, wListDictionaryItem* item, const void* value) +{ + WINPR_ASSERT(listDictionary); + WINPR_ASSERT(item); + + if (listDictionary->objectValue.fnObjectFree) + listDictionary->objectValue.fnObjectFree(item->value); + + if (listDictionary->objectValue.fnObjectNew) + item->value = listDictionary->objectValue.fnObjectNew(value); + else + item->value = (void*)(uintptr_t)value; +} + +static wListDictionaryItem* new_item(wListDictionary* listDictionary, const void* key, + const void* value) +{ + wListDictionaryItem* item = (wListDictionaryItem*)calloc(1, sizeof(wListDictionaryItem)); + if (!item) + return NULL; + + if (listDictionary->objectKey.fnObjectNew) + item->key = listDictionary->objectKey.fnObjectNew(key); + else + item->key = (void*)(uintptr_t)key; + if (!item->key) + goto fail; + + item_set(listDictionary, item, value); + if (value && !item->value) + goto fail; + + return item; + +fail: + item_free(listDictionary, item); + return NULL; +} + +/** + * Adds an entry with the specified key and value into the ListDictionary. + */ + +BOOL ListDictionary_Add(wListDictionary* listDictionary, const void* key, const void* value) +{ + BOOL ret = FALSE; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + wListDictionaryItem* item = new_item(listDictionary, key, value); + + if (!item) + goto out_error; + + if (!listDictionary->head) + { + listDictionary->head = item; + } + else + { + wListDictionaryItem* lastItem = listDictionary->head; + + while (lastItem->next) + lastItem = lastItem->next; + + lastItem->next = item; + } + + ret = TRUE; +out_error: + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return ret; +} + +/** + * Removes all entries from the ListDictionary. + */ + +void ListDictionary_Clear(wListDictionary* listDictionary) +{ + wListDictionaryItem* item = NULL; + wListDictionaryItem* nextItem = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + if (listDictionary->head) + { + item = listDictionary->head; + + while (item) + { + nextItem = item->next; + + item_free(listDictionary, item); + item = nextItem; + } + + listDictionary->head = NULL; + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); +} + +/** + * Determines whether the ListDictionary contains a specific key. + */ + +BOOL ListDictionary_Contains(wListDictionary* listDictionary, const void* key) +{ + wListDictionaryItem* item = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&(listDictionary->lock)); + + keyEquals = listDictionary->objectKey.fnObjectEquals; + item = listDictionary->head; + + while (item) + { + if (keyEquals(item->key, key)) + break; + + item = item->next; + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&(listDictionary->lock)); + + return (item) ? TRUE : FALSE; +} + +/** + * Removes the entry with the specified key from the ListDictionary. + */ + +static void* ListDictionary_RemoveOrTake(wListDictionary* listDictionary, const void* key, + BOOL take) +{ + void* value = NULL; + wListDictionaryItem* item = NULL; + wListDictionaryItem* prevItem = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + keyEquals = listDictionary->objectKey.fnObjectEquals; + item = listDictionary->head; + prevItem = NULL; + + while (item) + { + if (keyEquals(item->key, key)) + { + if (!prevItem) + listDictionary->head = item->next; + else + prevItem->next = item->next; + + if (take) + { + value = item->value; + item->value = NULL; + } + item_free(listDictionary, item); + break; + } + + prevItem = item; + item = item->next; + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return value; +} + +void ListDictionary_Remove(wListDictionary* listDictionary, const void* key) +{ + ListDictionary_RemoveOrTake(listDictionary, key, FALSE); +} + +void* ListDictionary_Take(wListDictionary* listDictionary, const void* key) +{ + return ListDictionary_RemoveOrTake(listDictionary, key, TRUE); +} + +/** + * Removes the first (head) entry from the list + */ + +static void* ListDictionary_Remove_Or_Take_Head(wListDictionary* listDictionary, BOOL take) +{ + wListDictionaryItem* item = NULL; + void* value = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + if (listDictionary->head) + { + item = listDictionary->head; + listDictionary->head = listDictionary->head->next; + if (take) + { + value = item->value; + item->value = NULL; + } + item_free(listDictionary, item); + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return value; +} + +void ListDictionary_Remove_Head(wListDictionary* listDictionary) +{ + ListDictionary_Remove_Or_Take_Head(listDictionary, FALSE); +} + +void* ListDictionary_Take_Head(wListDictionary* listDictionary) +{ + return ListDictionary_Remove_Or_Take_Head(listDictionary, TRUE); +} + +/** + * Get an item value using key + */ + +void* ListDictionary_GetItemValue(wListDictionary* listDictionary, const void* key) +{ + void* value = NULL; + wListDictionaryItem* item = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + keyEquals = listDictionary->objectKey.fnObjectEquals; + + if (listDictionary->head) + { + item = listDictionary->head; + + while (item) + { + if (keyEquals(item->key, key)) + break; + + item = item->next; + } + } + + value = (item) ? item->value : NULL; + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return value; +} + +/** + * Set an item value using key + */ + +BOOL ListDictionary_SetItemValue(wListDictionary* listDictionary, const void* key, + const void* value) +{ + BOOL status = FALSE; + wListDictionaryItem* item = NULL; + OBJECT_EQUALS_FN keyEquals = NULL; + + WINPR_ASSERT(listDictionary); + + if (listDictionary->synchronized) + EnterCriticalSection(&listDictionary->lock); + + keyEquals = listDictionary->objectKey.fnObjectEquals; + + if (listDictionary->head) + { + item = listDictionary->head; + + while (item) + { + if (keyEquals(item->key, key)) + break; + + item = item->next; + } + + if (item) + item_set(listDictionary, item, value); + + status = (item) ? TRUE : FALSE; + } + + if (listDictionary->synchronized) + LeaveCriticalSection(&listDictionary->lock); + + return status; +} + +static BOOL default_equal_function(const void* obj1, const void* obj2) +{ + return (obj1 == obj2); +} +/** + * Construction, Destruction + */ + +wListDictionary* ListDictionary_New(BOOL synchronized) +{ + wListDictionary* listDictionary = (wListDictionary*)calloc(1, sizeof(wListDictionary)); + + if (!listDictionary) + return NULL; + + listDictionary->synchronized = synchronized; + + if (!InitializeCriticalSectionAndSpinCount(&(listDictionary->lock), 4000)) + { + free(listDictionary); + return NULL; + } + + listDictionary->objectKey.fnObjectEquals = default_equal_function; + listDictionary->objectValue.fnObjectEquals = default_equal_function; + return listDictionary; +} + +void ListDictionary_Free(wListDictionary* listDictionary) +{ + if (listDictionary) + { + ListDictionary_Clear(listDictionary); + DeleteCriticalSection(&listDictionary->lock); + free(listDictionary); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessagePipe.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessagePipe.c new file mode 100644 index 0000000000000000000000000000000000000000..98adfe753735a287a0831415b8394c95f0d1cef5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessagePipe.c @@ -0,0 +1,80 @@ +/** + * WinPR: Windows Portable Runtime + * Message Pipe + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +/** + * Properties + */ + +/** + * Methods + */ + +void MessagePipe_PostQuit(wMessagePipe* pipe, int nExitCode) +{ + MessageQueue_PostQuit(pipe->In, nExitCode); + MessageQueue_PostQuit(pipe->Out, nExitCode); +} + +/** + * Construction, Destruction + */ + +wMessagePipe* MessagePipe_New(void) +{ + wMessagePipe* pipe = NULL; + + pipe = (wMessagePipe*)malloc(sizeof(wMessagePipe)); + + if (!pipe) + return NULL; + + pipe->In = MessageQueue_New(NULL); + if (!pipe->In) + goto error_in; + + pipe->Out = MessageQueue_New(NULL); + if (!pipe->Out) + goto error_out; + + return pipe; + +error_out: + MessageQueue_Free(pipe->In); +error_in: + free(pipe); + return NULL; +} + +void MessagePipe_Free(wMessagePipe* pipe) +{ + if (pipe) + { + MessageQueue_Free(pipe->In); + MessageQueue_Free(pipe->Out); + + free(pipe); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessageQueue.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessageQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..361685b41faedd26c33ae4598efa0be4b6feb959 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/MessageQueue.c @@ -0,0 +1,316 @@ +/** + * WinPR: Windows Portable Runtime + * Message Queue + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include + +struct s_wMessageQueue +{ + size_t head; + size_t tail; + size_t size; + size_t capacity; + BOOL closed; + wMessage* array; + CRITICAL_SECTION lock; + HANDLE event; + + wObject object; +}; + +/** + * Message Queue inspired from Windows: + * http://msdn.microsoft.com/en-us/library/ms632590/ + */ + +/** + * Properties + */ + +wObject* MessageQueue_Object(wMessageQueue* queue) +{ + WINPR_ASSERT(queue); + return &queue->object; +} + +/** + * Gets an event which is set when the queue is non-empty + */ + +HANDLE MessageQueue_Event(wMessageQueue* queue) +{ + WINPR_ASSERT(queue); + return queue->event; +} + +/** + * Gets the queue size + */ + +size_t MessageQueue_Size(wMessageQueue* queue) +{ + WINPR_ASSERT(queue); + EnterCriticalSection(&queue->lock); + const size_t ret = queue->size; + LeaveCriticalSection(&queue->lock); + return ret; +} + +/** + * Methods + */ + +BOOL MessageQueue_Wait(wMessageQueue* queue) +{ + BOOL status = FALSE; + + WINPR_ASSERT(queue); + if (WaitForSingleObject(queue->event, INFINITE) == WAIT_OBJECT_0) + status = TRUE; + + return status; +} + +static BOOL MessageQueue_EnsureCapacity(wMessageQueue* queue, size_t count) +{ + WINPR_ASSERT(queue); + + if (queue->size + count >= queue->capacity) + { + wMessage* new_arr = NULL; + size_t old_capacity = queue->capacity; + size_t new_capacity = queue->capacity * 2; + + if (new_capacity < queue->size + count) + new_capacity = queue->size + count; + + new_arr = (wMessage*)realloc(queue->array, sizeof(wMessage) * new_capacity); + if (!new_arr) + return FALSE; + queue->array = new_arr; + queue->capacity = new_capacity; + ZeroMemory(&(queue->array[old_capacity]), (new_capacity - old_capacity) * sizeof(wMessage)); + + /* rearrange wrapped entries */ + if (queue->tail <= queue->head) + { + CopyMemory(&(queue->array[old_capacity]), queue->array, queue->tail * sizeof(wMessage)); + queue->tail += old_capacity; + } + } + + return TRUE; +} + +BOOL MessageQueue_Dispatch(wMessageQueue* queue, const wMessage* message) +{ + wMessage* dst = NULL; + BOOL ret = FALSE; + WINPR_ASSERT(queue); + + if (!message) + return FALSE; + + WINPR_ASSERT(queue); + EnterCriticalSection(&queue->lock); + + if (queue->closed) + goto out; + + if (!MessageQueue_EnsureCapacity(queue, 1)) + goto out; + + dst = &(queue->array[queue->tail]); + *dst = *message; + dst->time = GetTickCount64(); + + queue->tail = (queue->tail + 1) % queue->capacity; + queue->size++; + + if (queue->size > 0) + (void)SetEvent(queue->event); + + if (message->id == WMQ_QUIT) + queue->closed = TRUE; + + ret = TRUE; +out: + LeaveCriticalSection(&queue->lock); + return ret; +} + +BOOL MessageQueue_Post(wMessageQueue* queue, void* context, UINT32 type, void* wParam, void* lParam) +{ + wMessage message = { 0 }; + + message.context = context; + message.id = type; + message.wParam = wParam; + message.lParam = lParam; + message.Free = NULL; + + return MessageQueue_Dispatch(queue, &message); +} + +BOOL MessageQueue_PostQuit(wMessageQueue* queue, int nExitCode) +{ + return MessageQueue_Post(queue, NULL, WMQ_QUIT, (void*)(size_t)nExitCode, NULL); +} + +int MessageQueue_Get(wMessageQueue* queue, wMessage* message) +{ + int status = -1; + + if (!MessageQueue_Wait(queue)) + return status; + + EnterCriticalSection(&queue->lock); + + if (queue->size > 0) + { + CopyMemory(message, &(queue->array[queue->head]), sizeof(wMessage)); + ZeroMemory(&(queue->array[queue->head]), sizeof(wMessage)); + queue->head = (queue->head + 1) % queue->capacity; + queue->size--; + + if (queue->size < 1) + (void)ResetEvent(queue->event); + + status = (message->id != WMQ_QUIT) ? 1 : 0; + } + + LeaveCriticalSection(&queue->lock); + + return status; +} + +int MessageQueue_Peek(wMessageQueue* queue, wMessage* message, BOOL remove) +{ + int status = 0; + + WINPR_ASSERT(queue); + EnterCriticalSection(&queue->lock); + + if (queue->size > 0) + { + CopyMemory(message, &(queue->array[queue->head]), sizeof(wMessage)); + status = 1; + + if (remove) + { + ZeroMemory(&(queue->array[queue->head]), sizeof(wMessage)); + queue->head = (queue->head + 1) % queue->capacity; + queue->size--; + + if (queue->size < 1) + (void)ResetEvent(queue->event); + } + } + + LeaveCriticalSection(&queue->lock); + + return status; +} + +/** + * Construction, Destruction + */ + +wMessageQueue* MessageQueue_New(const wObject* callback) +{ + wMessageQueue* queue = NULL; + + queue = (wMessageQueue*)calloc(1, sizeof(wMessageQueue)); + if (!queue) + return NULL; + + if (!InitializeCriticalSectionAndSpinCount(&queue->lock, 4000)) + goto fail; + + if (!MessageQueue_EnsureCapacity(queue, 32)) + goto fail; + + queue->event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!queue->event) + goto fail; + + if (callback) + queue->object = *callback; + + return queue; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + MessageQueue_Free(queue); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void MessageQueue_Free(wMessageQueue* queue) +{ + if (!queue) + return; + + if (queue->event) + MessageQueue_Clear(queue); + + (void)CloseHandle(queue->event); + DeleteCriticalSection(&queue->lock); + + free(queue->array); + free(queue); +} + +int MessageQueue_Clear(wMessageQueue* queue) +{ + int status = 0; + + WINPR_ASSERT(queue); + WINPR_ASSERT(queue->event); + + EnterCriticalSection(&queue->lock); + + while (queue->size > 0) + { + wMessage* msg = &(queue->array[queue->head]); + + /* Free resources of message. */ + if (queue->object.fnObjectUninit) + queue->object.fnObjectUninit(msg); + if (queue->object.fnObjectFree) + queue->object.fnObjectFree(msg); + + ZeroMemory(msg, sizeof(wMessage)); + + queue->head = (queue->head + 1) % queue->capacity; + queue->size--; + } + (void)ResetEvent(queue->event); + queue->closed = FALSE; + + LeaveCriticalSection(&queue->lock); + + return status; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Object.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Object.c new file mode 100644 index 0000000000000000000000000000000000000000..8bee86c04e6a679ca72305dd52f2b4cc9f946734 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Object.c @@ -0,0 +1,42 @@ +/** + * WinPR: Windows Portable Runtime + * Collections + * + * Copyright 2024 Armin Novak + * 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 +#include + +void* winpr_ObjectStringClone(const void* pvstr) +{ + const char* str = pvstr; + if (!str) + return NULL; + return _strdup(str); +} + +void* winpr_ObjectWStringClone(const void* pvstr) +{ + const WCHAR* str = pvstr; + if (!str) + return NULL; + return _wcsdup(str); +} + +void winpr_ObjectStringFree(void* pvstr) +{ + free(pvstr); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ObjectPool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ObjectPool.c new file mode 100644 index 0000000000000000000000000000000000000000..98f962ae999a7cdaa792d59e3ae0c08100ffde36 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/ObjectPool.c @@ -0,0 +1,185 @@ +/** + * WinPR: Windows Portable Runtime + * Object Pool + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +struct s_wObjectPool +{ + size_t size; + size_t capacity; + void** array; + CRITICAL_SECTION lock; + wObject object; + BOOL synchronized; +}; + +/** + * C Object Pool similar to C# BufferManager Class: + * http://msdn.microsoft.com/en-us/library/ms405814.aspx + */ + +/** + * Methods + */ + +static void ObjectPool_Lock(wObjectPool* pool) +{ + WINPR_ASSERT(pool); + if (pool->synchronized) + EnterCriticalSection(&pool->lock); +} + +static void ObjectPool_Unlock(wObjectPool* pool) +{ + WINPR_ASSERT(pool); + if (pool->synchronized) + LeaveCriticalSection(&pool->lock); +} + +/** + * Gets an object from the pool. + */ + +void* ObjectPool_Take(wObjectPool* pool) +{ + void* obj = NULL; + + ObjectPool_Lock(pool); + + if (pool->size > 0) + obj = pool->array[--(pool->size)]; + + if (!obj) + { + if (pool->object.fnObjectNew) + obj = pool->object.fnObjectNew(NULL); + } + + if (pool->object.fnObjectInit) + pool->object.fnObjectInit(obj); + + ObjectPool_Unlock(pool); + + return obj; +} + +/** + * Returns an object to the pool. + */ + +void ObjectPool_Return(wObjectPool* pool, void* obj) +{ + ObjectPool_Lock(pool); + + if ((pool->size + 1) >= pool->capacity) + { + size_t new_cap = 0; + void** new_arr = NULL; + + new_cap = pool->capacity * 2; + new_arr = (void**)realloc((void*)pool->array, sizeof(void*) * new_cap); + if (!new_arr) + goto out; + + pool->array = new_arr; + pool->capacity = new_cap; + } + + pool->array[(pool->size)++] = obj; + + if (pool->object.fnObjectUninit) + pool->object.fnObjectUninit(obj); + +out: + ObjectPool_Unlock(pool); +} + +wObject* ObjectPool_Object(wObjectPool* pool) +{ + WINPR_ASSERT(pool); + return &pool->object; +} + +/** + * Releases the buffers currently cached in the pool. + */ + +void ObjectPool_Clear(wObjectPool* pool) +{ + ObjectPool_Lock(pool); + + while (pool->size > 0) + { + (pool->size)--; + + if (pool->object.fnObjectFree) + pool->object.fnObjectFree(pool->array[pool->size]); + } + + ObjectPool_Unlock(pool); +} + +/** + * Construction, Destruction + */ + +wObjectPool* ObjectPool_New(BOOL synchronized) +{ + wObjectPool* pool = NULL; + + pool = (wObjectPool*)calloc(1, sizeof(wObjectPool)); + + if (pool) + { + pool->capacity = 32; + pool->size = 0; + pool->array = (void**)calloc(pool->capacity, sizeof(void*)); + if (!pool->array) + { + free(pool); + return NULL; + } + pool->synchronized = synchronized; + + if (pool->synchronized) + InitializeCriticalSectionAndSpinCount(&pool->lock, 4000); + } + + return pool; +} + +void ObjectPool_Free(wObjectPool* pool) +{ + if (pool) + { + ObjectPool_Clear(pool); + + if (pool->synchronized) + DeleteCriticalSection(&pool->lock); + + free((void*)pool->array); + + free(pool); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/PubSub.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/PubSub.c new file mode 100644 index 0000000000000000000000000000000000000000..147135338adc17ba93add76ea111acbe353f0347 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/PubSub.c @@ -0,0 +1,267 @@ +/** + * WinPR: Windows Portable Runtime + * Publisher/Subscriber Pattern + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include + +#include + +/** + * Events (C# Programming Guide) + * http://msdn.microsoft.com/en-us/library/awbftdfh.aspx + */ + +struct s_wPubSub +{ + CRITICAL_SECTION lock; + BOOL synchronized; + + size_t size; + size_t count; + wEventType* events; +}; + +/** + * Properties + */ + +wEventType* PubSub_GetEventTypes(wPubSub* pubSub, size_t* count) +{ + WINPR_ASSERT(pubSub); + if (count) + *count = pubSub->count; + + return pubSub->events; +} + +/** + * Methods + */ + +void PubSub_Lock(wPubSub* pubSub) +{ + WINPR_ASSERT(pubSub); + if (pubSub->synchronized) + EnterCriticalSection(&pubSub->lock); +} + +void PubSub_Unlock(wPubSub* pubSub) +{ + WINPR_ASSERT(pubSub); + if (pubSub->synchronized) + LeaveCriticalSection(&pubSub->lock); +} + +wEventType* PubSub_FindEventType(wPubSub* pubSub, const char* EventName) +{ + wEventType* event = NULL; + + WINPR_ASSERT(pubSub); + WINPR_ASSERT(EventName); + for (size_t index = 0; index < pubSub->count; index++) + { + if (strcmp(pubSub->events[index].EventName, EventName) == 0) + { + event = &(pubSub->events[index]); + break; + } + } + + return event; +} + +void PubSub_AddEventTypes(wPubSub* pubSub, wEventType* events, size_t count) +{ + WINPR_ASSERT(pubSub); + WINPR_ASSERT(events || (count == 0)); + if (pubSub->synchronized) + PubSub_Lock(pubSub); + + while (pubSub->count + count >= pubSub->size) + { + size_t new_size = 0; + wEventType* new_event = NULL; + + new_size = pubSub->size * 2; + new_event = (wEventType*)realloc(pubSub->events, new_size * sizeof(wEventType)); + if (!new_event) + goto fail; + pubSub->size = new_size; + pubSub->events = new_event; + } + + CopyMemory(&pubSub->events[pubSub->count], events, count * sizeof(wEventType)); + pubSub->count += count; + +fail: + if (pubSub->synchronized) + PubSub_Unlock(pubSub); +} + +int PubSub_Subscribe(wPubSub* pubSub, const char* EventName, ...) +{ + wEventType* event = NULL; + int status = -1; + WINPR_ASSERT(pubSub); + + va_list ap = { 0 }; + va_start(ap, EventName); + pEventHandler EventHandler = va_arg(ap, pEventHandler); + + if (pubSub->synchronized) + PubSub_Lock(pubSub); + + event = PubSub_FindEventType(pubSub, EventName); + + if (event) + { + status = 0; + + if (event->EventHandlerCount < MAX_EVENT_HANDLERS) + event->EventHandlers[event->EventHandlerCount++] = EventHandler; + else + status = -1; + } + + if (pubSub->synchronized) + PubSub_Unlock(pubSub); + + va_end(ap); + return status; +} + +int PubSub_Unsubscribe(wPubSub* pubSub, const char* EventName, ...) +{ + wEventType* event = NULL; + int status = -1; + WINPR_ASSERT(pubSub); + WINPR_ASSERT(EventName); + + va_list ap = { 0 }; + va_start(ap, EventName); + pEventHandler EventHandler = va_arg(ap, pEventHandler); + + if (pubSub->synchronized) + PubSub_Lock(pubSub); + + event = PubSub_FindEventType(pubSub, EventName); + + if (event) + { + status = 0; + + for (size_t index = 0; index < event->EventHandlerCount; index++) + { + if (event->EventHandlers[index] == EventHandler) + { + event->EventHandlers[index] = NULL; + event->EventHandlerCount--; + MoveMemory((void*)&event->EventHandlers[index], + (void*)&event->EventHandlers[index + 1], + (MAX_EVENT_HANDLERS - index - 1) * sizeof(pEventHandler)); + status = 1; + } + } + } + + if (pubSub->synchronized) + PubSub_Unlock(pubSub); + + va_end(ap); + return status; +} + +int PubSub_OnEvent(wPubSub* pubSub, const char* EventName, void* context, const wEventArgs* e) +{ + wEventType* event = NULL; + int status = -1; + + if (!pubSub) + return -1; + WINPR_ASSERT(e); + + if (pubSub->synchronized) + PubSub_Lock(pubSub); + + event = PubSub_FindEventType(pubSub, EventName); + + if (pubSub->synchronized) + PubSub_Unlock(pubSub); + + if (event) + { + status = 0; + + for (size_t index = 0; index < event->EventHandlerCount; index++) + { + if (event->EventHandlers[index]) + { + event->EventHandlers[index](context, e); + status++; + } + } + } + + return status; +} + +/** + * Construction, Destruction + */ + +wPubSub* PubSub_New(BOOL synchronized) +{ + wPubSub* pubSub = (wPubSub*)calloc(1, sizeof(wPubSub)); + + if (!pubSub) + return NULL; + + pubSub->synchronized = synchronized; + + if (pubSub->synchronized && !InitializeCriticalSectionAndSpinCount(&pubSub->lock, 4000)) + goto fail; + + pubSub->count = 0; + pubSub->size = 64; + + pubSub->events = (wEventType*)calloc(pubSub->size, sizeof(wEventType)); + if (!pubSub->events) + goto fail; + + return pubSub; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + PubSub_Free(pubSub); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void PubSub_Free(wPubSub* pubSub) +{ + if (pubSub) + { + if (pubSub->synchronized) + DeleteCriticalSection(&pubSub->lock); + + free(pubSub->events); + free(pubSub); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Queue.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Queue.c new file mode 100644 index 0000000000000000000000000000000000000000..0193c4658cc37945401f27b3b0f15d67de0678b2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Queue.c @@ -0,0 +1,351 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.Queue + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +struct s_wQueue +{ + size_t capacity; + size_t growthFactor; + BOOL synchronized; + + BYTE padding[4]; + + size_t head; + size_t tail; + size_t size; + void** array; + CRITICAL_SECTION lock; + HANDLE event; + + wObject object; + BOOL haveLock; + + BYTE padding2[4]; +}; + +/** + * C equivalent of the C# Queue Class: + * http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx + */ + +/** + * Properties + */ + +/** + * Gets the number of elements contained in the Queue. + */ + +size_t Queue_Count(wQueue* queue) +{ + size_t ret = 0; + + Queue_Lock(queue); + + ret = queue->size; + + Queue_Unlock(queue); + + return ret; +} + +/** + * Lock access to the ArrayList + */ + +void Queue_Lock(wQueue* queue) +{ + WINPR_ASSERT(queue); + if (queue->synchronized) + EnterCriticalSection(&queue->lock); +} + +/** + * Unlock access to the ArrayList + */ + +void Queue_Unlock(wQueue* queue) +{ + WINPR_ASSERT(queue); + if (queue->synchronized) + LeaveCriticalSection(&queue->lock); +} + +/** + * Gets an event which is set when the queue is non-empty + */ + +HANDLE Queue_Event(wQueue* queue) +{ + WINPR_ASSERT(queue); + return queue->event; +} + +wObject* Queue_Object(wQueue* queue) +{ + WINPR_ASSERT(queue); + return &queue->object; +} + +/** + * Methods + */ + +/** + * Removes all objects from the Queue. + */ + +void Queue_Clear(wQueue* queue) +{ + Queue_Lock(queue); + + for (size_t index = queue->head; index != queue->tail; index = (index + 1) % queue->capacity) + { + if (queue->object.fnObjectFree) + queue->object.fnObjectFree(queue->array[index]); + + queue->array[index] = NULL; + } + + queue->size = 0; + queue->head = queue->tail = 0; + (void)ResetEvent(queue->event); + Queue_Unlock(queue); +} + +/** + * Determines whether an element is in the Queue. + */ + +BOOL Queue_Contains(wQueue* queue, const void* obj) +{ + BOOL found = FALSE; + + Queue_Lock(queue); + + for (size_t index = 0; index < queue->tail; index++) + { + if (queue->object.fnObjectEquals(queue->array[index], obj)) + { + found = TRUE; + break; + } + } + + Queue_Unlock(queue); + + return found; +} + +static BOOL Queue_EnsureCapacity(wQueue* queue, size_t count) +{ + WINPR_ASSERT(queue); + + if (queue->size + count >= queue->capacity) + { + const size_t old_capacity = queue->capacity; + size_t new_capacity = queue->capacity * queue->growthFactor; + void** newArray = NULL; + if (new_capacity < queue->size + count) + new_capacity = queue->size + count; + newArray = (void**)realloc((void*)queue->array, sizeof(void*) * new_capacity); + + if (!newArray) + return FALSE; + + queue->capacity = new_capacity; + queue->array = newArray; + ZeroMemory((void*)&(queue->array[old_capacity]), + (new_capacity - old_capacity) * sizeof(void*)); + + /* rearrange wrapped entries */ + if (queue->tail <= queue->head) + { + CopyMemory((void*)&(queue->array[old_capacity]), (void*)queue->array, + queue->tail * sizeof(void*)); + queue->tail += old_capacity; + } + } + return TRUE; +} + +/** + * Adds an object to the end of the Queue. + */ + +BOOL Queue_Enqueue(wQueue* queue, const void* obj) +{ + BOOL ret = TRUE; + + Queue_Lock(queue); + + if (!Queue_EnsureCapacity(queue, 1)) + goto out; + + if (queue->object.fnObjectNew) + queue->array[queue->tail] = queue->object.fnObjectNew(obj); + else + { + union + { + const void* cv; + void* v; + } cnv; + cnv.cv = obj; + queue->array[queue->tail] = cnv.v; + } + queue->tail = (queue->tail + 1) % queue->capacity; + + const BOOL signalSet = queue->size == 0; + queue->size++; + + if (signalSet) + (void)SetEvent(queue->event); +out: + + Queue_Unlock(queue); + + return ret; +} + +/** + * Removes and returns the object at the beginning of the Queue. + */ + +void* Queue_Dequeue(wQueue* queue) +{ + void* obj = NULL; + + Queue_Lock(queue); + + if (queue->size > 0) + { + obj = queue->array[queue->head]; + queue->array[queue->head] = NULL; + queue->head = (queue->head + 1) % queue->capacity; + queue->size--; + } + + if (queue->size < 1) + (void)ResetEvent(queue->event); + + Queue_Unlock(queue); + + return obj; +} + +/** + * Returns the object at the beginning of the Queue without removing it. + */ + +void* Queue_Peek(wQueue* queue) +{ + void* obj = NULL; + + Queue_Lock(queue); + + if (queue->size > 0) + obj = queue->array[queue->head]; + + Queue_Unlock(queue); + + return obj; +} + +void Queue_Discard(wQueue* queue) +{ + void* obj = NULL; + + Queue_Lock(queue); + obj = Queue_Dequeue(queue); + + if (queue->object.fnObjectFree) + queue->object.fnObjectFree(obj); + Queue_Unlock(queue); +} + +static BOOL default_queue_equals(const void* obj1, const void* obj2) +{ + return (obj1 == obj2); +} + +/** + * Construction, Destruction + */ + +wQueue* Queue_New(BOOL synchronized, SSIZE_T capacity, SSIZE_T growthFactor) +{ + wObject* obj = NULL; + wQueue* queue = NULL; + queue = (wQueue*)calloc(1, sizeof(wQueue)); + + if (!queue) + return NULL; + + queue->synchronized = synchronized; + + queue->growthFactor = 2; + if (growthFactor > 0) + queue->growthFactor = (size_t)growthFactor; + + if (capacity <= 0) + capacity = 32; + if (!InitializeCriticalSectionAndSpinCount(&queue->lock, 4000)) + goto fail; + queue->haveLock = TRUE; + if (!Queue_EnsureCapacity(queue, (size_t)capacity)) + goto fail; + + queue->event = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (!queue->event) + goto fail; + + obj = Queue_Object(queue); + obj->fnObjectEquals = default_queue_equals; + + return queue; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + Queue_Free(queue); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void Queue_Free(wQueue* queue) +{ + if (!queue) + return; + + if (queue->haveLock) + { + Queue_Clear(queue); + DeleteCriticalSection(&queue->lock); + } + (void)CloseHandle(queue->event); + free((void*)queue->array); + free(queue); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Stack.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Stack.c new file mode 100644 index 0000000000000000000000000000000000000000..13f6ba17326a2fccbda58f68769b2768c70eb39c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/Stack.c @@ -0,0 +1,252 @@ +/** + * WinPR: Windows Portable Runtime + * System.Collections.Stack + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +struct s_wStack +{ + size_t size; + size_t capacity; + void** array; + CRITICAL_SECTION lock; + BOOL synchronized; + wObject object; +}; + +/** + * C equivalent of the C# Stack Class: + * http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx + */ + +/** + * Properties + */ + +/** + * Gets the number of elements contained in the Stack. + */ + +size_t Stack_Count(wStack* stack) +{ + size_t ret = 0; + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + ret = stack->size; + + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); + + return ret; +} + +/** + * Gets a value indicating whether access to the Stack is synchronized (thread safe). + */ + +BOOL Stack_IsSynchronized(wStack* stack) +{ + WINPR_ASSERT(stack); + return stack->synchronized; +} + +wObject* Stack_Object(wStack* stack) +{ + WINPR_ASSERT(stack); + return &stack->object; +} + +/** + * Methods + */ + +/** + * Removes all objects from the Stack. + */ + +void Stack_Clear(wStack* stack) +{ + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + for (size_t index = 0; index < stack->size; index++) + { + if (stack->object.fnObjectFree) + stack->object.fnObjectFree(stack->array[index]); + + stack->array[index] = NULL; + } + + stack->size = 0; + + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); +} + +/** + * Determines whether an element is in the Stack. + */ + +BOOL Stack_Contains(wStack* stack, const void* obj) +{ + BOOL found = FALSE; + + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + for (size_t i = 0; i < stack->size; i++) + { + if (stack->object.fnObjectEquals(stack->array[i], obj)) + { + found = TRUE; + break; + } + } + + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); + + return found; +} + +/** + * Inserts an object at the top of the Stack. + */ + +void Stack_Push(wStack* stack, void* obj) +{ + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + if ((stack->size + 1) >= stack->capacity) + { + const size_t new_cap = stack->capacity * 2; + void** new_arr = (void**)realloc((void*)stack->array, sizeof(void*) * new_cap); + + if (!new_arr) + goto end; + + stack->array = new_arr; + stack->capacity = new_cap; + } + + stack->array[(stack->size)++] = obj; + +end: + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); +} + +/** + * Removes and returns the object at the top of the Stack. + */ + +void* Stack_Pop(wStack* stack) +{ + void* obj = NULL; + + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + if (stack->size > 0) + obj = stack->array[--(stack->size)]; + + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); + + return obj; +} + +/** + * Returns the object at the top of the Stack without removing it. + */ + +void* Stack_Peek(wStack* stack) +{ + void* obj = NULL; + + WINPR_ASSERT(stack); + if (stack->synchronized) + EnterCriticalSection(&stack->lock); + + if (stack->size > 0) + obj = stack->array[stack->size - 1]; + + if (stack->synchronized) + LeaveCriticalSection(&stack->lock); + + return obj; +} + +static BOOL default_stack_equals(const void* obj1, const void* obj2) +{ + return (obj1 == obj2); +} + +/** + * Construction, Destruction + */ + +wStack* Stack_New(BOOL synchronized) +{ + wStack* stack = NULL; + stack = (wStack*)calloc(1, sizeof(wStack)); + + if (!stack) + return NULL; + + stack->object.fnObjectEquals = default_stack_equals; + stack->synchronized = synchronized; + stack->capacity = 32; + stack->array = (void**)calloc(stack->capacity, sizeof(void*)); + + if (!stack->array) + goto out_free; + + if (stack->synchronized && !InitializeCriticalSectionAndSpinCount(&stack->lock, 4000)) + goto out_free; + + return stack; +out_free: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + Stack_Free(stack); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void Stack_Free(wStack* stack) +{ + if (stack) + { + if (stack->synchronized) + DeleteCriticalSection(&stack->lock); + + free((void*)stack->array); + free(stack); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/StreamPool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/StreamPool.c new file mode 100644 index 0000000000000000000000000000000000000000..b550c9bad87f38f927c6256dfd50fda44c5f003b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/collections/StreamPool.c @@ -0,0 +1,528 @@ +/** + * WinPR: Windows Portable Runtime + * Object Pool + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include + +#include "../stream.h" +#include "../log.h" +#define TAG WINPR_TAG("utils.streampool") + +struct s_StreamPoolEntry +{ +#if defined(WITH_STREAMPOOL_DEBUG) + char** msg; + size_t lines; +#endif + wStream* s; +}; + +struct s_wStreamPool +{ + size_t aSize; + size_t aCapacity; + struct s_StreamPoolEntry* aArray; + + size_t uSize; + size_t uCapacity; + struct s_StreamPoolEntry* uArray; + + CRITICAL_SECTION lock; + BOOL synchronized; + size_t defaultSize; +}; + +static void discard_entry(struct s_StreamPoolEntry* entry, BOOL discardStream) +{ + if (!entry) + return; + +#if defined(WITH_STREAMPOOL_DEBUG) + free((void*)entry->msg); +#endif + + if (discardStream && entry->s) + Stream_Free(entry->s, entry->s->isAllocatedStream); + + const struct s_StreamPoolEntry empty = { 0 }; + *entry = empty; +} + +static struct s_StreamPoolEntry add_entry(wStream* s) +{ + struct s_StreamPoolEntry entry = { 0 }; + +#if defined(WITH_STREAMPOOL_DEBUG) + void* stack = winpr_backtrace(20); + if (stack) + entry.msg = winpr_backtrace_symbols(stack, &entry.lines); + winpr_backtrace_free(stack); +#endif + + entry.s = s; + return entry; +} + +/** + * Lock the stream pool + */ + +static INLINE void StreamPool_Lock(wStreamPool* pool) +{ + WINPR_ASSERT(pool); + if (pool->synchronized) + EnterCriticalSection(&pool->lock); +} + +/** + * Unlock the stream pool + */ + +static INLINE void StreamPool_Unlock(wStreamPool* pool) +{ + WINPR_ASSERT(pool); + if (pool->synchronized) + LeaveCriticalSection(&pool->lock); +} + +static BOOL StreamPool_EnsureCapacity(wStreamPool* pool, size_t count, BOOL usedOrAvailable) +{ + WINPR_ASSERT(pool); + + size_t* cap = (usedOrAvailable) ? &pool->uCapacity : &pool->aCapacity; + size_t* size = (usedOrAvailable) ? &pool->uSize : &pool->aSize; + struct s_StreamPoolEntry** array = (usedOrAvailable) ? &pool->uArray : &pool->aArray; + + size_t new_cap = 0; + if (*cap == 0) + new_cap = *size + count; + else if (*size + count > *cap) + new_cap = (*size + count + 2) / 2 * 3; + else if ((*size + count) < *cap / 3) + new_cap = *cap / 2; + + if (new_cap > 0) + { + struct s_StreamPoolEntry* new_arr = NULL; + + if (*cap < *size + count) + *cap += count; + + new_arr = + (struct s_StreamPoolEntry*)realloc(*array, sizeof(struct s_StreamPoolEntry) * new_cap); + if (!new_arr) + return FALSE; + *cap = new_cap; + *array = new_arr; + } + return TRUE; +} + +/** + * Methods + */ + +static void StreamPool_ShiftUsed(wStreamPool* pool, size_t index) +{ + WINPR_ASSERT(pool); + + const size_t pcount = 1; + const size_t off = index + pcount; + if (pool->uSize >= off) + { + for (size_t x = 0; x < pcount; x++) + { + struct s_StreamPoolEntry* cur = &pool->uArray[index + x]; + discard_entry(cur, FALSE); + } + MoveMemory(&pool->uArray[index], &pool->uArray[index + pcount], + (pool->uSize - index - pcount) * sizeof(struct s_StreamPoolEntry)); + pool->uSize -= pcount; + } +} + +/** + * Adds a used stream to the pool. + */ + +static void StreamPool_AddUsed(wStreamPool* pool, wStream* s) +{ + StreamPool_EnsureCapacity(pool, 1, TRUE); + pool->uArray[pool->uSize] = add_entry(s); + pool->uSize++; +} + +/** + * Removes a used stream from the pool. + */ + +static void StreamPool_RemoveUsed(wStreamPool* pool, wStream* s) +{ + WINPR_ASSERT(pool); + for (size_t index = 0; index < pool->uSize; index++) + { + struct s_StreamPoolEntry* cur = &pool->uArray[index]; + if (cur->s == s) + { + StreamPool_ShiftUsed(pool, index); + break; + } + } +} + +static void StreamPool_ShiftAvailable(wStreamPool* pool, size_t index) +{ + WINPR_ASSERT(pool); + + const size_t pcount = 1; + const size_t off = index + pcount; + if (pool->aSize >= off) + { + for (size_t x = 0; x < pcount; x++) + { + struct s_StreamPoolEntry* cur = &pool->aArray[index + x]; + discard_entry(cur, FALSE); + } + + MoveMemory(&pool->aArray[index], &pool->aArray[index + pcount], + (pool->aSize - index - pcount) * sizeof(struct s_StreamPoolEntry)); + pool->aSize -= pcount; + } +} + +/** + * Gets a stream from the pool. + */ + +wStream* StreamPool_Take(wStreamPool* pool, size_t size) +{ + BOOL found = FALSE; + size_t foundIndex = 0; + wStream* s = NULL; + + StreamPool_Lock(pool); + + if (size == 0) + size = pool->defaultSize; + + for (size_t index = 0; index < pool->aSize; index++) + { + struct s_StreamPoolEntry* cur = &pool->aArray[index]; + s = cur->s; + + if (Stream_Capacity(s) >= size) + { + found = TRUE; + foundIndex = index; + break; + } + } + + if (!found) + { + s = Stream_New(NULL, size); + if (!s) + goto out_fail; + } + else if (s) + { + Stream_SetPosition(s, 0); + Stream_SetLength(s, Stream_Capacity(s)); + StreamPool_ShiftAvailable(pool, foundIndex); + } + + if (s) + { + s->pool = pool; + s->count = 1; + StreamPool_AddUsed(pool, s); + } + +out_fail: + StreamPool_Unlock(pool); + + return s; +} + +/** + * Returns an object to the pool. + */ + +static void StreamPool_Remove(wStreamPool* pool, wStream* s) +{ + StreamPool_EnsureCapacity(pool, 1, FALSE); + Stream_EnsureValidity(s); + for (size_t x = 0; x < pool->aSize; x++) + { + wStream* cs = pool->aArray[x].s; + if (cs == s) + return; + } + pool->aArray[(pool->aSize)++] = add_entry(s); + StreamPool_RemoveUsed(pool, s); +} + +static void StreamPool_ReleaseOrReturn(wStreamPool* pool, wStream* s) +{ + StreamPool_Lock(pool); + if (s->count > 0) + s->count--; + if (s->count == 0) + StreamPool_Remove(pool, s); + StreamPool_Unlock(pool); +} + +void StreamPool_Return(wStreamPool* pool, wStream* s) +{ + WINPR_ASSERT(pool); + if (!s) + return; + + StreamPool_Lock(pool); + StreamPool_Remove(pool, s); + StreamPool_Unlock(pool); +} + +/** + * Increment stream reference count + */ + +void Stream_AddRef(wStream* s) +{ + WINPR_ASSERT(s); + if (s->pool) + { + StreamPool_Lock(s->pool); + s->count++; + StreamPool_Unlock(s->pool); + } +} + +/** + * Decrement stream reference count + */ + +void Stream_Release(wStream* s) +{ + WINPR_ASSERT(s); + if (s->pool) + StreamPool_ReleaseOrReturn(s->pool, s); +} + +/** + * Find stream in pool using pointer inside buffer + */ + +wStream* StreamPool_Find(wStreamPool* pool, const BYTE* ptr) +{ + wStream* s = NULL; + + StreamPool_Lock(pool); + + for (size_t index = 0; index < pool->uSize; index++) + { + struct s_StreamPoolEntry* cur = &pool->uArray[index]; + + if ((ptr >= Stream_Buffer(cur->s)) && + (ptr < (Stream_Buffer(cur->s) + Stream_Capacity(cur->s)))) + { + s = cur->s; + break; + } + } + + StreamPool_Unlock(pool); + + return s; +} + +/** + * Releases the streams currently cached in the pool. + */ + +void StreamPool_Clear(wStreamPool* pool) +{ + StreamPool_Lock(pool); + + for (size_t x = 0; x < pool->aSize; x++) + { + struct s_StreamPoolEntry* cur = &pool->aArray[x]; + discard_entry(cur, TRUE); + } + + if (pool->uSize > 0) + { + WLog_WARN(TAG, "Clearing StreamPool, but there are %" PRIuz " streams currently in use", + pool->uSize); + for (size_t x = 0; x < pool->uSize; x++) + { + struct s_StreamPoolEntry* cur = &pool->uArray[x]; + discard_entry(cur, TRUE); + } + } + + StreamPool_Unlock(pool); +} + +size_t StreamPool_UsedCount(wStreamPool* pool) +{ + StreamPool_Lock(pool); + size_t usize = pool->uSize; + StreamPool_Unlock(pool); + return usize; +} + +/** + * Construction, Destruction + */ + +wStreamPool* StreamPool_New(BOOL synchronized, size_t defaultSize) +{ + wStreamPool* pool = NULL; + + pool = (wStreamPool*)calloc(1, sizeof(wStreamPool)); + + if (pool) + { + pool->synchronized = synchronized; + pool->defaultSize = defaultSize; + + if (!StreamPool_EnsureCapacity(pool, 32, FALSE)) + goto fail; + if (!StreamPool_EnsureCapacity(pool, 32, TRUE)) + goto fail; + + InitializeCriticalSectionAndSpinCount(&pool->lock, 4000); + } + + return pool; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + StreamPool_Free(pool); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void StreamPool_Free(wStreamPool* pool) +{ + if (pool) + { + StreamPool_Clear(pool); + + DeleteCriticalSection(&pool->lock); + + free(pool->aArray); + free(pool->uArray); + + free(pool); + } +} + +char* StreamPool_GetStatistics(wStreamPool* pool, char* buffer, size_t size) +{ + WINPR_ASSERT(pool); + + if (!buffer || (size < 1)) + return NULL; + + size_t used = 0; + int offset = _snprintf(buffer, size - 1, + "aSize =%" PRIuz ", uSize =%" PRIuz ", aCapacity=%" PRIuz + ", uCapacity=%" PRIuz, + pool->aSize, pool->uSize, pool->aCapacity, pool->uCapacity); + if ((offset > 0) && ((size_t)offset < size)) + used += (size_t)offset; + +#if defined(WITH_STREAMPOOL_DEBUG) + StreamPool_Lock(pool); + + offset = _snprintf(&buffer[used], size - 1 - used, "\n-- dump used array take locations --\n"); + if ((offset > 0) && ((size_t)offset < size - used)) + used += (size_t)offset; + for (size_t x = 0; x < pool->uSize; x++) + { + const struct s_StreamPoolEntry* cur = &pool->uArray[x]; + WINPR_ASSERT(cur->msg || (cur->lines == 0)); + + for (size_t y = 0; y < cur->lines; y++) + { + offset = _snprintf(&buffer[used], size - 1 - used, "[%" PRIuz " | %" PRIuz "]: %s\n", x, + y, cur->msg[y]); + if ((offset > 0) && ((size_t)offset < size - used)) + used += (size_t)offset; + } + } + + offset = _snprintf(&buffer[used], size - 1 - used, "\n-- statistics called from --\n"); + if ((offset > 0) && ((size_t)offset < size - used)) + used += (size_t)offset; + + struct s_StreamPoolEntry entry = { 0 }; + void* stack = winpr_backtrace(20); + if (stack) + entry.msg = winpr_backtrace_symbols(stack, &entry.lines); + winpr_backtrace_free(stack); + + for (size_t x = 0; x < entry.lines; x++) + { + const char* msg = entry.msg[x]; + offset = _snprintf(&buffer[used], size - 1 - used, "[%" PRIuz "]: %s\n", x, msg); + if ((offset > 0) && ((size_t)offset < size - used)) + used += (size_t)offset; + } + free((void*)entry.msg); + StreamPool_Unlock(pool); +#endif + buffer[used] = '\0'; + return buffer; +} + +BOOL StreamPool_WaitForReturn(wStreamPool* pool, UINT32 timeoutMS) +{ + wLog* log = WLog_Get(TAG); + + /* HACK: We disconnected the transport above, now wait without a read or write lock until all + * streams in use have been returned to the pool. */ + while (timeoutMS > 0) + { + const size_t used = StreamPool_UsedCount(pool); + if (used == 0) + return TRUE; + WLog_Print(log, WLOG_DEBUG, "%" PRIuz " streams still in use, sleeping...", used); + + char buffer[4096] = { 0 }; + StreamPool_GetStatistics(pool, buffer, sizeof(buffer)); + WLog_Print(log, WLOG_TRACE, "Pool statistics: %s", buffer); + + UINT32 diff = 10; + if (timeoutMS != INFINITE) + { + diff = timeoutMS > 10 ? 10 : timeoutMS; + timeoutMS -= diff; + } + Sleep(diff); + } + + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/backtrace.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/backtrace.h new file mode 100644 index 0000000000000000000000000000000000000000..408f9880e68cf960421a1c57a6b67de948eebf2a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/backtrace.h @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * 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. + */ + +/* A stack unwinder. */ + +#ifndef _CORKSCREW_BACKTRACE_H +#define _CORKSCREW_BACKTRACE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include +#include +#include + + /* + * Describes a single frame of a backtrace. + */ + typedef struct + { + uintptr_t absolute_pc; /* absolute PC offset */ + uintptr_t stack_top; /* top of stack for this frame */ + size_t stack_size; /* size of this stack frame */ + } backtrace_frame_t; + + /* + * Describes the symbols associated with a backtrace frame. + */ + typedef struct + { + uintptr_t relative_pc; /* relative frame PC offset from the start of the library, + or the absolute PC if the library is unknown */ + uintptr_t relative_symbol_addr; /* relative offset of the symbol from the start of the + library or 0 if the library is unknown */ + char* map_name; /* executable or library name, or NULL if unknown */ + char* symbol_name; /* symbol name, or NULL if unknown */ + char* demangled_name; /* demangled symbol name, or NULL if unknown */ + } backtrace_symbol_t; + + /* + * Unwinds the call stack for the current thread of execution. + * Populates the backtrace array with the program counters from the call stack. + * Returns the number of frames collected, or -1 if an error occurred. + */ + ssize_t unwind_backtrace(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth); + + /* + * Unwinds the call stack for a thread within this process. + * Populates the backtrace array with the program counters from the call stack. + * Returns the number of frames collected, or -1 if an error occurred. + * + * The task is briefly suspended while the backtrace is being collected. + */ + ssize_t unwind_backtrace_thread(pid_t tid, backtrace_frame_t* backtrace, size_t ignore_depth, + size_t max_depth); + + /* + * Unwinds the call stack of a task within a remote process using ptrace(). + * Populates the backtrace array with the program counters from the call stack. + * Returns the number of frames collected, or -1 if an error occurred. + */ + ssize_t unwind_backtrace_ptrace(pid_t tid, const ptrace_context_t* context, + backtrace_frame_t* backtrace, size_t ignore_depth, + size_t max_depth); + + /* + * Gets the symbols for each frame of a backtrace. + * The symbols array must be big enough to hold one symbol record per frame. + * The symbols must later be freed using free_backtrace_symbols. + */ + void get_backtrace_symbols(const backtrace_frame_t* backtrace, size_t frames, + backtrace_symbol_t* backtrace_symbols); + + /* + * Gets the symbols for each frame of a backtrace from a remote process. + * The symbols array must be big enough to hold one symbol record per frame. + * The symbols must later be freed using free_backtrace_symbols. + */ + void get_backtrace_symbols_ptrace(const ptrace_context_t* context, + const backtrace_frame_t* backtrace, size_t frames, + backtrace_symbol_t* backtrace_symbols); + + /* + * Frees the storage associated with backtrace symbols. + */ + void free_backtrace_symbols(backtrace_symbol_t* backtrace_symbols, size_t frames); + + enum + { + // A hint for how big to make the line buffer for format_backtrace_line + MAX_BACKTRACE_LINE_LENGTH = 800, + }; + + /** + * Formats a line from a backtrace as a zero-terminated string into the specified buffer. + */ + void format_backtrace_line(unsigned frameNumber, const backtrace_frame_t* frame, + const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize); + +#ifdef __cplusplus +} +#endif + +#endif // _CORKSCREW_BACKTRACE_H diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..0fc2fd6ed854803b9c064497b72b8a4f338203e8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.c @@ -0,0 +1,260 @@ +/** + * WinPR: Windows Portable Runtime + * Debugging Utils + * + * Copyright 2014 Armin Novak + * 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. + */ + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +#include "debug.h" + +#define TAG "com.winpr.utils.debug" +#define LOGT(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_TRACE, __VA_ARGS__); \ + } while (0) +#define LOGD(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_DEBUG, __VA_ARGS__); \ + } while (0) +#define LOGI(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_INFO, __VA_ARGS__); \ + } while (0) +#define LOGW(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_WARN, __VA_ARGS__); \ + } while (0) +#define LOGE(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_ERROR, __VA_ARGS__); \ + } while (0) +#define LOGF(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_FATAL, __VA_ARGS__); \ + } while (0) + +static const char* support_msg = "Invalid stacktrace buffer! check if platform is supported!"; + +typedef struct +{ + backtrace_frame_t* buffer; + size_t max; + size_t used; +} t_corkscrew_data; + +typedef struct +{ + void* hdl; + ssize_t (*unwind_backtrace)(backtrace_frame_t* backtrace, size_t ignore_depth, + size_t max_depth); + ssize_t (*unwind_backtrace_thread)(pid_t tid, backtrace_frame_t* backtrace, size_t ignore_depth, + size_t max_depth); + ssize_t (*unwind_backtrace_ptrace)(pid_t tid, const ptrace_context_t* context, + backtrace_frame_t* backtrace, size_t ignore_depth, + size_t max_depth); + void (*get_backtrace_symbols)(const backtrace_frame_t* backtrace, size_t frames, + backtrace_symbol_t* backtrace_symbols); + void (*get_backtrace_symbols_ptrace)(const ptrace_context_t* context, + const backtrace_frame_t* backtrace, size_t frames, + backtrace_symbol_t* backtrace_symbols); + void (*free_backtrace_symbols)(backtrace_symbol_t* backtrace_symbols, size_t frames); + void (*format_backtrace_line)(unsigned frameNumber, const backtrace_frame_t* frame, + const backtrace_symbol_t* symbol, char* buffer, + size_t bufferSize); +} t_corkscrew; + +static pthread_once_t initialized = PTHREAD_ONCE_INIT; +static t_corkscrew* fkt = NULL; + +void load_library(void) +{ + static t_corkscrew lib; + { + lib.hdl = dlopen("libcorkscrew.so", RTLD_LAZY); + + if (!lib.hdl) + { + LOGF("dlopen error %s", dlerror()); + goto fail; + } + + lib.unwind_backtrace = dlsym(lib.hdl, "unwind_backtrace"); + + if (!lib.unwind_backtrace) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.unwind_backtrace_thread = dlsym(lib.hdl, "unwind_backtrace_thread"); + + if (!lib.unwind_backtrace_thread) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.unwind_backtrace_ptrace = dlsym(lib.hdl, "unwind_backtrace_ptrace"); + + if (!lib.unwind_backtrace_ptrace) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.get_backtrace_symbols = dlsym(lib.hdl, "get_backtrace_symbols"); + + if (!lib.get_backtrace_symbols) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.get_backtrace_symbols_ptrace = dlsym(lib.hdl, "get_backtrace_symbols_ptrace"); + + if (!lib.get_backtrace_symbols_ptrace) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.free_backtrace_symbols = dlsym(lib.hdl, "free_backtrace_symbols"); + + if (!lib.free_backtrace_symbols) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + lib.format_backtrace_line = dlsym(lib.hdl, "format_backtrace_line"); + + if (!lib.format_backtrace_line) + { + LOGF("dlsym error %s", dlerror()); + goto fail; + } + + fkt = &lib; + return; + } +fail: +{ + if (lib.hdl) + dlclose(lib.hdl); + + fkt = NULL; +} +} + +void winpr_corkscrew_backtrace_free(void* buffer) +{ + t_corkscrew_data* data = (t_corkscrew_data*)buffer; + if (!data) + return; + + free(data->buffer); + free(data); +} + +void* winpr_corkscrew_backtrace(DWORD size) +{ + t_corkscrew_data* data = calloc(1, sizeof(t_corkscrew_data)); + + if (!data) + return NULL; + + data->buffer = calloc(size, sizeof(backtrace_frame_t)); + + if (!data->buffer) + { + free(data); + return NULL; + } + + pthread_once(&initialized, load_library); + data->max = size; + data->used = fkt->unwind_backtrace(data->buffer, 0, size); + return data; +} + +char** winpr_corkscrew_backtrace_symbols(void* buffer, size_t* used) +{ + t_corkscrew_data* data = (t_corkscrew_data*)buffer; + if (used) + *used = 0; + + if (!data) + return NULL; + + pthread_once(&initialized, load_library); + + if (!fkt) + { + LOGF(support_msg); + return NULL; + } + else + { + size_t line_len = (data->max > 1024) ? data->max : 1024; + size_t array_size = data->used * sizeof(char*); + size_t lines_size = data->used * line_len; + char** vlines = calloc(1, array_size + lines_size); + backtrace_symbol_t* symbols = calloc(data->used, sizeof(backtrace_symbol_t)); + + if (!vlines || !symbols) + { + free(vlines); + free(symbols); + return NULL; + } + + /* Set the pointers in the allocated buffer's initial array section */ + for (size_t i = 0; i < data->used; i++) + vlines[i] = (char*)vlines + array_size + i * line_len; + + fkt->get_backtrace_symbols(data->buffer, data->used, symbols); + + for (size_t i = 0; i < data->used; i++) + fkt->format_backtrace_line(i, &data->buffer[i], &symbols[i], vlines[i], line_len); + + fkt->free_backtrace_symbols(symbols, data->used); + free(symbols); + + if (used) + *used = data->used; + + return vlines; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..e98b9bd531df81a0f933fe6f1748df1adb94f4b3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/debug.h @@ -0,0 +1,40 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2022 Armin Novak + * Copyright 2022 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_CORKSCREW_H +#define WINPR_DEBUG_CORKSCREW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + + void* winpr_corkscrew_backtrace(DWORD size); + void winpr_corkscrew_backtrace_free(void* buffer); + char** winpr_corkscrew_backtrace_symbols(void* buffer, size_t* used); + void winpr_corkscrew_backtrace_symbols_fd(void* buffer, int fd); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_DEBUG_CORKSCREW_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/demangle.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/demangle.h new file mode 100644 index 0000000000000000000000000000000000000000..75c01d7bf22c4ff24b584a2d04d6215b07431e18 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/demangle.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * 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. + */ + +/* C++ symbol name demangling. */ + +#ifndef _CORKSCREW_DEMANGLE_H +#define _CORKSCREW_DEMANGLE_H + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* + * Demangles a C++ symbol name. + * If name is NULL or if the name cannot be demangled, returns NULL. + * Otherwise, returns a newly allocated string that contains the demangled name. + * + * The caller must free the returned string using free(). + */ + char* demangle_symbol_name(const char* name); + +#ifdef __cplusplus +} +#endif + +#endif // _CORKSCREW_DEMANGLE_H diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/map_info.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/map_info.h new file mode 100644 index 0000000000000000000000000000000000000000..dc2275e38d66891f276ef6f1d6b260f4ba739f8b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/map_info.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * 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. + */ + +/* Process memory map. */ + +#ifndef _CORKSCREW_MAP_INFO_H +#define _CORKSCREW_MAP_INFO_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef struct + { + struct map_info* next; + uintptr_t start; + uintptr_t end; + bool is_readable; + bool is_writable; + bool is_executable; + void* data; // arbitrary data associated with the map by the user, initially NULL + char name[]; + } map_info_t; + + /* Loads memory map from /proc//maps. */ + map_info_t* load_map_info_list(pid_t tid); + + /* Frees memory map. */ + void free_map_info_list(map_info_t* milist); + + /* Finds the memory map that contains the specified address. */ + const map_info_t* find_map_info(const map_info_t* milist, uintptr_t addr); + + /* Returns true if the addr is in a readable map. */ + bool is_readable_map(const map_info_t* milist, uintptr_t addr); + /* Returns true if the addr is in a writable map. */ + bool is_writable_map(const map_info_t* milist, uintptr_t addr); + /* Returns true if the addr is in an executable map. */ + bool is_executable_map(const map_info_t* milist, uintptr_t addr); + + /* Acquires a reference to the memory map for this process. + * The result is cached and refreshed automatically. + * Make sure to release the map info when done. */ + map_info_t* acquire_my_map_info_list(); + + /* Releases a reference to the map info for this process that was + * previous acquired using acquire_my_map_info_list(). */ + void release_my_map_info_list(map_info_t* milist); + + /* Flushes the cached memory map so the next call to + * acquire_my_map_info_list() gets fresh data. */ + void flush_my_map_info_list(); + +#ifdef __cplusplus +} +#endif + +#endif // _CORKSCREW_MAP_INFO_H diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/ptrace.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/ptrace.h new file mode 100644 index 0000000000000000000000000000000000000000..8ff75753ea705c85f9f6947a2df997e009a0b5c0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/ptrace.h @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * 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. + */ + +/* Useful ptrace() utility functions. */ + +#ifndef _CORKSCREW_PTRACE_H +#define _CORKSCREW_PTRACE_H + +#include +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /* Stores information about a process that is used for several different + * ptrace() based operations. */ + typedef struct + { + map_info_t* map_info_list; + } ptrace_context_t; + + /* Describes how to access memory from a process. */ + typedef struct + { + pid_t tid; + const map_info_t* map_info_list; + } memory_t; + +#ifdef __i386__ + /* ptrace() register context. */ + typedef struct pt_regs_x86 + { + uint32_t ebx; + uint32_t ecx; + uint32_t edx; + uint32_t esi; + uint32_t edi; + uint32_t ebp; + uint32_t eax; + uint32_t xds; + uint32_t xes; + uint32_t xfs; + uint32_t xgs; + uint32_t orig_eax; + uint32_t eip; + uint32_t xcs; + uint32_t eflags; + uint32_t esp; + uint32_t xss; + } pt_regs_x86_t; +#endif + +#ifdef __mips__ + /* ptrace() GET_REGS context. */ + typedef struct pt_regs_mips + { + uint64_t regs[32]; + uint64_t lo; + uint64_t hi; + uint64_t cp0_epc; + uint64_t cp0_badvaddr; + uint64_t cp0_status; + uint64_t cp0_cause; + } pt_regs_mips_t; +#endif + + /* + * Initializes a memory structure for accessing memory from this process. + */ + void init_memory(memory_t* memory, const map_info_t* map_info_list); + + /* + * Initializes a memory structure for accessing memory from another process + * using ptrace(). + */ + void init_memory_ptrace(memory_t* memory, pid_t tid); + + /* + * Reads a word of memory safely. + * If the memory is local, ensures that the address is readable before dereferencing it. + * Returns false and a value of 0xffffffff if the word could not be read. + */ + bool try_get_word(const memory_t* memory, uintptr_t ptr, uint32_t* out_value); + + /* + * Reads a word of memory safely using ptrace(). + * Returns false and a value of 0xffffffff if the word could not be read. + */ + bool try_get_word_ptrace(pid_t tid, uintptr_t ptr, uint32_t* out_value); + + /* + * Loads information needed for examining a remote process using ptrace(). + * The caller must already have successfully attached to the process + * using ptrace(). + * + * The context can be used for any threads belonging to that process + * assuming ptrace() is attached to them before performing the actual + * unwinding. The context can continue to be used to decode backtraces + * even after ptrace() has been detached from the process. + */ + ptrace_context_t* load_ptrace_context(pid_t pid); + + /* + * Frees a ptrace context. + */ + void free_ptrace_context(ptrace_context_t* context); + + /* + * Finds a symbol using ptrace. + * Returns the containing map and information about the symbol, or + * NULL if one or the other is not available. + */ + void find_symbol_ptrace(const ptrace_context_t* context, uintptr_t addr, + const map_info_t** out_map_info, const symbol_t** out_symbol); + +#ifdef __cplusplus +} +#endif + +#endif // _CORKSCREW_PTRACE_H diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/symbol_table.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/symbol_table.h new file mode 100644 index 0000000000000000000000000000000000000000..380e17dce459d87e14e4ec8154434dff82caa0c7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/corkscrew/symbol_table.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * 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 _CORKSCREW_SYMBOL_TABLE_H +#define _CORKSCREW_SYMBOL_TABLE_H + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef struct + { + uintptr_t start; + uintptr_t end; + char* name; + } symbol_t; + + typedef struct + { + symbol_t* symbols; + size_t num_symbols; + } symbol_table_t; + + /* + * Loads a symbol table from a given file. + * Returns NULL on error. + */ + symbol_table_t* load_symbol_table(const char* filename); + + /* + * Frees a symbol table. + */ + void free_symbol_table(symbol_table_t* table); + + /* + * Finds a symbol associated with an address in the symbol table. + * Returns NULL if not found. + */ + const symbol_t* find_symbol(const symbol_table_t* table, uintptr_t addr); + +#ifdef __cplusplus +} +#endif + +#endif // _CORKSCREW_SYMBOL_TABLE_H diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/debug.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..54942c740d37fbd1ba9904e95d7a249705e774b0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/debug.c @@ -0,0 +1,243 @@ +/** + * WinPR: Windows Portable Runtime + * Debugging Utils + * + * Copyright 2014 Armin Novak + * 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. + */ + +#include +#include + +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO +WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO + +#define __STDC_WANT_LIB_EXT1__ 1 // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +WINPR_PRAGMA_DIAG_POP + +#include +#include +#include + +#include +#include + +#if defined(USE_EXECINFO) +#include +#endif + +#if defined(USE_UNWIND) +#include +#endif + +#if defined(WINPR_HAVE_CORKSCREW) +#include +#endif + +#if defined(_WIN32) || defined(_WIN64) +#include +#include +#endif + +#include +#include + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +#define TAG "com.winpr.utils.debug" +#define LOGT(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_TRACE, __VA_ARGS__); \ + } while (0) +#define LOGD(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_DEBUG, __VA_ARGS__); \ + } while (0) +#define LOGI(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_INFO, __VA_ARGS__); \ + } while (0) +#define LOGW(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_WARN, __VA_ARGS__); \ + } while (0) +#define LOGE(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_ERROR, __VA_ARGS__); \ + } while (0) +#define LOGF(...) \ + do \ + { \ + WLog_Print(WLog_Get(TAG), WLOG_FATAL, __VA_ARGS__); \ + } while (0) + +static const char* support_msg = "Invalid stacktrace buffer! check if platform is supported!"; + +void winpr_backtrace_free(void* buffer) +{ + if (!buffer) + return; + +#if defined(USE_UNWIND) + winpr_unwind_backtrace_free(buffer); +#elif defined(USE_EXECINFO) + winpr_execinfo_backtrace_free(buffer); +#elif defined(WINPR_HAVE_CORKSCREW) + winpr_corkscrew_backtrace_free(buffer); +#elif defined(_WIN32) || defined(_WIN64) + winpr_win_backtrace_free(buffer); +#else + free(buffer); + LOGF(support_msg); +#endif +} + +void* winpr_backtrace(DWORD size) +{ +#if defined(USE_UNWIND) + return winpr_unwind_backtrace(size); +#elif defined(USE_EXECINFO) + return winpr_execinfo_backtrace(size); +#elif defined(WINPR_HAVE_CORKSCREW) + return winpr_corkscrew_backtrace(size); +#elif (defined(_WIN32) || defined(_WIN64)) && !defined(_UWP) + return winpr_win_backtrace(size); +#else + LOGF(support_msg); + /* return a non NULL buffer to allow the backtrace function family to succeed without failing + */ + return _strdup(support_msg); +#endif +} + +char** winpr_backtrace_symbols(void* buffer, size_t* used) +{ + if (used) + *used = 0; + + if (!buffer) + { + LOGF(support_msg); + return NULL; + } + +#if defined(USE_UNWIND) + return winpr_unwind_backtrace_symbols(buffer, used); +#elif defined(USE_EXECINFO) + return winpr_execinfo_backtrace_symbols(buffer, used); +#elif defined(WINPR_HAVE_CORKSCREW) + return winpr_corkscrew_backtrace_symbols(buffer, used); +#elif (defined(_WIN32) || defined(_WIN64)) && !defined(_UWP) + return winpr_win_backtrace_symbols(buffer, used); +#else + LOGF(support_msg); + + /* We return a char** on heap that is compatible with free: + * + * 1. We allocate sizeof(char*) + strlen + 1 bytes. + * 2. The first sizeof(char*) bytes contain the pointer to the string following the pointer. + * 3. The at data + sizeof(char*) contains the actual string + */ + size_t len = strlen(support_msg); + char* ppmsg = calloc(sizeof(char*) + len + 1, sizeof(char)); + if (!ppmsg) + return NULL; + char** msgptr = (char**)ppmsg; + char* msg = &ppmsg[sizeof(char*)]; + + *msgptr = msg; + strncpy(msg, support_msg, len); + *used = 1; + return msgptr; +#endif +} + +void winpr_backtrace_symbols_fd(void* buffer, int fd) +{ + if (!buffer) + { + LOGF(support_msg); + return; + } + +#if defined(USE_EXECINFO) && !defined(USE_UNWIND) + winpr_execinfo_backtrace_symbols_fd(buffer, fd); +#elif !defined(ANDROID) + { + size_t used = 0; + char** lines = winpr_backtrace_symbols(buffer, &used); + + if (!lines) + return; + + for (size_t i = 0; i < used; i++) + (void)_write(fd, lines[i], (unsigned)strnlen(lines[i], UINT32_MAX)); + free((void*)lines); + } +#else + LOGF(support_msg); +#endif +} + +void winpr_log_backtrace(const char* tag, DWORD level, DWORD size) +{ + winpr_log_backtrace_ex(WLog_Get(tag), level, size); +} + +void winpr_log_backtrace_ex(wLog* log, DWORD level, DWORD size) +{ + size_t used = 0; + char** msg = NULL; + void* stack = winpr_backtrace(20); + + if (!stack) + { + WLog_Print(log, WLOG_ERROR, "winpr_backtrace failed!\n"); + goto fail; + } + + msg = winpr_backtrace_symbols(stack, &used); + + if (msg) + { + for (size_t x = 0; x < used; x++) + WLog_Print(log, level, "%" PRIuz ": %s", x, msg[x]); + } + free((void*)msg); + +fail: + winpr_backtrace_free(stack); +} + +char* winpr_strerror(INT32 dw, char* dmsg, size_t size) +{ +#ifdef __STDC_LIB_EXT1__ + (void)strerror_s(dw, dmsg, size); +#elif defined(WINPR_HAVE_STRERROR_R) + (void)strerror_r(dw, dmsg, size); +#else + (void)_snprintf(dmsg, size, "%s", strerror(dw)); +#endif + return dmsg; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..5f76dc48086074671a829dec9106efd41f5b8fda --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.c @@ -0,0 +1,98 @@ +/** + * WinPR: Windows Portable Runtime + * Debugging Utils + * + * Copyright 2014 Armin Novak + * 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. + */ + +#include +#include +#include + +#include + +#include "debug.h" + +typedef struct +{ + void** buffer; + size_t max; + size_t used; +} t_execinfo; + +void winpr_execinfo_backtrace_free(void* buffer) +{ + t_execinfo* data = (t_execinfo*)buffer; + if (!data) + return; + + free((void*)data->buffer); + free(data); +} + +void* winpr_execinfo_backtrace(DWORD size) +{ + t_execinfo* data = calloc(1, sizeof(t_execinfo)); + + if (!data) + return NULL; + + data->buffer = (void**)calloc(size, sizeof(void*)); + + if (!data->buffer) + { + free(data); + return NULL; + } + + assert(size <= INT32_MAX); + const int rc = backtrace(data->buffer, (int)size); + if (rc < 0) + { + free(data); + return NULL; + } + data->max = size; + data->used = (size_t)rc; + return data; +} + +char** winpr_execinfo_backtrace_symbols(void* buffer, size_t* used) +{ + t_execinfo* data = (t_execinfo*)buffer; + if (used) + *used = 0; + + if (!data) + return NULL; + + if (used) + *used = data->used; + + assert(data->used < INT32_MAX); + return backtrace_symbols(data->buffer, (int)data->used); +} + +void winpr_execinfo_backtrace_symbols_fd(void* buffer, int fd) +{ + t_execinfo* data = (t_execinfo*)buffer; + + if (!data) + return; + + assert(data->used <= INT32_MAX); + backtrace_symbols_fd(data->buffer, (int)data->used, fd); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..aaf7748a3daa131cef0b84240813ed097629e6d3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/execinfo/debug.h @@ -0,0 +1,40 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2022 Armin Novak + * Copyright 2022 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_EXECINFO_H +#define WINPR_DEBUG_EXECINFO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + + void* winpr_execinfo_backtrace(DWORD size); + void winpr_execinfo_backtrace_free(void* buffer); + char** winpr_execinfo_backtrace_symbols(void* buffer, size_t* used); + void winpr_execinfo_backtrace_symbols_fd(void* buffer, int fd); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_DEBUG_EXECINFO_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.c new file mode 100644 index 0000000000000000000000000000000000000000..a5cd1ef92a30fe643dad8971b8867bb30c90dfe1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.c @@ -0,0 +1,1317 @@ +/** + * WinPR: Windows Portable Runtime + * Image Utils + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2016 Inuvika Inc. + * Copyright 2016 David PHAM-VAN + * + * 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 + +#include + +#include +#include +#include + +#include + +#if defined(WINPR_UTILS_IMAGE_PNG) +#include +#endif + +#if defined(WINPR_UTILS_IMAGE_JPEG) +#define INT32 INT32_WINPR +#include +#undef INT32 +#endif + +#if defined(WINPR_UTILS_IMAGE_WEBP) +#include +#include +#endif + +#if defined(WITH_LODEPNG) +#include +#endif +#include + +#include "image.h" +#include "../log.h" +#define TAG WINPR_TAG("utils.image") + +static SSIZE_T winpr_convert_from_jpeg(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data); +static SSIZE_T winpr_convert_from_png(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data); +static SSIZE_T winpr_convert_from_webp(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data); + +BOOL writeBitmapFileHeader(wStream* s, const WINPR_BITMAP_FILE_HEADER* bf) +{ + if (!Stream_EnsureRemainingCapacity(s, sizeof(WINPR_BITMAP_FILE_HEADER))) + return FALSE; + + Stream_Write_UINT8(s, bf->bfType[0]); + Stream_Write_UINT8(s, bf->bfType[1]); + Stream_Write_UINT32(s, bf->bfSize); + Stream_Write_UINT16(s, bf->bfReserved1); + Stream_Write_UINT16(s, bf->bfReserved2); + Stream_Write_UINT32(s, bf->bfOffBits); + return TRUE; +} + +BOOL readBitmapFileHeader(wStream* s, WINPR_BITMAP_FILE_HEADER* bf) +{ + static wLog* log = NULL; + if (!log) + log = WLog_Get(TAG); + + if (!s || !bf || + (!Stream_CheckAndLogRequiredLengthWLog(log, s, sizeof(WINPR_BITMAP_FILE_HEADER)))) + return FALSE; + + Stream_Read_UINT8(s, bf->bfType[0]); + Stream_Read_UINT8(s, bf->bfType[1]); + Stream_Read_UINT32(s, bf->bfSize); + Stream_Read_UINT16(s, bf->bfReserved1); + Stream_Read_UINT16(s, bf->bfReserved2); + Stream_Read_UINT32(s, bf->bfOffBits); + + if (bf->bfSize < sizeof(WINPR_BITMAP_FILE_HEADER)) + { + WLog_Print(log, WLOG_ERROR, "Invalid bitmap::bfSize=%" PRIu32 ", require at least %" PRIuz, + bf->bfSize, sizeof(WINPR_BITMAP_FILE_HEADER)); + return FALSE; + } + + if ((bf->bfType[0] != 'B') || (bf->bfType[1] != 'M')) + { + WLog_Print(log, WLOG_ERROR, "Invalid bitmap header [%c%c], expected [BM]", bf->bfType[0], + bf->bfType[1]); + return FALSE; + } + return Stream_CheckAndLogRequiredCapacityWLog(log, s, + bf->bfSize - sizeof(WINPR_BITMAP_FILE_HEADER)); +} + +BOOL writeBitmapInfoHeader(wStream* s, const WINPR_BITMAP_INFO_HEADER* bi) +{ + if (!Stream_EnsureRemainingCapacity(s, sizeof(WINPR_BITMAP_INFO_HEADER))) + return FALSE; + + Stream_Write_UINT32(s, bi->biSize); + Stream_Write_INT32(s, bi->biWidth); + Stream_Write_INT32(s, bi->biHeight); + Stream_Write_UINT16(s, bi->biPlanes); + Stream_Write_UINT16(s, bi->biBitCount); + Stream_Write_UINT32(s, bi->biCompression); + Stream_Write_UINT32(s, bi->biSizeImage); + Stream_Write_INT32(s, bi->biXPelsPerMeter); + Stream_Write_INT32(s, bi->biYPelsPerMeter); + Stream_Write_UINT32(s, bi->biClrUsed); + Stream_Write_UINT32(s, bi->biClrImportant); + return TRUE; +} + +BOOL readBitmapInfoHeader(wStream* s, WINPR_BITMAP_INFO_HEADER* bi, size_t* poffset) +{ + if (!s || !bi || (!Stream_CheckAndLogRequiredLength(TAG, s, sizeof(WINPR_BITMAP_INFO_HEADER)))) + return FALSE; + + const size_t start = Stream_GetPosition(s); + Stream_Read_UINT32(s, bi->biSize); + Stream_Read_INT32(s, bi->biWidth); + Stream_Read_INT32(s, bi->biHeight); + Stream_Read_UINT16(s, bi->biPlanes); + Stream_Read_UINT16(s, bi->biBitCount); + Stream_Read_UINT32(s, bi->biCompression); + Stream_Read_UINT32(s, bi->biSizeImage); + Stream_Read_INT32(s, bi->biXPelsPerMeter); + Stream_Read_INT32(s, bi->biYPelsPerMeter); + Stream_Read_UINT32(s, bi->biClrUsed); + Stream_Read_UINT32(s, bi->biClrImportant); + + if ((bi->biBitCount < 1) || (bi->biBitCount > 32)) + { + WLog_WARN(TAG, "invalid biBitCount=%" PRIu32, bi->biBitCount); + return FALSE; + } + + /* https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader */ + size_t offset = 0; + switch (bi->biCompression) + { + case BI_RGB: + if (bi->biBitCount <= 8) + { + DWORD used = bi->biClrUsed; + if (used == 0) + used = (1 << bi->biBitCount) / 8; + offset += sizeof(RGBQUAD) * used; + } + if (bi->biSizeImage == 0) + { + UINT32 stride = WINPR_ASSERTING_INT_CAST( + uint32_t, ((((bi->biWidth * bi->biBitCount) + 31) & ~31) >> 3)); + bi->biSizeImage = WINPR_ASSERTING_INT_CAST(uint32_t, abs(bi->biHeight)) * stride; + } + break; + case BI_BITFIELDS: + offset += sizeof(DWORD) * 3; // 3 DWORD color masks + break; + default: + WLog_ERR(TAG, "unsupported biCompression %" PRIu32, bi->biCompression); + return FALSE; + } + + if (bi->biSizeImage == 0) + { + WLog_ERR(TAG, "invalid biSizeImage %" PRIuz, bi->biSizeImage); + return FALSE; + } + + const size_t pos = Stream_GetPosition(s) - start; + if (bi->biSize < pos) + { + WLog_ERR(TAG, "invalid biSize %" PRIuz " < (actual) offset %" PRIuz, bi->biSize, pos); + return FALSE; + } + + *poffset = offset; + return Stream_SafeSeek(s, bi->biSize - pos); +} + +BYTE* winpr_bitmap_construct_header(size_t width, size_t height, size_t bpp) +{ + BYTE* result = NULL; + WINPR_BITMAP_FILE_HEADER bf = { 0 }; + WINPR_BITMAP_INFO_HEADER bi = { 0 }; + wStream* s = NULL; + size_t imgSize = 0; + + imgSize = width * height * (bpp / 8); + if ((width > INT32_MAX) || (height > INT32_MAX) || (bpp > UINT16_MAX) || (imgSize > UINT32_MAX)) + return NULL; + + s = Stream_New(NULL, WINPR_IMAGE_BMP_HEADER_LEN); + if (!s) + return NULL; + + bf.bfType[0] = 'B'; + bf.bfType[1] = 'M'; + bf.bfReserved1 = 0; + bf.bfReserved2 = 0; + bi.biSize = (UINT32)sizeof(WINPR_BITMAP_INFO_HEADER); + bf.bfOffBits = (UINT32)sizeof(WINPR_BITMAP_FILE_HEADER) + bi.biSize; + bi.biSizeImage = (UINT32)imgSize; + bf.bfSize = bf.bfOffBits + bi.biSizeImage; + bi.biWidth = (INT32)width; + bi.biHeight = -1 * (INT32)height; + bi.biPlanes = 1; + bi.biBitCount = (UINT16)bpp; + bi.biCompression = BI_RGB; + bi.biXPelsPerMeter = (INT32)width; + bi.biYPelsPerMeter = (INT32)height; + bi.biClrUsed = 0; + bi.biClrImportant = 0; + + size_t offset = 0; + switch (bi.biCompression) + { + case BI_RGB: + if (bi.biBitCount <= 8) + { + DWORD used = bi.biClrUsed; + if (used == 0) + used = (1 << bi.biBitCount) / 8; + offset += sizeof(RGBQUAD) * used; + } + break; + case BI_BITFIELDS: + offset += sizeof(DWORD) * 3; // 3 DWORD color masks + break; + default: + return FALSE; + } + + if (!writeBitmapFileHeader(s, &bf)) + goto fail; + + if (!writeBitmapInfoHeader(s, &bi)) + goto fail; + + if (!Stream_EnsureRemainingCapacity(s, offset)) + goto fail; + + Stream_Zero(s, offset); + result = Stream_Buffer(s); +fail: + Stream_Free(s, result == 0); + return result; +} + +/** + * Refer to "Compressed Image File Formats: JPEG, PNG, GIF, XBM, BMP" book + */ + +WINPR_ATTR_MALLOC(free, 1) +static void* winpr_bitmap_write_buffer(const BYTE* data, size_t size, UINT32 width, UINT32 height, + UINT32 stride, UINT32 bpp, UINT32* pSize) +{ + WINPR_ASSERT(data || (size == 0)); + + void* result = NULL; + const size_t bpp_stride = 1ull * width * (bpp / 8); + if (bpp_stride > UINT32_MAX) + return NULL; + + wStream* s = Stream_New(NULL, 1024); + + if (stride == 0) + stride = (UINT32)bpp_stride; + + BYTE* bmp_header = winpr_bitmap_construct_header(width, height, bpp); + if (!bmp_header) + goto fail; + if (!Stream_EnsureRemainingCapacity(s, WINPR_IMAGE_BMP_HEADER_LEN)) + goto fail; + Stream_Write(s, bmp_header, WINPR_IMAGE_BMP_HEADER_LEN); + + if (!Stream_EnsureRemainingCapacity(s, 1ULL * stride * height)) + goto fail; + + for (size_t y = 0; y < height; y++) + { + const BYTE* line = &data[stride * y]; + + Stream_Write(s, line, stride); + } + + result = Stream_Buffer(s); + const size_t pos = Stream_GetPosition(s); + if (pos > UINT32_MAX) + goto fail; + *pSize = (UINT32)pos; +fail: + Stream_Free(s, result == NULL); + free(bmp_header); + return result; +} + +int winpr_bitmap_write(const char* filename, const BYTE* data, size_t width, size_t height, + size_t bpp) +{ + return winpr_bitmap_write_ex(filename, data, 0, width, height, bpp); +} + +int winpr_bitmap_write_ex(const char* filename, const BYTE* data, size_t stride, size_t width, + size_t height, size_t bpp) +{ + FILE* fp = NULL; + int ret = -1; + void* bmpdata = NULL; + const size_t bpp_stride = ((((width * bpp) + 31) & (size_t)~31) >> 3); + + if ((stride > UINT32_MAX) || (width > UINT32_MAX) || (height > UINT32_MAX) || + (bpp > UINT32_MAX)) + goto fail; + + if (stride == 0) + stride = bpp_stride; + + UINT32 bmpsize = 0; + const size_t size = stride * 1ull * height; + bmpdata = winpr_bitmap_write_buffer(data, size, (UINT32)width, (UINT32)height, (UINT32)stride, + (UINT32)bpp, &bmpsize); + if (!bmpdata) + goto fail; + + fp = winpr_fopen(filename, "w+b"); + if (!fp) + { + WLog_ERR(TAG, "failed to open file %s", filename); + goto fail; + } + + if (fwrite(bmpdata, bmpsize, 1, fp) != 1) + goto fail; + + ret = 0; +fail: + if (fp) + (void)fclose(fp); + free(bmpdata); + return ret; +} + +static int write_and_free(const char* filename, void* data, size_t size) +{ + int status = -1; + if (!data) + goto fail; + + FILE* fp = winpr_fopen(filename, "w+b"); + if (!fp) + goto fail; + + size_t w = fwrite(data, 1, size, fp); + (void)fclose(fp); + + status = (w == size) ? 1 : -1; +fail: + free(data); + return status; +} + +int winpr_image_write(wImage* image, const char* filename) +{ + WINPR_ASSERT(image); + return winpr_image_write_ex(image, WINPR_ASSERTING_INT_CAST(uint32_t, image->type), filename); +} + +int winpr_image_write_ex(wImage* image, UINT32 format, const char* filename) +{ + WINPR_ASSERT(image); + + size_t size = 0; + void* data = winpr_image_write_buffer(image, format, &size); + if (!data) + return -1; + return write_and_free(filename, data, size); +} + +static int winpr_image_bitmap_read_buffer(wImage* image, const BYTE* buffer, size_t size) +{ + int rc = -1; + BOOL vFlip = 0; + WINPR_BITMAP_FILE_HEADER bf = { 0 }; + WINPR_BITMAP_INFO_HEADER bi = { 0 }; + wStream sbuffer = { 0 }; + wStream* s = Stream_StaticConstInit(&sbuffer, buffer, size); + + if (!s) + return -1; + + size_t bmpoffset = 0; + if (!readBitmapFileHeader(s, &bf) || !readBitmapInfoHeader(s, &bi, &bmpoffset)) + goto fail; + + if ((bf.bfType[0] != 'B') || (bf.bfType[1] != 'M')) + { + WLog_WARN(TAG, "Invalid bitmap header %c%c", bf.bfType[0], bf.bfType[1]); + goto fail; + } + + image->type = WINPR_IMAGE_BITMAP; + + const size_t pos = Stream_GetPosition(s); + const size_t expect = bf.bfOffBits; + + if (pos != expect) + { + WLog_WARN(TAG, "pos=%" PRIuz ", expected %" PRIuz ", offset=" PRIuz, pos, expect, + bmpoffset); + goto fail; + } + + if (!Stream_CheckAndLogRequiredCapacity(TAG, s, bi.biSizeImage)) + goto fail; + + if (bi.biWidth <= 0) + { + WLog_WARN(TAG, "bi.biWidth=%" PRId32, bi.biWidth); + goto fail; + } + + image->width = (UINT32)bi.biWidth; + + if (bi.biHeight < 0) + { + vFlip = FALSE; + image->height = (UINT32)(-1 * bi.biHeight); + } + else + { + vFlip = TRUE; + image->height = (UINT32)bi.biHeight; + } + + if (image->height <= 0) + { + WLog_WARN(TAG, "image->height=%" PRIu32, image->height); + goto fail; + } + + image->bitsPerPixel = bi.biBitCount; + image->bytesPerPixel = (image->bitsPerPixel / 8UL); + const size_t bpp = (bi.biBitCount + 7UL) / 8UL; + image->scanline = + WINPR_ASSERTING_INT_CAST(uint32_t, bi.biWidth) * WINPR_ASSERTING_INT_CAST(uint32_t, bpp); + const size_t bmpsize = 1ULL * image->scanline * image->height; + if (bmpsize != bi.biSizeImage) + WLog_WARN(TAG, "bmpsize=%" PRIuz " != bi.biSizeImage=%" PRIu32, bmpsize, bi.biSizeImage); + if (bi.biSizeImage < bmpsize) + goto fail; + + image->data = NULL; + if (bi.biSizeImage > 0) + image->data = (BYTE*)malloc(bi.biSizeImage); + + if (!image->data) + goto fail; + + if (!vFlip) + Stream_Read(s, image->data, bi.biSizeImage); + else + { + BYTE* pDstData = &(image->data[(image->height - 1ull) * image->scanline]); + + for (size_t index = 0; index < image->height; index++) + { + Stream_Read(s, pDstData, image->scanline); + pDstData -= image->scanline; + } + } + + rc = 1; +fail: + + if (rc < 0) + { + free(image->data); + image->data = NULL; + } + + return rc; +} + +int winpr_image_read(wImage* image, const char* filename) +{ + int status = -1; + + FILE* fp = winpr_fopen(filename, "rb"); + if (!fp) + { + WLog_ERR(TAG, "failed to open file %s", filename); + return -1; + } + + (void)fseek(fp, 0, SEEK_END); + INT64 pos = _ftelli64(fp); + (void)fseek(fp, 0, SEEK_SET); + + if (pos > 0) + { + BYTE* buffer = malloc((size_t)pos); + if (buffer) + { + size_t r = fread(buffer, 1, (size_t)pos, fp); + if (r == (size_t)pos) + { + status = winpr_image_read_buffer(image, buffer, (size_t)pos); + } + } + free(buffer); + } + (void)fclose(fp); + return status; +} + +int winpr_image_read_buffer(wImage* image, const BYTE* buffer, size_t size) +{ + BYTE sig[12] = { 0 }; + int status = -1; + + if (size < sizeof(sig)) + return -1; + + CopyMemory(sig, buffer, sizeof(sig)); + + if ((sig[0] == 'B') && (sig[1] == 'M')) + { + image->type = WINPR_IMAGE_BITMAP; + status = winpr_image_bitmap_read_buffer(image, buffer, size); + } + else if ((sig[0] == 'R') && (sig[1] == 'I') && (sig[2] == 'F') && (sig[3] == 'F') && + (sig[8] == 'W') && (sig[9] == 'E') && (sig[10] == 'B') && (sig[11] == 'P')) + { + image->type = WINPR_IMAGE_WEBP; + const SSIZE_T rc = winpr_convert_from_webp(buffer, size, &image->width, &image->height, + &image->bitsPerPixel, &image->data); + if (rc >= 0) + { + image->bytesPerPixel = (image->bitsPerPixel + 7) / 8; + image->scanline = image->width * image->bytesPerPixel; + status = 1; + } + } + else if ((sig[0] == 0xFF) && (sig[1] == 0xD8) && (sig[2] == 0xFF) && (sig[3] == 0xE0) && + (sig[6] == 0x4A) && (sig[7] == 0x46) && (sig[8] == 0x49) && (sig[9] == 0x46) && + (sig[10] == 0x00)) + { + image->type = WINPR_IMAGE_JPEG; + const SSIZE_T rc = winpr_convert_from_jpeg(buffer, size, &image->width, &image->height, + &image->bitsPerPixel, &image->data); + if (rc >= 0) + { + image->bytesPerPixel = (image->bitsPerPixel + 7) / 8; + image->scanline = image->width * image->bytesPerPixel; + status = 1; + } + } + else if ((sig[0] == 0x89) && (sig[1] == 'P') && (sig[2] == 'N') && (sig[3] == 'G') && + (sig[4] == '\r') && (sig[5] == '\n') && (sig[6] == 0x1A) && (sig[7] == '\n')) + { + image->type = WINPR_IMAGE_PNG; + const SSIZE_T rc = winpr_convert_from_png(buffer, size, &image->width, &image->height, + &image->bitsPerPixel, &image->data); + if (rc >= 0) + { + image->bytesPerPixel = (image->bitsPerPixel + 7) / 8; + image->scanline = image->width * image->bytesPerPixel; + status = 1; + } + } + + return status; +} + +wImage* winpr_image_new(void) +{ + wImage* image = (wImage*)calloc(1, sizeof(wImage)); + + if (!image) + return NULL; + + return image; +} + +void winpr_image_free(wImage* image, BOOL bFreeBuffer) +{ + if (!image) + return; + + if (bFreeBuffer) + free(image->data); + + free(image); +} + +static void* winpr_convert_to_jpeg(const void* data, size_t size, UINT32 width, UINT32 height, + UINT32 stride, UINT32 bpp, UINT32* pSize) +{ + WINPR_ASSERT(data || (size == 0)); + WINPR_ASSERT(pSize); + + *pSize = 0; + +#if !defined(WINPR_UTILS_IMAGE_JPEG) + return NULL; +#else + BYTE* outbuffer = NULL; + unsigned long outsize = 0; + struct jpeg_compress_struct cinfo = { 0 }; + + const size_t expect1 = 1ull * stride * height; + const size_t bytes = (bpp + 7) / 8; + const size_t expect2 = 1ull * width * height * bytes; + if (expect1 != expect2) + return NULL; + if (expect1 > size) + return NULL; + + /* Set up the error handler. */ + struct jpeg_error_mgr jerr = { 0 }; + cinfo.err = jpeg_std_error(&jerr); + + jpeg_create_compress(&cinfo); + jpeg_mem_dest(&cinfo, &outbuffer, &outsize); + + cinfo.image_width = width; + cinfo.image_height = height; + WINPR_ASSERT(bpp <= INT32_MAX / 8); + cinfo.input_components = (int)(bpp + 7) / 8; + cinfo.in_color_space = (bpp > 24) ? JCS_EXT_BGRA : JCS_EXT_BGR; + cinfo.data_precision = 8; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, 100, TRUE); + /* Use 4:4:4 subsampling (default is 4:2:0) */ + cinfo.comp_info[0].h_samp_factor = cinfo.comp_info[0].v_samp_factor = 1; + + jpeg_start_compress(&cinfo, TRUE); + + const JSAMPLE* cdata = data; + for (size_t x = 0; x < height; x++) + { + WINPR_ASSERT(x * stride <= UINT32_MAX); + const JDIMENSION offset = (JDIMENSION)x * stride; + + /* libjpeg is not const correct, we must cast here to avoid issues + * with newer C compilers type check errors */ + JSAMPLE* coffset = WINPR_CAST_CONST_PTR_AWAY(&cdata[offset], JSAMPLE*); + if (jpeg_write_scanlines(&cinfo, &coffset, 1) != 1) + goto fail; + } + +fail: + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + WINPR_ASSERT(outsize <= UINT32_MAX); + *pSize = (UINT32)outsize; + return outbuffer; +#endif +} + +// NOLINTBEGIN(readability-non-const-parameter) +SSIZE_T winpr_convert_from_jpeg(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data) +// NOLINTEND(readability-non-const-parameter) +{ + WINPR_ASSERT(comp_data || (comp_data_bytes == 0)); + WINPR_ASSERT(width); + WINPR_ASSERT(height); + WINPR_ASSERT(bpp); + WINPR_ASSERT(ppdecomp_data); + +#if !defined(WINPR_UTILS_IMAGE_JPEG) + return -1; +#else + struct jpeg_decompress_struct cinfo = { 0 }; + struct jpeg_error_mgr jerr; + SSIZE_T size = -1; + BYTE* decomp_data = NULL; + + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress(&cinfo); + jpeg_mem_src(&cinfo, comp_data, comp_data_bytes); + + if (jpeg_read_header(&cinfo, 1) != JPEG_HEADER_OK) + goto fail; + + cinfo.out_color_space = cinfo.num_components > 3 ? JCS_EXT_RGBA : JCS_EXT_BGR; + + *width = cinfo.image_width; + *height = cinfo.image_height; + *bpp = cinfo.num_components * 8; + + if (!jpeg_start_decompress(&cinfo)) + goto fail; + + size_t stride = 1ULL * cinfo.image_width * cinfo.num_components; + + decomp_data = calloc(stride, cinfo.image_height); + if (decomp_data) + { + while (cinfo.output_scanline < cinfo.image_height) + { + JSAMPROW row = &decomp_data[cinfo.output_scanline * stride]; + if (jpeg_read_scanlines(&cinfo, &row, 1) != 1) + goto fail; + } + const size_t ssize = stride * cinfo.image_height; + WINPR_ASSERT(ssize < SSIZE_MAX); + size = (SSIZE_T)ssize; + } + jpeg_finish_decompress(&cinfo); + +fail: + jpeg_destroy_decompress(&cinfo); + *ppdecomp_data = decomp_data; + return size; +#endif +} + +static void* winpr_convert_to_webp(const void* data, size_t size, UINT32 width, UINT32 height, + UINT32 stride, UINT32 bpp, UINT32* pSize) +{ + WINPR_ASSERT(data || (size == 0)); + WINPR_ASSERT(pSize); + + *pSize = 0; + +#if !defined(WINPR_UTILS_IMAGE_WEBP) + return NULL; +#else + size_t dstSize = 0; + uint8_t* pDstData = NULL; + WINPR_ASSERT(width <= INT32_MAX); + WINPR_ASSERT(height <= INT32_MAX); + WINPR_ASSERT(stride <= INT32_MAX); + switch (bpp) + { + case 32: + dstSize = WebPEncodeLosslessBGRA(data, (int)width, (int)height, (int)stride, &pDstData); + break; + case 24: + dstSize = WebPEncodeLosslessBGR(data, (int)width, (int)height, (int)stride, &pDstData); + break; + default: + return NULL; + } + + void* rc = malloc(dstSize); + if (rc) + { + memcpy(rc, pDstData, dstSize); + + WINPR_ASSERT(dstSize <= UINT32_MAX); + *pSize = (UINT32)dstSize; + } + WebPFree(pDstData); + return rc; +#endif +} + +SSIZE_T winpr_convert_from_webp(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data) +{ + WINPR_ASSERT(comp_data || (comp_data_bytes == 0)); + WINPR_ASSERT(width); + WINPR_ASSERT(height); + WINPR_ASSERT(bpp); + WINPR_ASSERT(ppdecomp_data); + + *width = 0; + *height = 0; + *bpp = 0; + *ppdecomp_data = NULL; +#if !defined(WINPR_UTILS_IMAGE_WEBP) + return -1; +#else + + int w = 0; + int h = 0; + uint8_t* dst = WebPDecodeBGRA(comp_data, comp_data_bytes, &w, &h); + if (!dst || (w < 0) || (h < 0)) + { + free(dst); + return -1; + } + + *width = w; + *height = h; + *bpp = 32; + *ppdecomp_data = dst; + return 4ll * w * h; +#endif +} + +#if defined(WINPR_UTILS_IMAGE_PNG) +struct png_mem_encode +{ + char* buffer; + size_t size; +}; + +static void png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) +{ + /* with libpng15 next line causes pointer deference error; use libpng12 */ + struct png_mem_encode* p = + (struct png_mem_encode*)png_get_io_ptr(png_ptr); /* was png_ptr->io_ptr */ + size_t nsize = p->size + length; + + /* allocate or grow buffer */ + if (p->buffer) + { + char* tmp = realloc(p->buffer, nsize); + if (tmp) + p->buffer = tmp; + } + else + p->buffer = malloc(nsize); + + if (!p->buffer) + png_error(png_ptr, "Write Error"); + + /* copy new bytes to end of buffer */ + memcpy(p->buffer + p->size, data, length); + p->size += length; +} + +/* This is optional but included to show how png_set_write_fn() is called */ +static void png_flush(png_structp png_ptr) +{ +} + +static SSIZE_T save_png_to_buffer(UINT32 bpp, UINT32 width, UINT32 height, const uint8_t* data, + size_t size, void** pDstData) +{ + SSIZE_T rc = -1; + png_structp png_ptr = NULL; + png_infop info_ptr = NULL; + png_byte** row_pointers = NULL; + struct png_mem_encode state = { 0 }; + + *pDstData = NULL; + + if (!data || (size == 0)) + return 0; + + WINPR_ASSERT(pDstData); + + const size_t bytes_per_pixel = (bpp + 7) / 8; + const size_t bytes_per_row = width * bytes_per_pixel; + if (size < bytes_per_row * height) + goto fail; + + /* Initialize the write struct. */ + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (png_ptr == NULL) + goto fail; + + /* Initialize the info struct. */ + info_ptr = png_create_info_struct(png_ptr); + if (info_ptr == NULL) + goto fail; + + /* Set up error handling. */ + if (setjmp(png_jmpbuf(png_ptr))) + goto fail; + + /* Set image attributes. */ + int colorType = PNG_COLOR_TYPE_PALETTE; + if (bpp > 8) + colorType = PNG_COLOR_TYPE_RGB; + if (bpp > 16) + colorType = PNG_COLOR_TYPE_RGB; + if (bpp > 24) + colorType = PNG_COLOR_TYPE_RGBA; + + png_set_IHDR(png_ptr, info_ptr, width, height, 8, colorType, PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + + /* Initialize rows of PNG. */ + row_pointers = (png_byte**)png_malloc(png_ptr, height * sizeof(png_byte*)); + for (size_t y = 0; y < height; ++y) + { + uint8_t* row = png_malloc(png_ptr, sizeof(uint8_t) * bytes_per_row); + row_pointers[y] = (png_byte*)row; + for (size_t x = 0; x < width; ++x) + { + + *row++ = *data++; + if (bpp > 8) + *row++ = *data++; + if (bpp > 16) + *row++ = *data++; + if (bpp > 24) + *row++ = *data++; + } + } + + /* Actually write the image data. */ + png_set_write_fn(png_ptr, &state, png_write_data, png_flush); + png_set_rows(png_ptr, info_ptr, row_pointers); + png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL); + + /* Cleanup. */ + for (size_t y = 0; y < height; y++) + png_free(png_ptr, row_pointers[y]); + png_free(png_ptr, (void*)row_pointers); + + /* Finish writing. */ + if (state.size > SSIZE_MAX) + goto fail; + rc = (SSIZE_T)state.size; + *pDstData = state.buffer; +fail: + png_destroy_write_struct(&png_ptr, &info_ptr); + if (rc < 0) + free(state.buffer); + return rc; +} + +typedef struct +{ + png_bytep buffer; + png_uint_32 bufsize; + png_uint_32 current_pos; +} MEMORY_READER_STATE; + +static void read_data_memory(png_structp png_ptr, png_bytep data, size_t length) +{ + MEMORY_READER_STATE* f = png_get_io_ptr(png_ptr); + if (length > (f->bufsize - f->current_pos)) + png_error(png_ptr, "read error in read_data_memory (loadpng)"); + else + { + memcpy(data, f->buffer + f->current_pos, length); + f->current_pos += length; + } +} + +static void* winpr_read_png_from_buffer(const void* data, size_t SrcSize, size_t* pSize, + UINT32* pWidth, UINT32* pHeight, UINT32* pBpp) +{ + void* rc = NULL; + png_uint_32 width = 0; + png_uint_32 height = 0; + int bit_depth = 0; + int color_type = 0; + int interlace_type = 0; + int transforms = PNG_TRANSFORM_IDENTITY; + MEMORY_READER_STATE memory_reader_state = { 0 }; + png_bytepp row_pointers = NULL; + png_infop info_ptr = NULL; + if (SrcSize > UINT32_MAX) + return NULL; + + png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!png_ptr) + goto fail; + info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) + goto fail; + + memory_reader_state.buffer = WINPR_CAST_CONST_PTR_AWAY(data, png_bytep); + memory_reader_state.bufsize = (UINT32)SrcSize; + memory_reader_state.current_pos = 0; + + png_set_read_fn(png_ptr, &memory_reader_state, read_data_memory); + + transforms |= PNG_TRANSFORM_BGR; + png_read_png(png_ptr, info_ptr, transforms, NULL); + + if (png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, + NULL, NULL) != 1) + goto fail; + + WINPR_ASSERT(bit_depth >= 0); + const png_byte channelcount = png_get_channels(png_ptr, info_ptr); + const size_t bpp = channelcount * (size_t)bit_depth; + + row_pointers = png_get_rows(png_ptr, info_ptr); + if (row_pointers) + { + const size_t stride = 1ULL * width * bpp / 8ull; + const size_t png_stride = png_get_rowbytes(png_ptr, info_ptr); + const size_t size = 1ULL * width * height * bpp / 8ull; + const size_t copybytes = stride > png_stride ? png_stride : stride; + + rc = malloc(size); + if (rc) + { + char* cur = rc; + for (png_uint_32 i = 0; i < height; i++) + { + memcpy(cur, row_pointers[i], copybytes); + cur += stride; + } + *pSize = size; + *pWidth = width; + *pHeight = height; + WINPR_ASSERT(bpp <= UINT32_MAX); + *pBpp = (UINT32)bpp; + } + } +fail: + + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + return rc; +} +#endif + +static void* winpr_convert_to_png(const void* data, size_t size, UINT32 width, UINT32 height, + UINT32 stride, UINT32 bpp, UINT32* pSize) +{ + WINPR_ASSERT(data || (size == 0)); + WINPR_ASSERT(pSize); + + *pSize = 0; + +#if defined(WINPR_UTILS_IMAGE_PNG) + void* dst = NULL; + SSIZE_T rc = save_png_to_buffer(bpp, width, height, data, size, &dst); + if (rc <= 0) + return NULL; + *pSize = (UINT32)rc; + return dst; +#elif defined(WITH_LODEPNG) + { + BYTE* dst = NULL; + size_t dstsize = 0; + unsigned rc = 1; + + switch (bpp) + { + case 32: + rc = lodepng_encode32(&dst, &dstsize, data, width, height); + break; + case 24: + rc = lodepng_encode24(&dst, &dstsize, data, width, height); + break; + default: + break; + } + if (rc) + return NULL; + *pSize = (UINT32)dstsize; + return dst; + } +#else + return NULL; +#endif +} + +SSIZE_T winpr_convert_from_png(const BYTE* comp_data, size_t comp_data_bytes, UINT32* width, + UINT32* height, UINT32* bpp, BYTE** ppdecomp_data) +{ +#if defined(WINPR_UTILS_IMAGE_PNG) + size_t len = 0; + *ppdecomp_data = + winpr_read_png_from_buffer(comp_data, comp_data_bytes, &len, width, height, bpp); + if (!*ppdecomp_data) + return -1; + return (SSIZE_T)len; +#elif defined(WITH_LODEPNG) + *bpp = 32; + return lodepng_decode32((unsigned char**)ppdecomp_data, width, height, comp_data, + comp_data_bytes); +#else + return -1; +#endif +} + +BOOL winpr_image_format_is_supported(UINT32 format) +{ + switch (format) + { + case WINPR_IMAGE_BITMAP: +#if defined(WINPR_UTILS_IMAGE_PNG) || defined(WITH_LODEPNG) + case WINPR_IMAGE_PNG: +#endif +#if defined(WINPR_UTILS_IMAGE_JPEG) + case WINPR_IMAGE_JPEG: +#endif +#if defined(WINPR_UTILS_IMAGE_WEBP) + case WINPR_IMAGE_WEBP: +#endif + return TRUE; + default: + return FALSE; + } +} + +static BYTE* convert(const wImage* image, size_t* pstride, UINT32 flags) +{ + WINPR_ASSERT(image); + WINPR_ASSERT(pstride); + + *pstride = 0; + if (image->bitsPerPixel < 24) + return NULL; + + const size_t stride = image->width * 4ull; + BYTE* data = calloc(stride, image->height); + if (data) + { + for (size_t y = 0; y < image->height; y++) + { + const BYTE* srcLine = &image->data[image->scanline * y]; + BYTE* dstLine = &data[stride * y]; + if (image->bitsPerPixel == 32) + memcpy(dstLine, srcLine, stride); + else + { + for (size_t x = 0; x < image->width; x++) + { + const BYTE* src = &srcLine[image->bytesPerPixel * x]; + BYTE* dst = &dstLine[4ull * x]; + BYTE b = *src++; + BYTE g = *src++; + BYTE r = *src++; + + *dst++ = b; + *dst++ = g; + *dst++ = r; + *dst++ = 0xff; + } + } + } + *pstride = stride; + } + return data; +} + +static BOOL compare_byte_relaxed(BYTE a, BYTE b, UINT32 flags) +{ + if (a != b) + { + if ((flags & WINPR_IMAGE_CMP_FUZZY) != 0) + { + const int diff = abs((int)a) - abs((int)b); + /* filter out quantization errors */ + if (diff > 6) + return FALSE; + } + else + { + return FALSE; + } + } + return TRUE; +} + +static BOOL compare_pixel(const BYTE* pa, const BYTE* pb, UINT32 flags) +{ + WINPR_ASSERT(pa); + WINPR_ASSERT(pb); + + if (!compare_byte_relaxed(*pa++, *pb++, flags)) + return FALSE; + if (!compare_byte_relaxed(*pa++, *pb++, flags)) + return FALSE; + if (!compare_byte_relaxed(*pa++, *pb++, flags)) + return FALSE; + if ((flags & WINPR_IMAGE_CMP_IGNORE_ALPHA) == 0) + { + if (!compare_byte_relaxed(*pa++, *pb++, flags)) + return FALSE; + } + return TRUE; +} + +BOOL winpr_image_equal(const wImage* imageA, const wImage* imageB, UINT32 flags) +{ + if (imageA == imageB) + return TRUE; + if (!imageA || !imageB) + return FALSE; + + if (imageA->height != imageB->height) + return FALSE; + if (imageA->width != imageB->width) + return FALSE; + + if ((flags & WINPR_IMAGE_CMP_IGNORE_DEPTH) == 0) + { + if (imageA->bitsPerPixel != imageB->bitsPerPixel) + return FALSE; + if (imageA->bytesPerPixel != imageB->bytesPerPixel) + return FALSE; + } + + BOOL rc = FALSE; + size_t astride = 0; + size_t bstride = 0; + BYTE* dataA = convert(imageA, &astride, flags); + BYTE* dataB = convert(imageA, &bstride, flags); + if (dataA && dataB && (astride == bstride)) + { + rc = TRUE; + for (size_t y = 0; y < imageA->height; y++) + { + const BYTE* lineA = &dataA[astride * y]; + const BYTE* lineB = &dataB[bstride * y]; + + for (size_t x = 0; x < imageA->width; x++) + { + const BYTE* pa = &lineA[x * 4ull]; + const BYTE* pb = &lineB[x * 4ull]; + + if (!compare_pixel(pa, pb, flags)) + rc = FALSE; + } + } + } + free(dataA); + free(dataB); + return rc; +} + +const char* winpr_image_format_mime(UINT32 format) +{ + switch (format) + { + case WINPR_IMAGE_BITMAP: + return "image/bmp"; + case WINPR_IMAGE_PNG: + return "image/png"; + case WINPR_IMAGE_WEBP: + return "image/webp"; + case WINPR_IMAGE_JPEG: + return "image/jpeg"; + default: + return NULL; + } +} + +const char* winpr_image_format_extension(UINT32 format) +{ + switch (format) + { + case WINPR_IMAGE_BITMAP: + return "bmp"; + case WINPR_IMAGE_PNG: + return "png"; + case WINPR_IMAGE_WEBP: + return "webp"; + case WINPR_IMAGE_JPEG: + return "jpg"; + default: + return NULL; + } +} + +void* winpr_image_write_buffer(wImage* image, UINT32 format, size_t* psize) +{ + WINPR_ASSERT(image); + switch (format) + { + case WINPR_IMAGE_BITMAP: + { + UINT32 outsize = 0; + size_t size = 1ull * image->height * image->scanline; + void* data = winpr_bitmap_write_buffer(image->data, size, image->width, image->height, + image->scanline, image->bitsPerPixel, &outsize); + *psize = outsize; + return data; + } + case WINPR_IMAGE_WEBP: + { + UINT32 outsize = 0; + size_t size = 1ull * image->height * image->scanline; + void* data = winpr_convert_to_webp(image->data, size, image->width, image->height, + image->scanline, image->bitsPerPixel, &outsize); + *psize = outsize; + return data; + } + case WINPR_IMAGE_JPEG: + { + UINT32 outsize = 0; + size_t size = 1ull * image->height * image->scanline; + void* data = winpr_convert_to_jpeg(image->data, size, image->width, image->height, + image->scanline, image->bitsPerPixel, &outsize); + *psize = outsize; + return data; + } + case WINPR_IMAGE_PNG: + { + UINT32 outsize = 0; + size_t size = 1ull * image->height * image->scanline; + void* data = winpr_convert_to_png(image->data, size, image->width, image->height, + image->scanline, image->bitsPerPixel, &outsize); + *psize = outsize; + return data; + } + default: + *psize = 0; + return NULL; + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.h new file mode 100644 index 0000000000000000000000000000000000000000..81233ae5b8024e7e44adad357b71ea1fe42cc197 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/image.h @@ -0,0 +1,34 @@ +/* + * WinPR: Windows Portable Runtime + * Image Utils + * + * Copyright 2024 Armin Novak + * 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 LIBWINPR_UTILS_IMAGE_H +#define LIBWINPR_UTILS_IMAGE_H + +#include +#include +#include + +BOOL readBitmapFileHeader(wStream* s, WINPR_BITMAP_FILE_HEADER* bf); +BOOL writeBitmapFileHeader(wStream* s, const WINPR_BITMAP_FILE_HEADER* bf); + +BOOL readBitmapInfoHeader(wStream* s, WINPR_BITMAP_INFO_HEADER* bi, size_t* poffset); +BOOL writeBitmapInfoHeader(wStream* s, const WINPR_BITMAP_INFO_HEADER* bi); + +#endif /* LIBWINPR_UTILS_IMAGE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ini.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ini.c new file mode 100644 index 0000000000000000000000000000000000000000..8fec31f1e41fbb334f44fa200069d7136d75e781 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ini.c @@ -0,0 +1,885 @@ +/** + * WinPR: Windows Portable Runtime + * .ini config file + * + * Copyright 2014 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include + +typedef struct +{ + char* name; + char* value; +} wIniFileKey; + +typedef struct +{ + char* name; + size_t nKeys; + size_t cKeys; + wIniFileKey** keys; +} wIniFileSection; + +struct s_wIniFile +{ + char* line; + char* nextLine; + size_t lineLength; + char* tokctx; + char* buffer; + size_t buffersize; + char* filename; + BOOL readOnly; + size_t nSections; + size_t cSections; + wIniFileSection** sections; +}; + +static BOOL IniFile_Load_NextLine(wIniFile* ini, char* str) +{ + size_t length = 0; + + WINPR_ASSERT(ini); + + ini->nextLine = strtok_s(str, "\n", &ini->tokctx); + + if (ini->nextLine) + length = strlen(ini->nextLine); + + if (length > 0) + { + if (ini->nextLine[length - 1] == '\r') + { + ini->nextLine[length - 1] = '\0'; + length--; + } + + if (length < 1) + ini->nextLine = NULL; + } + + return (ini->nextLine) ? TRUE : FALSE; +} + +static BOOL IniFile_BufferResize(wIniFile* ini, size_t size) +{ + WINPR_ASSERT(ini); + if (size > ini->buffersize) + { + const size_t diff = size - ini->buffersize; + char* tmp = realloc(ini->buffer, size); + if (!tmp) + return FALSE; + + memset(&tmp[ini->buffersize], 0, diff * sizeof(char)); + ini->buffer = tmp; + ini->buffersize = size; + } + return TRUE; +} + +static BOOL IniFile_Load_String(wIniFile* ini, const char* iniString) +{ + size_t fileSize = 0; + + WINPR_ASSERT(ini); + + if (!iniString) + return FALSE; + + ini->line = NULL; + ini->nextLine = NULL; + fileSize = strlen(iniString); + + if (fileSize < 1) + return FALSE; + + if (!IniFile_BufferResize(ini, fileSize + 2)) + return FALSE; + + CopyMemory(ini->buffer, iniString, fileSize); + ini->buffer[fileSize] = '\n'; + IniFile_Load_NextLine(ini, ini->buffer); + return TRUE; +} + +static void IniFile_Close_File(FILE* fp) +{ + if (fp) + (void)fclose(fp); +} + +static FILE* IniFile_Open_File(wIniFile* ini, const char* filename) +{ + WINPR_ASSERT(ini); + + if (!filename) + return FALSE; + + if (ini->readOnly) + return winpr_fopen(filename, "rb"); + else + return winpr_fopen(filename, "w+b"); +} + +static BOOL IniFile_Load_File(wIniFile* ini, const char* filename) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(ini); + + FILE* fp = IniFile_Open_File(ini, filename); + if (!fp) + return FALSE; + + if (_fseeki64(fp, 0, SEEK_END) < 0) + goto out_file; + + const INT64 fileSize = _ftelli64(fp); + + if (fileSize < 0) + goto out_file; + + if (_fseeki64(fp, 0, SEEK_SET) < 0) + goto out_file; + + ini->line = NULL; + ini->nextLine = NULL; + + if (fileSize < 1) + goto out_file; + + if (!IniFile_BufferResize(ini, (size_t)fileSize + 2)) + goto out_file; + + if (fread(ini->buffer, (size_t)fileSize, 1ul, fp) != 1) + goto out_file; + + ini->buffer[fileSize] = '\n'; + IniFile_Load_NextLine(ini, ini->buffer); + rc = TRUE; + +out_file: + IniFile_Close_File(fp); + return rc; +} + +static BOOL IniFile_Load_HasNextLine(wIniFile* ini) +{ + WINPR_ASSERT(ini); + + return (ini->nextLine) ? TRUE : FALSE; +} + +static char* IniFile_Load_GetNextLine(wIniFile* ini) +{ + WINPR_ASSERT(ini); + + ini->line = ini->nextLine; + ini->lineLength = strlen(ini->line); + IniFile_Load_NextLine(ini, NULL); + return ini->line; +} + +static void IniFile_Key_Free(wIniFileKey* key) +{ + if (!key) + return; + + free(key->name); + free(key->value); + free(key); +} + +static wIniFileKey* IniFile_Key_New(const char* name, const char* value) +{ + if (!name || !value) + return NULL; + + wIniFileKey* key = calloc(1, sizeof(wIniFileKey)); + + if (key) + { + key->name = _strdup(name); + key->value = _strdup(value); + + if (!key->name || !key->value) + { + IniFile_Key_Free(key); + return NULL; + } + } + + return key; +} + +static void IniFile_Section_Free(wIniFileSection* section) +{ + if (!section) + return; + + free(section->name); + + for (size_t index = 0; index < section->nKeys; index++) + { + IniFile_Key_Free(section->keys[index]); + } + + free((void*)section->keys); + free(section); +} + +static BOOL IniFile_SectionKeysResize(wIniFileSection* section, size_t count) +{ + WINPR_ASSERT(section); + + if (section->nKeys + count >= section->cKeys) + { + const size_t new_size = section->cKeys + count + 1024; + const size_t diff = new_size - section->cKeys; + wIniFileKey** new_keys = + (wIniFileKey**)realloc((void*)section->keys, sizeof(wIniFileKey*) * new_size); + + if (!new_keys) + return FALSE; + + memset((void*)&new_keys[section->cKeys], 0, diff * sizeof(wIniFileKey*)); + section->cKeys = new_size; + section->keys = new_keys; + } + return TRUE; +} + +static wIniFileSection* IniFile_Section_New(const char* name) +{ + if (!name) + return NULL; + + wIniFileSection* section = calloc(1, sizeof(wIniFileSection)); + + if (!section) + goto fail; + + section->name = _strdup(name); + + if (!section->name) + goto fail; + + if (!IniFile_SectionKeysResize(section, 64)) + goto fail; + + return section; + +fail: + IniFile_Section_Free(section); + return NULL; +} + +static wIniFileSection* IniFile_GetSection(wIniFile* ini, const char* name) +{ + wIniFileSection* section = NULL; + + WINPR_ASSERT(ini); + + if (!name) + return NULL; + + for (size_t index = 0; index < ini->nSections; index++) + { + if (_stricmp(name, ini->sections[index]->name) == 0) + { + section = ini->sections[index]; + break; + } + } + + return section; +} + +static BOOL IniFile_SectionResize(wIniFile* ini, size_t count) +{ + WINPR_ASSERT(ini); + + if (ini->nSections + count >= ini->cSections) + { + const size_t new_size = ini->cSections + count + 1024; + const size_t diff = new_size - ini->cSections; + wIniFileSection** new_sect = + (wIniFileSection**)realloc((void*)ini->sections, sizeof(wIniFileSection*) * new_size); + + if (!new_sect) + return FALSE; + + memset((void*)&new_sect[ini->cSections], 0, diff * sizeof(wIniFileSection*)); + ini->cSections = new_size; + ini->sections = new_sect; + } + return TRUE; +} + +static wIniFileSection* IniFile_AddToSection(wIniFile* ini, const char* name) +{ + WINPR_ASSERT(ini); + + if (!name) + return NULL; + + wIniFileSection* section = IniFile_GetSection(ini, name); + + if (!section) + { + if (!IniFile_SectionResize(ini, 1)) + return NULL; + + section = IniFile_Section_New(name); + if (!section) + return NULL; + ini->sections[ini->nSections++] = section; + } + + return section; +} + +static wIniFileKey* IniFile_GetKey(wIniFileSection* section, const char* name) +{ + wIniFileKey* key = NULL; + + WINPR_ASSERT(section); + + if (!name) + return NULL; + + for (size_t index = 0; index < section->nKeys; index++) + { + if (_stricmp(name, section->keys[index]->name) == 0) + { + key = section->keys[index]; + break; + } + } + + return key; +} + +static wIniFileKey* IniFile_AddKey(wIniFileSection* section, const char* name, const char* value) +{ + WINPR_ASSERT(section); + + if (!name || !value) + return NULL; + + wIniFileKey* key = IniFile_GetKey(section, name); + + if (!key) + { + if (!IniFile_SectionKeysResize(section, 1)) + return NULL; + + key = IniFile_Key_New(name, value); + + if (!key) + return NULL; + + section->keys[section->nKeys++] = key; + } + else + { + free(key->value); + key->value = _strdup(value); + + if (!key->value) + return NULL; + } + + return key; +} + +static int IniFile_Load(wIniFile* ini) +{ + char* name = NULL; + char* value = NULL; + char* separator = NULL; + char* beg = NULL; + char* end = NULL; + wIniFileSection* section = NULL; + + WINPR_ASSERT(ini); + + while (IniFile_Load_HasNextLine(ini)) + { + char* line = IniFile_Load_GetNextLine(ini); + + if (line[0] == ';') + continue; + + if (line[0] == '[') + { + beg = &line[1]; + end = strchr(line, ']'); + + if (!end) + return -1; + + *end = '\0'; + IniFile_AddToSection(ini, beg); + section = ini->sections[ini->nSections - 1]; + } + else + { + separator = strchr(line, '='); + + if (separator == NULL) + return -1; + + end = separator; + + while ((&end[-1] > line) && ((end[-1] == ' ') || (end[-1] == '\t'))) + end--; + + *end = '\0'; + name = line; + beg = separator + 1; + + while (*beg && ((*beg == ' ') || (*beg == '\t'))) + beg++; + + if (*beg == '"') + beg++; + + end = &line[ini->lineLength]; + + while ((end > beg) && ((end[-1] == ' ') || (end[-1] == '\t'))) + end--; + + if (end[-1] == '"') + end[-1] = '\0'; + + value = beg; + + if (!IniFile_AddKey(section, name, value)) + return -1; + } + } + + return 1; +} + +static BOOL IniFile_SetFilename(wIniFile* ini, const char* name) +{ + WINPR_ASSERT(ini); + free(ini->filename); + ini->filename = NULL; + + if (!name) + return TRUE; + ini->filename = _strdup(name); + return ini->filename != NULL; +} + +int IniFile_ReadBuffer(wIniFile* ini, const char* buffer) +{ + BOOL status = 0; + + WINPR_ASSERT(ini); + + if (!buffer) + return -1; + + ini->readOnly = TRUE; + status = IniFile_Load_String(ini, buffer); + + if (!status) + return -1; + + return IniFile_Load(ini); +} + +int IniFile_ReadFile(wIniFile* ini, const char* filename) +{ + WINPR_ASSERT(ini); + + ini->readOnly = TRUE; + if (!IniFile_SetFilename(ini, filename)) + return -1; + if (!ini->filename) + return -1; + + if (!IniFile_Load_File(ini, filename)) + return -1; + + return IniFile_Load(ini); +} + +char** IniFile_GetSectionNames(wIniFile* ini, size_t* count) +{ + WINPR_ASSERT(ini); + + if (!count) + return NULL; + + if (ini->nSections > INT_MAX) + return NULL; + + size_t length = (sizeof(char*) * ini->nSections) + sizeof(char); + + for (size_t index = 0; index < ini->nSections; index++) + { + wIniFileSection* section = ini->sections[index]; + const size_t nameLength = strlen(section->name); + length += (nameLength + 1); + } + + char** sectionNames = (char**)calloc(length, sizeof(char*)); + + if (!sectionNames) + return NULL; + + char* p = (char*)&((BYTE*)sectionNames)[sizeof(char*) * ini->nSections]; + + for (size_t index = 0; index < ini->nSections; index++) + { + sectionNames[index] = p; + wIniFileSection* section = ini->sections[index]; + const size_t nameLength = strlen(section->name); + CopyMemory(p, section->name, nameLength + 1); + p += (nameLength + 1); + } + + *p = '\0'; + *count = ini->nSections; + return sectionNames; +} + +char** IniFile_GetSectionKeyNames(wIniFile* ini, const char* section, size_t* count) +{ + WINPR_ASSERT(ini); + + if (!section || !count) + return NULL; + + wIniFileSection* pSection = IniFile_GetSection(ini, section); + + if (!pSection) + return NULL; + + if (pSection->nKeys > INT_MAX) + return NULL; + + size_t length = (sizeof(char*) * pSection->nKeys) + sizeof(char); + + for (size_t index = 0; index < pSection->nKeys; index++) + { + wIniFileKey* pKey = pSection->keys[index]; + const size_t nameLength = strlen(pKey->name); + length += (nameLength + 1); + } + + char** keyNames = (char**)calloc(length, sizeof(char*)); + + if (!keyNames) + return NULL; + + char* p = (char*)&((BYTE*)keyNames)[sizeof(char*) * pSection->nKeys]; + + for (size_t index = 0; index < pSection->nKeys; index++) + { + keyNames[index] = p; + wIniFileKey* pKey = pSection->keys[index]; + const size_t nameLength = strlen(pKey->name); + CopyMemory(p, pKey->name, nameLength + 1); + p += (nameLength + 1); + } + + *p = '\0'; + *count = pSection->nKeys; + return keyNames; +} + +const char* IniFile_GetKeyValueString(wIniFile* ini, const char* section, const char* key) +{ + const char* value = NULL; + wIniFileKey* pKey = NULL; + wIniFileSection* pSection = NULL; + + WINPR_ASSERT(ini); + + pSection = IniFile_GetSection(ini, section); + + if (!pSection) + return NULL; + + pKey = IniFile_GetKey(pSection, key); + + if (!pKey) + return NULL; + + value = (const char*)pKey->value; + return value; +} + +int IniFile_GetKeyValueInt(wIniFile* ini, const char* section, const char* key) +{ + int err = 0; + long value = 0; + wIniFileKey* pKey = NULL; + wIniFileSection* pSection = NULL; + + WINPR_ASSERT(ini); + + pSection = IniFile_GetSection(ini, section); + + if (!pSection) + return 0; + + pKey = IniFile_GetKey(pSection, key); + + if (!pKey) + return 0; + + err = errno; + errno = 0; + value = strtol(pKey->value, NULL, 0); + if ((value < INT_MIN) || (value > INT_MAX) || (errno != 0)) + { + errno = err; + return 0; + } + return (int)value; +} + +int IniFile_SetKeyValueString(wIniFile* ini, const char* section, const char* key, + const char* value) +{ + wIniFileKey* pKey = NULL; + + WINPR_ASSERT(ini); + wIniFileSection* pSection = IniFile_GetSection(ini, section); + + if (!pSection) + pSection = IniFile_AddToSection(ini, section); + + if (!pSection) + return -1; + + pKey = IniFile_AddKey(pSection, key, value); + + if (!pKey) + return -1; + + return 1; +} + +int IniFile_SetKeyValueInt(wIniFile* ini, const char* section, const char* key, int value) +{ + char strVal[128] = { 0 }; + wIniFileKey* pKey = NULL; + wIniFileSection* pSection = NULL; + + WINPR_ASSERT(ini); + + (void)sprintf_s(strVal, sizeof(strVal), "%d", value); + pSection = IniFile_GetSection(ini, section); + + if (!pSection) + pSection = IniFile_AddToSection(ini, section); + + if (!pSection) + return -1; + + pKey = IniFile_AddKey(pSection, key, strVal); + + if (!pKey) + return -1; + + return 1; +} + +char* IniFile_WriteBuffer(wIniFile* ini) +{ + size_t offset = 0; + size_t size = 0; + char* buffer = NULL; + + WINPR_ASSERT(ini); + + for (size_t i = 0; i < ini->nSections; i++) + { + wIniFileSection* section = ini->sections[i]; + size += (strlen(section->name) + 3); + + for (size_t j = 0; j < section->nKeys; j++) + { + wIniFileKey* key = section->keys[j]; + size += (strlen(key->name) + strlen(key->value) + 2); + } + + size += 1; + } + + size += 1; + buffer = calloc(size + 1, sizeof(char)); + + if (!buffer) + return NULL; + + offset = 0; + + for (size_t i = 0; i < ini->nSections; i++) + { + wIniFileSection* section = ini->sections[i]; + (void)sprintf_s(&buffer[offset], size - offset, "[%s]\n", section->name); + offset += (strlen(section->name) + 3); + + for (size_t j = 0; j < section->nKeys; j++) + { + wIniFileKey* key = section->keys[j]; + (void)sprintf_s(&buffer[offset], size - offset, "%s=%s\n", key->name, key->value); + offset += (strlen(key->name) + strlen(key->value) + 2); + } + + (void)sprintf_s(&buffer[offset], size - offset, "\n"); + offset += 1; + } + + return buffer; +} + +int IniFile_WriteFile(wIniFile* ini, const char* filename) +{ + int ret = -1; + + WINPR_ASSERT(ini); + + char* buffer = IniFile_WriteBuffer(ini); + + if (!buffer) + return -1; + + const size_t length = strlen(buffer); + ini->readOnly = FALSE; + + if (!filename) + filename = ini->filename; + + FILE* fp = IniFile_Open_File(ini, filename); + if (!fp) + goto fail; + + if (fwrite((void*)buffer, length, 1, fp) != 1) + goto fail; + + ret = 1; + +fail: + IniFile_Close_File(fp); + free(buffer); + return ret; +} + +void IniFile_Free(wIniFile* ini) +{ + if (!ini) + return; + + IniFile_SetFilename(ini, NULL); + + for (size_t index = 0; index < ini->nSections; index++) + IniFile_Section_Free(ini->sections[index]); + + free((void*)ini->sections); + free(ini->buffer); + free(ini); +} + +wIniFile* IniFile_New(void) +{ + wIniFile* ini = (wIniFile*)calloc(1, sizeof(wIniFile)); + + if (!ini) + goto fail; + + if (!IniFile_SectionResize(ini, 64)) + goto fail; + + return ini; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + IniFile_Free(ini); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +wIniFile* IniFile_Clone(const wIniFile* ini) +{ + if (!ini) + return NULL; + + wIniFile* copy = IniFile_New(); + if (!copy) + goto fail; + + copy->lineLength = ini->lineLength; + if (!IniFile_SetFilename(copy, ini->filename)) + goto fail; + + if (ini->buffersize > 0) + { + if (!IniFile_BufferResize(copy, ini->buffersize)) + goto fail; + memcpy(copy->buffer, ini->buffer, copy->buffersize); + } + + copy->readOnly = ini->readOnly; + + for (size_t x = 0; x < ini->nSections; x++) + { + const wIniFileSection* cur = ini->sections[x]; + if (!cur) + goto fail; + + wIniFileSection* scopy = IniFile_AddToSection(copy, cur->name); + if (!scopy) + goto fail; + + for (size_t y = 0; y < cur->nKeys; y++) + { + const wIniFileKey* key = cur->keys[y]; + if (!key) + goto fail; + + IniFile_AddKey(scopy, key->name, key->value); + } + } + return copy; + +fail: + IniFile_Free(copy); + return NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/json/json.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/json/json.c new file mode 100644 index 0000000000000000000000000000000000000000..3fc99dfa03002fedcda56ab3a9073e250806525a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/json/json.c @@ -0,0 +1,675 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * JSON parser wrapper + * + * Copyright 2024 Armin Novak + * 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 +#include + +#include +#include + +#if defined(WITH_CJSON) +#include +#endif +#if defined(WITH_JSONC) +#include +#endif + +#if defined(WITH_CJSON) +#if CJSON_VERSION_MAJOR == 1 +#if CJSON_VERSION_MINOR <= 7 +#if CJSON_VERSION_PATCH < 13 +#define USE_CJSON_COMPAT +#endif +#endif +#endif +#endif + +#if defined(WITH_JSONC) +#if JSON_C_MAJOR_VERSION == 0 +#if JSON_C_MINOR_VERSION < 14 +static struct json_object* json_object_new_null(void) +{ + return NULL; +} +#endif +#endif +#endif + +#if defined(USE_CJSON_COMPAT) +static double cJSON_GetNumberValue(const cJSON* prop) +{ +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#define COMPAT_NAN_UNDEF +#else +#define NAN 0.0 / 0.0 +#define COMPAT_NAN_UNDEF +#endif +#endif + + if (!cJSON_IsNumber(prop)) + return NAN; + char* val = cJSON_GetStringValue(prop); + if (!val) + return NAN; + + errno = 0; + char* endptr = NULL; + double dval = strtod(val, &endptr); + if (val == endptr) + return NAN; + if (endptr != NULL) + return NAN; + if (errno != 0) + return NAN; + return dval; + +#ifdef COMPAT_NAN_UNDEF +#undef NAN +#endif +} + +static cJSON* cJSON_ParseWithLength(const char* value, size_t buffer_length) +{ + // Check for string '\0' termination. + const size_t slen = strnlen(value, buffer_length); + if (slen >= buffer_length) + { + if (value[buffer_length] != '\0') + return NULL; + } + return cJSON_Parse(value); +} +#endif + +int WINPR_JSON_version(char* buffer, size_t len) +{ +#if defined(WITH_JSONC) + return _snprintf(buffer, len, "json-c %s", json_c_version()); +#elif defined(WITH_CJSON) + return _snprintf(buffer, len, "cJSON %s", cJSON_Version()); +#else + return _snprintf(buffer, len, "JSON support not available"); +#endif +} + +WINPR_JSON* WINPR_JSON_Parse(const char* value) +{ +#if defined(WITH_JSONC) + return json_tokener_parse(value); +#elif defined(WITH_CJSON) + return cJSON_Parse(value); +#else + WINPR_UNUSED(value); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_ParseWithLength(const char* value, size_t buffer_length) +{ +#if defined(WITH_JSONC) + WINPR_ASSERT(buffer_length <= INT_MAX); + json_tokener* tok = json_tokener_new(); + if (!tok) + return NULL; + json_object* obj = json_tokener_parse_ex(tok, value, (int)buffer_length); + json_tokener_free(tok); + return obj; +#elif defined(WITH_CJSON) + return cJSON_ParseWithLength(value, buffer_length); +#else + WINPR_UNUSED(value); + WINPR_UNUSED(buffer_length); + return NULL; +#endif +} + +void WINPR_JSON_Delete(WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + json_object_put((json_object*)item); +#elif defined(WITH_CJSON) + cJSON_Delete((cJSON*)item); +#else + WINPR_UNUSED(item); +#endif +} + +WINPR_JSON* WINPR_JSON_GetArrayItem(const WINPR_JSON* array, size_t index) +{ +#if defined(WITH_JSONC) + return json_object_array_get_idx((const json_object*)array, index); +#elif defined(WITH_CJSON) + WINPR_ASSERT(index <= INT_MAX); + return cJSON_GetArrayItem((const cJSON*)array, (INT)index); +#else + WINPR_UNUSED(array); + WINPR_UNUSED(index); + return NULL; +#endif +} + +size_t WINPR_JSON_GetArraySize(const WINPR_JSON* array) +{ +#if defined(WITH_JSONC) + return json_object_array_length((const json_object*)array); +#elif defined(WITH_CJSON) + const int rc = cJSON_GetArraySize((const cJSON*)array); + if (rc <= 0) + return 0; + return (size_t)rc; +#else + WINPR_UNUSED(array); + return 0; +#endif +} + +WINPR_JSON* WINPR_JSON_GetObjectItem(const WINPR_JSON* object, const char* string) +{ +#if defined(WITH_JSONC) + return json_object_object_get((const json_object*)object, string); +#elif defined(WITH_CJSON) + return cJSON_GetObjectItem((const cJSON*)object, string); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(string); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_GetObjectItemCaseSensitive(const WINPR_JSON* object, const char* string) +{ +#if defined(WITH_JSONC) + return json_object_object_get((const json_object*)object, string); +#elif defined(WITH_CJSON) + return cJSON_GetObjectItemCaseSensitive((const cJSON*)object, string); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(string); + return NULL; +#endif +} + +BOOL WINPR_JSON_HasObjectItem(const WINPR_JSON* object, const char* string) +{ +#if defined(WITH_JSONC) + return json_object_object_get_ex((const json_object*)object, string, NULL); +#elif defined(WITH_CJSON) + return cJSON_HasObjectItem((const cJSON*)object, string); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(string); + return FALSE; +#endif +} + +const char* WINPR_JSON_GetErrorPtr(void) +{ +#if defined(WITH_JSONC) + return json_util_get_last_err(); +#elif defined(WITH_CJSON) + return cJSON_GetErrorPtr(); +#else + return NULL; +#endif +} + +const char* WINPR_JSON_GetStringValue(WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_get_string((json_object*)item); +#elif defined(WITH_CJSON) + return cJSON_GetStringValue((cJSON*)item); +#else + WINPR_UNUSED(item); + return NULL; +#endif +} + +double WINPR_JSON_GetNumberValue(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_get_double((const json_object*)item); +#elif defined(WITH_CJSON) + return cJSON_GetNumberValue((const cJSON*)item); +#else + WINPR_UNUSED(item); + return nan(""); +#endif +} + +BOOL WINPR_JSON_IsInvalid(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + if (WINPR_JSON_IsArray(item)) + return FALSE; + if (WINPR_JSON_IsObject(item)) + return FALSE; + if (WINPR_JSON_IsNull(item)) + return FALSE; + if (WINPR_JSON_IsNumber(item)) + return FALSE; + if (WINPR_JSON_IsBool(item)) + return FALSE; + if (WINPR_JSON_IsString(item)) + return FALSE; + return TRUE; +#elif defined(WITH_CJSON) + return cJSON_IsInvalid((const cJSON*)item); +#else + WINPR_UNUSED(item); + return TRUE; +#endif +} + +BOOL WINPR_JSON_IsFalse(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + if (!json_object_is_type((const json_object*)item, json_type_boolean)) + return FALSE; + json_bool val = json_object_get_boolean((const json_object*)item); + return val == 0; +#elif defined(WITH_CJSON) + return cJSON_IsFalse((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsTrue(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + if (!json_object_is_type((const json_object*)item, json_type_boolean)) + return FALSE; + json_bool val = json_object_get_boolean((const json_object*)item); + return val != 0; +#elif defined(WITH_CJSON) + return cJSON_IsTrue((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsBool(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_boolean); +#elif defined(WITH_CJSON) + return cJSON_IsBool((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsNull(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_null); +#elif defined(WITH_CJSON) + return cJSON_IsNull((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsNumber(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_int) || + json_object_is_type((const json_object*)item, json_type_double); +#elif defined(WITH_CJSON) + return cJSON_IsNumber((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsString(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_string); +#elif defined(WITH_CJSON) + return cJSON_IsString((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsArray(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_array); +#elif defined(WITH_CJSON) + return cJSON_IsArray((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +BOOL WINPR_JSON_IsObject(const WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + return json_object_is_type((const json_object*)item, json_type_object); +#elif defined(WITH_CJSON) + return cJSON_IsObject((const cJSON*)item); +#else + WINPR_UNUSED(item); + return FALSE; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateNull(void) +{ +#if defined(WITH_JSONC) + return json_object_new_null(); +#elif defined(WITH_CJSON) + return cJSON_CreateNull(); +#else + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateTrue(void) +{ +#if defined(WITH_JSONC) + return json_object_new_boolean(TRUE); +#elif defined(WITH_CJSON) + return cJSON_CreateTrue(); +#else + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateFalse(void) +{ +#if defined(WITH_JSONC) + return json_object_new_boolean(FALSE); +#elif defined(WITH_CJSON) + return cJSON_CreateFalse(); +#else + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateBool(BOOL boolean) +{ +#if defined(WITH_JSONC) + return json_object_new_boolean(boolean); +#elif defined(WITH_CJSON) + return cJSON_CreateBool(boolean); +#else + WINPR_UNUSED(boolean); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateNumber(double num) +{ +#if defined(WITH_JSONC) + return json_object_new_double(num); +#elif defined(WITH_CJSON) + return cJSON_CreateNumber(num); +#else + WINPR_UNUSED(num); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateString(const char* string) +{ +#if defined(WITH_JSONC) + return json_object_new_string(string); +#elif defined(WITH_CJSON) + return cJSON_CreateString(string); +#else + WINPR_UNUSED(string); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateArray(void) +{ +#if defined(WITH_JSONC) + return json_object_new_array(); +#elif defined(WITH_CJSON) + return cJSON_CreateArray(); +#else + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_CreateObject(void) +{ +#if defined(WITH_JSONC) + return json_object_new_object(); +#elif defined(WITH_CJSON) + return cJSON_CreateObject(); +#else + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddNullToObject(WINPR_JSON* object, const char* name) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_null(); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddNullToObject((cJSON*)object, name); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddTrueToObject(WINPR_JSON* object, const char* name) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_boolean(TRUE); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddTrueToObject((cJSON*)object, name); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddFalseToObject(WINPR_JSON* object, const char* name) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_boolean(FALSE); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddFalseToObject((cJSON*)object, name); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddBoolToObject(WINPR_JSON* object, const char* name, BOOL boolean) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_boolean(boolean); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddBoolToObject((cJSON*)object, name, boolean); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + WINPR_UNUSED(boolean); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddNumberToObject(WINPR_JSON* object, const char* name, double number) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_double(number); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddNumberToObject((cJSON*)object, name, number); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + WINPR_UNUSED(number); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddStringToObject(WINPR_JSON* object, const char* name, const char* string) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_string(string); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddStringToObject((cJSON*)object, name, string); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + WINPR_UNUSED(string); + return NULL; +#endif +} + +WINPR_JSON* WINPR_JSON_AddObjectToObject(WINPR_JSON* object, const char* name) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_object(); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddObjectToObject((cJSON*)object, name); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + return NULL; +#endif +} + +BOOL WINPR_JSON_AddItemToArray(WINPR_JSON* array, WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + const int rc = json_object_array_add((json_object*)array, (json_object*)item); + if (rc != 0) + return FALSE; + return TRUE; +#elif defined(WITH_CJSON) + return cJSON_AddItemToArray((cJSON*)array, (cJSON*)item); +#else + WINPR_UNUSED(array); + WINPR_UNUSED(item); + return FALSE; +#endif +} + +WINPR_JSON* WINPR_JSON_AddArrayToObject(WINPR_JSON* object, const char* name) +{ +#if defined(WITH_JSONC) + struct json_object* obj = json_object_new_array(); + if (json_object_object_add((json_object*)object, name, obj) != 0) + { + json_object_put(obj); + return NULL; + } + return obj; +#elif defined(WITH_CJSON) + return cJSON_AddArrayToObject((cJSON*)object, name); +#else + WINPR_UNUSED(object); + WINPR_UNUSED(name); + return NULL; +#endif +} + +char* WINPR_JSON_Print(WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + const char* str = json_object_to_json_string_ext((json_object*)item, JSON_C_TO_STRING_PRETTY); + if (!str) + return NULL; + return _strdup(str); +#elif defined(WITH_CJSON) + return cJSON_Print((const cJSON*)item); +#else + WINPR_UNUSED(item); + return NULL; +#endif +} + +char* WINPR_JSON_PrintUnformatted(WINPR_JSON* item) +{ +#if defined(WITH_JSONC) + const char* str = json_object_to_json_string_ext((json_object*)item, JSON_C_TO_STRING_PLAIN); + if (!str) + return NULL; + return _strdup(str); +#elif defined(WITH_CJSON) + return cJSON_PrintUnformatted((const cJSON*)item); +#else + WINPR_UNUSED(item); + return NULL; +#endif +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ntlm.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ntlm.c new file mode 100644 index 0000000000000000000000000000000000000000..25e0e5a595cce70c2eea65fb03f5bc06ee2b95ee --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ntlm.c @@ -0,0 +1,182 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include + +#include +#include + +/** + * Define NTOWFv1(Password, User, Domain) as + * MD4(UNICODE(Password)) + * EndDefine + */ + +BOOL NTOWFv1W(LPWSTR Password, UINT32 PasswordLength, BYTE* NtHash) +{ + if (!Password || !NtHash) + return FALSE; + + if (!winpr_Digest(WINPR_MD_MD4, (BYTE*)Password, (size_t)PasswordLength, NtHash, + WINPR_MD4_DIGEST_LENGTH)) + return FALSE; + + return TRUE; +} + +BOOL NTOWFv1A(LPSTR Password, UINT32 PasswordLength, BYTE* NtHash) +{ + LPWSTR PasswordW = NULL; + BOOL result = FALSE; + size_t pwdCharLength = 0; + + if (!NtHash) + return FALSE; + + PasswordW = ConvertUtf8NToWCharAlloc(Password, PasswordLength, &pwdCharLength); + if (!PasswordW) + return FALSE; + + if (!NTOWFv1W(PasswordW, (UINT32)pwdCharLength * sizeof(WCHAR), NtHash)) + goto out_fail; + + result = TRUE; +out_fail: + free(PasswordW); + return result; +} + +/** + * Define NTOWFv2(Password, User, Domain) as + * HMAC_MD5(MD4(UNICODE(Password)), + * UNICODE(ConcatenationOf(UpperCase(User), Domain))) + * EndDefine + */ + +BOOL NTOWFv2W(LPWSTR Password, UINT32 PasswordLength, LPWSTR User, UINT32 UserLength, LPWSTR Domain, + UINT32 DomainLength, BYTE* NtHash) +{ + BYTE NtHashV1[WINPR_MD5_DIGEST_LENGTH]; + + if ((!User) || (!Password) || (!NtHash)) + return FALSE; + + if (!NTOWFv1W(Password, PasswordLength, NtHashV1)) + return FALSE; + + return NTOWFv2FromHashW(NtHashV1, User, UserLength, Domain, DomainLength, NtHash); +} + +BOOL NTOWFv2A(LPSTR Password, UINT32 PasswordLength, LPSTR User, UINT32 UserLength, LPSTR Domain, + UINT32 DomainLength, BYTE* NtHash) +{ + LPWSTR UserW = NULL; + LPWSTR DomainW = NULL; + LPWSTR PasswordW = NULL; + BOOL result = FALSE; + size_t userCharLength = 0; + size_t domainCharLength = 0; + size_t pwdCharLength = 0; + + if (!NtHash) + return FALSE; + + UserW = ConvertUtf8NToWCharAlloc(User, UserLength, &userCharLength); + DomainW = ConvertUtf8NToWCharAlloc(Domain, DomainLength, &domainCharLength); + PasswordW = ConvertUtf8NToWCharAlloc(Password, PasswordLength, &pwdCharLength); + + if (!UserW || !DomainW || !PasswordW) + goto out_fail; + + if (!NTOWFv2W(PasswordW, (UINT32)pwdCharLength * sizeof(WCHAR), UserW, + (UINT32)userCharLength * sizeof(WCHAR), DomainW, + (UINT32)domainCharLength * sizeof(WCHAR), NtHash)) + goto out_fail; + + result = TRUE; +out_fail: + free(UserW); + free(DomainW); + free(PasswordW); + return result; +} + +BOOL NTOWFv2FromHashW(BYTE* NtHashV1, LPWSTR User, UINT32 UserLength, LPWSTR Domain, + UINT32 DomainLength, BYTE* NtHash) +{ + BYTE* buffer = NULL; + BYTE result = FALSE; + + if (!User || !NtHash) + return FALSE; + + if (!(buffer = (BYTE*)malloc(UserLength + DomainLength))) + return FALSE; + + /* Concatenate(UpperCase(User), Domain) */ + CopyMemory(buffer, User, UserLength); + CharUpperBuffW((LPWSTR)buffer, UserLength / 2); + + if (DomainLength > 0) + { + CopyMemory(&buffer[UserLength], Domain, DomainLength); + } + + /* Compute the HMAC-MD5 hash of the above value using the NTLMv1 hash as the key, the result is + * the NTLMv2 hash */ + if (!winpr_HMAC(WINPR_MD_MD5, NtHashV1, 16, buffer, UserLength + DomainLength, NtHash, + WINPR_MD5_DIGEST_LENGTH)) + goto out_fail; + + result = TRUE; +out_fail: + free(buffer); + return result; +} + +BOOL NTOWFv2FromHashA(BYTE* NtHashV1, LPSTR User, UINT32 UserLength, LPSTR Domain, + UINT32 DomainLength, BYTE* NtHash) +{ + LPWSTR UserW = NULL; + LPWSTR DomainW = NULL; + BOOL result = FALSE; + size_t userCharLength = 0; + size_t domainCharLength = 0; + if (!NtHash) + return FALSE; + + UserW = ConvertUtf8NToWCharAlloc(User, UserLength, &userCharLength); + DomainW = ConvertUtf8NToWCharAlloc(Domain, DomainLength, &domainCharLength); + + if (!UserW || !DomainW) + goto out_fail; + + if (!NTOWFv2FromHashW(NtHashV1, UserW, (UINT32)userCharLength * sizeof(WCHAR), DomainW, + (UINT32)domainCharLength * sizeof(WCHAR), NtHash)) + goto out_fail; + + result = TRUE; +out_fail: + free(UserW); + free(DomainW); + return result; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/print.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/print.c new file mode 100644 index 0000000000000000000000000000000000000000..4ab89edeb62e7e46b237fcaf9ab09a2cc9cc3216 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/print.c @@ -0,0 +1,262 @@ +/** + * WinPR: Windows Portable Runtime + * Print Utils + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include +#include + +#include +#include + +#include "../log.h" + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +void winpr_HexDump(const char* tag, UINT32 level, const void* data, size_t length) +{ + wLog* log = WLog_Get(tag); + winpr_HexLogDump(log, level, data, length); +} + +void winpr_HexLogDump(wLog* log, UINT32 level, const void* data, size_t length) +{ + const BYTE* p = data; + size_t line = 0; + size_t offset = 0; + const size_t maxlen = 20; /* 64bit SIZE_MAX as decimal */ + /* String line length: + * prefix '[1234] ' + * hexdump '01 02 03 04' + * separator ' ' + * ASIC line 'ab..cd' + * zero terminator '\0' + */ + const size_t blen = (maxlen + 3ULL) + (WINPR_HEXDUMP_LINE_LENGTH * 3ULL) + 3ULL + + WINPR_HEXDUMP_LINE_LENGTH + 1ULL; + size_t pos = 0; + + char* buffer = NULL; + + if (!WLog_IsLevelActive(log, level)) + return; + + if (!log) + return; + + buffer = malloc(blen); + + if (!buffer) + { + char ebuffer[256] = { 0 }; + WLog_Print(log, WLOG_ERROR, "malloc(%" PRIuz ") failed with [%" PRIuz "] %s", blen, errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return; + } + + while (offset < length) + { + int rc = _snprintf(&buffer[pos], blen - pos, "%04" PRIuz " ", offset); + + if (rc < 0) + goto fail; + + pos += (size_t)rc; + line = length - offset; + + if (line > WINPR_HEXDUMP_LINE_LENGTH) + line = WINPR_HEXDUMP_LINE_LENGTH; + + size_t i = 0; + for (; i < line; i++) + { + rc = _snprintf(&buffer[pos], blen - pos, "%02" PRIx8 " ", p[i]); + + if (rc < 0) + goto fail; + + pos += (size_t)rc; + } + + for (; i < WINPR_HEXDUMP_LINE_LENGTH; i++) + { + rc = _snprintf(&buffer[pos], blen - pos, " "); + + if (rc < 0) + goto fail; + + pos += (size_t)rc; + } + + for (size_t j = 0; j < line; j++) + { + rc = _snprintf(&buffer[pos], blen - pos, "%c", + (p[j] >= 0x20 && p[j] < 0x7F) ? (char)p[j] : '.'); + + if (rc < 0) + goto fail; + + pos += (size_t)rc; + } + + WLog_Print(log, level, "%s", buffer); + offset += line; + p += line; + pos = 0; + } + + WLog_Print(log, level, "[length=%" PRIuz "] ", length); +fail: + free(buffer); +} + +void winpr_CArrayDump(const char* tag, UINT32 level, const void* data, size_t length, size_t width) +{ + const BYTE* p = data; + size_t offset = 0; + const size_t llen = ((length > width) ? width : length) * 4ull + 1ull; + size_t pos = 0; + char* buffer = malloc(llen); + + if (!buffer) + { + char ebuffer[256] = { 0 }; + WLog_ERR(tag, "malloc(%" PRIuz ") failed with [%d] %s", llen, errno, + winpr_strerror(errno, ebuffer, sizeof(ebuffer))); + return; + } + + while (offset < length) + { + size_t line = length - offset; + + if (line > width) + line = width; + + pos = 0; + + for (size_t i = 0; i < line; i++) + { + const int rc = _snprintf(&buffer[pos], llen - pos, "\\x%02" PRIX8 "", p[i]); + if (rc < 0) + goto fail; + pos += (size_t)rc; + } + + WLog_LVL(tag, level, "%s", buffer); + offset += line; + p += line; + } + +fail: + free(buffer); +} + +static BYTE value(char c) +{ + if ((c >= '0') && (c <= '9')) + return (c - '0') & 0xFF; + if ((c >= 'A') && (c <= 'F')) + return (10 + c - 'A') & 0xFF; + if ((c >= 'a') && (c <= 'f')) + return (10 + c - 'a') & 0xFF; + return 0; +} + +size_t winpr_HexStringToBinBuffer(const char* str, size_t strLength, BYTE* data, size_t dataLength) +{ + size_t y = 0; + size_t maxStrLen = 0; + if (!str || !data || (strLength == 0) || (dataLength == 0)) + return 0; + + maxStrLen = strnlen(str, strLength); + for (size_t x = 0; x < maxStrLen;) + { + BYTE val = value(str[x++]); + if (x < maxStrLen) + val = (BYTE)(val << 4) | (value(str[x++])); + if (x < maxStrLen) + { + if (str[x] == ' ') + x++; + } + data[y++] = val; + if (y >= dataLength) + return y; + } + return y; +} + +size_t winpr_BinToHexStringBuffer(const BYTE* data, size_t length, char* dstStr, size_t dstSize, + BOOL space) +{ + const size_t n = space ? 3 : 2; + const char bin2hex[] = "0123456789ABCDEF"; + const size_t maxLength = MIN(length, dstSize / n); + + if (!data || !dstStr || (length == 0) || (dstSize == 0)) + return 0; + + for (size_t i = 0; i < maxLength; i++) + { + const int ln = data[i] & 0xF; + const int hn = (data[i] >> 4) & 0xF; + char* dst = &dstStr[i * n]; + + dst[0] = bin2hex[hn]; + dst[1] = bin2hex[ln]; + + if (space) + dst[2] = ' '; + } + + if (space && (maxLength > 0)) + { + dstStr[maxLength * n - 1] = '\0'; + return maxLength * n - 1; + } + dstStr[maxLength * n] = '\0'; + return maxLength * n; +} + +char* winpr_BinToHexString(const BYTE* data, size_t length, BOOL space) +{ + size_t rc = 0; + const size_t n = space ? 3 : 2; + const size_t size = (length + 1ULL) * n; + char* p = (char*)malloc(size); + + if (!p) + return NULL; + + rc = winpr_BinToHexStringBuffer(data, length, p, size, space); + if (rc == 0) + { + free(p); + return NULL; + } + + return p; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/sam.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/sam.c new file mode 100644 index 0000000000000000000000000000000000000000..eef08fe7a15bc661613e3277f0256f9f0682c354 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/sam.c @@ -0,0 +1,377 @@ +/** + * WinPR: Windows Portable Runtime + * Security Accounts Manager (SAM) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "../log.h" + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif + +#define TAG WINPR_TAG("utils") + +struct winpr_sam +{ + FILE* fp; + char* line; + char* buffer; + char* context; + BOOL readOnly; +}; + +static WINPR_SAM_ENTRY* SamEntryFromDataA(LPCSTR User, DWORD UserLength, LPCSTR Domain, + DWORD DomainLength) +{ + WINPR_SAM_ENTRY* entry = calloc(1, sizeof(WINPR_SAM_ENTRY)); + if (!entry) + return NULL; + if (User && (UserLength > 0)) + entry->User = _strdup(User); + entry->UserLength = UserLength; + if (Domain && (DomainLength > 0)) + entry->Domain = _strdup(Domain); + entry->DomainLength = DomainLength; + return entry; +} + +static BOOL SamAreEntriesEqual(const WINPR_SAM_ENTRY* a, const WINPR_SAM_ENTRY* b) +{ + if (!a || !b) + return FALSE; + if (a->UserLength != b->UserLength) + return FALSE; + if (a->DomainLength != b->DomainLength) + return FALSE; + if (a->UserLength > 0) + { + if (!a->User || !b->User) + return FALSE; + if (strncmp(a->User, b->User, a->UserLength) != 0) + return FALSE; + } + if (a->DomainLength > 0) + { + if (!a->Domain || !b->Domain) + return FALSE; + if (strncmp(a->Domain, b->Domain, a->DomainLength) != 0) + return FALSE; + } + return TRUE; +} + +WINPR_SAM* SamOpen(const char* filename, BOOL readOnly) +{ + FILE* fp = NULL; + WINPR_SAM* sam = NULL; + char* allocatedFileName = NULL; + + if (!filename) + { + allocatedFileName = winpr_GetConfigFilePath(TRUE, "SAM"); + filename = allocatedFileName; + } + + if (readOnly) + fp = winpr_fopen(filename, "r"); + else + { + fp = winpr_fopen(filename, "r+"); + + if (!fp) + fp = winpr_fopen(filename, "w+"); + } + free(allocatedFileName); + + if (fp) + { + sam = (WINPR_SAM*)calloc(1, sizeof(WINPR_SAM)); + + if (!sam) + { + (void)fclose(fp); + return NULL; + } + + sam->readOnly = readOnly; + sam->fp = fp; + } + else + { + WLog_DBG(TAG, "Could not open SAM file!"); + return NULL; + } + + return sam; +} + +static BOOL SamLookupStart(WINPR_SAM* sam) +{ + size_t readSize = 0; + INT64 fileSize = 0; + + if (!sam || !sam->fp) + return FALSE; + + if (_fseeki64(sam->fp, 0, SEEK_END) != 0) + return FALSE; + fileSize = _ftelli64(sam->fp); + if (_fseeki64(sam->fp, 0, SEEK_SET) != 0) + return FALSE; + + if (fileSize < 1) + return FALSE; + + sam->context = NULL; + sam->buffer = (char*)calloc((size_t)fileSize + 2, 1); + + if (!sam->buffer) + return FALSE; + + readSize = fread(sam->buffer, (size_t)fileSize, 1, sam->fp); + + if (!readSize) + { + if (!ferror(sam->fp)) + readSize = (size_t)fileSize; + } + + if (readSize < 1) + { + free(sam->buffer); + sam->buffer = NULL; + return FALSE; + } + + sam->buffer[fileSize] = '\n'; + sam->buffer[fileSize + 1] = '\0'; + sam->line = strtok_s(sam->buffer, "\n", &sam->context); + return TRUE; +} + +static void SamLookupFinish(WINPR_SAM* sam) +{ + free(sam->buffer); + sam->buffer = NULL; + sam->line = NULL; +} + +static BOOL SamReadEntry(WINPR_SAM* sam, WINPR_SAM_ENTRY* entry) +{ + char* p[5] = { 0 }; + size_t count = 0; + + if (!sam || !entry || !sam->line) + return FALSE; + + char* cur = sam->line; + + while ((cur = strchr(cur, ':')) != NULL) + { + count++; + cur++; + } + + if (count < 4) + return FALSE; + + p[0] = sam->line; + p[1] = strchr(p[0], ':') + 1; + p[2] = strchr(p[1], ':') + 1; + p[3] = strchr(p[2], ':') + 1; + p[4] = strchr(p[3], ':') + 1; + const size_t LmHashLength = WINPR_ASSERTING_INT_CAST(size_t, (p[3] - p[2] - 1)); + const size_t NtHashLength = WINPR_ASSERTING_INT_CAST(size_t, (p[4] - p[3] - 1)); + + if ((LmHashLength != 0) && (LmHashLength != 32)) + return FALSE; + + if ((NtHashLength != 0) && (NtHashLength != 32)) + return FALSE; + + entry->UserLength = (UINT32)(p[1] - p[0] - 1); + entry->User = (LPSTR)malloc(entry->UserLength + 1); + + if (!entry->User) + return FALSE; + + entry->User[entry->UserLength] = '\0'; + entry->DomainLength = (UINT32)(p[2] - p[1] - 1); + memcpy(entry->User, p[0], entry->UserLength); + + if (entry->DomainLength > 0) + { + entry->Domain = (LPSTR)malloc(entry->DomainLength + 1); + + if (!entry->Domain) + { + free(entry->User); + entry->User = NULL; + return FALSE; + } + + memcpy(entry->Domain, p[1], entry->DomainLength); + entry->Domain[entry->DomainLength] = '\0'; + } + else + entry->Domain = NULL; + + if (LmHashLength == 32) + winpr_HexStringToBinBuffer(p[2], LmHashLength, entry->LmHash, sizeof(entry->LmHash)); + + if (NtHashLength == 32) + winpr_HexStringToBinBuffer(p[3], NtHashLength, (BYTE*)entry->NtHash, sizeof(entry->NtHash)); + + return TRUE; +} + +void SamFreeEntry(WINPR_SAM* sam, WINPR_SAM_ENTRY* entry) +{ + if (entry) + { + if (entry->UserLength > 0) + free(entry->User); + + if (entry->DomainLength > 0) + free(entry->Domain); + + free(entry); + } +} + +void SamResetEntry(WINPR_SAM_ENTRY* entry) +{ + if (!entry) + return; + + if (entry->UserLength) + { + free(entry->User); + entry->User = NULL; + } + + if (entry->DomainLength) + { + free(entry->Domain); + entry->Domain = NULL; + } + + ZeroMemory(entry->LmHash, sizeof(entry->LmHash)); + ZeroMemory(entry->NtHash, sizeof(entry->NtHash)); +} + +WINPR_SAM_ENTRY* SamLookupUserA(WINPR_SAM* sam, LPCSTR User, UINT32 UserLength, LPCSTR Domain, + UINT32 DomainLength) +{ + size_t length = 0; + BOOL found = FALSE; + WINPR_SAM_ENTRY* search = SamEntryFromDataA(User, UserLength, Domain, DomainLength); + WINPR_SAM_ENTRY* entry = (WINPR_SAM_ENTRY*)calloc(1, sizeof(WINPR_SAM_ENTRY)); + + if (!entry || !search) + goto fail; + + if (!SamLookupStart(sam)) + goto fail; + + while (sam->line != NULL) + { + length = strlen(sam->line); + + if (length > 1) + { + if (sam->line[0] != '#') + { + if (!SamReadEntry(sam, entry)) + { + goto out_fail; + } + + if (SamAreEntriesEqual(entry, search)) + { + found = 1; + break; + } + } + } + + SamResetEntry(entry); + sam->line = strtok_s(NULL, "\n", &sam->context); + } + +out_fail: + SamLookupFinish(sam); +fail: + SamFreeEntry(sam, search); + + if (!found) + { + SamFreeEntry(sam, entry); + return NULL; + } + + return entry; +} + +WINPR_SAM_ENTRY* SamLookupUserW(WINPR_SAM* sam, LPCWSTR User, UINT32 UserLength, LPCWSTR Domain, + UINT32 DomainLength) +{ + WINPR_SAM_ENTRY* entry = NULL; + char* utfUser = NULL; + char* utfDomain = NULL; + size_t userCharLen = 0; + size_t domainCharLen = 0; + + utfUser = ConvertWCharNToUtf8Alloc(User, UserLength / sizeof(WCHAR), &userCharLen); + if (!utfUser) + goto fail; + if (DomainLength > 0) + { + utfDomain = ConvertWCharNToUtf8Alloc(Domain, DomainLength / sizeof(WCHAR), &domainCharLen); + if (!utfDomain) + goto fail; + } + entry = SamLookupUserA(sam, utfUser, (UINT32)userCharLen, utfDomain, (UINT32)domainCharLen); +fail: + free(utfUser); + free(utfDomain); + return entry; +} + +void SamClose(WINPR_SAM* sam) +{ + if (sam != NULL) + { + if (sam->fp) + (void)fclose(sam->fp); + free(sam); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ssl.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ssl.c new file mode 100644 index 0000000000000000000000000000000000000000..c4ab6e3e09ef3dee82505d92970f192d6865e56b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/ssl.c @@ -0,0 +1,447 @@ +/** + * WinPR: Windows Portable Runtime + * OpenSSL Library Initialization + * + * Copyright 2014 Thincast Technologies GmbH + * Copyright 2014 Norbert Federa + * + * 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 + +#include +#include +#include +#include +#include + +#ifdef WITH_OPENSSL + +#include +#include + +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) +#include +#endif + +#include "../log.h" +#define TAG WINPR_TAG("utils.ssl") + +static BOOL g_winpr_openssl_initialized_by_winpr = FALSE; + +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) +static OSSL_PROVIDER* s_winpr_openssl_provider_fips = NULL; +static OSSL_PROVIDER* s_winpr_openssl_provider_legacy = NULL; +static OSSL_PROVIDER* s_winpr_openssl_provider_default = NULL; +#endif + +/** + * Note from OpenSSL 1.1.0 "CHANGES": + * OpenSSL now uses a new threading API. It is no longer necessary to + * set locking callbacks to use OpenSSL in a multi-threaded environment. + */ + +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + +#define WINPR_OPENSSL_LOCKING_REQUIRED 1 + +static int g_winpr_openssl_num_locks = 0; +static HANDLE* g_winpr_openssl_locks = NULL; + +struct CRYPTO_dynlock_value +{ + HANDLE mutex; +}; + +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || defined(LIBRESSL_VERSION_NUMBER) +static unsigned long _winpr_openssl_id(void) +{ + return (unsigned long)GetCurrentThreadId(); +} +#endif + +static void _winpr_openssl_locking(int mode, int type, const char* file, int line) +{ + if (mode & CRYPTO_LOCK) + { + (void)WaitForSingleObject(g_winpr_openssl_locks[type], INFINITE); + } + else + { + (void)ReleaseMutex(g_winpr_openssl_locks[type]); + } +} + +static struct CRYPTO_dynlock_value* _winpr_openssl_dynlock_create(const char* file, int line) +{ + struct CRYPTO_dynlock_value* dynlock; + + if (!(dynlock = (struct CRYPTO_dynlock_value*)malloc(sizeof(struct CRYPTO_dynlock_value)))) + return NULL; + + if (!(dynlock->mutex = CreateMutex(NULL, FALSE, NULL))) + { + free(dynlock); + return NULL; + } + + return dynlock; +} + +static void _winpr_openssl_dynlock_lock(int mode, struct CRYPTO_dynlock_value* dynlock, + const char* file, int line) +{ + if (mode & CRYPTO_LOCK) + { + (void)WaitForSingleObject(dynlock->mutex, INFINITE); + } + else + { + (void)ReleaseMutex(dynlock->mutex); + } +} + +static void _winpr_openssl_dynlock_destroy(struct CRYPTO_dynlock_value* dynlock, const char* file, + int line) +{ + (void)CloseHandle(dynlock->mutex); + free(dynlock); +} + +static BOOL _winpr_openssl_initialize_locking(void) +{ + int count; + + /* OpenSSL static locking */ + + if (CRYPTO_get_locking_callback()) + { + WLog_WARN(TAG, "OpenSSL static locking callback is already set"); + } + else + { + if ((count = CRYPTO_num_locks()) > 0) + { + HANDLE* locks; + + if (!(locks = calloc(count, sizeof(HANDLE)))) + { + WLog_ERR(TAG, "error allocating lock table"); + return FALSE; + } + + for (int i = 0; i < count; i++) + { + if (!(locks[i] = CreateMutex(NULL, FALSE, NULL))) + { + WLog_ERR(TAG, "error creating lock #%d", i); + + while (i--) + { + if (locks[i]) + (void)CloseHandle(locks[i]); + } + + free(locks); + return FALSE; + } + } + + g_winpr_openssl_locks = locks; + g_winpr_openssl_num_locks = count; + CRYPTO_set_locking_callback(_winpr_openssl_locking); + } + } + + /* OpenSSL dynamic locking */ + + if (CRYPTO_get_dynlock_create_callback() || CRYPTO_get_dynlock_lock_callback() || + CRYPTO_get_dynlock_destroy_callback()) + { + WLog_WARN(TAG, "dynamic locking callbacks are already set"); + } + else + { + CRYPTO_set_dynlock_create_callback(_winpr_openssl_dynlock_create); + CRYPTO_set_dynlock_lock_callback(_winpr_openssl_dynlock_lock); + CRYPTO_set_dynlock_destroy_callback(_winpr_openssl_dynlock_destroy); + } + + /* Use the deprecated CRYPTO_get_id_callback() if building against OpenSSL < 1.0.0 */ +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || defined(LIBRESSL_VERSION_NUMBER) + + if (CRYPTO_get_id_callback()) + { + WLog_WARN(TAG, "OpenSSL id_callback is already set"); + } + else + { + CRYPTO_set_id_callback(_winpr_openssl_id); + } + +#endif + return TRUE; +} + +static BOOL _winpr_openssl_cleanup_locking(void) +{ + /* undo our static locking modifications */ + if (CRYPTO_get_locking_callback() == _winpr_openssl_locking) + { + CRYPTO_set_locking_callback(NULL); + + for (int i = 0; i < g_winpr_openssl_num_locks; i++) + { + (void)CloseHandle(g_winpr_openssl_locks[i]); + } + + g_winpr_openssl_num_locks = 0; + free(g_winpr_openssl_locks); + g_winpr_openssl_locks = NULL; + } + + /* unset our dynamic locking callbacks */ + + if (CRYPTO_get_dynlock_create_callback() == _winpr_openssl_dynlock_create) + { + CRYPTO_set_dynlock_create_callback(NULL); + } + + if (CRYPTO_get_dynlock_lock_callback() == _winpr_openssl_dynlock_lock) + { + CRYPTO_set_dynlock_lock_callback(NULL); + } + + if (CRYPTO_get_dynlock_destroy_callback() == _winpr_openssl_dynlock_destroy) + { + CRYPTO_set_dynlock_destroy_callback(NULL); + } + +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || defined(LIBRESSL_VERSION_NUMBER) + + if (CRYPTO_get_id_callback() == _winpr_openssl_id) + { + CRYPTO_set_id_callback(NULL); + } + +#endif + return TRUE; +} + +#endif /* OpenSSL < 1.1.0 */ + +static BOOL winpr_enable_fips(DWORD flags) +{ + if (flags & WINPR_SSL_INIT_ENABLE_FIPS) + { +#if (OPENSSL_VERSION_NUMBER < 0x10001000L) || defined(LIBRESSL_VERSION_NUMBER) + WLog_ERR(TAG, "Openssl fips mode not available on openssl versions less than 1.0.1!"); + return FALSE; +#else + WLog_DBG(TAG, "Ensuring openssl fips mode is enabled"); + +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) + s_winpr_openssl_provider_fips = OSSL_PROVIDER_load(NULL, "fips"); + if (s_winpr_openssl_provider_fips == NULL) + { + WLog_WARN(TAG, "OpenSSL FIPS provider failed to load"); + } + if (!EVP_default_properties_is_fips_enabled(NULL)) +#else + if (FIPS_mode() != 1) +#endif + { +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) + if (EVP_set_default_properties(NULL, "fips=yes")) +#else + if (FIPS_mode_set(1)) +#endif + WLog_INFO(TAG, "Openssl fips mode enabled!"); + else + { + WLog_ERR(TAG, "Openssl fips mode enable failed!"); + return FALSE; + } + } + +#endif + } + + return TRUE; +} + +static void winpr_openssl_cleanup(void) +{ + winpr_CleanupSSL(WINPR_SSL_INIT_DEFAULT); +} + +static BOOL CALLBACK winpr_openssl_initialize(PINIT_ONCE once, PVOID param, PVOID* context) +{ + DWORD flags = param ? *(PDWORD)param : WINPR_SSL_INIT_DEFAULT; + + if (flags & WINPR_SSL_INIT_ALREADY_INITIALIZED) + { + return TRUE; + } + +#ifdef WINPR_OPENSSL_LOCKING_REQUIRED + + if (flags & WINPR_SSL_INIT_ENABLE_LOCKING) + { + if (!_winpr_openssl_initialize_locking()) + { + return FALSE; + } + } + +#endif + /* SSL_load_error_strings() is void */ +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + SSL_load_error_strings(); + /* SSL_library_init() always returns "1" */ + SSL_library_init(); + OpenSSL_add_all_digests(); + OpenSSL_add_all_ciphers(); +#else + + if (OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS | + OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS | + OPENSSL_INIT_ENGINE_ALL_BUILTIN, + NULL) != 1) + return FALSE; + +#endif + +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) + /* The legacy provider is needed for MD4. */ + s_winpr_openssl_provider_legacy = OSSL_PROVIDER_load(NULL, "legacy"); + if (s_winpr_openssl_provider_legacy == NULL) + { + WLog_WARN(TAG, "OpenSSL LEGACY provider failed to load, no md4 support available!"); + } + s_winpr_openssl_provider_default = OSSL_PROVIDER_load(NULL, "default"); + if (s_winpr_openssl_provider_default == NULL) + { + WLog_WARN(TAG, "OpenSSL DEFAULT provider failed to load"); + } +#endif + + (void)atexit(winpr_openssl_cleanup); + g_winpr_openssl_initialized_by_winpr = TRUE; + return TRUE; +} + +/* exported functions */ + +BOOL winpr_InitializeSSL(DWORD flags) +{ + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + + if (!InitOnceExecuteOnce(&once, winpr_openssl_initialize, &flags, NULL)) + return FALSE; + + return winpr_enable_fips(flags); +} + +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) +static int unload(OSSL_PROVIDER* provider, void* data) +{ + if (!provider) + return 1; + const char* name = OSSL_PROVIDER_get0_name(provider); + if (!name) + return 1; + + OSSL_LIB_CTX* ctx = OSSL_LIB_CTX_get0_global_default(); + const int rc = OSSL_PROVIDER_available(ctx, name); + if (rc < 1) + return 1; + OSSL_PROVIDER_unload(provider); + return 1; +} +#endif + +BOOL winpr_CleanupSSL(DWORD flags) +{ + if (flags & WINPR_SSL_CLEANUP_GLOBAL) + { + if (!g_winpr_openssl_initialized_by_winpr) + { + WLog_WARN(TAG, "ssl was not initialized by winpr"); + return FALSE; + } + + g_winpr_openssl_initialized_by_winpr = FALSE; +#ifdef WINPR_OPENSSL_LOCKING_REQUIRED + _winpr_openssl_cleanup_locking(); +#endif +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + CRYPTO_cleanup_all_ex_data(); + ERR_free_strings(); + EVP_cleanup(); +#endif +#ifdef WINPR_OPENSSL_LOCKING_REQUIRED + flags |= WINPR_SSL_CLEANUP_THREAD; +#endif + } + +#ifdef WINPR_OPENSSL_LOCKING_REQUIRED + + if (flags & WINPR_SSL_CLEANUP_THREAD) + { +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) || defined(LIBRESSL_VERSION_NUMBER) + ERR_remove_state(0); +#else + ERR_remove_thread_state(NULL); +#endif + } + +#endif +#if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) + OSSL_LIB_CTX* ctx = OSSL_LIB_CTX_get0_global_default(); + OSSL_PROVIDER_do_all(ctx, unload, NULL); +#endif + + return TRUE; +} + +BOOL winpr_FIPSMode(void) +{ +#if (OPENSSL_VERSION_NUMBER < 0x10001000L) || defined(LIBRESSL_VERSION_NUMBER) + return FALSE; +#elif defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) + return (EVP_default_properties_is_fips_enabled(NULL) == 1); +#else + return (FIPS_mode() == 1); +#endif +} + +#else + +BOOL winpr_InitializeSSL(DWORD flags) +{ + return TRUE; +} + +BOOL winpr_CleanupSSL(DWORD flags) +{ + return TRUE; +} + +BOOL winpr_FIPSMode(void) +{ + return FALSE; +} + +#endif diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.c new file mode 100644 index 0000000000000000000000000000000000000000..145b54f5eff13a840aaee07f2c3732ca5f3d0165 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.c @@ -0,0 +1,523 @@ +/* + * WinPR: Windows Portable Runtime + * Stream Utils + * + * Copyright 2011 Vic Lee + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "stream.h" +#include "../log.h" + +#define STREAM_TAG WINPR_TAG("wStream") + +#define STREAM_ASSERT(cond) \ + do \ + { \ + if (!(cond)) \ + { \ + WLog_FATAL(STREAM_TAG, "%s [%s:%s:%" PRIuz "]", #cond, __FILE__, __func__, \ + (size_t)__LINE__); \ + winpr_log_backtrace(STREAM_TAG, WLOG_FATAL, 20); \ + abort(); \ + } \ + } while (0) + +BOOL Stream_EnsureCapacity(wStream* s, size_t size) +{ + WINPR_ASSERT(s); + if (s->capacity < size) + { + size_t position = 0; + size_t old_capacity = 0; + size_t new_capacity = 0; + BYTE* new_buf = NULL; + + old_capacity = s->capacity; + new_capacity = old_capacity; + + do + { + new_capacity *= 2; + } while (new_capacity < size); + + position = Stream_GetPosition(s); + + if (!s->isOwner) + { + new_buf = (BYTE*)malloc(new_capacity); + CopyMemory(new_buf, s->buffer, s->capacity); + s->isOwner = TRUE; + } + else + { + new_buf = (BYTE*)realloc(s->buffer, new_capacity); + } + + if (!new_buf) + return FALSE; + s->buffer = new_buf; + s->capacity = new_capacity; + s->length = new_capacity; + ZeroMemory(&s->buffer[old_capacity], s->capacity - old_capacity); + + Stream_SetPosition(s, position); + } + return TRUE; +} + +BOOL Stream_EnsureRemainingCapacity(wStream* s, size_t size) +{ + if (Stream_GetPosition(s) + size > Stream_Capacity(s)) + return Stream_EnsureCapacity(s, Stream_Capacity(s) + size); + return TRUE; +} + +wStream* Stream_New(BYTE* buffer, size_t size) +{ + wStream* s = NULL; + + if (!buffer && !size) + return NULL; + + s = malloc(sizeof(wStream)); + if (!s) + return NULL; + + if (buffer) + s->buffer = buffer; + else + s->buffer = (BYTE*)malloc(size); + + if (!s->buffer) + { + free(s); + return NULL; + } + + s->pointer = s->buffer; + s->capacity = size; + s->length = size; + + s->pool = NULL; + s->count = 0; + s->isAllocatedStream = TRUE; + s->isOwner = TRUE; + return s; +} + +wStream* Stream_StaticConstInit(wStream* s, const BYTE* buffer, size_t size) +{ + union + { + BYTE* b; + const BYTE* cb; + } cnv; + + cnv.cb = buffer; + return Stream_StaticInit(s, cnv.b, size); +} + +wStream* Stream_StaticInit(wStream* s, BYTE* buffer, size_t size) +{ + const wStream empty = { 0 }; + + WINPR_ASSERT(s); + WINPR_ASSERT(buffer); + + *s = empty; + s->buffer = s->pointer = buffer; + s->capacity = s->length = size; + s->pool = NULL; + s->count = 0; + s->isAllocatedStream = FALSE; + s->isOwner = FALSE; + return s; +} + +void Stream_EnsureValidity(wStream* s) +{ + size_t cur = 0; + + STREAM_ASSERT(s); + STREAM_ASSERT(s->pointer >= s->buffer); + + cur = (size_t)(s->pointer - s->buffer); + STREAM_ASSERT(cur <= s->capacity); + STREAM_ASSERT(s->length <= s->capacity); +} + +void Stream_Free(wStream* s, BOOL bFreeBuffer) +{ + if (s) + { + Stream_EnsureValidity(s); + if (bFreeBuffer && s->isOwner) + free(s->buffer); + + if (s->isAllocatedStream) + free(s); + } +} + +BOOL Stream_SetLength(wStream* _s, size_t _l) +{ + if ((_l) > Stream_Capacity(_s)) + { + _s->length = 0; + return FALSE; + } + _s->length = _l; + return TRUE; +} + +BOOL Stream_SetPosition(wStream* _s, size_t _p) +{ + if ((_p) > Stream_Capacity(_s)) + { + _s->pointer = _s->buffer; + return FALSE; + } + _s->pointer = _s->buffer + (_p); + return TRUE; +} + +void Stream_SealLength(wStream* _s) +{ + size_t cur = 0; + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->buffer <= _s->pointer); + cur = (size_t)(_s->pointer - _s->buffer); + WINPR_ASSERT(cur <= _s->capacity); + if (cur <= _s->capacity) + _s->length = cur; + else + { + WLog_FATAL(STREAM_TAG, "wStream API misuse: stream was written out of bounds"); + winpr_log_backtrace(STREAM_TAG, WLOG_FATAL, 20); + _s->length = 0; + } +} + +#if defined(WITH_WINPR_DEPRECATED) +BOOL Stream_SetPointer(wStream* _s, BYTE* _p) +{ + WINPR_ASSERT(_s); + if (!_p || (_s->buffer > _p) || (_s->buffer + _s->capacity < _p)) + { + _s->pointer = _s->buffer; + return FALSE; + } + _s->pointer = _p; + return TRUE; +} + +BOOL Stream_SetBuffer(wStream* _s, BYTE* _b) +{ + WINPR_ASSERT(_s); + WINPR_ASSERT(_b); + + _s->buffer = _b; + _s->pointer = _b; + return _s->buffer != NULL; +} + +void Stream_SetCapacity(wStream* _s, size_t _c) +{ + WINPR_ASSERT(_s); + _s->capacity = _c; +} + +#endif + +size_t Stream_GetRemainingCapacity(const wStream* _s) +{ + size_t cur = 0; + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->buffer <= _s->pointer); + cur = (size_t)(_s->pointer - _s->buffer); + WINPR_ASSERT(cur <= _s->capacity); + if (cur > _s->capacity) + { + WLog_FATAL(STREAM_TAG, "wStream API misuse: stream was written out of bounds"); + winpr_log_backtrace(STREAM_TAG, WLOG_FATAL, 20); + return 0; + } + return (_s->capacity - cur); +} + +size_t Stream_GetRemainingLength(const wStream* _s) +{ + size_t cur = 0; + WINPR_ASSERT(_s); + WINPR_ASSERT(_s->buffer <= _s->pointer); + WINPR_ASSERT(_s->length <= _s->capacity); + cur = (size_t)(_s->pointer - _s->buffer); + WINPR_ASSERT(cur <= _s->length); + if (cur > _s->length) + { + WLog_FATAL(STREAM_TAG, "wStream API misuse: stream was read out of bounds"); + winpr_log_backtrace(STREAM_TAG, WLOG_FATAL, 20); + return 0; + } + return (_s->length - cur); +} + +BOOL Stream_Write_UTF16_String(wStream* s, const WCHAR* src, size_t length) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(src || (length == 0)); + if (!s || !src) + return FALSE; + + if (!Stream_CheckAndLogRequiredCapacityOfSize(STREAM_TAG, (s), length, sizeof(WCHAR))) + return FALSE; + + for (size_t x = 0; x < length; x++) + Stream_Write_UINT16(s, src[x]); + + return TRUE; +} + +BOOL Stream_Read_UTF16_String(wStream* s, WCHAR* dst, size_t length) +{ + WINPR_ASSERT(s); + WINPR_ASSERT(dst); + + if (!Stream_CheckAndLogRequiredLengthOfSize(STREAM_TAG, s, length, sizeof(WCHAR))) + return FALSE; + + for (size_t x = 0; x < length; x++) + Stream_Read_UINT16(s, dst[x]); + + return TRUE; +} + +BOOL Stream_CheckAndLogRequiredCapacityEx(const char* tag, DWORD level, wStream* s, size_t nmemb, + size_t size, const char* fmt, ...) +{ + WINPR_ASSERT(size != 0); + const size_t actual = Stream_GetRemainingCapacity(s) / size; + + if (actual < nmemb) + { + va_list args; + + va_start(args, fmt); + Stream_CheckAndLogRequiredCapacityExVa(tag, level, s, nmemb, size, fmt, args); + va_end(args); + + return FALSE; + } + return TRUE; +} + +BOOL Stream_CheckAndLogRequiredCapacityExVa(const char* tag, DWORD level, wStream* s, size_t nmemb, + size_t size, const char* fmt, va_list args) +{ + WINPR_ASSERT(size != 0); + const size_t actual = Stream_GetRemainingCapacity(s) / size; + + if (actual < nmemb) + return Stream_CheckAndLogRequiredCapacityWLogExVa(WLog_Get(tag), level, s, nmemb, size, fmt, + args); + return TRUE; +} + +WINPR_ATTR_FORMAT_ARG(6, 0) +BOOL Stream_CheckAndLogRequiredCapacityWLogExVa(wLog* log, DWORD level, wStream* s, size_t nmemb, + size_t size, WINPR_FORMAT_ARG const char* fmt, + va_list args) +{ + + WINPR_ASSERT(size != 0); + const size_t actual = Stream_GetRemainingCapacity(s) / size; + + if (actual < nmemb) + { + char prefix[1024] = { 0 }; + + (void)vsnprintf(prefix, sizeof(prefix), fmt, args); + + WLog_Print(log, level, + "[%s] invalid remaining capacity, got %" PRIuz ", require at least %" PRIu64 + " [element size=%" PRIuz "]", + prefix, actual, nmemb, size); + winpr_log_backtrace_ex(log, level, 20); + return FALSE; + } + return TRUE; +} + +WINPR_ATTR_FORMAT_ARG(6, 7) +BOOL Stream_CheckAndLogRequiredCapacityWLogEx(wLog* log, DWORD level, wStream* s, size_t nmemb, + size_t size, WINPR_FORMAT_ARG const char* fmt, ...) +{ + + WINPR_ASSERT(size != 0); + const size_t actual = Stream_GetRemainingCapacity(s) / size; + + if (actual < nmemb) + { + va_list args; + + va_start(args, fmt); + Stream_CheckAndLogRequiredCapacityWLogExVa(log, level, s, nmemb, size, fmt, args); + va_end(args); + + return FALSE; + } + return TRUE; +} + +WINPR_ATTR_FORMAT_ARG(6, 7) +BOOL Stream_CheckAndLogRequiredLengthEx(const char* tag, DWORD level, wStream* s, size_t nmemb, + size_t size, WINPR_FORMAT_ARG const char* fmt, ...) +{ + WINPR_ASSERT(size > 0); + const size_t actual = Stream_GetRemainingLength(s) / size; + + if (actual < nmemb) + { + va_list args; + + va_start(args, fmt); + Stream_CheckAndLogRequiredLengthExVa(tag, level, s, nmemb, size, fmt, args); + va_end(args); + + return FALSE; + } + return TRUE; +} + +BOOL Stream_CheckAndLogRequiredLengthExVa(const char* tag, DWORD level, wStream* s, size_t nmemb, + size_t size, const char* fmt, va_list args) +{ + WINPR_ASSERT(size > 0); + const size_t actual = Stream_GetRemainingLength(s) / size; + + if (actual < nmemb) + return Stream_CheckAndLogRequiredLengthWLogExVa(WLog_Get(tag), level, s, nmemb, size, fmt, + args); + return TRUE; +} + +BOOL Stream_CheckAndLogRequiredLengthWLogEx(wLog* log, DWORD level, wStream* s, size_t nmemb, + size_t size, const char* fmt, ...) +{ + WINPR_ASSERT(size > 0); + const size_t actual = Stream_GetRemainingLength(s) / size; + + if (actual < nmemb) + { + va_list args; + + va_start(args, fmt); + Stream_CheckAndLogRequiredLengthWLogExVa(log, level, s, nmemb, size, fmt, args); + va_end(args); + + return FALSE; + } + return TRUE; +} + +WINPR_ATTR_FORMAT_ARG(6, 0) +BOOL Stream_CheckAndLogRequiredLengthWLogExVa(wLog* log, DWORD level, wStream* s, size_t nmemb, + size_t size, WINPR_FORMAT_ARG const char* fmt, + va_list args) +{ + WINPR_ASSERT(size > 0); + const size_t actual = Stream_GetRemainingLength(s) / size; + + if (actual < nmemb) + { + char prefix[1024] = { 0 }; + + (void)vsnprintf(prefix, sizeof(prefix), fmt, args); + + WLog_Print(log, level, + "[%s] invalid length, got %" PRIuz ", require at least %" PRIuz + " [element size=%" PRIuz "]", + prefix, actual, nmemb, size); + winpr_log_backtrace_ex(log, level, 20); + return FALSE; + } + return TRUE; +} + +SSIZE_T Stream_Write_UTF16_String_From_UTF8(wStream* s, size_t wcharLength, const char* src, + size_t length, BOOL fill) +{ + WCHAR* str = Stream_PointerAs(s, WCHAR); + + if (length == 0) + return 0; + + if (!Stream_CheckAndLogRequiredCapacityOfSize(STREAM_TAG, s, wcharLength, sizeof(WCHAR))) + return -1; + + SSIZE_T rc = ConvertUtf8NToWChar(src, length, str, wcharLength); + if (rc < 0) + return -1; + + Stream_Seek(s, (size_t)rc * sizeof(WCHAR)); + + if (fill) + Stream_Zero(s, (wcharLength - (size_t)rc) * sizeof(WCHAR)); + return rc; +} + +char* Stream_Read_UTF16_String_As_UTF8(wStream* s, size_t wcharLength, size_t* pUtfCharLength) +{ + const WCHAR* str = Stream_ConstPointer(s); + if (wcharLength > SIZE_MAX / sizeof(WCHAR)) + return NULL; + + if (!Stream_CheckAndLogRequiredLength(STREAM_TAG, s, wcharLength * sizeof(WCHAR))) + return NULL; + + Stream_Seek(s, wcharLength * sizeof(WCHAR)); + return ConvertWCharNToUtf8Alloc(str, wcharLength, pUtfCharLength); +} + +SSIZE_T Stream_Read_UTF16_String_As_UTF8_Buffer(wStream* s, size_t wcharLength, char* utfBuffer, + size_t utfBufferCharLength) +{ + const WCHAR* ptr = Stream_ConstPointer(s); + if (wcharLength > SIZE_MAX / sizeof(WCHAR)) + return -1; + + if (!Stream_CheckAndLogRequiredLength(STREAM_TAG, s, wcharLength * sizeof(WCHAR))) + return -1; + + Stream_Seek(s, wcharLength * sizeof(WCHAR)); + return ConvertWCharNToUtf8(ptr, wcharLength, utfBuffer, utfBufferCharLength); +} + +BOOL Stream_SafeSeekEx(wStream* s, size_t size, const char* file, size_t line, const char* fkt) +{ + if (!Stream_CheckAndLogRequiredLengthEx(STREAM_TAG, WLOG_WARN, s, size, 1, "%s(%s:%" PRIuz ")", + fkt, file, line)) + return FALSE; + + Stream_Seek(s, size); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..cc4eb7cbd13db787abd437ea4cbbb1d64e1a8fee --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/stream.h @@ -0,0 +1,28 @@ +/* + * WinPR: Windows Portable Runtime + * Stream Utils + * + * Copyright 2021 Armin Novak + * 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. + */ + +#ifndef LIBWINPR_UTILS_STREAM_H +#define LIBWINPR_UTILS_STREAM_H + +#include + +void Stream_EnsureValidity(wStream* s); + +#endif /* LIBWINPR_UTILS_STREAM_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/strlst.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/strlst.c new file mode 100644 index 0000000000000000000000000000000000000000..44a2135383648135ecd9af2202d94a5fc86985c0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/strlst.c @@ -0,0 +1,74 @@ +/* + * String List Utils + * + * Copyright 2018 Pascal Bourguignon + * + * 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 + +#include +#include +#include + +#include +#include + +void string_list_free(char** string_list) +{ + for (size_t i = 0; string_list[i]; i++) + { + free(string_list[i]); + } + + free((void*)string_list); +} + +int string_list_length(const char** string_list) +{ + int i = 0; + for (; string_list[i]; i++) + ; + + return i; +} + +char** string_list_copy(const char** string_list) +{ + int length = string_list_length(string_list); + char** copy = (char**)calloc(WINPR_ASSERTING_INT_CAST(size_t, length) + 1, sizeof(char*)); + + if (!copy) + { + return 0; + } + + for (int i = 0; i < length; i++) + { + copy[i] = _strdup(string_list[i]); + } + + copy[length] = 0; + return copy; +} + +void string_list_print(FILE* out, const char** string_list) +{ + for (int j = 0; string_list[j]; j++) + { + (void)fprintf(out, "[%2d]: %s\n", j, string_list[j]); + } + + (void)fflush(out); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..24095718f5f8bed69fae7c5552567aa2d448d3ad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/CMakeLists.txt @@ -0,0 +1,52 @@ +set(MODULE_NAME "TestWinPRUtils") +set(MODULE_PREFIX "TEST_WINPR_UTILS") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS + TestIni.c + TestVersion.c + TestImage.c + TestBacktrace.c + TestQueue.c + TestPrint.c + TestPubSub.c + TestStream.c + TestBitStream.c + TestArrayList.c + TestLinkedList.c + TestListDictionary.c + TestCmdLine.c + TestASN1.c + TestWLog.c + TestWLogCallback.c + TestHashTable.c + TestBufferPool.c + TestStreamPool.c + TestMessageQueue.c + TestMessagePipe.c +) + +if(WITH_LODEPNG) + list(APPEND ${MODULES_PREFIX}_TESTS TestImage.c) +endif() + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_compile_definitions(TEST_SOURCE_PATH="${CMAKE_CURRENT_SOURCE_DIR}") +add_compile_definitions(TEST_BINARY_PATH="${CMAKE_CURRENT_BINARY_DIR}") + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestASN1.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestASN1.c new file mode 100644 index 0000000000000000000000000000000000000000..99d9e5db2835499113c9ccb28bf10cb92ea4ae57 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestASN1.c @@ -0,0 +1,347 @@ +#include +#include + +static const BYTE boolContent[] = { 0x01, 0x01, 0xFF }; +static const BYTE badBoolContent[] = { 0x01, 0x04, 0xFF }; + +static const BYTE integerContent[] = { 0x02, 0x01, 0x02 }; +static const BYTE badIntegerContent[] = { 0x02, 0x04, 0x02 }; +static const BYTE positiveIntegerContent[] = { 0x02, 0x02, 0x00, 0xff }; +static const BYTE negativeIntegerContent[] = { 0x02, 0x01, 0xff }; + +static const BYTE seqContent[] = { 0x30, 0x22, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x1B, 0x44, + 0x69, 0x67, 0x69, 0x74, 0x61, 0x6C, 0x20, 0x53, 0x69, 0x67, + 0x6E, 0x61, 0x74, 0x75, 0x72, 0x65, 0x20, 0x54, 0x72, 0x75, + 0x73, 0x74, 0x20, 0x43, 0x6F, 0x2E, 0x31 }; + +static const BYTE contextualInteger[] = { 0xA0, 0x03, 0x02, 0x01, 0x02 }; + +static const BYTE oidContent[] = { 0x06, 0x03, 0x55, 0x04, 0x0A }; +static const BYTE badOidContent[] = { 0x06, 0x89, 0x55, 0x04, 0x0A }; +static const BYTE oidValue[] = { 0x55, 0x04, 0x0A }; + +static const BYTE ia5stringContent[] = { 0x16, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, + 0x63, 0x70, 0x73, 0x2E, 0x72, 0x6F, 0x6F, 0x74, 0x2D, + 0x78, 0x31, 0x2E, 0x6C, 0x65, 0x74, 0x73, 0x65, 0x6E, + 0x63, 0x72, 0x79, 0x70, 0x74, 0x2E, 0x6F, 0x72, 0x67 }; + +static const BYTE utctimeContent[] = { 0x17, 0x0D, 0x32, 0x31, 0x30, 0x33, 0x31, 0x37, + 0x31, 0x36, 0x34, 0x30, 0x34, 0x36, 0x5A }; + +int TestASN1Read(int argc, char* argv[]) +{ + WinPrAsn1Decoder decoder; + WinPrAsn1Decoder seqDecoder; + wStream staticS; + WinPrAsn1_BOOL boolV = 0; + WinPrAsn1_INTEGER integerV = 0; + WinPrAsn1_OID oidV; + WinPrAsn1_IA5STRING ia5stringV = NULL; + WinPrAsn1_UTCTIME utctimeV; + WinPrAsn1_tag tag = 0; + size_t len = 0; + BOOL error = 0; + + /* ============== Test INTEGERs ================ */ + Stream_StaticConstInit(&staticS, integerContent, sizeof(integerContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadInteger(&decoder, &integerV)) + return -1; + + Stream_StaticConstInit(&staticS, positiveIntegerContent, sizeof(positiveIntegerContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadInteger(&decoder, &integerV) && integerV != 0xff) + return -1; + + Stream_StaticConstInit(&staticS, negativeIntegerContent, sizeof(negativeIntegerContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadInteger(&decoder, &integerV) && integerV != -1) + return -1; + + Stream_StaticConstInit(&staticS, badIntegerContent, sizeof(badIntegerContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (WinPrAsn1DecReadInteger(&decoder, &integerV)) + return -1; + + /* ================ Test BOOL ================*/ + Stream_StaticConstInit(&staticS, boolContent, sizeof(boolContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadBoolean(&decoder, &boolV)) + return -10; + + Stream_StaticConstInit(&staticS, badBoolContent, sizeof(badBoolContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (WinPrAsn1DecReadBoolean(&decoder, &boolV)) + return -11; + + /* ================ Test OID ================*/ + Stream_StaticConstInit(&staticS, oidContent, sizeof(oidContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadOID(&decoder, &oidV, TRUE) || oidV.len != 3 || + (memcmp(oidV.data, oidValue, oidV.len) != 0)) + return -15; + WinPrAsn1FreeOID(&oidV); + + Stream_StaticConstInit(&staticS, badOidContent, sizeof(badOidContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (WinPrAsn1DecReadOID(&decoder, &oidV, TRUE)) + return -15; + WinPrAsn1FreeOID(&oidV); + + Stream_StaticConstInit(&staticS, ia5stringContent, sizeof(ia5stringContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadIA5String(&decoder, &ia5stringV) || + (strcmp(ia5stringV, "http://cps.root-x1.letsencrypt.org") != 0)) + return -16; + free(ia5stringV); + + /* ================ Test utc time ================*/ + Stream_StaticConstInit(&staticS, utctimeContent, sizeof(utctimeContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadUtcTime(&decoder, &utctimeV) || utctimeV.year != 2021 || + utctimeV.month != 3 || utctimeV.day != 17 || utctimeV.minute != 40 || utctimeV.tz != 'Z') + return -17; + + /* ================ Test sequence ================*/ + Stream_StaticConstInit(&staticS, seqContent, sizeof(seqContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadSequence(&decoder, &seqDecoder)) + return -20; + + Stream_StaticConstInit(&staticS, seqContent, sizeof(seqContent)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + if (!WinPrAsn1DecReadTagLenValue(&decoder, &tag, &len, &seqDecoder)) + return -21; + + if (tag != ER_TAG_SEQUENCE) + return -22; + + if (!WinPrAsn1DecPeekTag(&seqDecoder, &tag) || tag != ER_TAG_OBJECT_IDENTIFIER) + return -23; + + /* ================ Test contextual ================*/ + Stream_StaticConstInit(&staticS, contextualInteger, sizeof(contextualInteger)); + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + error = TRUE; + if (!WinPrAsn1DecReadContextualInteger(&decoder, 0, &error, &integerV) || error) + return -25; + + /* test reading a contextual integer that is not there (index 1). + * that should not touch the decoder read head and we shall be able to extract contextual tag 0 + * after that + */ + WinPrAsn1Decoder_Init(&decoder, WINPR_ASN1_DER, &staticS); + error = FALSE; + if (WinPrAsn1DecReadContextualInteger(&decoder, 1, &error, &integerV) || error) + return -26; + + error = FALSE; + if (!WinPrAsn1DecReadContextualInteger(&decoder, 0, &error, &integerV) || error) + return -27; + + return 0; +} + +static BYTE oid1_val[] = { 1 }; +static const WinPrAsn1_OID oid1 = { sizeof(oid1_val), oid1_val }; +static BYTE oid2_val[] = { 2, 2 }; +static WinPrAsn1_OID oid2 = { sizeof(oid2_val), oid2_val }; +static BYTE oid3_val[] = { 3, 3, 3 }; +static WinPrAsn1_OID oid3 = { sizeof(oid3_val), oid3_val }; +static BYTE oid4_val[] = { 4, 4, 4, 4 }; +static WinPrAsn1_OID oid4 = { sizeof(oid4_val), oid4_val }; + +int TestASN1Write(int argc, char* argv[]) +{ + wStream* s = NULL; + size_t expectedOuputSz = 0; + int retCode = 100; + WinPrAsn1_UTCTIME utcTime; + WinPrAsn1_IA5STRING ia5string = NULL; + WinPrAsn1Encoder* enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER); + if (!enc) + goto out; + + /* Let's encode something like: + * APP(3) + * SEQ2 + * OID1 + * OID2 + * SEQ3 + * OID3 + * OID4 + * + * [5] integer(200) + * [6] SEQ (empty) + * [7] UTC time (2016-03-17 16:40:41 UTC) + * [8] IA5String(test) + * [9] OctetString + * SEQ(empty) + * + */ + + /* APP(3) */ + retCode = 101; + if (!WinPrAsn1EncAppContainer(enc, 3)) + goto out; + + /* SEQ2 */ + retCode = 102; + if (!WinPrAsn1EncSeqContainer(enc)) + goto out; + + retCode = 103; + if (WinPrAsn1EncOID(enc, &oid1) != 3) + goto out; + + retCode = 104; + if (WinPrAsn1EncOID(enc, &oid2) != 4) + goto out; + + retCode = 105; + if (WinPrAsn1EncEndContainer(enc) != 9) + goto out; + + /* SEQ3 */ + retCode = 110; + if (!WinPrAsn1EncSeqContainer(enc)) + goto out; + + retCode = 111; + if (WinPrAsn1EncOID(enc, &oid3) != 5) + goto out; + + retCode = 112; + if (WinPrAsn1EncOID(enc, &oid4) != 6) + goto out; + + retCode = 113; + if (WinPrAsn1EncEndContainer(enc) != 13) + goto out; + + /* [5] integer(200) */ + retCode = 114; + if (WinPrAsn1EncContextualInteger(enc, 5, 200) != 6) + goto out; + + /* [6] SEQ (empty) */ + retCode = 115; + if (!WinPrAsn1EncContextualSeqContainer(enc, 6)) + goto out; + + retCode = 116; + if (WinPrAsn1EncEndContainer(enc) != 4) + goto out; + + /* [7] UTC time (2016-03-17 16:40:41 UTC) */ + retCode = 117; + utcTime.year = 2016; + utcTime.month = 3; + utcTime.day = 17; + utcTime.hour = 16; + utcTime.minute = 40; + utcTime.second = 41; + utcTime.tz = 'Z'; + if (WinPrAsn1EncContextualUtcTime(enc, 7, &utcTime) != 17) + goto out; + + /* [8] IA5String(test) */ + retCode = 118; + ia5string = "test"; + if (!WinPrAsn1EncContextualContainer(enc, 8)) + goto out; + + retCode = 119; + if (WinPrAsn1EncIA5String(enc, ia5string) != 6) + goto out; + + retCode = 120; + if (WinPrAsn1EncEndContainer(enc) != 8) + goto out; + + /* [9] OctetString + * SEQ(empty) + */ + retCode = 121; + if (!WinPrAsn1EncContextualOctetStringContainer(enc, 9)) + goto out; + + retCode = 122; + if (!WinPrAsn1EncSeqContainer(enc)) + goto out; + + retCode = 123; + if (WinPrAsn1EncEndContainer(enc) != 2) + goto out; + + retCode = 124; + if (WinPrAsn1EncEndContainer(enc) != 6) + goto out; + + /* close APP */ + expectedOuputSz = 24 + 6 + 4 + 17 + 8 + 6; + retCode = 200; + if (WinPrAsn1EncEndContainer(enc) != expectedOuputSz) + goto out; + + /* let's output the result */ + retCode = 201; + s = Stream_New(NULL, 1024); + if (!s) + goto out; + + retCode = 202; + if (!WinPrAsn1EncToStream(enc, s) || Stream_GetPosition(s) != expectedOuputSz) + goto out; + /* winpr_HexDump("", WLOG_ERROR, Stream_Buffer(s), Stream_GetPosition(s));*/ + + /* + * let's perform a mini-performance test, where we encode an ASN1 message with a big depth, + * so that we trigger reallocation routines in the encoder. We're gonna encode something like + * SEQ1 + * SEQ2 + * SEQ3 + * ... + * SEQ1000 + * INTEGER(2) + * + * As static chunks and containers are 50, a depth of 1000 should be enough + * + */ + WinPrAsn1Encoder_Reset(enc); + + retCode = 203; + for (size_t i = 0; i < 1000; i++) + { + if (!WinPrAsn1EncSeqContainer(enc)) + goto out; + } + + retCode = 204; + if (WinPrAsn1EncInteger(enc, 2) != 3) + goto out; + + retCode = 205; + for (size_t i = 0; i < 1000; i++) + { + if (!WinPrAsn1EncEndContainer(enc)) + goto out; + } + + retCode = 0; + +out: + if (s) + Stream_Free(s, TRUE); + WinPrAsn1Encoder_Free(&enc); + return retCode; +} + +int TestASN1(int argc, char* argv[]) +{ + int ret = TestASN1Read(argc, argv); + if (ret) + return ret; + + return TestASN1Write(argc, argv); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestArrayList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestArrayList.c new file mode 100644 index 0000000000000000000000000000000000000000..c36dbfcf177896e05bd519298722c53195b8dd84 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestArrayList.c @@ -0,0 +1,84 @@ + +#include +#include +#include + +int TestArrayList(int argc, char* argv[]) +{ + int res = -1; + SSIZE_T rc = 0; + size_t val = 0; + const size_t elemsToInsert = 10; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + wArrayList* arrayList = ArrayList_New(TRUE); + if (!arrayList) + return -1; + + for (size_t index = 0; index < elemsToInsert; index++) + { + if (!ArrayList_Append(arrayList, (void*)index)) + goto fail; + } + + size_t count = ArrayList_Count(arrayList); + + printf("ArrayList count: %" PRIuz "\n", count); + + SSIZE_T index = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + + printf("ArrayList index: %" PRIdz "\n", index); + + if (index != 6) + goto fail; + + ArrayList_Insert(arrayList, 5, (void*)(size_t)100); + + index = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + printf("ArrayList index: %" PRIdz "\n", index); + + if (index != 7) + goto fail; + + ArrayList_Remove(arrayList, (void*)(size_t)100); + + rc = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + printf("ArrayList index: %d\n", rc); + + if (rc != 6) + goto fail; + + for (size_t index = 0; index < elemsToInsert; index++) + { + val = (size_t)ArrayList_GetItem(arrayList, 0); + if (!ArrayList_RemoveAt(arrayList, 0)) + goto fail; + + if (val != index) + { + printf("ArrayList: shifted %" PRIdz " entries, expected value %" PRIdz ", got %" PRIdz + "\n", + index, index, val); + goto fail; + } + } + + rc = ArrayList_IndexOf(arrayList, (void*)elemsToInsert, -1, -1); + printf("ArrayList index: %d\n", rc); + if (rc != -1) + goto fail; + + count = ArrayList_Count(arrayList); + printf("ArrayList count: %" PRIuz "\n", count); + if (count != 0) + goto fail; + + ArrayList_Clear(arrayList); + res = 0; +fail: + ArrayList_Free(arrayList); + + return res; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBacktrace.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBacktrace.c new file mode 100644 index 0000000000000000000000000000000000000000..c3a89f19352c3d979fd3c01a07c8d266cb0c3a6c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBacktrace.c @@ -0,0 +1,34 @@ +#include +#include + +int TestBacktrace(int argc, char* argv[]) +{ + int rc = -1; + size_t used = 0; + char** msg = NULL; + void* stack = winpr_backtrace(20); + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!stack) + { + (void)fprintf(stderr, "winpr_backtrace failed!\n"); + return -1; + } + + msg = winpr_backtrace_symbols(stack, &used); + + if (msg) + { + for (size_t x = 0; x < used; x++) + printf("%" PRIuz ": %s\n", x, msg[x]); + + rc = 0; + } + + winpr_backtrace_symbols_fd(stack, fileno(stdout)); + winpr_backtrace_free(stack); + free((void*)msg); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBitStream.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBitStream.c new file mode 100644 index 0000000000000000000000000000000000000000..83c911cb607682b014522a1c3d343c93b61e1018 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBitStream.c @@ -0,0 +1,86 @@ + +#include +#include +#include +#include + +static void BitStrGen(void) +{ + char str[64] = { 0 }; + + for (DWORD i = 0; i < 256;) + { + printf("\t"); + + for (DWORD j = 0; j < 4; j++) + { + if (0) + { + /* Least Significant Bit First */ + str[0] = (i & (1 << 7)) ? '1' : '0'; + str[1] = (i & (1 << 6)) ? '1' : '0'; + str[2] = (i & (1 << 5)) ? '1' : '0'; + str[3] = (i & (1 << 4)) ? '1' : '0'; + str[4] = (i & (1 << 3)) ? '1' : '0'; + str[5] = (i & (1 << 2)) ? '1' : '0'; + str[6] = (i & (1 << 1)) ? '1' : '0'; + str[7] = (i & (1 << 0)) ? '1' : '0'; + str[8] = '\0'; + } + else + { + /* Most Significant Bit First */ + str[7] = (i & (1 << 7)) ? '1' : '0'; + str[6] = (i & (1 << 6)) ? '1' : '0'; + str[5] = (i & (1 << 5)) ? '1' : '0'; + str[4] = (i & (1 << 4)) ? '1' : '0'; + str[3] = (i & (1 << 3)) ? '1' : '0'; + str[2] = (i & (1 << 2)) ? '1' : '0'; + str[1] = (i & (1 << 1)) ? '1' : '0'; + str[0] = (i & (1 << 0)) ? '1' : '0'; + str[8] = '\0'; + } + + printf("\"%s\",%s", str, j == 3 ? "" : " "); + i++; + } + + printf("\n"); + } +} + +int TestBitStream(int argc, char* argv[]) +{ + wBitStream* bs = NULL; + BYTE buffer[1024] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + bs = BitStream_New(); + if (!bs) + return 1; + BitStream_Attach(bs, buffer, sizeof(buffer)); + BitStream_Write_Bits(bs, 0xAF, 8); /* 11110101 */ + BitStream_Write_Bits(bs, 0xF, 4); /* 1111 */ + BitStream_Write_Bits(bs, 0xA, 4); /* 0101 */ + BitStream_Flush(bs); + BitDump(__func__, WLOG_INFO, buffer, bs->position, BITDUMP_MSB_FIRST); + BitStream_Write_Bits(bs, 3, 2); /* 11 */ + BitStream_Write_Bits(bs, 0, 3); /* 000 */ + BitStream_Write_Bits(bs, 0x2D, 6); /* 101101 */ + BitStream_Write_Bits(bs, 0x19, 5); /* 11001 */ + // BitStream_Flush(bs); /* flush should be done automatically here (32 bits written) */ + BitDump(__func__, WLOG_INFO, buffer, bs->position, BITDUMP_MSB_FIRST); + BitStream_Write_Bits(bs, 3, 2); /* 11 */ + BitStream_Flush(bs); + BitDump(__func__, WLOG_INFO, buffer, bs->position, BITDUMP_MSB_FIRST); + BitStream_Write_Bits(bs, 00, 2); /* 00 */ + BitStream_Write_Bits(bs, 0xF, 4); /* 1111 */ + BitStream_Write_Bits(bs, 0, 20); + BitStream_Write_Bits(bs, 0xAFF, 12); /* 111111110101 */ + BitStream_Flush(bs); + BitDump(__func__, WLOG_INFO, buffer, bs->position, BITDUMP_MSB_FIRST); + BitStream_Free(bs); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBufferPool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBufferPool.c new file mode 100644 index 0000000000000000000000000000000000000000..0e224c9cd986f26393ba19cb30695e044dc67b5a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestBufferPool.c @@ -0,0 +1,68 @@ + +#include +#include +#include + +int TestBufferPool(int argc, char* argv[]) +{ + DWORD PoolSize = 0; + SSIZE_T BufferSize = 0; + wBufferPool* pool = NULL; + BYTE* Buffers[10] = { 0 }; + int DefaultSize = 1234; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + pool = BufferPool_New(TRUE, -1, 16); + if (!pool) + return -1; + + Buffers[0] = BufferPool_Take(pool, DefaultSize); + Buffers[1] = BufferPool_Take(pool, DefaultSize); + Buffers[2] = BufferPool_Take(pool, 2048); + if (!Buffers[0] || !Buffers[1] || !Buffers[2]) + return -1; + + BufferSize = BufferPool_GetBufferSize(pool, Buffers[0]); + + if (BufferSize != DefaultSize) + { + printf("BufferPool_GetBufferSize failure: Actual: %d Expected: %" PRIu32 "\n", BufferSize, + DefaultSize); + return -1; + } + + BufferSize = BufferPool_GetBufferSize(pool, Buffers[1]); + + if (BufferSize != DefaultSize) + { + printf("BufferPool_GetBufferSize failure: Actual: %d Expected: %" PRIu32 "\n", BufferSize, + DefaultSize); + return -1; + } + + BufferSize = BufferPool_GetBufferSize(pool, Buffers[2]); + + if (BufferSize != 2048) + { + printf("BufferPool_GetBufferSize failure: Actual: %d Expected: 2048\n", BufferSize); + return -1; + } + + BufferPool_Return(pool, Buffers[1]); + + PoolSize = BufferPool_GetPoolSize(pool); + + if (PoolSize != 2) + { + printf("BufferPool_GetPoolSize failure: Actual: %" PRIu32 " Expected: 2\n", PoolSize); + return -1; + } + + BufferPool_Clear(pool); + + BufferPool_Free(pool); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestCmdLine.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestCmdLine.c new file mode 100644 index 0000000000000000000000000000000000000000..9be3c212f90f6a448d3a5e77bf8427854c3895bf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestCmdLine.c @@ -0,0 +1,356 @@ +#include +#include +#include +#include +#include +#include + +static const char* testArgv[] = { "mstsc.exe", + "+z", + "/w:1024", + "/h:768", + "/bpp:32", + "/admin", + "/multimon", + "+fonts", + "-wallpaper", + "/v:localhost:3389", + "/valuelist:value1,value2", + "/valuelist-empty:", + 0 }; + +static const char testListAppName[] = "test app name"; +static const char* testListArgs[] = { + "a,b,c,d", "a:,\"b:xxx, yyy\",c", "a:,,,b", "a:,\",b", "\"a,b,c,d d d,fff\"", "", + NULL, "'a,b,\",c'", "\"a,b,',c\"", "', a, ', b,c'", "\"a,b,\",c\"" +}; + +static const char* testListArgs1[] = { testListAppName, "a", "b", "c", "d" }; +static const char* testListArgs2[] = { testListAppName, "a:", "b:xxx, yyy", "c" }; +// static const char* testListArgs3[] = {}; +// static const char* testListArgs4[] = {}; +static const char* testListArgs5[] = { testListAppName, "a", "b", "c", "d d d", "fff" }; +static const char* testListArgs6[] = { testListAppName }; +static const char* testListArgs7[] = { testListAppName }; +static const char* testListArgs8[] = { testListAppName, "a", "b", "\"", "c" }; +static const char* testListArgs9[] = { testListAppName, "a", "b", "'", "c" }; +// static const char* testListArgs10[] = {}; +// static const char* testListArgs11[] = {}; + +static const char** testListArgsResult[] = { testListArgs1, + testListArgs2, + NULL /* testListArgs3 */, + NULL /* testListArgs4 */, + testListArgs5, + testListArgs6, + testListArgs7, + testListArgs8, + testListArgs9, + NULL /* testListArgs10 */, + NULL /* testListArgs11 */ }; +static const size_t testListArgsCount[] = { + ARRAYSIZE(testListArgs1), + ARRAYSIZE(testListArgs2), + 0 /* ARRAYSIZE(testListArgs3) */, + 0 /* ARRAYSIZE(testListArgs4) */, + ARRAYSIZE(testListArgs5), + ARRAYSIZE(testListArgs6), + ARRAYSIZE(testListArgs7), + ARRAYSIZE(testListArgs8), + ARRAYSIZE(testListArgs9), + 0 /* ARRAYSIZE(testListArgs10) */, + 0 /* ARRAYSIZE(testListArgs11) */ +}; + +static BOOL checkResult(size_t index, char** actual, size_t actualCount) +{ + const char** result = testListArgsResult[index]; + const size_t resultCount = testListArgsCount[index]; + + if (resultCount != actualCount) + return FALSE; + + if (actualCount == 0) + { + return (actual == NULL); + } + else + { + if (!actual) + return FALSE; + + for (size_t x = 0; x < actualCount; x++) + { + const char* a = result[x]; + const char* b = actual[x]; + + if (strcmp(a, b) != 0) + return FALSE; + } + } + + return TRUE; +} + +static BOOL TestCommandLineParseCommaSeparatedValuesEx(void) +{ + WINPR_ASSERT(ARRAYSIZE(testListArgs) == ARRAYSIZE(testListArgsResult)); + WINPR_ASSERT(ARRAYSIZE(testListArgs) == ARRAYSIZE(testListArgsCount)); + + for (size_t x = 0; x < ARRAYSIZE(testListArgs); x++) + { + union + { + char* p; + char** pp; + const char** ppc; + } ptr; + const char* list = testListArgs[x]; + size_t count = 42; + ptr.pp = CommandLineParseCommaSeparatedValuesEx(testListAppName, list, &count); + BOOL valid = checkResult(x, ptr.pp, count); + free(ptr.p); + if (!valid) + return FALSE; + } + + return TRUE; +} + +int TestCmdLine(int argc, char* argv[]) +{ + int status = 0; + int ret = -1; + DWORD flags = 0; + long width = 0; + long height = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + int testArgc = 0; + char** command_line = NULL; + COMMAND_LINE_ARGUMENT_A args[] = { + { "v", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "destination server" }, + { "port", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "server port" }, + { "w", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "width" }, + { "h", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "height" }, + { "f", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, "fullscreen" }, + { "bpp", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, + "session bpp (color depth)" }, + { "admin", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, "console", + "admin (or console) session" }, + { "multimon", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, "multi-monitor" }, + { "a", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, "addin", "addin" }, + { "u", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "username" }, + { "p", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "password" }, + { "d", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "domain" }, + { "z", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, "compression" }, + { "audio", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "audio output mode" }, + { "mic", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, "audio input (microphone)" }, + { "fonts", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "smooth fonts (cleartype)" }, + { "aero", COMMAND_LINE_VALUE_BOOL, NULL, NULL, BoolValueFalse, -1, NULL, + "desktop composition" }, + { "window-drag", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "full window drag" }, + { "menu-anims", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "menu animations" }, + { "themes", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, "themes" }, + { "wallpaper", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, "wallpaper" }, + { "codec", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "codec" }, + { "nego", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "protocol security negotiation" }, + { "sec", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, + "force specific protocol security" }, +#if defined(WITH_FREERDP_DEPRECATED) + { "sec-rdp", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "rdp protocol security" }, + { "sec-tls", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "tls protocol security" }, + { "sec-nla", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueTrue, NULL, -1, NULL, + "nla protocol security" }, + { "sec-ext", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, + "nla extended protocol security" }, + { "cert-name", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, + "certificate name" }, + { "cert-ignore", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "ignore certificate" }, +#endif + { "valuelist", COMMAND_LINE_VALUE_REQUIRED, ",", NULL, NULL, -1, NULL, + "List of comma separated values." }, + { "valuelist-empty", COMMAND_LINE_VALUE_REQUIRED, ",", NULL, NULL, -1, NULL, + "List of comma separated values. Used to test correct behavior if an empty list was " + "passed." }, + { "version", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_VERSION, NULL, NULL, NULL, -1, + NULL, "print version" }, + { "help", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_HELP, NULL, NULL, NULL, -1, "?", + "print help" }, + { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } + }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + flags = COMMAND_LINE_SIGIL_SLASH | COMMAND_LINE_SEPARATOR_COLON | COMMAND_LINE_SIGIL_PLUS_MINUS; + testArgc = string_list_length(testArgv); + command_line = string_list_copy(testArgv); + + if (!command_line) + { + printf("Argument duplication failed (not enough memory?)\n"); + return ret; + } + + status = CommandLineParseArgumentsA(testArgc, command_line, args, flags, NULL, NULL, NULL); + + if (status != 0) + { + printf("CommandLineParseArgumentsA failure: %d\n", status); + goto out; + } + + arg = CommandLineFindArgumentA(args, "w"); + + if (strcmp("1024", arg->Value) != 0) + { + printf("CommandLineFindArgumentA: unexpected %s value %s\n", arg->Name, arg->Value); + goto out; + } + + arg = CommandLineFindArgumentA(args, "h"); + + if (strcmp("768", arg->Value) != 0) + { + printf("CommandLineFindArgumentA: unexpected %s value %s\n", arg->Name, arg->Value); + goto out; + } + + arg = CommandLineFindArgumentA(args, "f"); + + if (arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = CommandLineFindArgumentA(args, "admin"); + + if (!arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = CommandLineFindArgumentA(args, "multimon"); + + if (!arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = CommandLineFindArgumentA(args, "v"); + + if (strcmp("localhost:3389", arg->Value) != 0) + { + printf("CommandLineFindArgumentA: unexpected %s value %s\n", arg->Name, arg->Value); + goto out; + } + + arg = CommandLineFindArgumentA(args, "fonts"); + + if (!arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = CommandLineFindArgumentA(args, "wallpaper"); + + if (arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = CommandLineFindArgumentA(args, "help"); + + if (arg->Value) + { + printf("CommandLineFindArgumentA: unexpected %s value\n", arg->Name); + goto out; + } + + arg = args; + errno = 0; + + do + { + if (!(arg->Flags & COMMAND_LINE_VALUE_PRESENT)) + continue; + + printf("Argument: %s\n", arg->Name); + CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "v") + { + } + CommandLineSwitchCase(arg, "w") + { + width = strtol(arg->Value, NULL, 0); + + if (errno != 0) + goto out; + } + CommandLineSwitchCase(arg, "h") + { + height = strtol(arg->Value, NULL, 0); + + if (errno != 0) + goto out; + } + CommandLineSwitchCase(arg, "valuelist") + { + size_t count = 0; + char** p = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + free((void*)p); + + if (!p || count != 3) + { + printf("CommandLineParseCommaSeparatedValuesEx: invalid p or count (%" PRIuz + "!=3)\n", + count); + goto out; + } + } + CommandLineSwitchCase(arg, "valuelist-empty") + { + size_t count = 0; + char** p = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + free((void*)p); + + if (!p || count != 1) + { + printf("CommandLineParseCommaSeparatedValuesEx: invalid p or count (%" PRIuz + "!=1)\n", + count); + goto out; + } + } + CommandLineSwitchDefault(arg) + { + } + CommandLineSwitchEnd(arg) + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + if ((width != 1024) || (height != 768)) + { + printf("Unexpected width and height: Actual: (%ldx%ld), Expected: (1024x768)\n", width, + height); + goto out; + } + ret = 0; + +out: + string_list_free(command_line); + + if (!TestCommandLineParseCommaSeparatedValuesEx()) + return -1; + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestHashTable.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestHashTable.c new file mode 100644 index 0000000000000000000000000000000000000000..c1f2292d24b35518e98f8887b46069f9700eda50 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestHashTable.c @@ -0,0 +1,448 @@ + +#include +#include +#include + +static char* key1 = "key1"; +static char* key2 = "key2"; +static char* key3 = "key3"; + +static char* val1 = "val1"; +static char* val2 = "val2"; +static char* val3 = "val3"; + +static int test_hash_table_pointer(void) +{ + int rc = -1; + size_t count = 0; + char* value = NULL; + wHashTable* table = NULL; + table = HashTable_New(TRUE); + + if (!table) + return -1; + + if (!HashTable_Insert(table, key1, val1)) + goto fail; + if (!HashTable_Insert(table, key2, val2)) + goto fail; + if (!HashTable_Insert(table, key3, val3)) + goto fail; + count = HashTable_Count(table); + + if (count != 3) + { + printf("HashTable_Count: Expected : 3, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key2)) + goto fail; + count = HashTable_Count(table); + + if (count != 2) + { + printf("HashTable_Count: Expected : 2, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key3)) + goto fail; + count = HashTable_Count(table); + + if (count != 1) + { + printf("HashTable_Count: Expected : 1, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key1)) + goto fail; + count = HashTable_Count(table); + + if (count != 0) + { + printf("HashTable_Count: Expected : 0, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Insert(table, key1, val1)) + goto fail; + if (!HashTable_Insert(table, key2, val2)) + goto fail; + if (!HashTable_Insert(table, key3, val3)) + goto fail; + count = HashTable_Count(table); + + if (count != 3) + { + printf("HashTable_Count: Expected : 3, Actual: %" PRIuz "\n", count); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key1); + + if (strcmp(value, val1) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val1, value); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key2); + + if (strcmp(value, val2) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val2, value); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key3); + + if (strcmp(value, val3) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val3, value); + goto fail; + } + + if (!HashTable_SetItemValue(table, key2, "apple")) + goto fail; + value = (char*)HashTable_GetItemValue(table, key2); + + if (strcmp(value, "apple") != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", "apple", value); + goto fail; + } + + if (!HashTable_Contains(table, key2)) + { + printf("HashTable_Contains: Expected : TRUE, Actual: FALSE\n"); + goto fail; + } + + if (!HashTable_Remove(table, key2)) + { + printf("HashTable_Remove: Expected : TRUE, Actual: FALSE\n"); + goto fail; + } + + if (HashTable_Remove(table, key2)) + { + printf("HashTable_Remove: Expected : FALSE, Actual: TRUE\n"); + goto fail; + } + + HashTable_Clear(table); + count = HashTable_Count(table); + + if (count != 0) + { + printf("HashTable_Count: Expected : 0, Actual: %" PRIuz "\n", count); + goto fail; + } + + rc = 1; +fail: + HashTable_Free(table); + return rc; +} + +static int test_hash_table_string(void) +{ + int rc = -1; + size_t count = 0; + char* value = NULL; + wHashTable* table = HashTable_New(TRUE); + + if (!table) + return -1; + + if (!HashTable_SetupForStringData(table, TRUE)) + goto fail; + + if (!HashTable_Insert(table, key1, val1)) + goto fail; + if (!HashTable_Insert(table, key2, val2)) + goto fail; + if (!HashTable_Insert(table, key3, val3)) + goto fail; + count = HashTable_Count(table); + + if (count != 3) + { + printf("HashTable_Count: Expected : 3, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key2)) + goto fail; + count = HashTable_Count(table); + + if (count != 2) + { + printf("HashTable_Count: Expected : 3, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key3)) + goto fail; + count = HashTable_Count(table); + + if (count != 1) + { + printf("HashTable_Count: Expected : 1, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Remove(table, key1)) + goto fail; + count = HashTable_Count(table); + + if (count != 0) + { + printf("HashTable_Count: Expected : 0, Actual: %" PRIuz "\n", count); + goto fail; + } + + if (!HashTable_Insert(table, key1, val1)) + goto fail; + if (!HashTable_Insert(table, key2, val2)) + goto fail; + if (!HashTable_Insert(table, key3, val3)) + goto fail; + count = HashTable_Count(table); + + if (count != 3) + { + printf("HashTable_Count: Expected : 3, Actual: %" PRIuz "\n", count); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key1); + + if (strcmp(value, val1) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val1, value); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key2); + + if (strcmp(value, val2) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val2, value); + goto fail; + } + + value = (char*)HashTable_GetItemValue(table, key3); + + if (strcmp(value, val3) != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", val3, value); + goto fail; + } + + if (!HashTable_SetItemValue(table, key2, "apple")) + goto fail; + value = (char*)HashTable_GetItemValue(table, key2); + + if (strcmp(value, "apple") != 0) + { + printf("HashTable_GetItemValue: Expected : %s, Actual: %s\n", "apple", value); + goto fail; + } + + if (!HashTable_Contains(table, key2)) + { + printf("HashTable_Contains: Expected : TRUE, Actual: FALSE\n"); + goto fail; + } + + if (!HashTable_Remove(table, key2)) + { + printf("HashTable_Remove: Expected : TRUE, Actual: FALSE\n"); + goto fail; + } + + if (HashTable_Remove(table, key2)) + { + printf("HashTable_Remove: Expected : FALSE, Actual: TRUE\n"); + goto fail; + } + + HashTable_Clear(table); + count = HashTable_Count(table); + + if (count != 0) + { + printf("HashTable_Count: Expected : 0, Actual: %" PRIuz "\n", count); + goto fail; + } + + rc = 1; +fail: + HashTable_Free(table); + return rc; +} + +typedef struct +{ + wHashTable* table; + size_t strlenCounter; + size_t foreachCalls; + + BOOL test3error; +} ForeachData; + +static BOOL foreachFn1(const void* key, void* value, void* arg) +{ + ForeachData* d = (ForeachData*)arg; + WINPR_UNUSED(key); + d->strlenCounter += strlen((const char*)value); + return TRUE; +} + +static BOOL foreachFn2(const void* key, void* value, void* arg) +{ + ForeachData* d = (ForeachData*)arg; + WINPR_UNUSED(key); + WINPR_UNUSED(value); + d->foreachCalls++; + + if (d->foreachCalls == 2) + return FALSE; + return TRUE; +} + +static BOOL foreachFn3(const void* key, void* value, void* arg) +{ + const char* keyStr = (const char*)key; + + ForeachData* d = (ForeachData*)arg; + ForeachData d2; + + WINPR_UNUSED(value); + WINPR_ASSERT(keyStr); + + if (strcmp(keyStr, "key1") == 0) + { + /* when we pass on key1, let's remove key2 and check that the value is not + * visible anymore (even if has just been marked for removal)*/ + HashTable_Remove(d->table, "key2"); + + if (HashTable_Contains(d->table, "key2")) + { + d->test3error = TRUE; + return FALSE; + } + + if (HashTable_ContainsValue(d->table, "value2")) + { + d->test3error = TRUE; + return FALSE; + } + + /* number of elements of the table shall be correct too */ + if (HashTable_Count(d->table) != 2) + { + d->test3error = TRUE; + return FALSE; + } + + /* we try recursive HashTable_Foreach */ + d2.table = d->table; + d2.strlenCounter = 0; + + if (!HashTable_Foreach(d->table, foreachFn1, &d2)) + { + d->test3error = TRUE; + return FALSE; + } + if (d2.strlenCounter != 8) + { + d->test3error = TRUE; + return FALSE; + } + } + return TRUE; +} + +static int test_hash_foreach(void) +{ + ForeachData foreachData; + wHashTable* table = NULL; + int retCode = 0; + + foreachData.table = table = HashTable_New(TRUE); + if (!table) + return -1; + + if (!HashTable_SetupForStringData(table, TRUE)) + goto out; + + if (HashTable_Insert(table, key1, val1) < 0 || HashTable_Insert(table, key2, val2) < 0 || + HashTable_Insert(table, key3, val3) < 0) + { + retCode = -2; + goto out; + } + + /* let's try a first trivial foreach */ + foreachData.strlenCounter = 0; + if (!HashTable_Foreach(table, foreachFn1, &foreachData)) + { + retCode = -10; + goto out; + } + if (foreachData.strlenCounter != 12) + { + retCode = -11; + goto out; + } + + /* interrupted foreach */ + foreachData.foreachCalls = 0; + if (HashTable_Foreach(table, foreachFn2, &foreachData)) + { + retCode = -20; + goto out; + } + if (foreachData.foreachCalls != 2) + { + retCode = -21; + goto out; + } + + /* let's try a foreach() call that will remove a value from the table in the callback */ + foreachData.test3error = FALSE; + if (!HashTable_Foreach(table, foreachFn3, &foreachData)) + { + retCode = -30; + goto out; + } + if (foreachData.test3error) + { + retCode = -31; + goto out; + } + +out: + HashTable_Free(table); + return retCode; +} + +int TestHashTable(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (test_hash_table_pointer() < 0) + return 1; + + if (test_hash_table_string() < 0) + return 2; + + if (test_hash_foreach() < 0) + return 3; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestImage.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestImage.c new file mode 100644 index 0000000000000000000000000000000000000000..a19dc1bcf0ad2c573e3067821725a331db321391 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestImage.c @@ -0,0 +1,232 @@ +#include +#include +#include +#include +#include +#include + +static const char test_src_filename[] = TEST_SOURCE_PATH "/rgb"; +static const char test_bin_filename[] = TEST_BINARY_PATH "/rgb"; + +static BOOL test_image_equal(const wImage* imageA, const wImage* imageB) +{ + return winpr_image_equal(imageA, imageB, + WINPR_IMAGE_CMP_IGNORE_DEPTH | WINPR_IMAGE_CMP_IGNORE_ALPHA | + WINPR_IMAGE_CMP_FUZZY); +} + +static BOOL test_equal_to(const wImage* bmp, const char* name, UINT32 format) +{ + BOOL rc = FALSE; + wImage* cmp = winpr_image_new(); + if (!cmp) + goto fail; + + char path[MAX_PATH] = { 0 }; + (void)_snprintf(path, sizeof(path), "%s.%s", name, winpr_image_format_extension(format)); + const int cmpSize = winpr_image_read(cmp, path); + if (cmpSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_read failed for %s", __func__, path); + goto fail; + } + + rc = test_image_equal(bmp, cmp); + if (!rc) + (void)fprintf(stderr, "[%s] winpr_image_eqal failed", __func__); + +fail: + winpr_image_free(cmp, TRUE); + return rc; +} + +static BOOL test_equal(void) +{ + BOOL rc = FALSE; + wImage* bmp = winpr_image_new(); + + if (!bmp) + goto fail; + + char path[MAX_PATH] = { 0 }; + (void)_snprintf(path, sizeof(path), "%s.bmp", test_src_filename); + PathCchConvertStyleA(path, sizeof(path), PATH_STYLE_NATIVE); + + const int bmpSize = winpr_image_read(bmp, path); + if (bmpSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_read failed for %s", __func__, path); + goto fail; + } + + for (UINT32 x = 0; x < UINT8_MAX; x++) + { + if (!winpr_image_format_is_supported(x)) + continue; + if (!test_equal_to(bmp, test_src_filename, x)) + goto fail; + } + + rc = TRUE; +fail: + winpr_image_free(bmp, TRUE); + + return rc; +} + +static BOOL test_read_write_compare(const char* tname, const char* tdst, UINT32 format) +{ + BOOL rc = FALSE; + wImage* bmp1 = winpr_image_new(); + wImage* bmp2 = winpr_image_new(); + wImage* bmp3 = winpr_image_new(); + if (!bmp1 || !bmp2 || !bmp3) + goto fail; + + char spath[MAX_PATH] = { 0 }; + char dpath[MAX_PATH] = { 0 }; + char bpath1[MAX_PATH] = { 0 }; + char bpath2[MAX_PATH] = { 0 }; + (void)_snprintf(spath, sizeof(spath), "%s.%s", tname, winpr_image_format_extension(format)); + (void)_snprintf(dpath, sizeof(dpath), "%s.%s", tdst, winpr_image_format_extension(format)); + (void)_snprintf(bpath1, sizeof(bpath1), "%s.src.%s", dpath, + winpr_image_format_extension(WINPR_IMAGE_BITMAP)); + (void)_snprintf(bpath2, sizeof(bpath2), "%s.bin.%s", dpath, + winpr_image_format_extension(WINPR_IMAGE_BITMAP)); + PathCchConvertStyleA(spath, sizeof(spath), PATH_STYLE_NATIVE); + PathCchConvertStyleA(dpath, sizeof(dpath), PATH_STYLE_NATIVE); + PathCchConvertStyleA(bpath1, sizeof(bpath1), PATH_STYLE_NATIVE); + PathCchConvertStyleA(bpath2, sizeof(bpath2), PATH_STYLE_NATIVE); + + const int bmpRSize = winpr_image_read(bmp1, spath); + if (bmpRSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_read failed for %s", __func__, spath); + goto fail; + } + + const int bmpWSize = winpr_image_write(bmp1, dpath); + if (bmpWSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_write failed for %s", __func__, dpath); + goto fail; + } + + const int bmp2RSize = winpr_image_read(bmp2, dpath); + if (bmp2RSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_read failed for %s", __func__, dpath); + goto fail; + } + + const int bmpSrcWSize = winpr_image_write_ex(bmp1, WINPR_IMAGE_BITMAP, bpath1); + if (bmpSrcWSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_write_ex failed for %s", __func__, bpath1); + goto fail; + } + + /* write a bitmap and read it back. + * this tests if we have the proper internal format */ + const int bmpBinWSize = winpr_image_write_ex(bmp2, WINPR_IMAGE_BITMAP, bpath2); + if (bmpBinWSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_write_ex failed for %s", __func__, bpath2); + goto fail; + } + + const int bmp3RSize = winpr_image_read(bmp3, bpath2); + if (bmp3RSize <= 0) + { + (void)fprintf(stderr, "[%s] winpr_image_read failed for %s", __func__, bpath2); + goto fail; + } + + if (!winpr_image_equal(bmp1, bmp2, + WINPR_IMAGE_CMP_IGNORE_DEPTH | WINPR_IMAGE_CMP_IGNORE_ALPHA | + WINPR_IMAGE_CMP_FUZZY)) + { + (void)fprintf(stderr, "[%s] winpr_image_eqal failed bmp1 bmp2", __func__); + goto fail; + } + + rc = winpr_image_equal(bmp3, bmp2, + WINPR_IMAGE_CMP_IGNORE_DEPTH | WINPR_IMAGE_CMP_IGNORE_ALPHA | + WINPR_IMAGE_CMP_FUZZY); + if (!rc) + (void)fprintf(stderr, "[%s] winpr_image_eqal failed bmp3 bmp2", __func__); +fail: + winpr_image_free(bmp1, TRUE); + winpr_image_free(bmp2, TRUE); + winpr_image_free(bmp3, TRUE); + return rc; +} + +static BOOL test_read_write(void) +{ + BOOL rc = TRUE; + for (UINT32 x = 0; x < UINT8_MAX; x++) + { + if (!winpr_image_format_is_supported(x)) + continue; + if (!test_read_write_compare(test_src_filename, test_bin_filename, x)) + rc = FALSE; + } + return rc; +} + +static BOOL test_load_file(const char* name) +{ + BOOL rc = FALSE; + wImage* image = winpr_image_new(); + if (!image || !name) + goto fail; + + const int res = winpr_image_read(image, name); + rc = (res > 0) ? TRUE : FALSE; + +fail: + winpr_image_free(image, TRUE); + return rc; +} + +static BOOL test_load(void) +{ + const char* names[] = { + "rgb.16a.bmp", "rgb.16a.nocolor.bmp", "rgb.16.bmp", "rgb.16.nocolor.bmp", + "rgb.16x.bmp", "rgb.16x.nocolor.bmp", "rgb.24.bmp", "rgb.24.nocolor.bmp", + "rgb.32.bmp", "rgb.32.nocolor.bmp", "rgb.32x.bmp", "rgb.32x.nocolor.bmp", + "rgb.bmp" + }; + + for (size_t x = 0; x < ARRAYSIZE(names); x++) + { + const char* name = names[x]; + char* fname = GetCombinedPath(TEST_SOURCE_PATH, name); + const BOOL res = test_load_file(fname); + free(fname); + if (!res) + return FALSE; + } + + return TRUE; +} + +int TestImage(int argc, char* argv[]) +{ + int rc = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_equal()) + rc -= 1; + + if (!test_read_write()) + rc -= 2; + + if (!test_load()) + rc -= 4; + + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestIni.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestIni.c new file mode 100644 index 0000000000000000000000000000000000000000..5e4143e5ecda38df2831052353edf8d77f61afeb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestIni.c @@ -0,0 +1,160 @@ + +#include +#include + +static const char TEST_INI_01[] = "; This is a sample .ini config file\n" + "\n" + "[first_section]\n" + "one = 1\n" + "five = 5\n" + "animal = BIRD\n" + "\n" + "[second_section]\n" + "path = \"/usr/local/bin\"\n" + "URL = \"http://www.example.com/~username\"\n" + "\n"; + +static const char TEST_INI_02[] = "[FreeRDS]\n" + "prefix=\"/usr/local\"\n" + "bindir=\"bin\"\n" + "sbindir=\"sbin\"\n" + "libdir=\"lib\"\n" + "datarootdir=\"share\"\n" + "localstatedir=\"var\"\n" + "sysconfdir=\"etc\"\n" + "\n"; + +static const char TEST_INI_03[] = "[FreeRDS]\n" + "prefix=\"/usr/local\"\n" + "bindir=\"bin\"\n" + "# some illegal string\n" + "sbindir=\"sbin\"\n" + "libdir=\"lib\"\n" + "invalid key-value pair\n" + "datarootdir=\"share\"\n" + "localstatedir=\"var\"\n" + "sysconfdir=\"etc\"\n" + "\n"; + +int TestIni(int argc, char* argv[]) +{ + int rc = -1; + size_t nKeys = 0; + size_t nSections = 0; + UINT32 iValue = 0; + wIniFile* ini = NULL; + const char* sValue = NULL; + char** keyNames = NULL; + char** sectionNames = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /* First Sample */ + ini = IniFile_New(); + if (!ini) + goto fail; + + if (IniFile_ReadBuffer(ini, TEST_INI_01) < 0) + goto fail; + + free((void*)sectionNames); + sectionNames = IniFile_GetSectionNames(ini, &nSections); + if (!sectionNames && (nSections > 0)) + goto fail; + + for (size_t i = 0; i < nSections; i++) + { + free((void*)keyNames); + keyNames = IniFile_GetSectionKeyNames(ini, sectionNames[i], &nKeys); + printf("[%s]\n", sectionNames[i]); + if (!keyNames && (nKeys > 0)) + goto fail; + for (size_t j = 0; j < nKeys; j++) + { + sValue = IniFile_GetKeyValueString(ini, sectionNames[i], keyNames[j]); + printf("%s = %s\n", keyNames[j], sValue); + } + } + + iValue = IniFile_GetKeyValueInt(ini, "first_section", "one"); + + if (iValue != 1) + { + printf("IniFile_GetKeyValueInt failure\n"); + goto fail; + } + + iValue = IniFile_GetKeyValueInt(ini, "first_section", "five"); + + if (iValue != 5) + { + printf("IniFile_GetKeyValueInt failure\n"); + goto fail; + } + + sValue = IniFile_GetKeyValueString(ini, "first_section", "animal"); + + if (strcmp(sValue, "BIRD") != 0) + { + printf("IniFile_GetKeyValueString failure\n"); + goto fail; + } + + sValue = IniFile_GetKeyValueString(ini, "second_section", "path"); + + if (strcmp(sValue, "/usr/local/bin") != 0) + { + printf("IniFile_GetKeyValueString failure\n"); + goto fail; + } + + sValue = IniFile_GetKeyValueString(ini, "second_section", "URL"); + + if (strcmp(sValue, "http://www.example.com/~username") != 0) + { + printf("IniFile_GetKeyValueString failure\n"); + goto fail; + } + + IniFile_Free(ini); + /* Second Sample */ + ini = IniFile_New(); + if (!ini) + goto fail; + if (IniFile_ReadBuffer(ini, TEST_INI_02) < 0) + goto fail; + free((void*)sectionNames); + sectionNames = IniFile_GetSectionNames(ini, &nSections); + if (!sectionNames && (nSections > 0)) + goto fail; + + for (size_t i = 0; i < nSections; i++) + { + free((void*)keyNames); + keyNames = IniFile_GetSectionKeyNames(ini, sectionNames[i], &nKeys); + printf("[%s]\n", sectionNames[i]); + + if (!keyNames && (nKeys > 0)) + goto fail; + for (size_t j = 0; j < nKeys; j++) + { + sValue = IniFile_GetKeyValueString(ini, sectionNames[i], keyNames[j]); + printf("%s = %s\n", keyNames[j], sValue); + } + } + + IniFile_Free(ini); + /* Third sample - invalid input */ + ini = IniFile_New(); + + if (IniFile_ReadBuffer(ini, TEST_INI_03) != -1) + goto fail; + + rc = 0; +fail: + free((void*)keyNames); + free((void*)sectionNames); + IniFile_Free(ini); + return rc; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestLinkedList.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestLinkedList.c new file mode 100644 index 0000000000000000000000000000000000000000..6c6a2c3c36d4917e194d9a8d8088c55a64288c04 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestLinkedList.c @@ -0,0 +1,135 @@ + +#include +#include +#include + +int TestLinkedList(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + wLinkedList* list = LinkedList_New(); + if (!list) + return -1; + + if (!LinkedList_AddFirst(list, (void*)(size_t)1)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)2)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)3)) + return -1; + size_t count = LinkedList_Count(list); + + if (count != 3) + { + printf("LinkedList_Count: expected 3, actual: %" PRIuz "\n", count); + return -1; + } + + LinkedList_Enumerator_Reset(list); + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\t%p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + printf("LinkedList First: %p Last: %p\n", LinkedList_First(list), LinkedList_Last(list)); + LinkedList_RemoveFirst(list); + LinkedList_RemoveLast(list); + count = LinkedList_Count(list); + + if (count != 1) + { + printf("LinkedList_Count: expected 1, actual: %" PRIuz "\n", count); + return -1; + } + + LinkedList_Enumerator_Reset(list); + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\t%p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + printf("LinkedList First: %p Last: %p\n", LinkedList_First(list), LinkedList_Last(list)); + LinkedList_RemoveFirst(list); + LinkedList_RemoveLast(list); + count = LinkedList_Count(list); + + if (count != 0) + { + printf("LinkedList_Count: expected 0, actual: %" PRIuz "\n", count); + return -1; + } + + if (!LinkedList_AddFirst(list, (void*)(size_t)4)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)5)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)6)) + return -1; + count = LinkedList_Count(list); + + if (count != 3) + { + printf("LinkedList_Count: expected 3, actual: %" PRIuz "\n", count); + return -1; + } + + LinkedList_Enumerator_Reset(list); + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\t%p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + printf("LinkedList First: %p Last: %p\n", LinkedList_First(list), LinkedList_Last(list)); + if (!LinkedList_Remove(list, (void*)(size_t)5)) + return -1; + LinkedList_Enumerator_Reset(list); + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\t%p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + printf("LinkedList First: %p Last: %p\n", LinkedList_First(list), LinkedList_Last(list)); + LinkedList_Free(list); + /* Test enumerator robustness */ + /* enumerator on an empty list */ + list = LinkedList_New(); + if (!list) + return -1; + LinkedList_Enumerator_Reset(list); + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\terror: %p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + LinkedList_Free(list); + /* Use an enumerator without reset */ + list = LinkedList_New(); + if (!list) + return -1; + if (!LinkedList_AddFirst(list, (void*)(size_t)4)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)5)) + return -1; + if (!LinkedList_AddLast(list, (void*)(size_t)6)) + return -1; + + while (LinkedList_Enumerator_MoveNext(list)) + { + printf("\t%p\n", LinkedList_Enumerator_Current(list)); + } + + printf("\n"); + LinkedList_Free(list); + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestListDictionary.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestListDictionary.c new file mode 100644 index 0000000000000000000000000000000000000000..17257c806fa31663d0d442ea450a5d7664059081 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestListDictionary.c @@ -0,0 +1,178 @@ + +#include +#include +#include + +static char* key1 = "key1"; +static char* key2 = "key2"; +static char* key3 = "key3"; + +static char* val1 = "val1"; +static char* val2 = "val2"; +static char* val3 = "val3"; + +int TestListDictionary(int argc, char* argv[]) +{ + size_t count = 0; + char* value = NULL; + wListDictionary* list = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + list = ListDictionary_New(TRUE); + if (!list) + return -1; + + if (!ListDictionary_Add(list, key1, val1) || !ListDictionary_Add(list, key2, val2) || + !ListDictionary_Add(list, key3, val3)) + return -1; + + count = ListDictionary_Count(list); + + if (count != 3) + { + printf("ListDictionary_Count: Expected : 3, Actual: %" PRIuz "\n", count); + return -1; + } + + ListDictionary_Remove(list, key2); + + count = ListDictionary_Count(list); + + if (count != 2) + { + printf("ListDictionary_Count: Expected : 2, Actual: %" PRIuz "\n", count); + return -1; + } + + ListDictionary_Remove(list, key3); + + count = ListDictionary_Count(list); + + if (count != 1) + { + printf("ListDictionary_Count: Expected : 1, Actual: %" PRIuz "\n", count); + return -1; + } + + ListDictionary_Remove(list, key1); + + count = ListDictionary_Count(list); + + if (count != 0) + { + printf("ListDictionary_Count: Expected : 0, Actual: %" PRIuz "\n", count); + return -1; + } + + if (!ListDictionary_Add(list, key1, val1) || !ListDictionary_Add(list, key2, val2) || + !ListDictionary_Add(list, key3, val3)) + return -1; + + count = ListDictionary_Count(list); + + if (count != 3) + { + printf("ListDictionary_Count: Expected : 3, Actual: %" PRIuz "\n", count); + return -1; + } + + value = (char*)ListDictionary_GetItemValue(list, key1); + + if (strcmp(value, val1) != 0) + { + printf("ListDictionary_GetItemValue: Expected : %" PRIuz ", Actual: %" PRIuz "\n", + (size_t)val1, (size_t)value); + return -1; + } + + value = (char*)ListDictionary_GetItemValue(list, key2); + + if (strcmp(value, val2) != 0) + { + printf("ListDictionary_GetItemValue: Expected : %" PRIuz ", Actual: %" PRIuz "\n", + (size_t)val2, (size_t)value); + return -1; + } + + value = (char*)ListDictionary_GetItemValue(list, key3); + + if (strcmp(value, val3) != 0) + { + printf("ListDictionary_GetItemValue: Expected : %" PRIuz ", Actual: %" PRIuz "\n", + (size_t)val3, (size_t)value); + return -1; + } + + ListDictionary_SetItemValue(list, key2, "apple"); + + value = (char*)ListDictionary_GetItemValue(list, key2); + + if (strcmp(value, "apple") != 0) + { + printf("ListDictionary_GetItemValue: Expected : %s, Actual: %s\n", "apple", value); + return -1; + } + + if (!ListDictionary_Contains(list, key2)) + { + printf("ListDictionary_Contains: Expected : TRUE, Actual: FALSE\n"); + return -1; + } + + if (!ListDictionary_Take(list, key2)) + { + printf("ListDictionary_Remove: Expected : TRUE, Actual: FALSE\n"); + return -1; + } + + if (ListDictionary_Take(list, key2)) + { + printf("ListDictionary_Remove: Expected : FALSE, Actual: TRUE\n"); + return -1; + } + + value = ListDictionary_Take_Head(list); + count = ListDictionary_Count(list); + if ((strncmp(value, val1, 4) != 0) || (count != 1)) + { + printf("ListDictionary_Remove_Head: Expected : %s, Actual: %s Count: %" PRIuz "\n", val1, + value, count); + return -1; + } + + value = ListDictionary_Take_Head(list); + count = ListDictionary_Count(list); + if ((strncmp(value, val3, 4) != 0) || (count != 0)) + { + printf("ListDictionary_Remove_Head: Expected : %s, Actual: %s Count: %" PRIuz "\n", val3, + value, count); + return -1; + } + + value = ListDictionary_Take_Head(list); + if (value) + { + printf("ListDictionary_Remove_Head: Expected : (null), Actual: %s\n", value); + return -1; + } + + if (!ListDictionary_Add(list, key1, val1) || !ListDictionary_Add(list, key2, val2) || + !ListDictionary_Add(list, key3, val3)) + return -1; + + ListDictionary_Clear(list); + + count = ListDictionary_Count(list); + + if (count != 0) + { + printf("ListDictionary_Count: Expected : 0, Actual: %" PRIuz "\n", count); + return -1; + } + + ListDictionary_Free(list); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessagePipe.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessagePipe.c new file mode 100644 index 0000000000000000000000000000000000000000..bfa4ab6d58ec3882cff12dd6f1ee4a33a21e1c4c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessagePipe.c @@ -0,0 +1,105 @@ + +#include +#include +#include + +static DWORD WINAPI message_echo_pipe_client_thread(LPVOID arg) +{ + int index = 0; + wMessagePipe* pipe = (wMessagePipe*)arg; + + while (index < 100) + { + wMessage message = { 0 }; + int count = -1; + + if (!MessageQueue_Post(pipe->In, NULL, 0, (void*)(size_t)index, NULL)) + break; + + if (!MessageQueue_Wait(pipe->Out)) + break; + + if (!MessageQueue_Peek(pipe->Out, &message, TRUE)) + break; + + if (message.id == WMQ_QUIT) + break; + + count = (int)(size_t)message.wParam; + + if (count != index) + printf("Echo count mismatch: Actual: %d, Expected: %d\n", count, index); + + index++; + } + + MessageQueue_PostQuit(pipe->In, 0); + + return 0; +} + +static DWORD WINAPI message_echo_pipe_server_thread(LPVOID arg) +{ + wMessage message = { 0 }; + wMessagePipe* pipe = (wMessagePipe*)arg; + + while (MessageQueue_Wait(pipe->In)) + { + if (MessageQueue_Peek(pipe->In, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + break; + + if (!MessageQueue_Dispatch(pipe->Out, &message)) + break; + } + } + + return 0; +} + +int TestMessagePipe(int argc, char* argv[]) +{ + HANDLE ClientThread = NULL; + HANDLE ServerThread = NULL; + wMessagePipe* EchoPipe = NULL; + int ret = 1; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!(EchoPipe = MessagePipe_New())) + { + printf("failed to create message pipe\n"); + goto out; + } + + if (!(ClientThread = + CreateThread(NULL, 0, message_echo_pipe_client_thread, (void*)EchoPipe, 0, NULL))) + { + printf("failed to create client thread\n"); + goto out; + } + + if (!(ServerThread = + CreateThread(NULL, 0, message_echo_pipe_server_thread, (void*)EchoPipe, 0, NULL))) + { + printf("failed to create server thread\n"); + goto out; + } + + (void)WaitForSingleObject(ClientThread, INFINITE); + (void)WaitForSingleObject(ServerThread, INFINITE); + + ret = 0; + +out: + if (EchoPipe) + MessagePipe_Free(EchoPipe); + if (ClientThread) + (void)CloseHandle(ClientThread); + if (ServerThread) + (void)CloseHandle(ServerThread); + + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessageQueue.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessageQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..0856f325fd03be8542ecbaa7321c3ce55e4d219b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestMessageQueue.c @@ -0,0 +1,56 @@ + +#include +#include +#include + +static DWORD WINAPI message_queue_consumer_thread(LPVOID arg) +{ + wMessage message = { 0 }; + wMessageQueue* queue = (wMessageQueue*)arg; + + while (MessageQueue_Wait(queue)) + { + if (MessageQueue_Peek(queue, &message, TRUE)) + { + if (message.id == WMQ_QUIT) + break; + + printf("Message.Type: %" PRIu32 "\n", message.id); + } + } + + return 0; +} + +int TestMessageQueue(int argc, char* argv[]) +{ + HANDLE thread = NULL; + wMessageQueue* queue = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!(queue = MessageQueue_New(NULL))) + { + printf("failed to create message queue\n"); + return 1; + } + + if (!(thread = CreateThread(NULL, 0, message_queue_consumer_thread, (void*)queue, 0, NULL))) + { + printf("failed to create thread\n"); + MessageQueue_Free(queue); + return 1; + } + + if (!MessageQueue_Post(queue, NULL, 123, NULL, NULL) || + !MessageQueue_Post(queue, NULL, 456, NULL, NULL) || + !MessageQueue_Post(queue, NULL, 789, NULL, NULL) || !MessageQueue_PostQuit(queue, 0) || + WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) + return -1; + + MessageQueue_Free(queue); + (void)CloseHandle(thread); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPrint.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPrint.c new file mode 100644 index 0000000000000000000000000000000000000000..81f60f506fce83887a6647d68bb31f78fe0bd610 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPrint.c @@ -0,0 +1,401 @@ + +#include +#include +#include +#include + +/** + * C Programming/C Reference/stdio.h/printf: + * http://en.wikibooks.org/wiki/C_Programming/C_Reference/stdio.h/printf + * + * C Programming/Procedures and functions/printf: + * http://en.wikibooks.org/wiki/C_Programming/Procedures_and_functions/printf + * + * C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output: + * http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output + */ + +#define _printf printf // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +static BOOL test_bin_tohex_string(void) +{ + BOOL rc = FALSE; + { + const BYTE binbuffer[33] = { 0 }; + const char empty[33] = { 0 }; + char strbuffer[33] = { 0 }; + + size_t len = + winpr_BinToHexStringBuffer(NULL, sizeof(binbuffer), strbuffer, sizeof(strbuffer), TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer, 0, strbuffer, sizeof(strbuffer), TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = + winpr_BinToHexStringBuffer(binbuffer, sizeof(binbuffer), NULL, sizeof(strbuffer), TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer, sizeof(binbuffer), strbuffer, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer, 0, strbuffer, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer, sizeof(binbuffer), NULL, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(NULL, sizeof(binbuffer), strbuffer, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + + len = winpr_BinToHexStringBuffer(binbuffer, 0, NULL, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(NULL, 0, NULL, 0, TRUE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer, 0, NULL, 0, FALSE); + if (len != 0) + goto fail; + if (memcmp(strbuffer, empty, sizeof(strbuffer)) != 0) + goto fail; + } + { + const BYTE binbuffer1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }; + const char strbuffer1[] = "0102030405060708090A0B0C0D0E0F1011"; + const char strbuffer1_space[] = "01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11"; + + char buffer[1024] = { 0 }; + size_t len = winpr_BinToHexStringBuffer(binbuffer1, sizeof(binbuffer1), buffer, + sizeof(buffer), FALSE); + if (len != strnlen(strbuffer1, sizeof(strbuffer1))) + goto fail; + if (memcmp(strbuffer1, buffer, sizeof(strbuffer1)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer1, sizeof(binbuffer1), buffer, sizeof(buffer), + TRUE); + if (len != strnlen(strbuffer1_space, sizeof(strbuffer1_space))) + goto fail; + if (memcmp(strbuffer1_space, buffer, sizeof(strbuffer1_space)) != 0) + goto fail; + } + { + const BYTE binbuffer1[] = { 0xF1, 0xe2, 0xD3, 0xc4, 0xB5, 0xA6, 0x97, 0x88, 0x79, + 0x6A, 0x5b, 0x4C, 0x3d, 0x2E, 0x1f, 0x00, 0xfF }; + const char strbuffer1[] = "F1E2D3C4B5A69788796A5B4C3D2E1F00FF"; + const char strbuffer1_space[] = "F1 E2 D3 C4 B5 A6 97 88 79 6A 5B 4C 3D 2E 1F 00 FF"; + char buffer[1024] = { 0 }; + size_t len = winpr_BinToHexStringBuffer(binbuffer1, sizeof(binbuffer1), buffer, + sizeof(buffer), FALSE); + if (len != strnlen(strbuffer1, sizeof(strbuffer1))) + goto fail; + if (memcmp(strbuffer1, buffer, sizeof(strbuffer1)) != 0) + goto fail; + len = winpr_BinToHexStringBuffer(binbuffer1, sizeof(binbuffer1), buffer, sizeof(buffer), + TRUE); + if (len != strnlen(strbuffer1_space, sizeof(strbuffer1_space))) + goto fail; + if (memcmp(strbuffer1_space, buffer, sizeof(strbuffer1_space)) != 0) + goto fail; + } + { + } + rc = TRUE; +fail: + return rc; +} + +static BOOL test_bin_tohex_string_alloc(void) +{ + BOOL rc = FALSE; + char* str = NULL; + { + const BYTE binbuffer[33] = { 0 }; + + str = winpr_BinToHexString(NULL, sizeof(binbuffer), TRUE); + if (str) + goto fail; + str = winpr_BinToHexString(binbuffer, 0, TRUE); + if (str) + goto fail; + str = winpr_BinToHexString(binbuffer, 0, FALSE); + if (str) + goto fail; + str = winpr_BinToHexString(NULL, sizeof(binbuffer), FALSE); + if (str) + goto fail; + } + { + const BYTE binbuffer1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }; + const char strbuffer1[] = "0102030405060708090A0B0C0D0E0F1011"; + const char strbuffer1_space[] = "01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11"; + + str = winpr_BinToHexString(binbuffer1, sizeof(binbuffer1), FALSE); + if (!str) + goto fail; + if (memcmp(strbuffer1, str, sizeof(strbuffer1)) != 0) + goto fail; + free(str); + str = winpr_BinToHexString(binbuffer1, sizeof(binbuffer1), TRUE); + if (!str) + goto fail; + if (memcmp(strbuffer1_space, str, sizeof(strbuffer1_space)) != 0) + goto fail; + free(str); + str = NULL; + } + { + const BYTE binbuffer1[] = { 0xF1, 0xe2, 0xD3, 0xc4, 0xB5, 0xA6, 0x97, 0x88, 0x79, + 0x6A, 0x5b, 0x4C, 0x3d, 0x2E, 0x1f, 0x00, 0xfF }; + const char strbuffer1[] = "F1E2D3C4B5A69788796A5B4C3D2E1F00FF"; + const char strbuffer1_space[] = "F1 E2 D3 C4 B5 A6 97 88 79 6A 5B 4C 3D 2E 1F 00 FF"; + str = winpr_BinToHexString(binbuffer1, sizeof(binbuffer1), FALSE); + if (!str) + goto fail; + if (memcmp(strbuffer1, str, sizeof(strbuffer1)) != 0) + goto fail; + + free(str); + str = winpr_BinToHexString(binbuffer1, sizeof(binbuffer1), TRUE); + if (!str) + goto fail; + if (memcmp(strbuffer1_space, str, sizeof(strbuffer1_space)) != 0) + goto fail; + free(str); + str = NULL; + } + rc = TRUE; +fail: + free(str); + return rc; +} + +static BOOL test_hex_string_to_bin(void) +{ + BOOL rc = FALSE; + { + const char stringbuffer[] = "123456789ABCDEFabcdef"; + const BYTE empty[1024] = { 0 }; + BYTE buffer[1024] = { 0 }; + size_t len = winpr_HexStringToBinBuffer(NULL, 0, NULL, 0); + if (len != 0) + goto fail; + if (memcmp(buffer, empty, sizeof(buffer)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(NULL, sizeof(stringbuffer), buffer, sizeof(buffer)); + if (len != 0) + goto fail; + if (memcmp(buffer, empty, sizeof(buffer)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, 0, buffer, sizeof(buffer)); + if (len != 0) + goto fail; + if (memcmp(buffer, empty, sizeof(buffer)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), NULL, sizeof(buffer)); + if (len != 0) + goto fail; + if (memcmp(buffer, empty, sizeof(buffer)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, 0); + if (len != 0) + goto fail; + if (memcmp(buffer, empty, sizeof(buffer)) != 0) + goto fail; + } + { + const char stringbuffer[] = "123456789ABCDEF1abcdef"; + const BYTE expected[] = { + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf1, 0xab, 0xcd, 0xef + }; + BYTE buffer[32] = { 0 }; + size_t len = + winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, sizeof(buffer)); + if (len != sizeof(expected)) + goto fail; + if (memcmp(buffer, expected, sizeof(expected)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, + sizeof(expected) / 2); + if (len != sizeof(expected) / 2) + goto fail; + if (memcmp(buffer, expected, sizeof(expected) / 2) != 0) + goto fail; + } + { + const char stringbuffer[] = "12 34 56 78 9A BC DE F1 ab cd ef"; + const BYTE expected[] = { + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf1, 0xab, 0xcd, 0xef + }; + BYTE buffer[1024] = { 0 }; + size_t len = + winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, sizeof(buffer)); + if (len != sizeof(expected)) + goto fail; + if (memcmp(buffer, expected, sizeof(expected)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, + sizeof(expected) / 2); + if (len != sizeof(expected) / 2) + goto fail; + if (memcmp(buffer, expected, sizeof(expected) / 2) != 0) + goto fail; + } + { + const char stringbuffer[] = "123456789ABCDEF1abcdef9"; + const BYTE expected[] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, + 0xde, 0xf1, 0xab, 0xcd, 0xef, 0x09 }; + BYTE buffer[1024] = { 0 }; + size_t len = + winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, sizeof(buffer)); + if (len != sizeof(expected)) + goto fail; + if (memcmp(buffer, expected, sizeof(expected)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, + sizeof(expected) / 2); + if (len != sizeof(expected) / 2) + goto fail; + if (memcmp(buffer, expected, sizeof(expected) / 2) != 0) + goto fail; + } + { + const char stringbuffer[] = "12 34 56 78 9A BC DE F1 ab cd ef 9"; + const BYTE expected[] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, + 0xde, 0xf1, 0xab, 0xcd, 0xef, 0x09 }; + BYTE buffer[1024] = { 0 }; + size_t len = + winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, sizeof(buffer)); + if (len != sizeof(expected)) + goto fail; + if (memcmp(buffer, expected, sizeof(expected)) != 0) + goto fail; + len = winpr_HexStringToBinBuffer(stringbuffer, sizeof(stringbuffer), buffer, + sizeof(expected) / 2); + if (len != sizeof(expected) / 2) + goto fail; + if (memcmp(buffer, expected, sizeof(expected) / 2) != 0) + goto fail; + } + rc = TRUE; +fail: + return rc; +} + +int TestPrint(int argc, char* argv[]) +{ + int a = 0; + int b = 0; + float c = NAN; + float d = NAN; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + /** + * 7 + * 7 + * 007 + * 5.10 + */ + + a = 15; + b = a / 2; + _printf("%d\n", b); + _printf("%3d\n", b); + _printf("%03d\n", b); + c = 15.3f; + d = c / 3.0f; + _printf("%3.2f\n", d); + + /** + * 0 -17.778 + * 20 -6.667 + * 40 04.444 + * 60 15.556 + * 80 26.667 + * 100 37.778 + * 120 48.889 + * 140 60.000 + * 160 71.111 + * 180 82.222 + * 200 93.333 + * 220 104.444 + * 240 115.556 + * 260 126.667 + * 280 137.778 + * 300 148.889 + */ + + for (int a = 0; a <= 300; a = a + 20) + _printf("%3d %06.3f\n", a, (5.0 / 9.0) * (a - 32)); + + /** + * The color: blue + * First number: 12345 + * Second number: 0025 + * Third number: 1234 + * Float number: 3.14 + * Hexadecimal: ff + * Octal: 377 + * Unsigned value: 150 + * Just print the percentage sign % + */ + + _printf("The color: %s\n", "blue"); + _printf("First number: %d\n", 12345); + _printf("Second number: %04d\n", 25); + _printf("Third number: %i\n", 1234); + _printf("Float number: %3.2f\n", 3.14159); + _printf("Hexadecimal: %x/%X\n", 255, 255); + _printf("Octal: %o\n", 255); + _printf("Unsigned value: %u\n", 150); + _printf("Just print the percentage sign %%\n"); + + /** + * :Hello, world!: + * : Hello, world!: + * :Hello, wor: + * :Hello, world!: + * :Hello, world! : + * :Hello, world!: + * : Hello, wor: + * :Hello, wor : + */ + + _printf(":%s:\n", "Hello, world!"); + _printf(":%15s:\n", "Hello, world!"); + _printf(":%.10s:\n", "Hello, world!"); + _printf(":%-10s:\n", "Hello, world!"); + _printf(":%-15s:\n", "Hello, world!"); + _printf(":%.15s:\n", "Hello, world!"); + _printf(":%15.10s:\n", "Hello, world!"); + _printf(":%-15.10s:\n", "Hello, world!"); + + if (!test_bin_tohex_string()) + return -1; + if (!test_bin_tohex_string_alloc()) + return -1; + if (!test_hex_string_to_bin()) + return -1; + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPubSub.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPubSub.c new file mode 100644 index 0000000000000000000000000000000000000000..0b05b15c59bda90f450113a9a263a91fe01d853c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestPubSub.c @@ -0,0 +1,73 @@ + +#include +#include +#include + +DEFINE_EVENT_BEGIN(MouseMotion) +int x; +int y; +DEFINE_EVENT_END(MouseMotion) + +DEFINE_EVENT_BEGIN(MouseButton) +int x; +int y; +int flags; +int button; +DEFINE_EVENT_END(MouseButton) + +static void MouseMotionEventHandler(void* context, const MouseMotionEventArgs* e) +{ + printf("MouseMotionEvent: x: %d y: %d\n", e->x, e->y); +} + +static void MouseButtonEventHandler(void* context, const MouseButtonEventArgs* e) +{ + printf("MouseButtonEvent: x: %d y: %d flags: %d button: %d\n", e->x, e->y, e->flags, e->button); +} + +static wEventType Node_Events[] = { DEFINE_EVENT_ENTRY(MouseMotion), + DEFINE_EVENT_ENTRY(MouseButton) }; + +#define NODE_EVENT_COUNT (sizeof(Node_Events) / sizeof(wEventType)) + +int TestPubSub(int argc, char* argv[]) +{ + wPubSub* node = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + node = PubSub_New(TRUE); + if (!node) + return -1; + + PubSub_AddEventTypes(node, Node_Events, NODE_EVENT_COUNT); + + PubSub_SubscribeMouseMotion(node, MouseMotionEventHandler); + PubSub_SubscribeMouseButton(node, MouseButtonEventHandler); + + /* Call Event Handler */ + { + MouseMotionEventArgs e; + + e.x = 64; + e.y = 128; + + PubSub_OnMouseMotion(node, NULL, &e); + } + + { + MouseButtonEventArgs e; + + e.x = 23; + e.y = 56; + e.flags = 7; + e.button = 1; + + PubSub_OnMouseButton(node, NULL, &e); + } + + PubSub_Free(node); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestQueue.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..5f0c5955eb89bfb8540ecdc497052bc234f6094b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestQueue.c @@ -0,0 +1,58 @@ + +#include +#include +#include + +int TestQueue(int argc, char* argv[]) +{ + size_t item = 0; + size_t count = 0; + wQueue* queue = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + queue = Queue_New(TRUE, -1, -1); + if (!queue) + return -1; + + for (size_t index = 1; index <= 10; index++) + { + Queue_Enqueue(queue, (void*)index); + } + + count = Queue_Count(queue); + printf("queue count: %" PRIuz "\n", count); + + for (size_t index = 1; index <= 10; index++) + { + item = (size_t)Queue_Dequeue(queue); + + if (item != index) + return -1; + } + + count = Queue_Count(queue); + printf("queue count: %" PRIuz "\n", count); + + Queue_Enqueue(queue, (void*)(size_t)1); + Queue_Enqueue(queue, (void*)(size_t)2); + Queue_Enqueue(queue, (void*)(size_t)3); + + Queue_Dequeue(queue); + Queue_Dequeue(queue); + + Queue_Enqueue(queue, (void*)(size_t)4); + Queue_Enqueue(queue, (void*)(size_t)5); + Queue_Enqueue(queue, (void*)(size_t)6); + + Queue_Dequeue(queue); + Queue_Dequeue(queue); + Queue_Dequeue(queue); + Queue_Dequeue(queue); + + Queue_Clear(queue); + Queue_Free(queue); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStream.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStream.c new file mode 100644 index 0000000000000000000000000000000000000000..34fd6fe5b6a0dc9b6224e965801728317662ae72 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStream.c @@ -0,0 +1,858 @@ +#include +#include +#include +#include + +static BOOL TestStream_Verify(wStream* s, size_t mincap, size_t len, size_t pos) +{ + if (Stream_Buffer(s) == NULL) + { + printf("stream buffer is null\n"); + return FALSE; + } + + if (Stream_ConstPointer(s) == NULL) + { + printf("stream pointer is null\n"); + return FALSE; + } + + if (Stream_PointerAs(s, BYTE) < Stream_Buffer(s)) + { + printf("stream pointer (%p) or buffer (%p) is invalid\n", Stream_ConstPointer(s), + (void*)Stream_Buffer(s)); + return FALSE; + } + + if (Stream_Capacity(s) < mincap) + { + printf("stream capacity is %" PRIuz " but minimum expected value is %" PRIuz "\n", + Stream_Capacity(s), mincap); + return FALSE; + } + + if (Stream_Length(s) != len) + { + printf("stream has unexpected length (%" PRIuz " instead of %" PRIuz ")\n", + Stream_Length(s), len); + return FALSE; + } + + if (Stream_GetPosition(s) != pos) + { + printf("stream has unexpected position (%" PRIuz " instead of %" PRIuz ")\n", + Stream_GetPosition(s), pos); + return FALSE; + } + + if (Stream_GetPosition(s) > Stream_Length(s)) + { + printf("stream position (%" PRIuz ") exceeds length (%" PRIuz ")\n", Stream_GetPosition(s), + Stream_Length(s)); + return FALSE; + } + + if (Stream_GetPosition(s) > Stream_Capacity(s)) + { + printf("stream position (%" PRIuz ") exceeds capacity (%" PRIuz ")\n", + Stream_GetPosition(s), Stream_Capacity(s)); + return FALSE; + } + + if (Stream_Length(s) > Stream_Capacity(s)) + { + printf("stream length (%" PRIuz ") exceeds capacity (%" PRIuz ")\n", Stream_Length(s), + Stream_Capacity(s)); + return FALSE; + } + + if (Stream_GetRemainingLength(s) != len - pos) + { + printf("stream remaining length (%" PRIuz " instead of %" PRIuz ")\n", + Stream_GetRemainingLength(s), len - pos); + return FALSE; + } + + return TRUE; +} + +static BOOL TestStream_New(void) +{ + /* Test creation of a 0-size stream with no buffer */ + wStream* s = Stream_New(NULL, 0); + + if (s) + return FALSE; + Stream_Free(s, TRUE); + + return TRUE; +} + +static BOOL TestStream_Static(void) +{ + BYTE buffer[20] = { 0 }; + wStream staticStream = { 0 }; + wStream* s = &staticStream; + UINT16 v = 0; + /* Test creation of a static stream */ + Stream_StaticInit(s, buffer, sizeof(buffer)); + Stream_Write_UINT16(s, 0xcab1); + Stream_SetPosition(s, 0); + Stream_Read_UINT16(s, v); + + if (v != 0xcab1) + return FALSE; + + Stream_SetPosition(s, 0); + Stream_Write_UINT16(s, 1); + + if (!Stream_EnsureRemainingCapacity(s, 10)) /* we can ask for 10 bytes */ + return FALSE; + + /* 30 is bigger than the buffer, it will be reallocated on the heap */ + if (!Stream_EnsureRemainingCapacity(s, 30) || !s->isOwner) + return FALSE; + + Stream_Write_UINT16(s, 2); + Stream_SetPosition(s, 0); + Stream_Read_UINT16(s, v); + + if (v != 1) + return FALSE; + + Stream_Read_UINT16(s, v); + + if (v != 2) + return FALSE; + + // Intentional warning as the stream is not allocated. + // Still, Stream_Free should not release such memory, therefore this statement + // is required to test that. + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + Stream_Free(s, TRUE); + WINPR_PRAGMA_DIAG_POP + return TRUE; +} + +static BOOL TestStream_Create(size_t count, BOOL selfAlloc) +{ + size_t len = 0; + size_t cap = 0; + wStream* s = NULL; + void* buffer = NULL; + + for (size_t i = 0; i < count; i++) + { + len = cap = i + 1; + + if (selfAlloc) + { + if (!(buffer = malloc(cap))) + { + printf("%s: failed to allocate buffer of size %" PRIuz "\n", __func__, cap); + goto fail; + } + } + + if (!(s = Stream_New(selfAlloc ? buffer : NULL, len))) + { + printf("%s: Stream_New failed for stream #%" PRIuz "\n", __func__, i); + goto fail; + } + + if (!TestStream_Verify(s, cap, len, 0)) + { + goto fail; + } + + for (size_t pos = 0; pos < len; pos++) + { + Stream_SetPosition(s, pos); + Stream_SealLength(s); + + if (!TestStream_Verify(s, cap, pos, pos)) + { + goto fail; + } + } + + if (selfAlloc) + { + memset(buffer, (BYTE)(i % 256), cap); + + if (memcmp(buffer, Stream_Buffer(s), cap) != 0) + { + printf("%s: buffer memory corruption\n", __func__); + goto fail; + } + } + + Stream_Free(s, buffer ? FALSE : TRUE); + free(buffer); + } + + return TRUE; +fail: + free(buffer); + + if (s) + { + Stream_Free(s, buffer ? FALSE : TRUE); + } + + return FALSE; +} + +static BOOL TestStream_Extent(UINT32 maxSize) +{ + wStream* s = NULL; + BOOL result = FALSE; + + if (!(s = Stream_New(NULL, 1))) + { + printf("%s: Stream_New failed\n", __func__); + return FALSE; + } + + for (UINT32 i = 1; i < maxSize; i++) + { + if (i % 2) + { + if (!Stream_EnsureRemainingCapacity(s, i)) + goto fail; + } + else + { + if (!Stream_EnsureCapacity(s, i)) + goto fail; + } + + Stream_SetPosition(s, i); + Stream_SealLength(s); + + if (!TestStream_Verify(s, i, i, i)) + { + printf("%s: failed to verify stream in iteration %" PRIu32 "\n", __func__, i); + goto fail; + } + } + + result = TRUE; +fail: + + if (s) + { + Stream_Free(s, TRUE); + } + + return result; +} + +#define Stream_Peek_UINT8_BE Stream_Peek_UINT8 +#define Stream_Read_UINT8_BE Stream_Read_UINT8 +#define Stream_Peek_Get_UINT8_BE Stream_Peek_Get_UINT8 +#define Stream_Get_UINT8_BE Stream_Get_UINT8 +#define Stream_Peek_INT8_BE Stream_Peek_INT8 +#define Stream_Peek_Get_INT8_BE Stream_Peek_Get_INT8 +#define Stream_Read_INT8_BE Stream_Read_INT8 +#define Stream_Get_INT8_BE Stream_Get_INT8 + +#define TestStream_PeekAndRead(_s, _r, _t) \ + do \ + { \ + _t _a = 0; \ + _t _b = 0; \ + BYTE* _p = Stream_Buffer(_s); \ + Stream_SetPosition(_s, 0); \ + Stream_Peek_##_t(_s, _a); \ + Stream_Read_##_t(_s, _b); \ + if (_a != _b) \ + { \ + printf("%s: test1 " #_t "_LE failed\n", __func__); \ + (_r) = FALSE; \ + } \ + Stream_Rewind(_s, sizeof(_t)); \ + const _t _d = Stream_Peek_Get_##_t(_s); \ + const _t _c = Stream_Get_##_t(_s); \ + if (_c != _d) \ + { \ + printf("%s: test1 " #_t "_LE failed\n", __func__); \ + (_r) = FALSE; \ + } \ + for (size_t _i = 0; _i < sizeof(_t); _i++) \ + { \ + if (((_a >> (_i * 8)) & 0xFF) != _p[_i]) \ + { \ + printf("%s: test2 " #_t "_LE failed\n", __func__); \ + (_r) = FALSE; \ + break; \ + } \ + } \ + /* printf("a: 0x%016llX\n", a); */ \ + Stream_SetPosition(_s, 0); \ + Stream_Peek_##_t##_BE(_s, _a); \ + Stream_Read_##_t##_BE(_s, _b); \ + if (_a != _b) \ + { \ + printf("%s: test1 " #_t "_BE failed\n", __func__); \ + (_r) = FALSE; \ + } \ + Stream_Rewind(_s, sizeof(_t)); \ + const _t _e = Stream_Peek_Get_##_t##_BE(_s); \ + const _t _f = Stream_Get_##_t##_BE(_s); \ + if (_e != _f) \ + { \ + printf("%s: test1 " #_t "_BE failed\n", __func__); \ + (_r) = FALSE; \ + } \ + for (size_t _i = 0; _i < sizeof(_t); _i++) \ + { \ + if (((_a >> (_i * 8)) & 0xFF) != _p[sizeof(_t) - _i - 1]) \ + { \ + printf("%s: test2 " #_t "_BE failed\n", __func__); \ + (_r) = FALSE; \ + break; \ + } \ + } \ + /* printf("a: 0x%016llX\n", a); */ \ + } while (0) + +static BOOL TestStream_WriteAndRead(UINT64 value) +{ + union + { + UINT8 u8; + UINT16 u16; + UINT32 u32; + UINT64 u64; + INT8 i8; + INT16 i16; + INT32 i32; + INT64 i64; + } val; + val.u64 = value; + + wStream* s = Stream_New(NULL, 1024); + if (!s) + return FALSE; + BOOL rc = FALSE; + + { + Stream_Write_UINT8(s, val.u8); + Stream_Rewind_UINT8(s); + const UINT8 ru8 = Stream_Get_UINT8(s); + Stream_Rewind_UINT8(s); + if (val.u8 != ru8) + goto fail; + } + { + Stream_Write_UINT16(s, val.u16); + Stream_Rewind_UINT16(s); + const UINT16 ru = Stream_Get_UINT16(s); + Stream_Rewind_UINT16(s); + if (val.u16 != ru) + goto fail; + } + { + Stream_Write_UINT16_BE(s, val.u16); + Stream_Rewind_UINT16(s); + const UINT16 ru = Stream_Get_UINT16_BE(s); + Stream_Rewind_UINT16(s); + if (val.u16 != ru) + goto fail; + } + { + Stream_Write_UINT32(s, val.u32); + Stream_Rewind_UINT32(s); + const UINT32 ru = Stream_Get_UINT32(s); + Stream_Rewind_UINT32(s); + if (val.u32 != ru) + goto fail; + } + { + Stream_Write_UINT32_BE(s, val.u32); + Stream_Rewind_UINT32(s); + const UINT32 ru = Stream_Get_UINT32_BE(s); + Stream_Rewind_UINT32(s); + if (val.u32 != ru) + goto fail; + } + { + Stream_Write_UINT64(s, val.u64); + Stream_Rewind_UINT64(s); + const UINT64 ru = Stream_Get_UINT64(s); + Stream_Rewind_UINT64(s); + if (val.u64 != ru) + goto fail; + } + { + Stream_Write_UINT64_BE(s, val.u64); + Stream_Rewind_UINT64(s); + const UINT64 ru = Stream_Get_UINT64_BE(s); + Stream_Rewind_UINT64(s); + if (val.u64 != ru) + goto fail; + } + { + Stream_Write_INT8(s, val.i8); + Stream_Rewind(s, 1); + const INT8 ru8 = Stream_Get_INT8(s); + Stream_Rewind(s, 1); + if (val.i8 != ru8) + goto fail; + } + { + Stream_Write_INT16(s, val.i16); + Stream_Rewind(s, 2); + const INT16 ru = Stream_Get_INT16(s); + Stream_Rewind(s, 2); + if (val.i16 != ru) + goto fail; + } + { + Stream_Write_INT16_BE(s, val.i16); + Stream_Rewind(s, 2); + const INT16 ru = Stream_Get_INT16_BE(s); + Stream_Rewind(s, 2); + if (val.i16 != ru) + goto fail; + } + { + Stream_Write_INT32(s, val.i32); + Stream_Rewind(s, 4); + const INT32 ru = Stream_Get_INT32(s); + Stream_Rewind(s, 4); + if (val.i32 != ru) + goto fail; + } + { + Stream_Write_INT32_BE(s, val.i32); + Stream_Rewind(s, 4); + const INT32 ru = Stream_Get_INT32_BE(s); + Stream_Rewind(s, 4); + if (val.i32 != ru) + goto fail; + } + { + Stream_Write_INT64(s, val.i64); + Stream_Rewind(s, 8); + const INT64 ru = Stream_Get_INT64(s); + Stream_Rewind(s, 8); + if (val.i64 != ru) + goto fail; + } + { + Stream_Write_INT64_BE(s, val.i64); + Stream_Rewind(s, 8); + const INT64 ru = Stream_Get_INT64_BE(s); + Stream_Rewind(s, 8); + if (val.i64 != ru) + goto fail; + } + + rc = TRUE; +fail: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Reading(void) +{ + BYTE src[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; + wStream* s = NULL; + BOOL result = TRUE; + + if (!(s = Stream_New(src, sizeof(src)))) + { + printf("%s: Stream_New failed\n", __func__); + return FALSE; + } + + TestStream_PeekAndRead(s, result, UINT8); + TestStream_PeekAndRead(s, result, INT8); + TestStream_PeekAndRead(s, result, UINT16); + TestStream_PeekAndRead(s, result, INT16); + TestStream_PeekAndRead(s, result, UINT32); + TestStream_PeekAndRead(s, result, INT32); + TestStream_PeekAndRead(s, result, UINT64); + TestStream_PeekAndRead(s, result, INT64); + Stream_Free(s, FALSE); + return result; +} + +static BOOL TestStream_Write(void) +{ + BOOL rc = FALSE; + UINT8 u8 = 0; + UINT16 u16 = 0; + UINT32 u32 = 0; + UINT64 u64 = 0; + const BYTE data[] = "someteststreamdata"; + wStream* s = Stream_New(NULL, 100); + + if (!s) + goto out; + + if (s->pointer != s->buffer) + goto out; + + Stream_Write(s, data, sizeof(data)); + + if (memcmp(Stream_Buffer(s), data, sizeof(data)) == 0) + rc = TRUE; + + if (s->pointer != s->buffer + sizeof(data)) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Write_UINT8(s, 42); + + if (s->pointer != s->buffer + 1) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Peek_UINT8(s, u8); + + if (u8 != 42) + goto out; + + Stream_Write_UINT16(s, 0x1234); + + if (s->pointer != s->buffer + 2) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Peek_UINT16(s, u16); + + if (u16 != 0x1234) + goto out; + + Stream_Write_UINT32(s, 0x12345678UL); + + if (s->pointer != s->buffer + 4) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Peek_UINT32(s, u32); + + if (u32 != 0x12345678UL) + goto out; + + Stream_Write_UINT64(s, 0x1234567890ABCDEFULL); + + if (s->pointer != s->buffer + 8) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Peek_UINT64(s, u64); + + if (u64 != 0x1234567890ABCDEFULL) + goto out; + +out: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Seek(void) +{ + BOOL rc = FALSE; + wStream* s = Stream_New(NULL, 100); + + if (!s) + goto out; + + if (s->pointer != s->buffer) + goto out; + + Stream_Seek(s, 5); + + if (s->pointer != s->buffer + 5) + goto out; + + Stream_Seek_UINT8(s); + + if (s->pointer != s->buffer + 6) + goto out; + + Stream_Seek_UINT16(s); + + if (s->pointer != s->buffer + 8) + goto out; + + Stream_Seek_UINT32(s); + + if (s->pointer != s->buffer + 12) + goto out; + + Stream_Seek_UINT64(s); + + if (s->pointer != s->buffer + 20) + goto out; + + rc = TRUE; +out: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Rewind(void) +{ + BOOL rc = FALSE; + wStream* s = Stream_New(NULL, 100); + + if (!s) + goto out; + + if (s->pointer != s->buffer) + goto out; + + Stream_Seek(s, 100); + + if (s->pointer != s->buffer + 100) + goto out; + + Stream_Rewind(s, 10); + + if (s->pointer != s->buffer + 90) + goto out; + + Stream_Rewind_UINT8(s); + + if (s->pointer != s->buffer + 89) + goto out; + + Stream_Rewind_UINT16(s); + + if (s->pointer != s->buffer + 87) + goto out; + + Stream_Rewind_UINT32(s); + + if (s->pointer != s->buffer + 83) + goto out; + + Stream_Rewind_UINT64(s); + + if (s->pointer != s->buffer + 75) + goto out; + + rc = TRUE; +out: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Zero(void) +{ + BOOL rc = FALSE; + const BYTE data[] = "someteststreamdata"; + wStream* s = Stream_New(NULL, sizeof(data)); + + if (!s) + goto out; + + Stream_Write(s, data, sizeof(data)); + + if (memcmp(Stream_Buffer(s), data, sizeof(data)) != 0) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Zero(s, 5); + + if (s->pointer != s->buffer + 5) + goto out; + + if (memcmp(Stream_ConstPointer(s), data + 5, sizeof(data) - 5) != 0) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + for (UINT32 x = 0; x < 5; x++) + { + UINT8 val = 0; + Stream_Read_UINT8(s, val); + + if (val != 0) + goto out; + } + + rc = TRUE; +out: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Fill(void) +{ + BOOL rc = FALSE; + const BYTE fill[7] = "XXXXXXX"; + const BYTE data[] = "someteststreamdata"; + wStream* s = Stream_New(NULL, sizeof(data)); + + if (!s) + goto out; + + Stream_Write(s, data, sizeof(data)); + + if (memcmp(Stream_Buffer(s), data, sizeof(data)) != 0) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Fill(s, fill[0], sizeof(fill)); + + if (s->pointer != s->buffer + sizeof(fill)) + goto out; + + if (memcmp(Stream_ConstPointer(s), data + sizeof(fill), sizeof(data) - sizeof(fill)) != 0) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + if (memcmp(Stream_ConstPointer(s), fill, sizeof(fill)) != 0) + goto out; + + rc = TRUE; +out: + Stream_Free(s, TRUE); + return rc; +} + +static BOOL TestStream_Copy(void) +{ + BOOL rc = FALSE; + const BYTE data[] = "someteststreamdata"; + wStream* s = Stream_New(NULL, sizeof(data)); + wStream* d = Stream_New(NULL, sizeof(data)); + + if (!s || !d) + goto out; + + if (s->pointer != s->buffer) + goto out; + + Stream_Write(s, data, sizeof(data)); + + if (memcmp(Stream_Buffer(s), data, sizeof(data)) != 0) + goto out; + + if (s->pointer != s->buffer + sizeof(data)) + goto out; + + Stream_SetPosition(s, 0); + + if (s->pointer != s->buffer) + goto out; + + Stream_Copy(s, d, sizeof(data)); + + if (s->pointer != s->buffer + sizeof(data)) + goto out; + + if (d->pointer != d->buffer + sizeof(data)) + goto out; + + if (Stream_GetPosition(s) != Stream_GetPosition(d)) + goto out; + + if (memcmp(Stream_Buffer(s), data, sizeof(data)) != 0) + goto out; + + if (memcmp(Stream_Buffer(d), data, sizeof(data)) != 0) + goto out; + + rc = TRUE; +out: + Stream_Free(s, TRUE); + Stream_Free(d, TRUE); + return rc; +} + +int TestStream(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!TestStream_Create(200, FALSE)) + return 1; + + if (!TestStream_Create(200, TRUE)) + return 2; + + if (!TestStream_Extent(4096)) + return 3; + + if (!TestStream_Reading()) + return 4; + + if (!TestStream_New()) + return 5; + + if (!TestStream_Write()) + return 6; + + if (!TestStream_Seek()) + return 7; + + if (!TestStream_Rewind()) + return 8; + + if (!TestStream_Zero()) + return 9; + + if (!TestStream_Fill()) + return 10; + + if (!TestStream_Copy()) + return 11; + + if (!TestStream_Static()) + return 12; + + if (!TestStream_WriteAndRead(0x1234567890abcdef)) + return 13; + + for (size_t x = 0; x < 10; x++) + { + UINT64 val = 0; + winpr_RAND(&val, sizeof(val)); + if (!TestStream_WriteAndRead(val)) + return 14; + } + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStreamPool.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStreamPool.c new file mode 100644 index 0000000000000000000000000000000000000000..615a5ac9bff2e5aba4f5b77416a152648260e03a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestStreamPool.c @@ -0,0 +1,82 @@ + +#include +#include +#include + +#define BUFFER_SIZE 16384 + +int TestStreamPool(int argc, char* argv[]) +{ + wStream* s[5] = { 0 }; + char buffer[8192] = { 0 }; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + wStreamPool* pool = StreamPool_New(TRUE, BUFFER_SIZE); + + s[0] = StreamPool_Take(pool, 0); + s[1] = StreamPool_Take(pool, 0); + s[2] = StreamPool_Take(pool, 0); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + Stream_Release(s[0]); + Stream_Release(s[1]); + Stream_Release(s[2]); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + s[3] = StreamPool_Take(pool, 0); + s[4] = StreamPool_Take(pool, 0); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + Stream_Release(s[3]); + Stream_Release(s[4]); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + s[2] = StreamPool_Take(pool, 0); + s[3] = StreamPool_Take(pool, 0); + s[4] = StreamPool_Take(pool, 0); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + Stream_AddRef(s[2]); + + Stream_AddRef(s[3]); + Stream_AddRef(s[3]); + + Stream_AddRef(s[4]); + Stream_AddRef(s[4]); + Stream_AddRef(s[4]); + + Stream_Release(s[2]); + Stream_Release(s[2]); + + Stream_Release(s[3]); + Stream_Release(s[3]); + Stream_Release(s[3]); + + Stream_Release(s[4]); + Stream_Release(s[4]); + Stream_Release(s[4]); + Stream_Release(s[4]); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + s[2] = StreamPool_Take(pool, 0); + s[3] = StreamPool_Take(pool, 0); + s[4] = StreamPool_Take(pool, 0); + + printf("%s\n", StreamPool_GetStatistics(pool, buffer, sizeof(buffer))); + + Stream_Release(s[2]); + Stream_Release(s[3]); + Stream_Release(s[4]); + + StreamPool_Free(pool); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestVersion.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestVersion.c new file mode 100644 index 0000000000000000000000000000000000000000..b204b0ff76848c48749fdd3487e95073350b89ff --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestVersion.c @@ -0,0 +1,47 @@ + +#include + +#include +#include + +int TestVersion(int argc, char* argv[]) +{ + const char* version = NULL; + const char* git = NULL; + const char* build = NULL; + int major = 0; + int minor = 0; + int revision = 0; + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + winpr_get_version(&major, &minor, &revision); + + if (major != WINPR_VERSION_MAJOR) + return -1; + + if (minor != WINPR_VERSION_MINOR) + return -1; + + if (revision != WINPR_VERSION_REVISION) + return -1; + + version = winpr_get_version_string(); + + if (!version) + return -1; + + git = winpr_get_build_revision(); + + if (!git) + return -1; + + if (strncmp(git, WINPR_GIT_REVISION, sizeof(WINPR_GIT_REVISION)) != 0) + return -1; + + build = winpr_get_build_config(); + + if (!build) + return -1; + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLog.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLog.c new file mode 100644 index 0000000000000000000000000000000000000000..f75b85d02d813c4f0421f9c9d0cede39b0b63e3c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLog.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include + +int TestWLog(int argc, char* argv[]) +{ + wLog* root = NULL; + wLog* logA = NULL; + wLog* logB = NULL; + wLogLayout* layout = NULL; + wLogAppender* appender = NULL; + char* tmp_path = NULL; + char* wlog_file = NULL; + int result = 1; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!(tmp_path = GetKnownPath(KNOWN_PATH_TEMP))) + { + (void)fprintf(stderr, "Failed to get temporary directory!\n"); + goto out; + } + + root = WLog_GetRoot(); + + WLog_SetLogAppenderType(root, WLOG_APPENDER_BINARY); + + appender = WLog_GetLogAppender(root); + if (!WLog_ConfigureAppender(appender, "outputfilename", "test_w.log")) + goto out; + if (!WLog_ConfigureAppender(appender, "outputfilepath", tmp_path)) + goto out; + + layout = WLog_GetLogLayout(root); + WLog_Layout_SetPrefixFormat(root, layout, "[%lv:%mn] [%fl|%fn|%ln] - "); + + WLog_OpenAppender(root); + + logA = WLog_Get("com.test.ChannelA"); + logB = WLog_Get("com.test.ChannelB"); + + WLog_SetLogLevel(logA, WLOG_INFO); + WLog_SetLogLevel(logB, WLOG_ERROR); + + WLog_Print(logA, WLOG_INFO, "this is a test"); + WLog_Print(logA, WLOG_WARN, "this is a %dnd %s", 2, "test"); + WLog_Print(logA, WLOG_ERROR, "this is an error"); + WLog_Print(logA, WLOG_TRACE, "this is a trace output"); + + WLog_Print(logB, WLOG_INFO, "just some info"); + WLog_Print(logB, WLOG_WARN, "we're warning a %dnd %s", 2, "time"); + WLog_Print(logB, WLOG_ERROR, "we've got an error"); + WLog_Print(logB, WLOG_TRACE, "leaving a trace behind"); + + WLog_CloseAppender(root); + + if ((wlog_file = GetCombinedPath(tmp_path, "test_w.log"))) + winpr_DeleteFile(wlog_file); + + result = 0; +out: + free(wlog_file); + free(tmp_path); + + return result; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLogCallback.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLogCallback.c new file mode 100644 index 0000000000000000000000000000000000000000..b1ce67b567306a11b2e8324a951915e24bb94fbf --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/test/TestWLogCallback.c @@ -0,0 +1,128 @@ +#include +#include +#include +#include + +typedef struct +{ + UINT32 level; + char* msg; + char* channel; +} test_t; + +static const char* function = NULL; +static const char* channels[] = { "com.test.channelA", "com.test.channelB" }; + +static const test_t messages[] = { { WLOG_INFO, "this is a test", "com.test.channelA" }, + { WLOG_INFO, "Just some info", "com.test.channelB" }, + { WLOG_WARN, "this is a %dnd %s", "com.test.channelA" }, + { WLOG_WARN, "we're warning a %dnd %s", "com.test.channelB" }, + { WLOG_ERROR, "this is an error", "com.test.channelA" }, + { WLOG_ERROR, "we've got an error", "com.test.channelB" }, + { WLOG_TRACE, "this is a trace output", "com.test.channelA" }, + { WLOG_TRACE, "leaving a trace behind", "com.test.channelB" } }; + +static BOOL success = TRUE; +static int pos = 0; + +static BOOL check(const wLogMessage* msg) +{ + BOOL rc = TRUE; + if (!msg) + rc = FALSE; + else if (strcmp(msg->FileName, __FILE__) != 0) + rc = FALSE; + else if (strcmp(msg->FunctionName, function) != 0) + rc = FALSE; + else if (strcmp(msg->PrefixString, messages[pos].channel) != 0) + rc = FALSE; + else if (msg->Level != messages[pos].level) + rc = FALSE; + else if (strcmp(msg->FormatString, messages[pos].msg) != 0) + rc = FALSE; + pos++; + + if (!rc) + { + (void)fprintf(stderr, "Test failed!\n"); + success = FALSE; + } + return rc; +} + +static BOOL CallbackAppenderMessage(const wLogMessage* msg) +{ + check(msg); + return TRUE; +} + +static BOOL CallbackAppenderData(const wLogMessage* msg) +{ + (void)fprintf(stdout, "%s\n", __func__); + return TRUE; +} + +static BOOL CallbackAppenderImage(const wLogMessage* msg) +{ + (void)fprintf(stdout, "%s\n", __func__); + return TRUE; +} + +static BOOL CallbackAppenderPackage(const wLogMessage* msg) +{ + (void)fprintf(stdout, "%s\n", __func__); + return TRUE; +} + +int TestWLogCallback(int argc, char* argv[]) +{ + wLog* root = NULL; + wLog* logA = NULL; + wLog* logB = NULL; + wLogLayout* layout = NULL; + wLogAppender* appender = NULL; + wLogCallbacks callbacks; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + function = __func__; + + root = WLog_GetRoot(); + + WLog_SetLogAppenderType(root, WLOG_APPENDER_CALLBACK); + + appender = WLog_GetLogAppender(root); + + callbacks.data = CallbackAppenderData; + callbacks.image = CallbackAppenderImage; + callbacks.message = CallbackAppenderMessage; + callbacks.package = CallbackAppenderPackage; + + if (!WLog_ConfigureAppender(appender, "callbacks", (void*)&callbacks)) + return -1; + + layout = WLog_GetLogLayout(root); + WLog_Layout_SetPrefixFormat(root, layout, "%mn"); + + WLog_OpenAppender(root); + + logA = WLog_Get(channels[0]); + logB = WLog_Get(channels[1]); + + WLog_SetLogLevel(logA, WLOG_TRACE); + WLog_SetLogLevel(logB, WLOG_TRACE); + + WLog_Print(logA, messages[0].level, messages[0].msg); + WLog_Print(logB, messages[1].level, messages[1].msg); + WLog_Print(logA, messages[2].level, messages[2].msg, 2, "test"); + WLog_Print(logB, messages[3].level, messages[3].msg, 2, "time"); + WLog_Print(logA, messages[4].level, messages[4].msg); + WLog_Print(logB, messages[5].level, messages[5].msg); + WLog_Print(logA, messages[6].level, messages[6].msg); + WLog_Print(logB, messages[7].level, messages[7].msg); + + WLog_CloseAppender(root); + + return success ? 0 : -1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..585f21d7c5382eb45d10f5ee44cef6de9c2cd99a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.c @@ -0,0 +1,202 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2022 Armin Novak + * Copyright 2022 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 _GNU_SOURCE +#define _GNU_SOURCE // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) +#endif + +#include +#include +#include + +#include +#include "debug.h" + +#include +#include "../log.h" + +#include + +#define TAG WINPR_TAG("utils.unwind") + +#define UNWIND_MAX_LINE_SIZE 1024ULL + +typedef struct +{ + union + { + uintptr_t uw; + void* pv; + } pc; + union + { + uintptr_t uptr; + void* pv; + } langSpecificData; +} unwind_info_t; + +typedef struct +{ + size_t pos; + size_t size; + unwind_info_t* info; +} unwind_context_t; + +static const char* unwind_reason_str(_Unwind_Reason_Code code) +{ + switch (code) + { +#if defined(__arm__) && !defined(__USING_SJLJ_EXCEPTIONS__) && !defined(__ARM_DWARF_EH__) && \ + !defined(__SEH__) + case _URC_OK: + return "_URC_OK"; +#else + case _URC_NO_REASON: + return "_URC_NO_REASON"; + case _URC_FATAL_PHASE2_ERROR: + return "_URC_FATAL_PHASE2_ERROR"; + case _URC_FATAL_PHASE1_ERROR: + return "_URC_FATAL_PHASE1_ERROR"; + case _URC_NORMAL_STOP: + return "_URC_NORMAL_STOP"; +#endif + case _URC_FOREIGN_EXCEPTION_CAUGHT: + return "_URC_FOREIGN_EXCEPTION_CAUGHT"; + case _URC_END_OF_STACK: + return "_URC_END_OF_STACK"; + case _URC_HANDLER_FOUND: + return "_URC_HANDLER_FOUND"; + case _URC_INSTALL_CONTEXT: + return "_URC_INSTALL_CONTEXT"; + case _URC_CONTINUE_UNWIND: + return "_URC_CONTINUE_UNWIND"; +#if defined(__arm__) && !defined(__USING_SJLJ_EXCEPTIONS__) && !defined(__ARM_DWARF_EH__) && \ + !defined(__SEH__) + case _URC_FAILURE: + return "_URC_FAILURE"; +#endif + default: + return "_URC_UNKNOWN"; + } +} + +static const char* unwind_reason_str_buffer(_Unwind_Reason_Code code, char* buffer, size_t size) +{ + const char* str = unwind_reason_str(code); + (void)_snprintf(buffer, size, "%s [0x%02x]", str, code); + return buffer; +} + +static _Unwind_Reason_Code unwind_backtrace_callback(struct _Unwind_Context* context, void* arg) +{ + unwind_context_t* ctx = arg; + + assert(ctx); + + if (ctx->pos < ctx->size) + { + unwind_info_t* info = &ctx->info[ctx->pos++]; + info->pc.uw = _Unwind_GetIP(context); + + /* _Unwind_GetLanguageSpecificData has various return value definitions, + * cast to the type we expect and disable linter warnings + */ + // NOLINTNEXTLINE(google-readability-casting,readability-redundant-casting) + info->langSpecificData.pv = (void*)_Unwind_GetLanguageSpecificData(context); + } + + return _URC_NO_REASON; +} + +void* winpr_unwind_backtrace(DWORD size) +{ + _Unwind_Reason_Code rc = _URC_FOREIGN_EXCEPTION_CAUGHT; + unwind_context_t* ctx = calloc(1, sizeof(unwind_context_t)); + if (!ctx) + goto fail; + ctx->size = size; + ctx->info = calloc(size, sizeof(unwind_info_t)); + if (!ctx->info) + goto fail; + + rc = _Unwind_Backtrace(unwind_backtrace_callback, ctx); + if (rc != _URC_END_OF_STACK) + { + char buffer[64] = { 0 }; + WLog_ERR(TAG, "_Unwind_Backtrace failed with %s", + unwind_reason_str_buffer(rc, buffer, sizeof(buffer))); + goto fail; + } + + return ctx; +fail: + winpr_unwind_backtrace_free(ctx); + return NULL; +} + +void winpr_unwind_backtrace_free(void* buffer) +{ + unwind_context_t* ctx = buffer; + if (!ctx) + return; + free(ctx->info); + free(ctx); +} + +char** winpr_unwind_backtrace_symbols(void* buffer, size_t* used) +{ + union + { + void* pv; + char* cp; + char** cpp; + } cnv; + unwind_context_t* ctx = buffer; + cnv.cpp = NULL; + + if (!ctx) + return NULL; + + cnv.pv = calloc(ctx->pos * (sizeof(char*) + UNWIND_MAX_LINE_SIZE), sizeof(char*)); + if (!cnv.pv) + return NULL; + + if (used) + *used = ctx->pos; + + for (size_t x = 0; x < ctx->pos; x++) + { + char* msg = cnv.cp + ctx->pos * sizeof(char*) + x * UNWIND_MAX_LINE_SIZE; + const unwind_info_t* info = &ctx->info[x]; + Dl_info dlinfo = { 0 }; + int rc = dladdr(info->pc.pv, &dlinfo); + + cnv.cpp[x] = msg; + + if (rc == 0) + (void)_snprintf(msg, UNWIND_MAX_LINE_SIZE, "unresolvable, address=%p", info->pc.pv); + else + (void)_snprintf(msg, UNWIND_MAX_LINE_SIZE, "dli_fname=%s [%p], dli_sname=%s [%p]", + dlinfo.dli_fname, dlinfo.dli_fbase, dlinfo.dli_sname, dlinfo.dli_saddr); + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): function is an allocator + return cnv.cpp; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..25ea827c771ac0c7f7f9089fb28ad81a4918568f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/unwind/debug.h @@ -0,0 +1,45 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2022 Armin Novak + * Copyright 2022 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_UNWIND_H +#define WINPR_DEBUG_UNWIND_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include +#include + + void winpr_unwind_backtrace_free(void* buffer); + + WINPR_ATTR_MALLOC(winpr_unwind_backtrace_free, 1) + void* winpr_unwind_backtrace(DWORD size); + + WINPR_ATTR_MALLOC(free, 1) + char** winpr_unwind_backtrace_symbols(void* buffer, size_t* used); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_DEBUG_UNWIND_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..84e04c2cdfd786ccad82480c406fd98f3fff42e2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.c @@ -0,0 +1,168 @@ +/** + * WinPR: Windows Portable Runtime + * Debugging Utils + * + * Copyright 2014 Armin Novak + * 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. + */ + +#include +#include + +#include +#include +#include + +#include "debug.h" + +#ifndef MIN +#define MIN(a, b) (a) < (b) ? (a) : (b) +#endif + +typedef struct +{ + PVOID* stack; + ULONG used; + ULONG max; +} t_win_stack; + +void winpr_win_backtrace_free(void* buffer) +{ + t_win_stack* data = (t_win_stack*)buffer; + if (!data) + return; + + free(data->stack); + free(data); +} + +void* winpr_win_backtrace(DWORD size) +{ + HANDLE process = GetCurrentProcess(); + t_win_stack* data = calloc(1, sizeof(t_win_stack)); + + if (!data) + return NULL; + + data->max = size; + data->stack = calloc(data->max, sizeof(PVOID)); + + if (!data->stack) + { + free(data); + return NULL; + } + + SymInitialize(process, NULL, TRUE); + data->used = RtlCaptureStackBackTrace(2, size, data->stack, NULL); + return data; +} + +char** winpr_win_backtrace_symbols(void* buffer, size_t* used) +{ + if (used) + *used = 0; + + if (!buffer) + return NULL; + + { + size_t line_len = 1024; + HANDLE process = GetCurrentProcess(); + t_win_stack* data = (t_win_stack*)buffer; + size_t array_size = data->used * sizeof(char*); + size_t lines_size = data->used * line_len; + char** vlines = calloc(1, array_size + lines_size); + SYMBOL_INFO* symbol = calloc(1, sizeof(SYMBOL_INFO) + line_len * sizeof(char)); + IMAGEHLP_LINE64* line = (IMAGEHLP_LINE64*)calloc(1, sizeof(IMAGEHLP_LINE64)); + + if (!vlines || !symbol || !line) + { + free(vlines); + free(symbol); + free(line); + return NULL; + } + + line->SizeOfStruct = sizeof(IMAGEHLP_LINE64); + symbol->MaxNameLen = (ULONG)line_len; + symbol->SizeOfStruct = sizeof(SYMBOL_INFO); + + /* Set the pointers in the allocated buffer's initial array section */ + for (size_t i = 0; i < data->used; i++) + vlines[i] = (char*)vlines + array_size + i * line_len; + + for (size_t i = 0; i < data->used; i++) + { + DWORD64 address = (DWORD64)(data->stack[i]); + DWORD displacement; + SymFromAddr(process, address, 0, symbol); + + if (SymGetLineFromAddr64(process, address, &displacement, line)) + { + sprintf_s(vlines[i], line_len, "%016" PRIx64 ": %s in %s:%" PRIu32, symbol->Address, + symbol->Name, line->FileName, line->LineNumber); + } + else + sprintf_s(vlines[i], line_len, "%016" PRIx64 ": %s", symbol->Address, symbol->Name); + } + + if (used) + *used = data->used; + + free(symbol); + free(line); + return vlines; + } +} + +char* winpr_win_strerror(DWORD dw, char* dmsg, size_t size) +{ + DWORD rc; + DWORD nSize = 0; + DWORD dwFlags = 0; + LPTSTR msg = NULL; + BOOL alloc = FALSE; + dwFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; +#ifdef FORMAT_MESSAGE_ALLOCATE_BUFFER + alloc = TRUE; + dwFlags |= FORMAT_MESSAGE_ALLOCATE_BUFFER; +#else + nSize = (DWORD)(size * sizeof(WCHAR)); + msg = (LPTSTR)calloc(nSize, sizeof(WCHAR)); +#endif + rc = FormatMessage(dwFlags, NULL, dw, 0, alloc ? (LPTSTR)&msg : msg, nSize, NULL); + + if (rc) + { +#if defined(UNICODE) + WideCharToMultiByte(CP_ACP, 0, msg, rc, dmsg, (int)MIN(size - 1, INT_MAX), NULL, NULL); +#else /* defined(UNICODE) */ + memcpy(dmsg, msg, MIN(rc, size - 1)); +#endif /* defined(UNICODE) */ + dmsg[MIN(rc, size - 1)] = 0; +#ifdef FORMAT_MESSAGE_ALLOCATE_BUFFER + LocalFree(msg); +#else + free(msg); +#endif + } + else + { + _snprintf(dmsg, size, "FAILURE: 0x%08" PRIX32 "", GetLastError()); + } + + return dmsg; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..c36b87a58412af76fed970b43a82061695c96a42 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/windows/debug.h @@ -0,0 +1,40 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Debugging helpers + * + * Copyright 2022 Armin Novak + * Copyright 2022 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_WIN_H +#define WINPR_DEBUG_WIN_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + + void* winpr_win_backtrace(DWORD size); + void winpr_win_backtrace_free(void* buffer); + char** winpr_win_backtrace_symbols(void* buffer, size_t* used); + char* winpr_win_strerror(DWORD dw, char* dmsg, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif /* WINPR_DEBUG_WIN_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/winpr.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/winpr.c new file mode 100644 index 0000000000000000000000000000000000000000..1271464d46c3da9bb337d01c5ad7b0ca6d84b58d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/winpr.c @@ -0,0 +1,67 @@ +/** + * WinPR: Windows Portable Runtime + * Debugging Utils + * + * Copyright 2015 Armin Novak + * Copyright 2015 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 + +#include + +#include +#include +#include +#include +#include +#include +#include + +#if !defined(WIN32) +#include +#endif + +void winpr_get_version(int* major, int* minor, int* revision) +{ + if (major) + *major = WINPR_VERSION_MAJOR; + if (minor) + *minor = WINPR_VERSION_MINOR; + if (revision) + *revision = WINPR_VERSION_REVISION; +} + +const char* winpr_get_version_string(void) +{ + return WINPR_VERSION_FULL; +} + +const char* winpr_get_build_revision(void) +{ + return WINPR_GIT_REVISION; +} + +const char* winpr_get_build_config(void) +{ + static const char build_config[] = + "Build configuration: " WINPR_BUILD_CONFIG "\n" + "Build type: " WINPR_BUILD_TYPE "\n" + "CFLAGS: " WINPR_CFLAGS "\n" + "Compiler: " WINPR_COMPILER_ID ", " WINPR_COMPILER_VERSION "\n" + "Target architecture: " WINPR_TARGET_ARCH "\n"; + + return build_config; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.c new file mode 100644 index 0000000000000000000000000000000000000000..7b99f5ef7c1b6b766de51b492cdfd818e87fbb16 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.c @@ -0,0 +1,177 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include "Appender.h" + +void WLog_Appender_Free(wLog* log, wLogAppender* appender) +{ + if (!appender) + return; + + if (appender->Layout) + { + WLog_Layout_Free(log, appender->Layout); + appender->Layout = NULL; + } + + DeleteCriticalSection(&appender->lock); + appender->Free(appender); +} + +wLogAppender* WLog_GetLogAppender(wLog* log) +{ + if (!log) + return NULL; + + if (!log->Appender) + return WLog_GetLogAppender(log->Parent); + + return log->Appender; +} + +BOOL WLog_OpenAppender(wLog* log) +{ + int status = 0; + wLogAppender* appender = NULL; + + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->Open) + return TRUE; + + if (!appender->active) + { + status = appender->Open(log, appender); + appender->active = TRUE; + } + + return status; +} + +BOOL WLog_CloseAppender(wLog* log) +{ + int status = 0; + wLogAppender* appender = NULL; + + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->Close) + return TRUE; + + if (appender->active) + { + status = appender->Close(log, appender); + appender->active = FALSE; + } + + return status; +} + +static wLogAppender* WLog_Appender_New(wLog* log, DWORD logAppenderType) +{ + wLogAppender* appender = NULL; + + if (!log) + return NULL; + + switch (logAppenderType) + { + case WLOG_APPENDER_CONSOLE: + appender = WLog_ConsoleAppender_New(log); + break; + case WLOG_APPENDER_FILE: + appender = WLog_FileAppender_New(log); + break; + case WLOG_APPENDER_BINARY: + appender = WLog_BinaryAppender_New(log); + break; + case WLOG_APPENDER_CALLBACK: + appender = WLog_CallbackAppender_New(log); + break; +#ifdef WINPR_HAVE_SYSLOG_H + case WLOG_APPENDER_SYSLOG: + appender = WLog_SyslogAppender_New(log); + break; +#endif +#ifdef WINPR_HAVE_JOURNALD_H + case WLOG_APPENDER_JOURNALD: + appender = WLog_JournaldAppender_New(log); + break; +#endif + case WLOG_APPENDER_UDP: + appender = WLog_UdpAppender_New(log); + break; + default: + (void)fprintf(stderr, "%s: unknown handler type %" PRIu32 "\n", __func__, + logAppenderType); + appender = NULL; + break; + } + + if (!appender) + appender = WLog_ConsoleAppender_New(log); + + if (!appender) + return NULL; + + if (!(appender->Layout = WLog_Layout_New(log))) + { + WLog_Appender_Free(log, appender); + return NULL; + } + + InitializeCriticalSectionAndSpinCount(&appender->lock, 4000); + + return appender; +} + +BOOL WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType) +{ + if (!log) + return FALSE; + + if (log->Appender) + { + WLog_Appender_Free(log, log->Appender); + log->Appender = NULL; + } + + log->Appender = WLog_Appender_New(log, logAppenderType); + return log->Appender != NULL; +} + +BOOL WLog_ConfigureAppender(wLogAppender* appender, const char* setting, void* value) +{ + /* Just check the settings string is not empty */ + if (!appender || !setting || (strnlen(setting, 2) == 0)) + return FALSE; + + if (appender->Set) + return appender->Set(appender, setting, value); + else + return FALSE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.h new file mode 100644 index 0000000000000000000000000000000000000000..00f81196fb41aadf5520c8caa378dfa57d5fcd65 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Appender.h @@ -0,0 +1,39 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_APPENDER_PRIVATE_H +#define WINPR_WLOG_APPENDER_PRIVATE_H + +#include "wlog.h" + +void WLog_Appender_Free(wLog* log, wLogAppender* appender); + +#include "FileAppender.h" +#include "ConsoleAppender.h" +#include "BinaryAppender.h" +#include "CallbackAppender.h" +#ifdef WINPR_HAVE_JOURNALD_H +#include "JournaldAppender.h" +#endif +#ifdef WINPR_HAVE_SYSLOG_H +#include "SyslogAppender.h" +#endif +#include "UdpAppender.h" + +#endif /* WINPR_WLOG_APPENDER_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..88ba33c865c6363b101f4d051f7ef69a54e9f16f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.c @@ -0,0 +1,239 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include "BinaryAppender.h" +#include +#include +#include +#include +#include + +typedef struct +{ + WLOG_APPENDER_COMMON(); + + char* FileName; + char* FilePath; + char* FullFileName; + FILE* FileDescriptor; +} wLogBinaryAppender; + +static BOOL WLog_BinaryAppender_Open(wLog* log, wLogAppender* appender) +{ + wLogBinaryAppender* binaryAppender = NULL; + if (!log || !appender) + return FALSE; + + binaryAppender = (wLogBinaryAppender*)appender; + if (!binaryAppender->FileName) + { + binaryAppender->FileName = (char*)malloc(MAX_PATH); + if (!binaryAppender->FileName) + return FALSE; + (void)sprintf_s(binaryAppender->FileName, MAX_PATH, "%" PRIu32 ".wlog", + GetCurrentProcessId()); + } + + if (!binaryAppender->FilePath) + { + binaryAppender->FilePath = GetKnownSubPath(KNOWN_PATH_TEMP, "wlog"); + if (!binaryAppender->FilePath) + return FALSE; + } + + if (!binaryAppender->FullFileName) + { + binaryAppender->FullFileName = + GetCombinedPath(binaryAppender->FilePath, binaryAppender->FileName); + if (!binaryAppender->FullFileName) + return FALSE; + } + + if (!winpr_PathFileExists(binaryAppender->FilePath)) + { + if (!winpr_PathMakePath(binaryAppender->FilePath, 0)) + return FALSE; + UnixChangeFileMode(binaryAppender->FilePath, 0xFFFF); + } + + binaryAppender->FileDescriptor = winpr_fopen(binaryAppender->FullFileName, "a+"); + + if (!binaryAppender->FileDescriptor) + return FALSE; + + return TRUE; +} + +static BOOL WLog_BinaryAppender_Close(wLog* log, wLogAppender* appender) +{ + wLogBinaryAppender* binaryAppender = NULL; + + if (!appender) + return FALSE; + + binaryAppender = (wLogBinaryAppender*)appender; + if (!binaryAppender->FileDescriptor) + return TRUE; + + if (binaryAppender->FileDescriptor) + (void)fclose(binaryAppender->FileDescriptor); + + binaryAppender->FileDescriptor = NULL; + + return TRUE; +} + +static BOOL WLog_BinaryAppender_WriteMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + FILE* fp = NULL; + wStream* s = NULL; + size_t MessageLength = 0; + size_t FileNameLength = 0; + size_t FunctionNameLength = 0; + size_t TextStringLength = 0; + BOOL ret = TRUE; + wLogBinaryAppender* binaryAppender = NULL; + + if (!log || !appender || !message) + return FALSE; + + binaryAppender = (wLogBinaryAppender*)appender; + + fp = binaryAppender->FileDescriptor; + + if (!fp) + return FALSE; + + FileNameLength = strnlen(message->FileName, INT_MAX); + FunctionNameLength = strnlen(message->FunctionName, INT_MAX); + TextStringLength = strnlen(message->TextString, INT_MAX); + + MessageLength = + 16 + (4 + FileNameLength + 1) + (4 + FunctionNameLength + 1) + (4 + TextStringLength + 1); + + if ((MessageLength > UINT32_MAX) || (FileNameLength > UINT32_MAX) || + (FunctionNameLength > UINT32_MAX) || (TextStringLength > UINT32_MAX)) + return FALSE; + + s = Stream_New(NULL, MessageLength); + if (!s) + return FALSE; + + Stream_Write_UINT32(s, (UINT32)MessageLength); + + Stream_Write_UINT32(s, message->Type); + Stream_Write_UINT32(s, message->Level); + + WINPR_ASSERT(message->LineNumber <= UINT32_MAX); + Stream_Write_UINT32(s, (UINT32)message->LineNumber); + + Stream_Write_UINT32(s, (UINT32)FileNameLength); + Stream_Write(s, message->FileName, FileNameLength + 1); + + Stream_Write_UINT32(s, (UINT32)FunctionNameLength); + Stream_Write(s, message->FunctionName, FunctionNameLength + 1); + + Stream_Write_UINT32(s, (UINT32)TextStringLength); + Stream_Write(s, message->TextString, TextStringLength + 1); + + Stream_SealLength(s); + + if (fwrite(Stream_Buffer(s), MessageLength, 1, fp) != 1) + ret = FALSE; + + Stream_Free(s, TRUE); + + return ret; +} + +static BOOL WLog_BinaryAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + return TRUE; +} + +static BOOL WLog_BinaryAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + return TRUE; +} + +static BOOL WLog_BinaryAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + wLogBinaryAppender* binaryAppender = (wLogBinaryAppender*)appender; + + /* Just check if the value string is longer than 0 */ + if (!value || (strnlen(value, 2) == 0)) + return FALSE; + + if (!strcmp("outputfilename", setting)) + { + binaryAppender->FileName = _strdup((const char*)value); + if (!binaryAppender->FileName) + return FALSE; + } + else if (!strcmp("outputfilepath", setting)) + { + binaryAppender->FilePath = _strdup((const char*)value); + if (!binaryAppender->FilePath) + return FALSE; + } + else + return FALSE; + + return TRUE; +} + +static void WLog_BinaryAppender_Free(wLogAppender* appender) +{ + wLogBinaryAppender* binaryAppender = NULL; + if (appender) + { + binaryAppender = (wLogBinaryAppender*)appender; + free(binaryAppender->FileName); + free(binaryAppender->FilePath); + free(binaryAppender->FullFileName); + free(binaryAppender); + } +} + +wLogAppender* WLog_BinaryAppender_New(wLog* log) +{ + wLogBinaryAppender* BinaryAppender = NULL; + + BinaryAppender = (wLogBinaryAppender*)calloc(1, sizeof(wLogBinaryAppender)); + if (!BinaryAppender) + return NULL; + + BinaryAppender->Type = WLOG_APPENDER_BINARY; + BinaryAppender->Open = WLog_BinaryAppender_Open; + BinaryAppender->Close = WLog_BinaryAppender_Close; + BinaryAppender->WriteMessage = WLog_BinaryAppender_WriteMessage; + BinaryAppender->WriteDataMessage = WLog_BinaryAppender_WriteDataMessage; + BinaryAppender->WriteImageMessage = WLog_BinaryAppender_WriteImageMessage; + BinaryAppender->Free = WLog_BinaryAppender_Free; + BinaryAppender->Set = WLog_BinaryAppender_Set; + + return (wLogAppender*)BinaryAppender; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..fb65d9fa785d2d4e48dd81e69688744a8416a2b8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/BinaryAppender.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_BINARY_APPENDER_PRIVATE_H +#define WINPR_WLOG_BINARY_APPENDER_PRIVATE_H + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_BinaryAppender_New(wLog* log); + +#endif /* WINPR_WLOG_BINARY_APPENDER_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..c9f40344b3fb436aad9e316f0cc5f7488a902bbb --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.c @@ -0,0 +1,168 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2014 Armin Novak + * + * 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 + +#include "CallbackAppender.h" + +typedef struct +{ + WLOG_APPENDER_COMMON(); + + wLogCallbacks* callbacks; +} wLogCallbackAppender; + +static BOOL WLog_CallbackAppender_Open(wLog* log, wLogAppender* appender) +{ + return TRUE; +} + +static BOOL WLog_CallbackAppender_Close(wLog* log, wLogAppender* appender) +{ + return TRUE; +} + +static BOOL WLog_CallbackAppender_WriteMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogCallbackAppender* callbackAppender = NULL; + + if (!appender) + return FALSE; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + + callbackAppender = (wLogCallbackAppender*)appender; + + if (callbackAppender->callbacks && callbackAppender->callbacks->message) + return callbackAppender->callbacks->message(message); + else + return FALSE; +} + +static BOOL WLog_CallbackAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogCallbackAppender* callbackAppender = NULL; + + if (!appender) + return FALSE; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + + callbackAppender = (wLogCallbackAppender*)appender; + if (callbackAppender->callbacks && callbackAppender->callbacks->data) + return callbackAppender->callbacks->data(message); + else + return FALSE; +} + +static BOOL WLog_CallbackAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogCallbackAppender* callbackAppender = NULL; + + if (!appender) + return FALSE; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + + callbackAppender = (wLogCallbackAppender*)appender; + if (callbackAppender->callbacks && callbackAppender->callbacks->image) + return callbackAppender->callbacks->image(message); + else + return FALSE; +} + +static BOOL WLog_CallbackAppender_WritePacketMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogCallbackAppender* callbackAppender = NULL; + + if (!appender) + return FALSE; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + + callbackAppender = (wLogCallbackAppender*)appender; + if (callbackAppender->callbacks && callbackAppender->callbacks->package) + return callbackAppender->callbacks->package(message); + else + return FALSE; +} + +static BOOL WLog_CallbackAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + wLogCallbackAppender* callbackAppender = (wLogCallbackAppender*)appender; + + if (!value || (strcmp(setting, "callbacks") != 0)) + return FALSE; + + if (!(callbackAppender->callbacks = calloc(1, sizeof(wLogCallbacks)))) + { + return FALSE; + } + + callbackAppender->callbacks = memcpy(callbackAppender->callbacks, value, sizeof(wLogCallbacks)); + return TRUE; +} + +static void WLog_CallbackAppender_Free(wLogAppender* appender) +{ + wLogCallbackAppender* callbackAppender = NULL; + if (!appender) + { + return; + } + + callbackAppender = (wLogCallbackAppender*)appender; + + free(callbackAppender->callbacks); + free(appender); +} + +wLogAppender* WLog_CallbackAppender_New(wLog* log) +{ + wLogCallbackAppender* CallbackAppender = NULL; + + CallbackAppender = (wLogCallbackAppender*)calloc(1, sizeof(wLogCallbackAppender)); + if (!CallbackAppender) + return NULL; + + CallbackAppender->Type = WLOG_APPENDER_CALLBACK; + + CallbackAppender->Open = WLog_CallbackAppender_Open; + CallbackAppender->Close = WLog_CallbackAppender_Close; + CallbackAppender->WriteMessage = WLog_CallbackAppender_WriteMessage; + CallbackAppender->WriteDataMessage = WLog_CallbackAppender_WriteDataMessage; + CallbackAppender->WriteImageMessage = WLog_CallbackAppender_WriteImageMessage; + CallbackAppender->WritePacketMessage = WLog_CallbackAppender_WritePacketMessage; + CallbackAppender->Free = WLog_CallbackAppender_Free; + CallbackAppender->Set = WLog_CallbackAppender_Set; + + return (wLogAppender*)CallbackAppender; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..cd10f7d3fb986254b63fd67a62ab7577f870823e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/CallbackAppender.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2014 Armin Novak + * + * 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_WLOG_CALLBACK_APPENDER_PRIVATE_H +#define WINPR_WLOG_CALLBACK_APPENDER_PRIVATE_H + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_CallbackAppender_New(wLog* log); + +#endif /* WINPR_WLOG_CALLBACK_APPENDER_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..2c542034c8877c82f605a97115c181c0ed635eea --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.c @@ -0,0 +1,276 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include "ConsoleAppender.h" +#include "Message.h" + +#ifdef ANDROID +#include +#endif + +#define WLOG_CONSOLE_DEFAULT 0 +#define WLOG_CONSOLE_STDOUT 1 +#define WLOG_CONSOLE_STDERR 2 +#define WLOG_CONSOLE_DEBUG 4 + +typedef struct +{ + WLOG_APPENDER_COMMON(); + + int outputStream; +} wLogConsoleAppender; + +static BOOL WLog_ConsoleAppender_Open(wLog* log, wLogAppender* appender) +{ + return TRUE; +} + +static BOOL WLog_ConsoleAppender_Close(wLog* log, wLogAppender* appender) +{ + return TRUE; +} + +static BOOL WLog_ConsoleAppender_WriteMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + FILE* fp = NULL; + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogConsoleAppender* consoleAppender = NULL; + if (!appender) + return FALSE; + + consoleAppender = (wLogConsoleAppender*)appender; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + +#ifdef _WIN32 + if (consoleAppender->outputStream == WLOG_CONSOLE_DEBUG) + { + OutputDebugStringA(message->PrefixString); + OutputDebugStringA(message->TextString); + OutputDebugStringA("\n"); + + return TRUE; + } +#endif +#ifdef ANDROID + (void)fp; + android_LogPriority level; + switch (message->Level) + { + case WLOG_TRACE: + level = ANDROID_LOG_VERBOSE; + break; + case WLOG_DEBUG: + level = ANDROID_LOG_DEBUG; + break; + case WLOG_INFO: + level = ANDROID_LOG_INFO; + break; + case WLOG_WARN: + level = ANDROID_LOG_WARN; + break; + case WLOG_ERROR: + level = ANDROID_LOG_ERROR; + break; + case WLOG_FATAL: + level = ANDROID_LOG_FATAL; + break; + case WLOG_OFF: + level = ANDROID_LOG_SILENT; + break; + default: + level = ANDROID_LOG_FATAL; + break; + } + + if (level != ANDROID_LOG_SILENT) + __android_log_print(level, log->Name, "%s%s", message->PrefixString, message->TextString); + +#else + switch (consoleAppender->outputStream) + { + case WLOG_CONSOLE_STDOUT: + fp = stdout; + break; + case WLOG_CONSOLE_STDERR: + fp = stderr; + break; + default: + switch (message->Level) + { + case WLOG_TRACE: + case WLOG_DEBUG: + case WLOG_INFO: + fp = stdout; + break; + default: + fp = stderr; + break; + } + break; + } + + if (message->Level != WLOG_OFF) + (void)fprintf(fp, "%s%s\n", message->PrefixString, message->TextString); +#endif + return TRUE; +} + +static int g_DataId = 0; + +static BOOL WLog_ConsoleAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ +#if defined(ANDROID) + return FALSE; +#else + int DataId = 0; + char* FullFileName = NULL; + + DataId = g_DataId++; + FullFileName = WLog_Message_GetOutputFileName(DataId, "dat"); + + WLog_DataMessage_Write(FullFileName, message->Data, message->Length); + + free(FullFileName); + + return TRUE; +#endif +} + +static int g_ImageId = 0; + +static BOOL WLog_ConsoleAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ +#if defined(ANDROID) + return FALSE; +#else + int ImageId = 0; + char* FullFileName = NULL; + + ImageId = g_ImageId++; + FullFileName = WLog_Message_GetOutputFileName(ImageId, "bmp"); + + WLog_ImageMessage_Write(FullFileName, message->ImageData, message->ImageWidth, + message->ImageHeight, message->ImageBpp); + + free(FullFileName); + + return TRUE; +#endif +} + +static int g_PacketId = 0; + +static BOOL WLog_ConsoleAppender_WritePacketMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ +#if defined(ANDROID) + return FALSE; +#else + char* FullFileName = NULL; + + g_PacketId++; + + if (!appender->PacketMessageContext) + { + FullFileName = WLog_Message_GetOutputFileName(-1, "pcap"); + appender->PacketMessageContext = (void*)Pcap_Open(FullFileName, TRUE); + free(FullFileName); + } + + if (appender->PacketMessageContext) + return WLog_PacketMessage_Write((wPcap*)appender->PacketMessageContext, message->PacketData, + message->PacketLength, message->PacketFlags); + + return TRUE; +#endif +} +static BOOL WLog_ConsoleAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + wLogConsoleAppender* consoleAppender = (wLogConsoleAppender*)appender; + + /* Just check the value string is not empty */ + if (!value || (strnlen(value, 2) == 0)) + return FALSE; + + if (strcmp("outputstream", setting) != 0) + return FALSE; + + if (!strcmp("stdout", value)) + consoleAppender->outputStream = WLOG_CONSOLE_STDOUT; + else if (!strcmp("stderr", value)) + consoleAppender->outputStream = WLOG_CONSOLE_STDERR; + else if (!strcmp("default", value)) + consoleAppender->outputStream = WLOG_CONSOLE_DEFAULT; + else if (!strcmp("debug", value)) + consoleAppender->outputStream = WLOG_CONSOLE_DEBUG; + else + return FALSE; + + return TRUE; +} + +static void WLog_ConsoleAppender_Free(wLogAppender* appender) +{ + if (appender) + { + if (appender->PacketMessageContext) + { + Pcap_Close((wPcap*)appender->PacketMessageContext); + } + + free(appender); + } +} + +wLogAppender* WLog_ConsoleAppender_New(wLog* log) +{ + wLogConsoleAppender* ConsoleAppender = NULL; + + ConsoleAppender = (wLogConsoleAppender*)calloc(1, sizeof(wLogConsoleAppender)); + + if (!ConsoleAppender) + return NULL; + + ConsoleAppender->Type = WLOG_APPENDER_CONSOLE; + + ConsoleAppender->Open = WLog_ConsoleAppender_Open; + ConsoleAppender->Close = WLog_ConsoleAppender_Close; + ConsoleAppender->WriteMessage = WLog_ConsoleAppender_WriteMessage; + ConsoleAppender->WriteDataMessage = WLog_ConsoleAppender_WriteDataMessage; + ConsoleAppender->WriteImageMessage = WLog_ConsoleAppender_WriteImageMessage; + ConsoleAppender->WritePacketMessage = WLog_ConsoleAppender_WritePacketMessage; + ConsoleAppender->Set = WLog_ConsoleAppender_Set; + ConsoleAppender->Free = WLog_ConsoleAppender_Free; + + ConsoleAppender->outputStream = WLOG_CONSOLE_DEFAULT; + +#ifdef _WIN32 + if (IsDebuggerPresent()) + ConsoleAppender->outputStream = WLOG_CONSOLE_DEBUG; +#endif + + return (wLogAppender*)ConsoleAppender; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..f6a1405ca573ef53a94f9f95b7ab772dbb199eb3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ConsoleAppender.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_CONSOLE_APPENDER_PRIVATE_H +#define WINPR_WLOG_CONSOLE_APPENDER_PRIVATE_H + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_ConsoleAppender_New(wLog* log); + +#endif /* WINPR_WLOG_CONSOLE_APPENDER_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.c new file mode 100644 index 0000000000000000000000000000000000000000..f1aa4c1181c5bd4c4ad5b4372c633c958e5f6416 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.c @@ -0,0 +1,48 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include "wlog.h" + +#include "DataMessage.h" + +#include + +#include "../../log.h" +#define TAG WINPR_TAG("utils.wlog") + +BOOL WLog_DataMessage_Write(const char* filename, const void* data, size_t length) +{ + FILE* fp = NULL; + BOOL ret = TRUE; + + fp = winpr_fopen(filename, "w+b"); + + if (!fp) + { + // WLog_ERR(TAG, "failed to open file %s", filename); + return FALSE; + } + + if (fwrite(data, length, 1, fp) != 1) + ret = FALSE; + (void)fclose(fp); + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.h new file mode 100644 index 0000000000000000000000000000000000000000..db2c09e47c6f907c882216d00e97aa1fe2872d5c --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/DataMessage.h @@ -0,0 +1,25 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_DATA_MESSAGE_PRIVATE_H +#define WINPR_WLOG_DATA_MESSAGE_PRIVATE_H + +BOOL WLog_DataMessage_Write(const char* filename, const void* data, size_t length); + +#endif /* WINPR_WLOG_DATA_MESSAGE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..9a896f9dc46a25eeea303625a0eee53e59a62ee5 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.c @@ -0,0 +1,287 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include "FileAppender.h" +#include "Message.h" + +#include +#include +#include +#include + +typedef struct +{ + WLOG_APPENDER_COMMON(); + + char* FileName; + char* FilePath; + char* FullFileName; + FILE* FileDescriptor; +} wLogFileAppender; + +static BOOL WLog_FileAppender_SetOutputFileName(wLogFileAppender* appender, const char* filename) +{ + appender->FileName = _strdup(filename); + + if (!appender->FileName) + return FALSE; + + return TRUE; +} + +static BOOL WLog_FileAppender_SetOutputFilePath(wLogFileAppender* appender, const char* filepath) +{ + appender->FilePath = _strdup(filepath); + + if (!appender->FilePath) + return FALSE; + + return TRUE; +} + +static BOOL WLog_FileAppender_Open(wLog* log, wLogAppender* appender) +{ + wLogFileAppender* fileAppender = NULL; + + if (!log || !appender) + return FALSE; + + fileAppender = (wLogFileAppender*)appender; + + if (!fileAppender->FilePath) + { + fileAppender->FilePath = GetKnownSubPath(KNOWN_PATH_TEMP, "wlog"); + + if (!fileAppender->FilePath) + return FALSE; + } + + if (!fileAppender->FileName) + { + fileAppender->FileName = (char*)malloc(MAX_PATH); + + if (!fileAppender->FileName) + return FALSE; + + (void)sprintf_s(fileAppender->FileName, MAX_PATH, "%" PRIu32 ".log", GetCurrentProcessId()); + } + + if (!fileAppender->FullFileName) + { + fileAppender->FullFileName = + GetCombinedPath(fileAppender->FilePath, fileAppender->FileName); + + if (!fileAppender->FullFileName) + return FALSE; + } + + if (!winpr_PathFileExists(fileAppender->FilePath)) + { + if (!winpr_PathMakePath(fileAppender->FilePath, 0)) + return FALSE; + + UnixChangeFileMode(fileAppender->FilePath, 0xFFFF); + } + + fileAppender->FileDescriptor = winpr_fopen(fileAppender->FullFileName, "a+"); + + if (!fileAppender->FileDescriptor) + return FALSE; + + return TRUE; +} + +static BOOL WLog_FileAppender_Close(wLog* log, wLogAppender* appender) +{ + wLogFileAppender* fileAppender = NULL; + + if (!log || !appender) + return FALSE; + + fileAppender = (wLogFileAppender*)appender; + + if (!fileAppender->FileDescriptor) + return TRUE; + + (void)fclose(fileAppender->FileDescriptor); + fileAppender->FileDescriptor = NULL; + return TRUE; +} + +static BOOL WLog_FileAppender_WriteMessage(wLog* log, wLogAppender* appender, wLogMessage* message) +{ + FILE* fp = NULL; + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogFileAppender* fileAppender = NULL; + + if (!log || !appender || !message) + return FALSE; + + fileAppender = (wLogFileAppender*)appender; + fp = fileAppender->FileDescriptor; + + if (!fp) + return FALSE; + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + (void)fprintf(fp, "%s%s\n", message->PrefixString, message->TextString); + (void)fflush(fp); /* slow! */ + return TRUE; +} + +static int g_DataId = 0; + +static BOOL WLog_FileAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + int DataId = 0; + char* FullFileName = NULL; + + if (!log || !appender || !message) + return FALSE; + + DataId = g_DataId++; + FullFileName = WLog_Message_GetOutputFileName(DataId, "dat"); + WLog_DataMessage_Write(FullFileName, message->Data, message->Length); + free(FullFileName); + return TRUE; +} + +static int g_ImageId = 0; + +static BOOL WLog_FileAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + int ImageId = 0; + char* FullFileName = NULL; + + if (!log || !appender || !message) + return FALSE; + + ImageId = g_ImageId++; + FullFileName = WLog_Message_GetOutputFileName(ImageId, "bmp"); + WLog_ImageMessage_Write(FullFileName, message->ImageData, message->ImageWidth, + message->ImageHeight, message->ImageBpp); + free(FullFileName); + return TRUE; +} + +static BOOL WLog_FileAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + wLogFileAppender* fileAppender = (wLogFileAppender*)appender; + + /* Just check the value string is not empty */ + if (!value || (strnlen(value, 2) == 0)) + return FALSE; + + if (!strcmp("outputfilename", setting)) + return WLog_FileAppender_SetOutputFileName(fileAppender, (const char*)value); + + if (!strcmp("outputfilepath", setting)) + return WLog_FileAppender_SetOutputFilePath(fileAppender, (const char*)value); + + return FALSE; +} + +static void WLog_FileAppender_Free(wLogAppender* appender) +{ + wLogFileAppender* fileAppender = NULL; + + if (appender) + { + fileAppender = (wLogFileAppender*)appender; + free(fileAppender->FileName); + free(fileAppender->FilePath); + free(fileAppender->FullFileName); + free(fileAppender); + } +} + +wLogAppender* WLog_FileAppender_New(wLog* log) +{ + LPSTR env = NULL; + LPCSTR name = NULL; + DWORD nSize = 0; + wLogFileAppender* FileAppender = NULL; + FileAppender = (wLogFileAppender*)calloc(1, sizeof(wLogFileAppender)); + + if (!FileAppender) + return NULL; + + FileAppender->Type = WLOG_APPENDER_FILE; + FileAppender->Open = WLog_FileAppender_Open; + FileAppender->Close = WLog_FileAppender_Close; + FileAppender->WriteMessage = WLog_FileAppender_WriteMessage; + FileAppender->WriteDataMessage = WLog_FileAppender_WriteDataMessage; + FileAppender->WriteImageMessage = WLog_FileAppender_WriteImageMessage; + FileAppender->Free = WLog_FileAppender_Free; + FileAppender->Set = WLog_FileAppender_Set; + name = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH"; + nSize = GetEnvironmentVariableA(name, NULL, 0); + + if (nSize) + { + BOOL status = 0; + env = (LPSTR)malloc(nSize); + + if (!env) + goto error_free; + + if (GetEnvironmentVariableA(name, env, nSize) != nSize - 1) + { + free(env); + goto error_free; + } + + status = WLog_FileAppender_SetOutputFilePath(FileAppender, env); + free(env); + + if (!status) + goto error_free; + } + + name = "WLOG_FILEAPPENDER_OUTPUT_FILE_NAME"; + nSize = GetEnvironmentVariableA(name, NULL, 0); + + if (nSize) + { + BOOL status = FALSE; + env = (LPSTR)malloc(nSize); + + if (!env) + goto error_output_file_name; + + if (GetEnvironmentVariableA(name, env, nSize) == nSize - 1) + status = WLog_FileAppender_SetOutputFileName(FileAppender, env); + free(env); + + if (!status) + goto error_output_file_name; + } + + return (wLogAppender*)FileAppender; +error_output_file_name: + free(FileAppender->FilePath); +error_free: + free(FileAppender); + return NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..8938488c0f030e524305c789c01028a7c8afb88e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/FileAppender.h @@ -0,0 +1,28 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_FILE_APPENDER_PRIVATE_H +#define WINPR_WLOG_FILE_APPENDER_PRIVATE_H + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_FileAppender_New(wLog* log); + +#endif /* WINPR_WLOG_FILE_APPENDER_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.c new file mode 100644 index 0000000000000000000000000000000000000000..ce600323f88d46389566a431a66b529a95fd0607 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.c @@ -0,0 +1,37 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include "wlog.h" +#include + +#include "ImageMessage.h" + +BOOL WLog_ImageMessage_Write(char* filename, void* data, size_t width, size_t height, size_t bpp) +{ + int status = 0; + + status = winpr_bitmap_write(filename, data, width, height, bpp); + + if (status < 0) + return FALSE; + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.h new file mode 100644 index 0000000000000000000000000000000000000000..15ed81b94ab83e8be9ddf11fbf326fcc0bfa5bc0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/ImageMessage.h @@ -0,0 +1,25 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_IMAGE_MESSAGE_PRIVATE_H +#define WINPR_WLOG_IMAGE_MESSAGE_PRIVATE_H + +BOOL WLog_ImageMessage_Write(char* filename, void* data, size_t width, size_t height, size_t bpp); + +#endif /* WINPR_WLOG_IMAGE_MESSAGE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..7efa81388512ad6f067fff81da9a5b0424eeea4a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.c @@ -0,0 +1,215 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * 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 + +#include "JournaldAppender.h" + +#include +#include +#include + +#include +#include + +typedef struct +{ + WLOG_APPENDER_COMMON(); + char* identifier; + FILE* stream; +} wLogJournaldAppender; + +static BOOL WLog_JournaldAppender_Open(wLog* log, wLogAppender* appender) +{ + int fd = 0; + wLogJournaldAppender* journaldAppender = NULL; + + if (!log || !appender) + return FALSE; + + journaldAppender = (wLogJournaldAppender*)appender; + if (journaldAppender->stream) + return TRUE; + + fd = sd_journal_stream_fd(journaldAppender->identifier, LOG_INFO, 1); + if (fd < 0) + return FALSE; + + journaldAppender->stream = fdopen(fd, "w"); + if (!journaldAppender->stream) + { + close(fd); + return FALSE; + } + + setbuffer(journaldAppender->stream, NULL, 0); + return TRUE; +} + +static BOOL WLog_JournaldAppender_Close(wLog* log, wLogAppender* appender) +{ + if (!log || !appender) + return FALSE; + + return TRUE; +} + +static BOOL WLog_JournaldAppender_WriteMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + char* formatStr = NULL; + wLogJournaldAppender* journaldAppender = NULL; + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + + if (!log || !appender || !message) + return FALSE; + + journaldAppender = (wLogJournaldAppender*)appender; + + switch (message->Level) + { + case WLOG_TRACE: + case WLOG_DEBUG: + formatStr = "<7>%s%s\n"; + break; + case WLOG_INFO: + formatStr = "<6>%s%s\n"; + break; + case WLOG_WARN: + formatStr = "<4>%s%s\n"; + break; + case WLOG_ERROR: + formatStr = "<3>%s%s\n"; + break; + case WLOG_FATAL: + formatStr = "<2>%s%s\n"; + break; + case WLOG_OFF: + return TRUE; + default: + (void)fprintf(stderr, "%s: unknown level %" PRIu32 "\n", __func__, message->Level); + return FALSE; + } + + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + + if (message->Level != WLOG_OFF) + { + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL(void) + fprintf(journaldAppender->stream, formatStr, message->PrefixString, message->TextString); + WINPR_PRAGMA_DIAG_POP + } + return TRUE; +} + +static BOOL WLog_JournaldAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + if (!log || !appender || !message) + return FALSE; + + return TRUE; +} + +static BOOL WLog_JournaldAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + if (!log || !appender || !message) + return FALSE; + + return TRUE; +} + +static BOOL WLog_JournaldAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + wLogJournaldAppender* journaldAppender = (wLogJournaldAppender*)appender; + + /* Just check the value string is not empty */ + if (!value || (strnlen(value, 2) == 0)) + return FALSE; + + if (strcmp("identifier", setting) != 0) + return FALSE; + + /* If the stream is already open the identifier can't be changed */ + if (journaldAppender->stream) + return FALSE; + + if (journaldAppender->identifier) + free(journaldAppender->identifier); + + return ((journaldAppender->identifier = _strdup((const char*)value)) != NULL); +} + +static void WLog_JournaldAppender_Free(wLogAppender* appender) +{ + wLogJournaldAppender* journaldAppender = NULL; + if (appender) + { + journaldAppender = (wLogJournaldAppender*)appender; + if (journaldAppender->stream) + (void)fclose(journaldAppender->stream); + free(journaldAppender->identifier); + free(journaldAppender); + } +} + +wLogAppender* WLog_JournaldAppender_New(wLog* log) +{ + wLogJournaldAppender* appender = NULL; + DWORD nSize = 0; + LPCSTR name = "WLOG_JOURNALD_ID"; + + appender = (wLogJournaldAppender*)calloc(1, sizeof(wLogJournaldAppender)); + if (!appender) + return NULL; + + appender->Type = WLOG_APPENDER_JOURNALD; + appender->Open = WLog_JournaldAppender_Open; + appender->Close = WLog_JournaldAppender_Close; + appender->WriteMessage = WLog_JournaldAppender_WriteMessage; + appender->WriteDataMessage = WLog_JournaldAppender_WriteDataMessage; + appender->WriteImageMessage = WLog_JournaldAppender_WriteImageMessage; + appender->Set = WLog_JournaldAppender_Set; + appender->Free = WLog_JournaldAppender_Free; + + nSize = GetEnvironmentVariableA(name, NULL, 0); + if (nSize) + { + appender->identifier = (LPSTR)malloc(nSize); + if (!appender->identifier) + goto error_open; + + if (GetEnvironmentVariableA(name, appender->identifier, nSize) != nSize - 1) + goto error_open; + + if (!WLog_JournaldAppender_Open(log, (wLogAppender*)appender)) + goto error_open; + } + + return (wLogAppender*)appender; + +error_open: + free(appender->identifier); + free(appender); + return NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..49223c51647bcdd757e3d8d67226eae630af2941 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/JournaldAppender.h @@ -0,0 +1,31 @@ +/** + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of the copyright holders not be used in + * advertising or publicity pertaining to distribution of the software + * without specific, written prior permission. The copyright holders make + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef WINPR_LIBWINPR_UTILS_WLOG_JOURNALDAPPENDER_H_ +#define WINPR_LIBWINPR_UTILS_WLOG_JOURNALDAPPENDER_H_ + +#include "wlog.h" + +wLogAppender* WLog_JournaldAppender_New(wLog* log); + +#endif /* WINPR_LIBWINPR_UTILS_WLOG_JOURNALDAPPENDER_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.c new file mode 100644 index 0000000000000000000000000000000000000000..31f4f0a8c7d12966f5af17f412efb568c6fe48e7 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.c @@ -0,0 +1,389 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "wlog.h" + +#include "Layout.h" + +#if defined __linux__ && !defined ANDROID +#include +#include +#endif + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +struct format_option_recurse; + +struct format_tid_arg +{ + char tid[32]; +}; + +struct format_option +{ + const char* fmt; + size_t fmtlen; + const char* replace; + size_t replacelen; + const char* (*fkt)(void*); + void* arg; + const char* (*ext)(const struct format_option* opt, const char* str, size_t* preplacelen, + size_t* pskiplen); + struct format_option_recurse* recurse; +}; + +struct format_option_recurse +{ + struct format_option* options; + size_t nroptions; + wLog* log; + wLogLayout* layout; + wLogMessage* message; + char buffer[WLOG_MAX_PREFIX_SIZE]; +}; + +/** + * Log Layout + */ +WINPR_ATTR_FORMAT_ARG(3, 0) +static void WLog_PrintMessagePrefixVA(wLog* log, wLogMessage* message, + WINPR_FORMAT_ARG const char* format, va_list args) +{ + WINPR_ASSERT(message); + (void)vsnprintf(message->PrefixString, WLOG_MAX_PREFIX_SIZE - 1, format, args); +} + +WINPR_ATTR_FORMAT_ARG(3, 4) +static void WLog_PrintMessagePrefix(wLog* log, wLogMessage* message, + WINPR_FORMAT_ARG const char* format, ...) +{ + va_list args; + va_start(args, format); + WLog_PrintMessagePrefixVA(log, message, format, args); + va_end(args); +} + +static const char* get_tid(void* arg) +{ + struct format_tid_arg* targ = arg; + WINPR_ASSERT(targ); + + size_t tid = 0; +#if defined __linux__ && !defined ANDROID + /* On Linux we prefer to see the LWP id */ + tid = (size_t)syscall(SYS_gettid); +#else + tid = (size_t)GetCurrentThreadId(); +#endif + (void)_snprintf(targ->tid, sizeof(targ->tid), "%08" PRIxz, tid); + return targ->tid; +} + +static BOOL log_invalid_fmt(const char* what) +{ + (void)fprintf(stderr, "Invalid format string '%s'\n", what); + return FALSE; +} + +static BOOL check_and_log_format_size(char* format, size_t size, size_t index, size_t add) +{ + /* format string must be '\0' terminated, so abort at size - 1 */ + if (index + add + 1 >= size) + { + (void)fprintf(stderr, + "Format string too long ['%s', max %" PRIuz ", used %" PRIuz + ", adding %" PRIuz "]\n", + format, size, index, add); + return FALSE; + } + return TRUE; +} + +static int opt_compare_fn(const void* a, const void* b) +{ + const char* what = a; + const struct format_option* opt = b; + if (!opt) + return -1; + return strncmp(what, opt->fmt, opt->fmtlen); +} + +static BOOL replace_format_string(const char* FormatString, struct format_option_recurse* recurse, + char* format, size_t formatlen); + +static const char* skip_if_null(const struct format_option* opt, const char* fmt, + size_t* preplacelen, size_t* pskiplen) +{ + WINPR_ASSERT(opt); + WINPR_ASSERT(fmt); + WINPR_ASSERT(preplacelen); + WINPR_ASSERT(pskiplen); + + *preplacelen = 0; + *pskiplen = 0; + + const char* str = &fmt[opt->fmtlen]; /* Skip first %{ from string */ + const char* end = strstr(str, opt->replace); + if (!end) + return NULL; + *pskiplen = WINPR_ASSERTING_INT_CAST(size_t, end - fmt) + opt->replacelen; + + if (!opt->arg) + return NULL; + + const size_t replacelen = WINPR_ASSERTING_INT_CAST(size_t, end - str); + + char buffer[WLOG_MAX_PREFIX_SIZE] = { 0 }; + memcpy(buffer, str, MIN(replacelen, ARRAYSIZE(buffer) - 1)); + + if (!replace_format_string(buffer, opt->recurse, opt->recurse->buffer, + ARRAYSIZE(opt->recurse->buffer))) + return NULL; + + *preplacelen = strnlen(opt->recurse->buffer, ARRAYSIZE(opt->recurse->buffer)); + return opt->recurse->buffer; +} + +static BOOL replace_format_string(const char* FormatString, struct format_option_recurse* recurse, + char* format, size_t formatlen) +{ + WINPR_ASSERT(FormatString); + WINPR_ASSERT(recurse); + + size_t index = 0; + + while (*FormatString) + { + const struct format_option* opt = + bsearch(FormatString, recurse->options, recurse->nroptions, + sizeof(struct format_option), opt_compare_fn); + if (opt) + { + size_t replacelen = opt->replacelen; + size_t fmtlen = opt->fmtlen; + const char* replace = opt->replace; + const void* arg = opt->arg; + + if (opt->ext) + replace = opt->ext(opt, FormatString, &replacelen, &fmtlen); + if (opt->fkt) + arg = opt->fkt(opt->arg); + + if (replace && (replacelen > 0)) + { + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL + const int rc = _snprintf(&format[index], formatlen - index, replace, arg); + WINPR_PRAGMA_DIAG_POP + if (rc < 0) + return FALSE; + if (!check_and_log_format_size(format, formatlen, index, + WINPR_ASSERTING_INT_CAST(size_t, rc))) + return FALSE; + index += WINPR_ASSERTING_INT_CAST(size_t, rc); + } + FormatString += fmtlen; + } + else + { + /* Unknown format string */ + if (*FormatString == '%') + return log_invalid_fmt(FormatString); + + if (!check_and_log_format_size(format, formatlen, index, 1)) + return FALSE; + format[index++] = *FormatString++; + } + } + + if (!check_and_log_format_size(format, formatlen, index, 0)) + return FALSE; + return TRUE; +} + +BOOL WLog_Layout_GetMessagePrefix(wLog* log, wLogLayout* layout, wLogMessage* message) +{ + char format[WLOG_MAX_PREFIX_SIZE] = { 0 }; + + WINPR_ASSERT(layout); + WINPR_ASSERT(message); + + struct format_tid_arg targ = { 0 }; + + SYSTEMTIME localTime = { 0 }; + GetLocalTime(&localTime); + + struct format_option_recurse recurse = { + .options = NULL, .nroptions = 0, .log = log, .layout = layout, .message = message + }; + +#define ENTRY(x) x, sizeof(x) - 1 + struct format_option options[] = { + { ENTRY("%ctx"), ENTRY("%s"), log->custom, log->context, NULL, &recurse }, /* log context */ + { ENTRY("%dw"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wDayOfWeek, NULL, + &recurse }, /* day of week */ + { ENTRY("%dy"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wDay, NULL, + &recurse }, /* day of year */ + { ENTRY("%fl"), ENTRY("%s"), NULL, WINPR_CAST_CONST_PTR_AWAY(message->FileName, void*), + NULL, &recurse }, /* file */ + { ENTRY("%fn"), ENTRY("%s"), NULL, WINPR_CAST_CONST_PTR_AWAY(message->FunctionName, void*), + NULL, &recurse }, /* function */ + { ENTRY("%hr"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wHour, NULL, + &recurse }, /* hours */ + { ENTRY("%ln"), ENTRY("%" PRIuz), NULL, (void*)message->LineNumber, NULL, + &recurse }, /* line number */ + { ENTRY("%lv"), ENTRY("%s"), NULL, + WINPR_CAST_CONST_PTR_AWAY(WLOG_LEVELS[message->Level], void*), NULL, + &recurse }, /* log level */ + { ENTRY("%mi"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wMinute, NULL, + &recurse }, /* minutes */ + { ENTRY("%ml"), ENTRY("%03u"), NULL, (void*)(size_t)localTime.wMilliseconds, NULL, + &recurse }, /* milliseconds */ + { ENTRY("%mn"), ENTRY("%s"), NULL, log->Name, NULL, &recurse }, /* module name */ + { ENTRY("%mo"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wMonth, NULL, + &recurse }, /* month */ + { ENTRY("%pid"), ENTRY("%u"), NULL, (void*)(size_t)GetCurrentProcessId(), NULL, + &recurse }, /* process id */ + { ENTRY("%se"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wSecond, NULL, + &recurse }, /* seconds */ + { ENTRY("%tid"), ENTRY("%s"), get_tid, &targ, NULL, &recurse }, /* thread id */ + { ENTRY("%yr"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wYear, NULL, + &recurse }, /* year */ + { ENTRY("%{"), ENTRY("%}"), NULL, log->context, skip_if_null, + &recurse }, /* skip if no context */ + }; + + recurse.options = options; + recurse.nroptions = ARRAYSIZE(options); + + if (!replace_format_string(layout->FormatString, &recurse, format, ARRAYSIZE(format))) + return FALSE; + + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_FORMAT_SECURITY + + WLog_PrintMessagePrefix(log, message, format); + + WINPR_PRAGMA_DIAG_POP + + return TRUE; +} + +wLogLayout* WLog_GetLogLayout(wLog* log) +{ + wLogAppender* appender = NULL; + appender = WLog_GetLogAppender(log); + return appender->Layout; +} + +BOOL WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format) +{ + free(layout->FormatString); + layout->FormatString = NULL; + + if (format) + { + layout->FormatString = _strdup(format); + + if (!layout->FormatString) + return FALSE; + } + + return TRUE; +} + +wLogLayout* WLog_Layout_New(wLog* log) +{ + LPCSTR prefix = "WLOG_PREFIX"; + DWORD nSize = 0; + char* env = NULL; + wLogLayout* layout = NULL; + layout = (wLogLayout*)calloc(1, sizeof(wLogLayout)); + + if (!layout) + return NULL; + + nSize = GetEnvironmentVariableA(prefix, NULL, 0); + + if (nSize) + { + env = (LPSTR)malloc(nSize); + + if (!env) + { + free(layout); + return NULL; + } + + if (GetEnvironmentVariableA(prefix, env, nSize) != nSize - 1) + { + free(env); + free(layout); + return NULL; + } + } + + if (env) + layout->FormatString = env; + else + { +#ifdef ANDROID + layout->FormatString = _strdup("[pid=%pid:tid=%tid] - [%fn]%{[%ctx]%}: "); +#else + layout->FormatString = + _strdup("[%hr:%mi:%se:%ml] [%pid:%tid] [%lv][%mn] - [%fn]%{[%ctx]%}: "); +#endif + + if (!layout->FormatString) + { + free(layout); + return NULL; + } + } + + return layout; +} + +void WLog_Layout_Free(wLog* log, wLogLayout* layout) +{ + if (layout) + { + if (layout->FormatString) + { + free(layout->FormatString); + layout->FormatString = NULL; + } + + free(layout); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.h new file mode 100644 index 0000000000000000000000000000000000000000..8698077a0cb69e7f416bc23d09aeb3b8bb23faf3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Layout.h @@ -0,0 +1,41 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_LAYOUT_PRIVATE_H +#define WINPR_WLOG_LAYOUT_PRIVATE_H + +#include "wlog.h" + +/** + * Log Layout + */ + +struct s_wLogLayout +{ + DWORD Type; + + LPSTR FormatString; +}; + +void WLog_Layout_Free(wLog* log, wLogLayout* layout); + +WINPR_ATTR_MALLOC(WLog_Layout_Free, 2) +wLogLayout* WLog_Layout_New(wLog* log); + +#endif /* WINPR_WLOG_LAYOUT_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.c new file mode 100644 index 0000000000000000000000000000000000000000..ab3b5afedecf29ea910dfd47e81ab7f54d522672 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.c @@ -0,0 +1,64 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include "wlog.h" + +#include "Message.h" + +char* WLog_Message_GetOutputFileName(int id, const char* ext) +{ + DWORD ProcessId = 0; + char* FilePath = NULL; + char* FileName = NULL; + char* FullFileName = NULL; + + if (!(FileName = (char*)malloc(256))) + return NULL; + + FilePath = GetKnownSubPath(KNOWN_PATH_TEMP, "wlog"); + + if (!winpr_PathFileExists(FilePath)) + { + if (!winpr_PathMakePath(FilePath, NULL)) + { + free(FileName); + free(FilePath); + return NULL; + } + } + + ProcessId = GetCurrentProcessId(); + if (id >= 0) + (void)sprintf_s(FileName, 256, "%" PRIu32 "-%d.%s", ProcessId, id, ext); + else + (void)sprintf_s(FileName, 256, "%" PRIu32 ".%s", ProcessId, ext); + + FullFileName = GetCombinedPath(FilePath, FileName); + + free(FileName); + free(FilePath); + + return FullFileName; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.h new file mode 100644 index 0000000000000000000000000000000000000000..c65b33cf05e6a84e6ae40015ca3f00d02d72af82 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/Message.h @@ -0,0 +1,29 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_MESSAGE_PRIVATE_H +#define WINPR_WLOG_MESSAGE_PRIVATE_H + +#include "DataMessage.h" +#include "ImageMessage.h" +#include "PacketMessage.h" + +char* WLog_Message_GetOutputFileName(int id, const char* ext); + +#endif /* WINPR_WLOG_MESSAGE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.c new file mode 100644 index 0000000000000000000000000000000000000000..ffa9479d8ec52e64cb96aa77cee027f252ec9ec0 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.c @@ -0,0 +1,470 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * 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 + +#include "wlog.h" + +#include "PacketMessage.h" + +#include +#include +#include +#include +#include + +#include "../../log.h" +#define TAG WINPR_TAG("utils.wlog") + +static BOOL Pcap_Read_Header(wPcap* pcap, wPcapHeader* header) +{ + if (pcap && pcap->fp && fread((void*)header, sizeof(wPcapHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +/* currently unused code */ +#if 0 +static BOOL Pcap_Read_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) +{ + if (pcap && pcap->fp && (fread((void*) record, sizeof(wPcapRecordHeader), 1, pcap->fp) == 1)) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Read_Record(wPcap* pcap, wPcapRecord* record) +{ + if (pcap && pcap->fp) + { + if (!Pcap_Read_RecordHeader(pcap, &record->header)) + return FALSE; + record->length = record->header.incl_len; + record->data = malloc(record->length); + if (!record->data) + return FALSE; + if (fread(record->data, record->length, 1, pcap->fp) != 1) + { + free(record->data); + record->length = 0; + record->data = NULL; + return FALSE; + } + } + return TRUE; +} + +static BOOL Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) +{ + wPcapRecord* record = NULL; + + if (!pcap->tail) + { + pcap->tail = (wPcapRecord*) calloc(1, sizeof(wPcapRecord)); + if (!pcap->tail) + return FALSE; + pcap->head = pcap->tail; + pcap->record = pcap->head; + record = pcap->tail; + } + else + { + record = (wPcapRecord*) calloc(1, sizeof(wPcapRecord)); + if (!record) + return FALSE; + pcap->tail->next = record; + pcap->tail = record; + } + + if (!pcap->record) + pcap->record = record; + + record->data = data; + record->length = length; + record->header.incl_len = length; + record->header.orig_len = length; + + UINT64 ns = winpr_GetUnixTimeNS(); + record->header.ts_sec = WINPR_TIME_NS_TO_S(ns); + record->header.ts_usec = WINPR_TIME_NS_REM_US(ns); + return TRUE; +} + +static BOOL Pcap_HasNext_Record(wPcap* pcap) +{ + if (pcap->file_size - (_ftelli64(pcap->fp)) <= 16) + return FALSE; + + return TRUE; +} + +static BOOL Pcap_GetNext_RecordHeader(wPcap* pcap, wPcapRecord* record) +{ + if (!Pcap_HasNext_Record(pcap) || !Pcap_Read_RecordHeader(pcap, &record->header)) + return FALSE; + + record->length = record->header.incl_len; + return TRUE; +} + +static BOOL Pcap_GetNext_RecordContent(wPcap* pcap, wPcapRecord* record) +{ + if (pcap && pcap->fp && fread(record->data, record->length, 1, pcap->fp) == 1) + return TRUE; + + return FALSE; +} + +static BOOL Pcap_GetNext_Record(wPcap* pcap, wPcapRecord* record) +{ + if (!Pcap_HasNext_Record(pcap)) + return FALSE; + + return Pcap_Read_Record(pcap, record); +} +#endif + +static BOOL Pcap_Write_Header(wPcap* pcap, wPcapHeader* header) +{ + if (pcap && pcap->fp && fwrite((void*)header, sizeof(wPcapHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) +{ + if (pcap && pcap->fp && fwrite((void*)record, sizeof(wPcapRecordHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_RecordContent(wPcap* pcap, wPcapRecord* record) +{ + if (pcap && pcap->fp && fwrite(record->data, record->length, 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_Record(wPcap* pcap, wPcapRecord* record) +{ + return Pcap_Write_RecordHeader(pcap, &record->header) && Pcap_Write_RecordContent(pcap, record); +} + +wPcap* Pcap_Open(char* name, BOOL write) +{ + wPcap* pcap = NULL; + FILE* pcap_fp = winpr_fopen(name, write ? "w+b" : "rb"); + + if (!pcap_fp) + { + WLog_ERR(TAG, "opening pcap file"); + return NULL; + } + + pcap = (wPcap*)calloc(1, sizeof(wPcap)); + + if (!pcap) + goto out_fail; + + pcap->name = name; + pcap->write = write; + pcap->record_count = 0; + pcap->fp = pcap_fp; + + if (write) + { + pcap->header.magic_number = PCAP_MAGIC_NUMBER; + pcap->header.version_major = 2; + pcap->header.version_minor = 4; + pcap->header.thiszone = 0; + pcap->header.sigfigs = 0; + pcap->header.snaplen = 0xFFFFFFFF; + pcap->header.network = 1; /* ethernet */ + if (!Pcap_Write_Header(pcap, &pcap->header)) + goto out_fail; + } + else + { + if (_fseeki64(pcap->fp, 0, SEEK_END) < 0) + goto out_fail; + pcap->file_size = (SSIZE_T)_ftelli64(pcap->fp); + if (pcap->file_size < 0) + goto out_fail; + if (_fseeki64(pcap->fp, 0, SEEK_SET) < 0) + goto out_fail; + if (!Pcap_Read_Header(pcap, &pcap->header)) + goto out_fail; + } + + return pcap; + +out_fail: + if (pcap_fp) + (void)fclose(pcap_fp); + free(pcap); + return NULL; +} + +void Pcap_Flush(wPcap* pcap) +{ + if (!pcap || !pcap->fp) + return; + + while (pcap->record) + { + if (!Pcap_Write_Record(pcap, pcap->record)) + return; + pcap->record = pcap->record->next; + } + + (void)fflush(pcap->fp); +} + +void Pcap_Close(wPcap* pcap) +{ + if (!pcap || !pcap->fp) + return; + + Pcap_Flush(pcap); + (void)fclose(pcap->fp); + free(pcap); +} + +static BOOL WLog_PacketMessage_Write_EthernetHeader(wPcap* pcap, wEthernetHeader* ethernet) +{ + wStream* s = NULL; + wStream sbuffer = { 0 }; + BYTE buffer[14] = { 0 }; + BOOL ret = TRUE; + + if (!pcap || !pcap->fp || !ethernet) + return FALSE; + + s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + if (!s) + return FALSE; + Stream_Write(s, ethernet->Destination, 6); + Stream_Write(s, ethernet->Source, 6); + Stream_Write_UINT16_BE(s, ethernet->Type); + if (fwrite(buffer, sizeof(buffer), 1, pcap->fp) != 1) + ret = FALSE; + + return ret; +} + +static UINT16 IPv4Checksum(const BYTE* ipv4, int length) +{ + long checksum = 0; + + while (length > 1) + { + const UINT16 tmp16 = *((const UINT16*)ipv4); + checksum += tmp16; + length -= 2; + ipv4 += 2; + } + + if (length > 0) + checksum += *ipv4; + + while (checksum >> 16) + checksum = (checksum & 0xFFFF) + (checksum >> 16); + + return (UINT16)(~checksum); +} + +static BOOL WLog_PacketMessage_Write_IPv4Header(wPcap* pcap, wIPv4Header* ipv4) +{ + wStream* s = NULL; + wStream sbuffer = { 0 }; + BYTE buffer[20] = { 0 }; + int ret = TRUE; + + if (!pcap || !pcap->fp || !ipv4) + return FALSE; + + s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + if (!s) + return FALSE; + Stream_Write_UINT8(s, (BYTE)((ipv4->Version << 4) | ipv4->InternetHeaderLength)); + Stream_Write_UINT8(s, ipv4->TypeOfService); + Stream_Write_UINT16_BE(s, ipv4->TotalLength); + Stream_Write_UINT16_BE(s, ipv4->Identification); + Stream_Write_UINT16_BE(s, (UINT16)((ipv4->InternetProtocolFlags << 13) | ipv4->FragmentOffset)); + Stream_Write_UINT8(s, ipv4->TimeToLive); + Stream_Write_UINT8(s, ipv4->Protocol); + Stream_Write_UINT16(s, ipv4->HeaderChecksum); + Stream_Write_UINT32_BE(s, ipv4->SourceAddress); + Stream_Write_UINT32_BE(s, ipv4->DestinationAddress); + ipv4->HeaderChecksum = IPv4Checksum((BYTE*)buffer, 20); + Stream_Rewind(s, 10); + Stream_Write_UINT16(s, ipv4->HeaderChecksum); + + if (fwrite(buffer, sizeof(buffer), 1, pcap->fp) != 1) + ret = FALSE; + + return ret; +} + +static BOOL WLog_PacketMessage_Write_TcpHeader(wPcap* pcap, wTcpHeader* tcp) +{ + wStream* s = NULL; + wStream sbuffer = { 0 }; + BYTE buffer[20] = { 0 }; + BOOL ret = TRUE; + + if (!pcap || !pcap->fp || !tcp) + return FALSE; + + s = Stream_StaticInit(&sbuffer, buffer, sizeof(buffer)); + if (!s) + return FALSE; + Stream_Write_UINT16_BE(s, tcp->SourcePort); + Stream_Write_UINT16_BE(s, tcp->DestinationPort); + Stream_Write_UINT32_BE(s, tcp->SequenceNumber); + Stream_Write_UINT32_BE(s, tcp->AcknowledgementNumber); + Stream_Write_UINT8(s, (UINT8)((tcp->Offset << 4) | (tcp->Reserved & 0xF))); + Stream_Write_UINT8(s, tcp->TcpFlags); + Stream_Write_UINT16_BE(s, tcp->Window); + Stream_Write_UINT16_BE(s, tcp->Checksum); + Stream_Write_UINT16_BE(s, tcp->UrgentPointer); + + if (pcap->fp) + { + if (fwrite(buffer, sizeof(buffer), 1, pcap->fp) != 1) + ret = FALSE; + } + + return ret; +} + +static UINT32 g_InboundSequenceNumber = 0; +static UINT32 g_OutboundSequenceNumber = 0; + +BOOL WLog_PacketMessage_Write(wPcap* pcap, void* data, size_t length, DWORD flags) +{ + wTcpHeader tcp; + wIPv4Header ipv4; + wPcapRecord record; + wEthernetHeader ethernet; + ethernet.Type = 0x0800; + + if (!pcap || !pcap->fp) + return FALSE; + + if (flags & WLOG_PACKET_OUTBOUND) + { + /* 00:15:5D:01:64:04 */ + ethernet.Source[0] = 0x00; + ethernet.Source[1] = 0x15; + ethernet.Source[2] = 0x5D; + ethernet.Source[3] = 0x01; + ethernet.Source[4] = 0x64; + ethernet.Source[5] = 0x04; + /* 00:15:5D:01:64:01 */ + ethernet.Destination[0] = 0x00; + ethernet.Destination[1] = 0x15; + ethernet.Destination[2] = 0x5D; + ethernet.Destination[3] = 0x01; + ethernet.Destination[4] = 0x64; + ethernet.Destination[5] = 0x01; + } + else + { + /* 00:15:5D:01:64:01 */ + ethernet.Source[0] = 0x00; + ethernet.Source[1] = 0x15; + ethernet.Source[2] = 0x5D; + ethernet.Source[3] = 0x01; + ethernet.Source[4] = 0x64; + ethernet.Source[5] = 0x01; + /* 00:15:5D:01:64:04 */ + ethernet.Destination[0] = 0x00; + ethernet.Destination[1] = 0x15; + ethernet.Destination[2] = 0x5D; + ethernet.Destination[3] = 0x01; + ethernet.Destination[4] = 0x64; + ethernet.Destination[5] = 0x04; + } + + ipv4.Version = 4; + ipv4.InternetHeaderLength = 5; + ipv4.TypeOfService = 0; + ipv4.TotalLength = (UINT16)(length + 20 + 20); + ipv4.Identification = 0; + ipv4.InternetProtocolFlags = 0x02; + ipv4.FragmentOffset = 0; + ipv4.TimeToLive = 128; + ipv4.Protocol = 6; /* TCP */ + ipv4.HeaderChecksum = 0; + + if (flags & WLOG_PACKET_OUTBOUND) + { + ipv4.SourceAddress = 0xC0A80196; /* 192.168.1.150 */ + ipv4.DestinationAddress = 0x4A7D64C8; /* 74.125.100.200 */ + } + else + { + ipv4.SourceAddress = 0x4A7D64C8; /* 74.125.100.200 */ + ipv4.DestinationAddress = 0xC0A80196; /* 192.168.1.150 */ + } + + tcp.SourcePort = 3389; + tcp.DestinationPort = 3389; + + if (flags & WLOG_PACKET_OUTBOUND) + { + tcp.SequenceNumber = g_OutboundSequenceNumber; + tcp.AcknowledgementNumber = g_InboundSequenceNumber; + g_OutboundSequenceNumber += length; + } + else + { + tcp.SequenceNumber = g_InboundSequenceNumber; + tcp.AcknowledgementNumber = g_OutboundSequenceNumber; + g_InboundSequenceNumber += length; + } + + tcp.Offset = 5; + tcp.Reserved = 0; + tcp.TcpFlags = 0x0018; + tcp.Window = 0x7FFF; + tcp.Checksum = 0; + tcp.UrgentPointer = 0; + record.data = data; + record.length = length; + const size_t offset = 14 + 20 + 20; + WINPR_ASSERT(record.length <= UINT32_MAX - offset); + record.header.incl_len = (UINT32)record.length + offset; + record.header.orig_len = (UINT32)record.length + offset; + record.next = NULL; + + UINT64 ns = winpr_GetUnixTimeNS(); + record.header.ts_sec = (UINT32)WINPR_TIME_NS_TO_S(ns); + record.header.ts_usec = WINPR_TIME_NS_REM_US(ns); + + if (!Pcap_Write_RecordHeader(pcap, &record.header) || + !WLog_PacketMessage_Write_EthernetHeader(pcap, ðernet) || + !WLog_PacketMessage_Write_IPv4Header(pcap, &ipv4) || + !WLog_PacketMessage_Write_TcpHeader(pcap, &tcp) || !Pcap_Write_RecordContent(pcap, &record)) + return FALSE; + (void)fflush(pcap->fp); + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.h new file mode 100644 index 0000000000000000000000000000000000000000..088ee8f98a2ccbaaac984ae985bb182ed371e61b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/PacketMessage.h @@ -0,0 +1,111 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_PACKET_MESSAGE_PRIVATE_H +#define WINPR_WLOG_PACKET_MESSAGE_PRIVATE_H + +#include "wlog.h" + +#define PCAP_MAGIC_NUMBER 0xA1B2C3D4 + +typedef struct +{ + UINT32 magic_number; /* magic number */ + UINT16 version_major; /* major version number */ + UINT16 version_minor; /* minor version number */ + INT32 thiszone; /* GMT to local correction */ + UINT32 sigfigs; /* accuracy of timestamps */ + UINT32 snaplen; /* max length of captured packets, in octets */ + UINT32 network; /* data link type */ +} wPcapHeader; + +typedef struct +{ + UINT32 ts_sec; /* timestamp seconds */ + UINT32 ts_usec; /* timestamp microseconds */ + UINT32 incl_len; /* number of octets of packet saved in file */ + UINT32 orig_len; /* actual length of packet */ +} wPcapRecordHeader; + +typedef struct s_wPcapRecort +{ + wPcapRecordHeader header; + void* data; + size_t length; + struct s_wPcapRecort* next; +} wPcapRecord; + +typedef struct +{ + FILE* fp; + char* name; + BOOL write; + SSIZE_T file_size; + size_t record_count; + wPcapHeader header; + wPcapRecord* head; + wPcapRecord* tail; + wPcapRecord* record; +} wPcap; + +wPcap* Pcap_Open(char* name, BOOL write); +void Pcap_Close(wPcap* pcap); + +void Pcap_Flush(wPcap* pcap); + +typedef struct +{ + BYTE Destination[6]; + BYTE Source[6]; + UINT16 Type; +} wEthernetHeader; + +typedef struct +{ + BYTE Version; + BYTE InternetHeaderLength; + BYTE TypeOfService; + UINT16 TotalLength; + UINT16 Identification; + BYTE InternetProtocolFlags; + UINT16 FragmentOffset; + BYTE TimeToLive; + BYTE Protocol; + UINT16 HeaderChecksum; + UINT32 SourceAddress; + UINT32 DestinationAddress; +} wIPv4Header; + +typedef struct +{ + UINT16 SourcePort; + UINT16 DestinationPort; + UINT32 SequenceNumber; + UINT32 AcknowledgementNumber; + BYTE Offset; + BYTE Reserved; + BYTE TcpFlags; + UINT16 Window; + UINT16 Checksum; + UINT16 UrgentPointer; +} wTcpHeader; + +BOOL WLog_PacketMessage_Write(wPcap* pcap, void* data, size_t length, DWORD flags); + +#endif /* WINPR_WLOG_PACKET_MESSAGE_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..73baade741dd5caaf58a42fe245fd6c90ee34b26 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.c @@ -0,0 +1,137 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * 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 + +#include "SyslogAppender.h" +#include + +typedef struct +{ + WLOG_APPENDER_COMMON(); +} wLogSyslogAppender; + +static int getSyslogLevel(DWORD level) +{ + switch (level) + { + case WLOG_TRACE: + case WLOG_DEBUG: + return LOG_DEBUG; + case WLOG_INFO: + return LOG_INFO; + case WLOG_WARN: + return LOG_WARNING; + case WLOG_ERROR: + return LOG_ERR; + case WLOG_FATAL: + return LOG_CRIT; + case WLOG_OFF: + default: + return -1; + } +} + +static BOOL WLog_SyslogAppender_Open(wLog* log, wLogAppender* appender) +{ + if (!log || !appender) + return FALSE; + + return TRUE; +} + +static BOOL WLog_SyslogAppender_Close(wLog* log, wLogAppender* appender) +{ + if (!log || !appender) + return FALSE; + + return TRUE; +} + +static BOOL WLog_SyslogAppender_WriteMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + int syslogLevel = 0; + + if (!log || !appender || !message) + return FALSE; + + syslogLevel = getSyslogLevel(message->Level); + if (syslogLevel >= 0) + syslog(syslogLevel, "%s", message->TextString); + + return TRUE; +} + +static BOOL WLog_SyslogAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + int syslogLevel = 0; + + if (!log || !appender || !message) + return FALSE; + + syslogLevel = getSyslogLevel(message->Level); + if (syslogLevel >= 0) + syslog(syslogLevel, "skipped data message of %" PRIuz " bytes", message->Length); + + return TRUE; +} + +static BOOL WLog_SyslogAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + int syslogLevel = 0; + + if (!log || !appender || !message) + return FALSE; + + syslogLevel = getSyslogLevel(message->Level); + if (syslogLevel >= 0) + syslog(syslogLevel, "skipped image (%" PRIuz "x%" PRIuz "x%" PRIuz ")", message->ImageWidth, + message->ImageHeight, message->ImageBpp); + + return TRUE; +} + +static void WLog_SyslogAppender_Free(wLogAppender* appender) +{ + free(appender); +} + +wLogAppender* WLog_SyslogAppender_New(wLog* log) +{ + wLogSyslogAppender* appender = NULL; + + appender = (wLogSyslogAppender*)calloc(1, sizeof(wLogSyslogAppender)); + if (!appender) + return NULL; + + appender->Type = WLOG_APPENDER_SYSLOG; + + appender->Open = WLog_SyslogAppender_Open; + appender->Close = WLog_SyslogAppender_Close; + appender->WriteMessage = WLog_SyslogAppender_WriteMessage; + appender->WriteDataMessage = WLog_SyslogAppender_WriteDataMessage; + appender->WriteImageMessage = WLog_SyslogAppender_WriteImageMessage; + appender->Free = WLog_SyslogAppender_Free; + + return (wLogAppender*)appender; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..bbb30d5c84cd87fc3d5723c324b74f7cebf5b849 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/SyslogAppender.h @@ -0,0 +1,32 @@ +/** + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of the copyright holders not be used in + * advertising or publicity pertaining to distribution of the software + * without specific, written prior permission. The copyright holders make + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef WINPR_LIBWINPR_UTILS_WLOG_SYSLOGAPPENDER_H_ +#define WINPR_LIBWINPR_UTILS_WLOG_SYSLOGAPPENDER_H_ + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_SyslogAppender_New(wLog* log); + +#endif /* WINPR_LIBWINPR_UTILS_WLOG_SYSLOGAPPENDER_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.c new file mode 100644 index 0000000000000000000000000000000000000000..17044f89301c341d48d925ac99b3e548a5cda6fe --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.c @@ -0,0 +1,224 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * 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 + +#include +#include +#include + +#include "wlog.h" + +typedef struct +{ + WLOG_APPENDER_COMMON(); + char* host; + struct sockaddr targetAddr; + int targetAddrLen; + SOCKET sock; +} wLogUdpAppender; + +static BOOL WLog_UdpAppender_Open(wLog* log, wLogAppender* appender) +{ + wLogUdpAppender* udpAppender = NULL; + char addressString[256] = { 0 }; + struct addrinfo hints = { 0 }; + struct addrinfo* result = { 0 }; + int status = 0; + char* colonPos = NULL; + + if (!appender) + return FALSE; + + udpAppender = (wLogUdpAppender*)appender; + + if (udpAppender->targetAddrLen) /* already opened */ + return TRUE; + + colonPos = strchr(udpAppender->host, ':'); + + if (!colonPos) + return FALSE; + + const size_t addrLen = WINPR_ASSERTING_INT_CAST(size_t, (colonPos - udpAppender->host)); + memcpy(addressString, udpAppender->host, addrLen); + addressString[addrLen] = '\0'; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + status = getaddrinfo(addressString, colonPos + 1, &hints, &result); + + if (status != 0) + return FALSE; + + if (result->ai_addrlen > sizeof(udpAppender->targetAddr)) + { + freeaddrinfo(result); + return FALSE; + } + + memcpy(&udpAppender->targetAddr, result->ai_addr, result->ai_addrlen); + udpAppender->targetAddrLen = (int)result->ai_addrlen; + freeaddrinfo(result); + return TRUE; +} + +static BOOL WLog_UdpAppender_Close(wLog* log, wLogAppender* appender) +{ + if (!log || !appender) + return FALSE; + + return TRUE; +} + +static BOOL WLog_UdpAppender_WriteMessage(wLog* log, wLogAppender* appender, wLogMessage* message) +{ + char prefix[WLOG_MAX_PREFIX_SIZE] = { 0 }; + wLogUdpAppender* udpAppender = NULL; + + if (!log || !appender || !message) + return FALSE; + + udpAppender = (wLogUdpAppender*)appender; + message->PrefixString = prefix; + WLog_Layout_GetMessagePrefix(log, appender->Layout, message); + (void)_sendto(udpAppender->sock, message->PrefixString, + (int)strnlen(message->PrefixString, INT_MAX), 0, &udpAppender->targetAddr, + udpAppender->targetAddrLen); + (void)_sendto(udpAppender->sock, message->TextString, + (int)strnlen(message->TextString, INT_MAX), 0, &udpAppender->targetAddr, + udpAppender->targetAddrLen); + (void)_sendto(udpAppender->sock, "\n", 1, 0, &udpAppender->targetAddr, + udpAppender->targetAddrLen); + return TRUE; +} + +static BOOL WLog_UdpAppender_WriteDataMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + if (!log || !appender || !message) + return FALSE; + + return TRUE; +} + +static BOOL WLog_UdpAppender_WriteImageMessage(wLog* log, wLogAppender* appender, + wLogMessage* message) +{ + if (!log || !appender || !message) + return FALSE; + + return TRUE; +} + +static BOOL WLog_UdpAppender_Set(wLogAppender* appender, const char* setting, void* value) +{ + const char target[] = "target"; + wLogUdpAppender* udpAppender = (wLogUdpAppender*)appender; + + /* Just check the value string is not empty */ + if (!value || (strnlen(value, 2) == 0)) + return FALSE; + + if (strncmp(target, setting, sizeof(target)) != 0) + return FALSE; + + udpAppender->targetAddrLen = 0; + + if (udpAppender->host) + free(udpAppender->host); + + udpAppender->host = _strdup((const char*)value); + return (udpAppender->host != NULL) && WLog_UdpAppender_Open(NULL, appender); +} + +static void WLog_UdpAppender_Free(wLogAppender* appender) +{ + wLogUdpAppender* udpAppender = NULL; + + if (appender) + { + udpAppender = (wLogUdpAppender*)appender; + + if (udpAppender->sock != INVALID_SOCKET) + { + closesocket(udpAppender->sock); + udpAppender->sock = INVALID_SOCKET; + } + + free(udpAppender->host); + free(udpAppender); + } +} + +wLogAppender* WLog_UdpAppender_New(wLog* log) +{ + wLogUdpAppender* appender = NULL; + DWORD nSize = 0; + LPCSTR name = NULL; + appender = (wLogUdpAppender*)calloc(1, sizeof(wLogUdpAppender)); + + if (!appender) + return NULL; + + appender->Type = WLOG_APPENDER_UDP; + appender->Open = WLog_UdpAppender_Open; + appender->Close = WLog_UdpAppender_Close; + appender->WriteMessage = WLog_UdpAppender_WriteMessage; + appender->WriteDataMessage = WLog_UdpAppender_WriteDataMessage; + appender->WriteImageMessage = WLog_UdpAppender_WriteImageMessage; + appender->Free = WLog_UdpAppender_Free; + appender->Set = WLog_UdpAppender_Set; + appender->sock = _socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (appender->sock == INVALID_SOCKET) + goto error_sock; + + name = "WLOG_UDP_TARGET"; + nSize = GetEnvironmentVariableA(name, NULL, 0); + + if (nSize) + { + appender->host = (LPSTR)malloc(nSize); + + if (!appender->host) + goto error_open; + + if (GetEnvironmentVariableA(name, appender->host, nSize) != nSize - 1) + goto error_open; + + if (!WLog_UdpAppender_Open(log, (wLogAppender*)appender)) + goto error_open; + } + else + { + appender->host = _strdup("127.0.0.1:20000"); + + if (!appender->host) + goto error_open; + } + + return (wLogAppender*)appender; +error_open: + free(appender->host); + closesocket(appender->sock); +error_sock: + free(appender); + return NULL; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.h new file mode 100644 index 0000000000000000000000000000000000000000..eda98b99bd21bc1d3dca5dbe6a30b2a48f70936b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/UdpAppender.h @@ -0,0 +1,34 @@ +/** + * Copyright © 2015 Thincast Technologies GmbH + * Copyright © 2015 David FORT + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of the copyright holders not be used in + * advertising or publicity pertaining to distribution of the software + * without specific, written prior permission. The copyright holders make + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef WINPR_LIBWINPR_UTILS_WLOG_UDPAPPENDER_H_ +#define WINPR_LIBWINPR_UTILS_WLOG_UDPAPPENDER_H_ + +#include + +#include "wlog.h" + +WINPR_ATTR_MALLOC(WLog_Appender_Free, 2) +wLogAppender* WLog_UdpAppender_New(wLog* log); + +#endif /* WINPR_LIBWINPR_UTILS_WLOG_UDPAPPENDER_H_ */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.c new file mode 100644 index 0000000000000000000000000000000000000000..e8a88373e2820ce25b6bdf7c1afbd7551f555186 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.c @@ -0,0 +1,1076 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#if defined(ANDROID) +#include +#include "../log.h" +#endif + +#include "wlog.h" + +typedef struct +{ + DWORD Level; + LPSTR* Names; + size_t NameCount; +} wLogFilter; + +#define WLOG_FILTER_NOT_FILTERED (-1) +#define WLOG_FILTER_NOT_INITIALIZED (-2) +/** + * References for general logging concepts: + * + * Short introduction to log4j: + * http://logging.apache.org/log4j/1.2/manual.html + * + * logging - Logging facility for Python: + * http://docs.python.org/2/library/logging.html + */ + +LPCSTR WLOG_LEVELS[7] = { "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "OFF" }; + +static INIT_ONCE g_WLogInitialized = INIT_ONCE_STATIC_INIT; +static DWORD g_FilterCount = 0; +static wLogFilter* g_Filters = NULL; +static wLog* g_RootLog = NULL; + +static wLog* WLog_New(LPCSTR name, wLog* rootLogger); +static void WLog_Free(wLog* log); +static LONG WLog_GetFilterLogLevel(wLog* log); +static int WLog_ParseLogLevel(LPCSTR level); +static BOOL WLog_ParseFilter(wLog* root, wLogFilter* filter, LPCSTR name); +static BOOL WLog_ParseFilters(wLog* root); +static wLog* WLog_Get_int(wLog* root, LPCSTR name); + +#if !defined(_WIN32) +static void WLog_Uninit_(void) __attribute__((destructor)); +#endif + +static void WLog_Uninit_(void) +{ + wLog* child = NULL; + wLog* root = g_RootLog; + + if (!root) + return; + + for (DWORD index = 0; index < root->ChildrenCount; index++) + { + child = root->Children[index]; + WLog_Free(child); + } + + WLog_Free(root); + g_RootLog = NULL; +} + +static void WLog_Lock(wLog* log) +{ + WINPR_ASSERT(log); + EnterCriticalSection(&log->lock); +} + +static void WLog_Unlock(wLog* log) +{ + WINPR_ASSERT(log); + LeaveCriticalSection(&log->lock); +} + +static BOOL CALLBACK WLog_InitializeRoot(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context) +{ + char* env = NULL; + DWORD nSize = 0; + DWORD logAppenderType = 0; + LPCSTR appender = "WLOG_APPENDER"; + + WINPR_UNUSED(InitOnce); + WINPR_UNUSED(Parameter); + WINPR_UNUSED(Context); + + if (!(g_RootLog = WLog_New("", NULL))) + return FALSE; + + g_RootLog->IsRoot = TRUE; + logAppenderType = WLOG_APPENDER_CONSOLE; + nSize = GetEnvironmentVariableA(appender, NULL, 0); + + if (nSize) + { + env = (LPSTR)malloc(nSize); + + if (!env) + goto fail; + + if (GetEnvironmentVariableA(appender, env, nSize) != nSize - 1) + { + (void)fprintf(stderr, "%s environment variable modified in my back", appender); + free(env); + goto fail; + } + + if (_stricmp(env, "CONSOLE") == 0) + logAppenderType = WLOG_APPENDER_CONSOLE; + else if (_stricmp(env, "FILE") == 0) + logAppenderType = WLOG_APPENDER_FILE; + else if (_stricmp(env, "BINARY") == 0) + logAppenderType = WLOG_APPENDER_BINARY; + +#ifdef WINPR_HAVE_SYSLOG_H + else if (_stricmp(env, "SYSLOG") == 0) + logAppenderType = WLOG_APPENDER_SYSLOG; + +#endif /* WINPR_HAVE_SYSLOG_H */ +#ifdef WINPR_HAVE_JOURNALD_H + else if (_stricmp(env, "JOURNALD") == 0) + logAppenderType = WLOG_APPENDER_JOURNALD; + +#endif + else if (_stricmp(env, "UDP") == 0) + logAppenderType = WLOG_APPENDER_UDP; + + free(env); + } + + if (!WLog_SetLogAppenderType(g_RootLog, logAppenderType)) + goto fail; + + if (!WLog_ParseFilters(g_RootLog)) + goto fail; + + (void)atexit(WLog_Uninit_); + + return TRUE; +fail: + WLog_Uninit_(); + return FALSE; +} + +static BOOL log_recursion(LPCSTR file, LPCSTR fkt, size_t line) +{ + BOOL status = FALSE; + char** msg = NULL; + size_t used = 0; + void* bt = winpr_backtrace(20); +#if defined(ANDROID) + LPCSTR tag = WINPR_TAG("utils.wlog"); +#endif + + if (!bt) + return FALSE; + + msg = winpr_backtrace_symbols(bt, &used); + + if (!msg) + goto out; + +#if defined(ANDROID) + + if (__android_log_print(ANDROID_LOG_FATAL, tag, "Recursion detected!!!") < 0) + goto out; + + if (__android_log_print(ANDROID_LOG_FATAL, tag, "Check %s [%s:%zu]", fkt, file, line) < 0) + goto out; + + for (size_t i = 0; i < used; i++) + if (__android_log_print(ANDROID_LOG_FATAL, tag, "%zu: %s", i, msg[i]) < 0) + goto out; + +#else + + if (fprintf(stderr, "[%s]: Recursion detected!\n", fkt) < 0) + goto out; + + if (fprintf(stderr, "[%s]: Check %s:%" PRIuz "\n", fkt, file, line) < 0) + goto out; + + for (size_t i = 0; i < used; i++) + if (fprintf(stderr, "%s: %" PRIuz ": %s\n", fkt, i, msg[i]) < 0) + goto out; + +#endif + status = TRUE; +out: + free((void*)msg); + winpr_backtrace_free(bt); + return status; +} + +static BOOL WLog_Write(wLog* log, wLogMessage* message) +{ + BOOL status = FALSE; + wLogAppender* appender = NULL; + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->active) + if (!WLog_OpenAppender(log)) + return FALSE; + + EnterCriticalSection(&appender->lock); + + if (appender->WriteMessage) + { + if (appender->recursive) + status = log_recursion(message->FileName, message->FunctionName, message->LineNumber); + else + { + appender->recursive = TRUE; + status = appender->WriteMessage(log, appender, message); + appender->recursive = FALSE; + } + } + + LeaveCriticalSection(&appender->lock); + return status; +} + +static BOOL WLog_WriteData(wLog* log, wLogMessage* message) +{ + BOOL status = 0; + wLogAppender* appender = NULL; + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->active) + if (!WLog_OpenAppender(log)) + return FALSE; + + if (!appender->WriteDataMessage) + return FALSE; + + EnterCriticalSection(&appender->lock); + + if (appender->recursive) + status = log_recursion(message->FileName, message->FunctionName, message->LineNumber); + else + { + appender->recursive = TRUE; + status = appender->WriteDataMessage(log, appender, message); + appender->recursive = FALSE; + } + + LeaveCriticalSection(&appender->lock); + return status; +} + +static BOOL WLog_WriteImage(wLog* log, wLogMessage* message) +{ + BOOL status = 0; + wLogAppender* appender = NULL; + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->active) + if (!WLog_OpenAppender(log)) + return FALSE; + + if (!appender->WriteImageMessage) + return FALSE; + + EnterCriticalSection(&appender->lock); + + if (appender->recursive) + status = log_recursion(message->FileName, message->FunctionName, message->LineNumber); + else + { + appender->recursive = TRUE; + status = appender->WriteImageMessage(log, appender, message); + appender->recursive = FALSE; + } + + LeaveCriticalSection(&appender->lock); + return status; +} + +static BOOL WLog_WritePacket(wLog* log, wLogMessage* message) +{ + BOOL status = 0; + wLogAppender* appender = NULL; + appender = WLog_GetLogAppender(log); + + if (!appender) + return FALSE; + + if (!appender->active) + if (!WLog_OpenAppender(log)) + return FALSE; + + if (!appender->WritePacketMessage) + return FALSE; + + EnterCriticalSection(&appender->lock); + + if (appender->recursive) + status = log_recursion(message->FileName, message->FunctionName, message->LineNumber); + else + { + appender->recursive = TRUE; + status = appender->WritePacketMessage(log, appender, message); + appender->recursive = FALSE; + } + + LeaveCriticalSection(&appender->lock); + return status; +} + +BOOL WLog_PrintMessageVA(wLog* log, DWORD type, DWORD level, size_t line, const char* file, + const char* function, va_list args) +{ + BOOL status = FALSE; + wLogMessage message = { 0 }; + message.Type = type; + message.Level = level; + message.LineNumber = line; + message.FileName = file; + message.FunctionName = function; + + switch (type) + { + case WLOG_MESSAGE_TEXT: + message.FormatString = va_arg(args, const char*); + + if (!strchr(message.FormatString, '%')) + { + message.TextString = message.FormatString; + status = WLog_Write(log, &message); + } + else + { + char formattedLogMessage[WLOG_MAX_STRING_SIZE] = { 0 }; + + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL + if (vsnprintf(formattedLogMessage, WLOG_MAX_STRING_SIZE - 1, message.FormatString, + args) < 0) + return FALSE; + WINPR_PRAGMA_DIAG_POP + + message.TextString = formattedLogMessage; + status = WLog_Write(log, &message); + } + + break; + + case WLOG_MESSAGE_DATA: + message.Data = va_arg(args, void*); + message.Length = va_arg(args, size_t); + status = WLog_WriteData(log, &message); + break; + + case WLOG_MESSAGE_IMAGE: + message.ImageData = va_arg(args, void*); + message.ImageWidth = va_arg(args, size_t); + message.ImageHeight = va_arg(args, size_t); + message.ImageBpp = va_arg(args, size_t); + status = WLog_WriteImage(log, &message); + break; + + case WLOG_MESSAGE_PACKET: + message.PacketData = va_arg(args, void*); + message.PacketLength = va_arg(args, size_t); + message.PacketFlags = va_arg(args, unsigned); + status = WLog_WritePacket(log, &message); + break; + + default: + break; + } + + return status; +} + +BOOL WLog_PrintMessage(wLog* log, DWORD type, DWORD level, size_t line, const char* file, + const char* function, ...) +{ + BOOL status = 0; + va_list args; + va_start(args, function); + status = WLog_PrintMessageVA(log, type, level, line, file, function, args); + va_end(args); + return status; +} + +DWORD WLog_GetLogLevel(wLog* log) +{ + if (!log) + return WLOG_OFF; + + if (log->FilterLevel <= WLOG_FILTER_NOT_INITIALIZED) + log->FilterLevel = WLog_GetFilterLogLevel(log); + + if (log->FilterLevel > WLOG_FILTER_NOT_FILTERED) + return (DWORD)log->FilterLevel; + else if (log->Level == WLOG_LEVEL_INHERIT) + log->Level = WLog_GetLogLevel(log->Parent); + + return log->Level; +} + +BOOL WLog_IsLevelActive(wLog* _log, DWORD _log_level) +{ + DWORD level = 0; + + if (!_log) + return FALSE; + + level = WLog_GetLogLevel(_log); + + if (level == WLOG_OFF) + return FALSE; + + return _log_level >= level; +} + +BOOL WLog_SetStringLogLevel(wLog* log, LPCSTR level) +{ + int lvl = 0; + + if (!log || !level) + return FALSE; + + lvl = WLog_ParseLogLevel(level); + + if (lvl < 0) + return FALSE; + + return WLog_SetLogLevel(log, (DWORD)lvl); +} + +static BOOL WLog_reset_log_filters(wLog* log) +{ + if (!log) + return FALSE; + + log->FilterLevel = WLOG_FILTER_NOT_INITIALIZED; + + for (DWORD x = 0; x < log->ChildrenCount; x++) + { + wLog* child = log->Children[x]; + + if (!WLog_reset_log_filters(child)) + return FALSE; + } + + return TRUE; +} + +static BOOL WLog_AddStringLogFilters_int(wLog* root, LPCSTR filter) +{ + LPSTR p = NULL; + LPCSTR filterStr = NULL; + + if (!filter) + return FALSE; + + DWORD count = 1; + LPCSTR cpp = filter; + + while ((cpp = strchr(cpp, ',')) != NULL) + { + count++; + cpp++; + } + + DWORD pos = g_FilterCount; + DWORD size = g_FilterCount + count; + wLogFilter* tmp = (wLogFilter*)realloc(g_Filters, size * sizeof(wLogFilter)); + + if (!tmp) + return FALSE; + + g_Filters = tmp; + LPSTR cp = (LPSTR)_strdup(filter); + + if (!cp) + return FALSE; + + p = cp; + filterStr = cp; + + do + { + p = strchr(p, ','); + + if (p) + *p = '\0'; + + if (pos < size) + { + if (!WLog_ParseFilter(root, &g_Filters[pos++], filterStr)) + { + free(cp); + return FALSE; + } + } + else + break; + + if (p) + { + filterStr = p + 1; + p++; + } + } while (p != NULL); + + g_FilterCount = size; + free(cp); + return WLog_reset_log_filters(root); +} + +BOOL WLog_AddStringLogFilters(LPCSTR filter) +{ + /* Ensure logger is initialized */ + wLog* root = WLog_GetRoot(); + return WLog_AddStringLogFilters_int(root, filter); +} + +static BOOL WLog_UpdateInheritLevel(wLog* log, DWORD logLevel) +{ + if (!log) + return FALSE; + + if (log->inherit) + { + log->Level = logLevel; + + for (DWORD x = 0; x < log->ChildrenCount; x++) + { + wLog* child = log->Children[x]; + + if (!WLog_UpdateInheritLevel(child, logLevel)) + return FALSE; + } + } + + return TRUE; +} + +BOOL WLog_SetLogLevel(wLog* log, DWORD logLevel) +{ + if (!log) + return FALSE; + + if ((logLevel > WLOG_OFF) && (logLevel != WLOG_LEVEL_INHERIT)) + logLevel = WLOG_OFF; + + log->Level = logLevel; + log->inherit = (logLevel == WLOG_LEVEL_INHERIT) ? TRUE : FALSE; + + for (DWORD x = 0; x < log->ChildrenCount; x++) + { + wLog* child = log->Children[x]; + + if (!WLog_UpdateInheritLevel(child, logLevel)) + return FALSE; + } + + return WLog_reset_log_filters(log); +} + +int WLog_ParseLogLevel(LPCSTR level) +{ + int iLevel = -1; + + if (!level) + return -1; + + if (_stricmp(level, "TRACE") == 0) + iLevel = WLOG_TRACE; + else if (_stricmp(level, "DEBUG") == 0) + iLevel = WLOG_DEBUG; + else if (_stricmp(level, "INFO") == 0) + iLevel = WLOG_INFO; + else if (_stricmp(level, "WARN") == 0) + iLevel = WLOG_WARN; + else if (_stricmp(level, "ERROR") == 0) + iLevel = WLOG_ERROR; + else if (_stricmp(level, "FATAL") == 0) + iLevel = WLOG_FATAL; + else if (_stricmp(level, "OFF") == 0) + iLevel = WLOG_OFF; + + return iLevel; +} + +BOOL WLog_ParseFilter(wLog* root, wLogFilter* filter, LPCSTR name) +{ + const char* pc = NULL; + char* p = NULL; + char* q = NULL; + size_t count = 0; + LPSTR names = NULL; + int iLevel = 0; + count = 1; + + WINPR_UNUSED(root); + + if (!name) + return FALSE; + + pc = name; + + if (pc) + { + while ((pc = strchr(pc, '.')) != NULL) + { + count++; + pc++; + } + } + + names = _strdup(name); + + if (!names) + return FALSE; + + filter->NameCount = count; + filter->Names = (LPSTR*)calloc((count + 1UL), sizeof(LPSTR)); + + if (!filter->Names) + { + free(names); + filter->NameCount = 0; + return FALSE; + } + + filter->Names[count] = NULL; + count = 0; + p = (char*)names; + filter->Names[count++] = p; + q = strrchr(p, ':'); + + if (!q) + { + free(names); + free((void*)filter->Names); + filter->Names = NULL; + filter->NameCount = 0; + return FALSE; + } + + *q = '\0'; + q++; + iLevel = WLog_ParseLogLevel(q); + + if (iLevel < 0) + { + free(names); + free((void*)filter->Names); + filter->Names = NULL; + filter->NameCount = 0; + return FALSE; + } + + filter->Level = (DWORD)iLevel; + + while ((p = strchr(p, '.')) != NULL) + { + if (count < filter->NameCount) + filter->Names[count++] = p + 1; + + *p = '\0'; + p++; + } + + return TRUE; +} + +BOOL WLog_ParseFilters(wLog* root) +{ + LPCSTR filter = "WLOG_FILTER"; + BOOL res = FALSE; + char* env = NULL; + DWORD nSize = 0; + free(g_Filters); + g_Filters = NULL; + g_FilterCount = 0; + nSize = GetEnvironmentVariableA(filter, NULL, 0); + + if (nSize < 1) + return TRUE; + + env = (LPSTR)malloc(nSize); + + if (!env) + return FALSE; + + if (GetEnvironmentVariableA(filter, env, nSize) == nSize - 1) + res = WLog_AddStringLogFilters_int(root, env); + + free(env); + return res; +} + +LONG WLog_GetFilterLogLevel(wLog* log) +{ + BOOL match = FALSE; + + if (log->FilterLevel >= 0) + return log->FilterLevel; + + log->FilterLevel = WLOG_FILTER_NOT_FILTERED; + for (DWORD i = 0; i < g_FilterCount; i++) + { + const wLogFilter* filter = &g_Filters[i]; + for (DWORD j = 0; j < filter->NameCount; j++) + { + if (j >= log->NameCount) + break; + + if (_stricmp(filter->Names[j], "*") == 0) + { + match = TRUE; + assert(filter->Level <= INT32_MAX); + log->FilterLevel = (LONG)filter->Level; + break; + } + + if (_stricmp(filter->Names[j], log->Names[j]) != 0) + break; + + if (j == (log->NameCount - 1)) + { + match = log->NameCount == filter->NameCount; + if (match) + { + assert(filter->Level <= INT32_MAX); + log->FilterLevel = (LONG)filter->Level; + } + break; + } + } + + if (match) + break; + } + + return log->FilterLevel; +} + +static BOOL WLog_ParseName(wLog* log, LPCSTR name) +{ + const char* cp = name; + char* p = NULL; + size_t count = 1; + LPSTR names = NULL; + + while ((cp = strchr(cp, '.')) != NULL) + { + count++; + cp++; + } + + names = _strdup(name); + + if (!names) + return FALSE; + + log->NameCount = count; + log->Names = (LPSTR*)calloc((count + 1UL), sizeof(LPSTR)); + + if (!log->Names) + { + free(names); + return FALSE; + } + + log->Names[count] = NULL; + count = 0; + p = (char*)names; + log->Names[count++] = p; + + while ((p = strchr(p, '.')) != NULL) + { + if (count < log->NameCount) + log->Names[count++] = p + 1; + + *p = '\0'; + p++; + } + + return TRUE; +} + +wLog* WLog_New(LPCSTR name, wLog* rootLogger) +{ + wLog* log = NULL; + char* env = NULL; + DWORD nSize = 0; + int iLevel = 0; + log = (wLog*)calloc(1, sizeof(wLog)); + + if (!log) + return NULL; + + log->Name = _strdup(name); + + if (!log->Name) + goto out_fail; + + if (!WLog_ParseName(log, name)) + goto out_fail; + + log->Parent = rootLogger; + log->ChildrenCount = 0; + log->ChildrenSize = 16; + log->FilterLevel = WLOG_FILTER_NOT_INITIALIZED; + + if (!(log->Children = (wLog**)calloc(log->ChildrenSize, sizeof(wLog*)))) + goto out_fail; + + log->Appender = NULL; + + if (rootLogger) + { + log->Level = WLOG_LEVEL_INHERIT; + log->inherit = TRUE; + } + else + { + LPCSTR level = "WLOG_LEVEL"; + log->Level = WLOG_INFO; + nSize = GetEnvironmentVariableA(level, NULL, 0); + + if (nSize) + { + env = (LPSTR)malloc(nSize); + + if (!env) + goto out_fail; + + if (GetEnvironmentVariableA(level, env, nSize) != nSize - 1) + { + (void)fprintf(stderr, "%s environment variable changed in my back !\n", level); + free(env); + goto out_fail; + } + + iLevel = WLog_ParseLogLevel(env); + free(env); + + if (iLevel >= 0) + { + if (!WLog_SetLogLevel(log, (DWORD)iLevel)) + goto out_fail; + } + } + } + + iLevel = WLog_GetFilterLogLevel(log); + + if (iLevel >= 0) + { + if (!WLog_SetLogLevel(log, (DWORD)iLevel)) + goto out_fail; + } + + InitializeCriticalSectionAndSpinCount(&log->lock, 4000); + + return log; +out_fail: + WLog_Free(log); + return NULL; +} + +void WLog_Free(wLog* log) +{ + if (log) + { + if (log->Appender) + { + WLog_Appender_Free(log, log->Appender); + log->Appender = NULL; + } + + free(log->Name); + + /* The first element in this array is allocated, the rest are indices into this variable */ + if (log->Names) + free(log->Names[0]); + free((void*)log->Names); + free((void*)log->Children); + DeleteCriticalSection(&log->lock); + free(log); + } +} + +wLog* WLog_GetRoot(void) +{ + if (!InitOnceExecuteOnce(&g_WLogInitialized, WLog_InitializeRoot, NULL, NULL)) + return NULL; + + return g_RootLog; +} + +static BOOL WLog_AddChild(wLog* parent, wLog* child) +{ + BOOL status = FALSE; + + WLog_Lock(parent); + + if (parent->ChildrenCount >= parent->ChildrenSize) + { + wLog** tmp = NULL; + parent->ChildrenSize *= 2; + + if (!parent->ChildrenSize) + { + free((void*)parent->Children); + parent->Children = NULL; + } + else + { + tmp = (wLog**)realloc((void*)parent->Children, sizeof(wLog*) * parent->ChildrenSize); + + if (!tmp) + { + free((void*)parent->Children); + parent->Children = NULL; + goto exit; + } + + parent->Children = tmp; + } + } + + if (!parent->Children) + goto exit; + + parent->Children[parent->ChildrenCount++] = child; + child->Parent = parent; + + WLog_Unlock(parent); + + status = TRUE; +exit: + return status; +} + +static wLog* WLog_FindChild(wLog* root, LPCSTR name) +{ + wLog* child = NULL; + BOOL found = FALSE; + + if (!root) + return NULL; + + WLog_Lock(root); + + for (DWORD index = 0; index < root->ChildrenCount; index++) + { + child = root->Children[index]; + + if (strcmp(child->Name, name) == 0) + { + found = TRUE; + break; + } + } + + WLog_Unlock(root); + + return (found) ? child : NULL; +} + +static wLog* WLog_Get_int(wLog* root, LPCSTR name) +{ + wLog* log = NULL; + + if (!(log = WLog_FindChild(root, name))) + { + if (!root) + return NULL; + + if (!(log = WLog_New(name, root))) + return NULL; + + if (!WLog_AddChild(root, log)) + { + WLog_Free(log); + return NULL; + } + } + + return log; +} + +wLog* WLog_Get(LPCSTR name) +{ + wLog* root = WLog_GetRoot(); + return WLog_Get_int(root, name); +} + +#if defined(WITH_WINPR_DEPRECATED) +BOOL WLog_Init(void) +{ + return WLog_GetRoot() != NULL; +} + +BOOL WLog_Uninit(void) +{ + wLog* root = g_RootLog; + + if (!root) + return FALSE; + + WLog_Lock(root); + + for (DWORD index = 0; index < root->ChildrenCount; index++) + { + wLog* child = root->Children[index]; + WLog_Free(child); + } + + WLog_Unlock(root); + + WLog_Free(root); + g_RootLog = NULL; + + return TRUE; +} +#endif + +BOOL WLog_SetContext(wLog* log, const char* (*fkt)(void*), void* context) +{ + WINPR_ASSERT(log); + + log->custom = fkt; + log->context = context; + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.h new file mode 100644 index 0000000000000000000000000000000000000000..2d4a41eb9a6028fe9f3025caea1ef9b270a84ff8 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/utils/wlog/wlog.h @@ -0,0 +1,92 @@ +/** + * WinPR: Windows Portable Runtime + * WinPR Logger + * + * Copyright 2013 Marc-Andre Moreau + * + * 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_WLOG_PRIVATE_H +#define WINPR_WLOG_PRIVATE_H + +#include + +#define WLOG_MAX_PREFIX_SIZE 512 +#define WLOG_MAX_STRING_SIZE 8192 + +typedef BOOL (*WLOG_APPENDER_OPEN_FN)(wLog* log, wLogAppender* appender); +typedef BOOL (*WLOG_APPENDER_CLOSE_FN)(wLog* log, wLogAppender* appender); +typedef BOOL (*WLOG_APPENDER_WRITE_MESSAGE_FN)(wLog* log, wLogAppender* appender, + wLogMessage* message); +typedef BOOL (*WLOG_APPENDER_WRITE_DATA_MESSAGE_FN)(wLog* log, wLogAppender* appender, + wLogMessage* message); +typedef BOOL (*WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN)(wLog* log, wLogAppender* appender, + wLogMessage* message); +typedef BOOL (*WLOG_APPENDER_WRITE_PACKET_MESSAGE_FN)(wLog* log, wLogAppender* appender, + wLogMessage* message); +typedef BOOL (*WLOG_APPENDER_SET)(wLogAppender* appender, const char* setting, void* value); +typedef void (*WLOG_APPENDER_FREE)(wLogAppender* appender); + +#define WLOG_APPENDER_COMMON() \ + DWORD Type; \ + BOOL active; \ + wLogLayout* Layout; \ + CRITICAL_SECTION lock; \ + BOOL recursive; \ + void* TextMessageContext; \ + void* DataMessageContext; \ + void* ImageMessageContext; \ + void* PacketMessageContext; \ + WLOG_APPENDER_OPEN_FN Open; \ + WLOG_APPENDER_CLOSE_FN Close; \ + WLOG_APPENDER_WRITE_MESSAGE_FN WriteMessage; \ + WLOG_APPENDER_WRITE_DATA_MESSAGE_FN WriteDataMessage; \ + WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN WriteImageMessage; \ + WLOG_APPENDER_WRITE_PACKET_MESSAGE_FN WritePacketMessage; \ + WLOG_APPENDER_FREE Free; \ + WLOG_APPENDER_SET Set + +struct s_wLogAppender +{ + WLOG_APPENDER_COMMON(); +}; + +struct s_wLog +{ + LPSTR Name; + LONG FilterLevel; + DWORD Level; + + BOOL IsRoot; + BOOL inherit; + LPSTR* Names; + size_t NameCount; + wLogAppender* Appender; + + wLog* Parent; + wLog** Children; + DWORD ChildrenCount; + DWORD ChildrenSize; + CRITICAL_SECTION lock; + const char* (*custom)(void*); + void* context; +}; + +extern const char* WLOG_LEVELS[7]; +BOOL WLog_Layout_GetMessagePrefix(wLog* log, wLogLayout* layout, wLogMessage* message); + +#include "Layout.h" +#include "Appender.h" + +#endif /* WINPR_WLOG_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8cc0c5e2a40c30a70d89a0ece720dc5f23cf0a33 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/CMakeLists.txt @@ -0,0 +1,22 @@ +# WinPR: Windows Portable Runtime +# libwinpr-winsock cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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(winsock.c) + +if(WIN32) + winpr_library_add_public(ws2_32) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..1aaeb3cea5c91373bdc00dec2c9092009f749a70 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/ModuleOptions.cmake @@ -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 "winsock") +set(MINWIN_LONG_NAME "Windows Sockets (Winsock)") +set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/winsock.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/winsock.c new file mode 100644 index 0000000000000000000000000000000000000000..fc29cee3dedf20d9ef03fa4113d5126bf08cdd9f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/winsock/winsock.c @@ -0,0 +1,1296 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Sockets (Winsock) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include + +#include + +#ifdef WINPR_HAVE_UNISTD_H +#include +#endif +#ifdef WINPR_HAVE_SYS_FILIO_H +#include +#endif +#ifdef WINPR_HAVE_SYS_SOCKIO_H +#include +#endif + +#ifndef _WIN32 +#include +#endif + +#ifdef __APPLE__ +#define WSAIOCTL_IFADDRS +#include +#endif + +/** + * ws2_32.dll: + * + * __WSAFDIsSet + * accept + * bind + * closesocket + * connect + * freeaddrinfo + * FreeAddrInfoEx + * FreeAddrInfoExW + * FreeAddrInfoW + * getaddrinfo + * GetAddrInfoExA + * GetAddrInfoExCancel + * GetAddrInfoExOverlappedResult + * GetAddrInfoExW + * GetAddrInfoW + * gethostbyaddr + * gethostbyname + * gethostname + * GetHostNameW + * getnameinfo + * GetNameInfoW + * getpeername + * getprotobyname + * getprotobynumber + * getservbyname + * getservbyport + * getsockname + * getsockopt + * htonl + * htons + * inet_addr + * inet_ntoa + * inet_ntop + * inet_pton + * InetNtopW + * InetPtonW + * ioctlsocket + * listen + * ntohl + * ntohs + * recv + * recvfrom + * select + * send + * sendto + * SetAddrInfoExA + * SetAddrInfoExW + * setsockopt + * shutdown + * socket + * WahCloseApcHelper + * WahCloseHandleHelper + * WahCloseNotificationHandleHelper + * WahCloseSocketHandle + * WahCloseThread + * WahCompleteRequest + * WahCreateHandleContextTable + * WahCreateNotificationHandle + * WahCreateSocketHandle + * WahDestroyHandleContextTable + * WahDisableNonIFSHandleSupport + * WahEnableNonIFSHandleSupport + * WahEnumerateHandleContexts + * WahInsertHandleContext + * WahNotifyAllProcesses + * WahOpenApcHelper + * WahOpenCurrentThread + * WahOpenHandleHelper + * WahOpenNotificationHandleHelper + * WahQueueUserApc + * WahReferenceContextByHandle + * WahRemoveHandleContext + * WahWaitForNotification + * WahWriteLSPEvent + * WEP + * WPUCompleteOverlappedRequest + * WPUGetProviderPathEx + * WSAAccept + * WSAAddressToStringA + * WSAAddressToStringW + * WSAAdvertiseProvider + * WSAAsyncGetHostByAddr + * WSAAsyncGetHostByName + * WSAAsyncGetProtoByName + * WSAAsyncGetProtoByNumber + * WSAAsyncGetServByName + * WSAAsyncGetServByPort + * WSAAsyncSelect + * WSACancelAsyncRequest + * WSACancelBlockingCall + * WSACleanup + * WSACloseEvent + * WSAConnect + * WSAConnectByList + * WSAConnectByNameA + * WSAConnectByNameW + * WSACreateEvent + * WSADuplicateSocketA + * WSADuplicateSocketW + * WSAEnumNameSpaceProvidersA + * WSAEnumNameSpaceProvidersExA + * WSAEnumNameSpaceProvidersExW + * WSAEnumNameSpaceProvidersW + * WSAEnumNetworkEvents + * WSAEnumProtocolsA + * WSAEnumProtocolsW + * WSAEventSelect + * WSAGetLastError + * WSAGetOverlappedResult + * WSAGetQOSByName + * WSAGetServiceClassInfoA + * WSAGetServiceClassInfoW + * WSAGetServiceClassNameByClassIdA + * WSAGetServiceClassNameByClassIdW + * WSAHtonl + * WSAHtons + * WSAInstallServiceClassA + * WSAInstallServiceClassW + * WSAIoctl + * WSAIsBlocking + * WSAJoinLeaf + * WSALookupServiceBeginA + * WSALookupServiceBeginW + * WSALookupServiceEnd + * WSALookupServiceNextA + * WSALookupServiceNextW + * WSANSPIoctl + * WSANtohl + * WSANtohs + * WSAPoll + * WSAProviderCompleteAsyncCall + * WSAProviderConfigChange + * WSApSetPostRoutine + * WSARecv + * WSARecvDisconnect + * WSARecvFrom + * WSARemoveServiceClass + * WSAResetEvent + * WSASend + * WSASendDisconnect + * WSASendMsg + * WSASendTo + * WSASetBlockingHook + * WSASetEvent + * WSASetLastError + * WSASetServiceA + * WSASetServiceW + * WSASocketA + * WSASocketW + * WSAStartup + * WSAStringToAddressA + * WSAStringToAddressW + * WSAUnadvertiseProvider + * WSAUnhookBlockingHook + * WSAWaitForMultipleEvents + * WSCDeinstallProvider + * WSCDeinstallProviderEx + * WSCEnableNSProvider + * WSCEnumProtocols + * WSCEnumProtocolsEx + * WSCGetApplicationCategory + * WSCGetApplicationCategoryEx + * WSCGetProviderInfo + * WSCGetProviderPath + * WSCInstallNameSpace + * WSCInstallNameSpaceEx + * WSCInstallNameSpaceEx2 + * WSCInstallProvider + * WSCInstallProviderAndChains + * WSCInstallProviderEx + * WSCSetApplicationCategory + * WSCSetApplicationCategoryEx + * WSCSetProviderInfo + * WSCUnInstallNameSpace + * WSCUnInstallNameSpaceEx2 + * WSCUpdateProvider + * WSCUpdateProviderEx + * WSCWriteNameSpaceOrder + * WSCWriteProviderOrder + * WSCWriteProviderOrderEx + */ + +#ifdef _WIN32 + +#if (_WIN32_WINNT < 0x0600) + +PCSTR winpr_inet_ntop(INT Family, PVOID pAddr, PSTR pStringBuf, size_t StringBufSize) +{ + if (Family == AF_INET) + { + struct sockaddr_in in = { 0 }; + + in.sin_family = AF_INET; + memcpy(&in.sin_addr, pAddr, sizeof(struct in_addr)); + getnameinfo((struct sockaddr*)&in, sizeof(struct sockaddr_in), pStringBuf, StringBufSize, + NULL, 0, NI_NUMERICHOST); + return pStringBuf; + } + else if (Family == AF_INET6) + { + struct sockaddr_in6 in = { 0 }; + + in.sin6_family = AF_INET6; + memcpy(&in.sin6_addr, pAddr, sizeof(struct in_addr6)); + getnameinfo((struct sockaddr*)&in, sizeof(struct sockaddr_in6), pStringBuf, StringBufSize, + NULL, 0, NI_NUMERICHOST); + return pStringBuf; + } + + return NULL; +} + +INT winpr_inet_pton(INT Family, PCSTR pszAddrString, PVOID pAddrBuf) +{ + SOCKADDR_STORAGE addr; + int addr_len = sizeof(addr); + + if ((Family != AF_INET) && (Family != AF_INET6)) + return -1; + + if (WSAStringToAddressA((char*)pszAddrString, Family, NULL, (struct sockaddr*)&addr, + &addr_len) != 0) + return 0; + + if (Family == AF_INET) + { + memcpy(pAddrBuf, &((struct sockaddr_in*)&addr)->sin_addr, sizeof(struct in_addr)); + } + else if (Family == AF_INET6) + { + memcpy(pAddrBuf, &((struct sockaddr_in6*)&addr)->sin6_addr, sizeof(struct in6_addr)); + } + + return 1; +} + +#endif /* (_WIN32_WINNT < 0x0600) */ + +#else /* _WIN32 */ + +#include +#include +#include +#include +#include +#include +#include + +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif + +int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData) +{ + WINPR_ASSERT(lpWSAData); + + ZeroMemory(lpWSAData, sizeof(WSADATA)); + lpWSAData->wVersion = wVersionRequired; + lpWSAData->wHighVersion = MAKEWORD(2, 2); + return 0; /* success */ +} + +int WSACleanup(void) +{ + return 0; /* success */ +} + +void WSASetLastError(int iError) +{ + switch (iError) + { + /* Base error codes */ + case WSAEINTR: + errno = EINTR; + break; + + case WSAEBADF: + errno = EBADF; + break; + + case WSAEACCES: + errno = EACCES; + break; + + case WSAEFAULT: + errno = EFAULT; + break; + + case WSAEINVAL: + errno = EINVAL; + break; + + case WSAEMFILE: + errno = EMFILE; + break; + + /* BSD sockets error codes */ + + case WSAEWOULDBLOCK: + errno = EWOULDBLOCK; + break; + + case WSAEINPROGRESS: + errno = EINPROGRESS; + break; + + case WSAEALREADY: + errno = EALREADY; + break; + + case WSAENOTSOCK: + errno = ENOTSOCK; + break; + + case WSAEDESTADDRREQ: + errno = EDESTADDRREQ; + break; + + case WSAEMSGSIZE: + errno = EMSGSIZE; + break; + + case WSAEPROTOTYPE: + errno = EPROTOTYPE; + break; + + case WSAENOPROTOOPT: + errno = ENOPROTOOPT; + break; + + case WSAEPROTONOSUPPORT: + errno = EPROTONOSUPPORT; + break; + + case WSAESOCKTNOSUPPORT: + errno = ESOCKTNOSUPPORT; + break; + + case WSAEOPNOTSUPP: + errno = EOPNOTSUPP; + break; + + case WSAEPFNOSUPPORT: + errno = EPFNOSUPPORT; + break; + + case WSAEAFNOSUPPORT: + errno = EAFNOSUPPORT; + break; + + case WSAEADDRINUSE: + errno = EADDRINUSE; + break; + + case WSAEADDRNOTAVAIL: + errno = EADDRNOTAVAIL; + break; + + case WSAENETDOWN: + errno = ENETDOWN; + break; + + case WSAENETUNREACH: + errno = ENETUNREACH; + break; + + case WSAENETRESET: + errno = ENETRESET; + break; + + case WSAECONNABORTED: + errno = ECONNABORTED; + break; + + case WSAECONNRESET: + errno = ECONNRESET; + break; + + case WSAENOBUFS: + errno = ENOBUFS; + break; + + case WSAEISCONN: + errno = EISCONN; + break; + + case WSAENOTCONN: + errno = ENOTCONN; + break; + + case WSAESHUTDOWN: + errno = ESHUTDOWN; + break; + + case WSAETOOMANYREFS: + errno = ETOOMANYREFS; + break; + + case WSAETIMEDOUT: + errno = ETIMEDOUT; + break; + + case WSAECONNREFUSED: + errno = ECONNREFUSED; + break; + + case WSAELOOP: + errno = ELOOP; + break; + + case WSAENAMETOOLONG: + errno = ENAMETOOLONG; + break; + + case WSAEHOSTDOWN: + errno = EHOSTDOWN; + break; + + case WSAEHOSTUNREACH: + errno = EHOSTUNREACH; + break; + + case WSAENOTEMPTY: + errno = ENOTEMPTY; + break; +#ifdef EPROCLIM + + case WSAEPROCLIM: + errno = EPROCLIM; + break; +#endif + + case WSAEUSERS: + errno = EUSERS; + break; + + case WSAEDQUOT: + errno = EDQUOT; + break; + + case WSAESTALE: + errno = ESTALE; + break; + + case WSAEREMOTE: + errno = EREMOTE; + break; + default: + break; + } +} + +int WSAGetLastError(void) +{ + int iError = 0; + + switch (errno) + { + /* Base error codes */ + case EINTR: + iError = WSAEINTR; + break; + + case EBADF: + iError = WSAEBADF; + break; + + case EACCES: + iError = WSAEACCES; + break; + + case EFAULT: + iError = WSAEFAULT; + break; + + case EINVAL: + iError = WSAEINVAL; + break; + + case EMFILE: + iError = WSAEMFILE; + break; + + /* BSD sockets error codes */ + + case EWOULDBLOCK: + iError = WSAEWOULDBLOCK; + break; + + case EINPROGRESS: + iError = WSAEINPROGRESS; + break; + + case EALREADY: + iError = WSAEALREADY; + break; + + case ENOTSOCK: + iError = WSAENOTSOCK; + break; + + case EDESTADDRREQ: + iError = WSAEDESTADDRREQ; + break; + + case EMSGSIZE: + iError = WSAEMSGSIZE; + break; + + case EPROTOTYPE: + iError = WSAEPROTOTYPE; + break; + + case ENOPROTOOPT: + iError = WSAENOPROTOOPT; + break; + + case EPROTONOSUPPORT: + iError = WSAEPROTONOSUPPORT; + break; + + case ESOCKTNOSUPPORT: + iError = WSAESOCKTNOSUPPORT; + break; + + case EOPNOTSUPP: + iError = WSAEOPNOTSUPP; + break; + + case EPFNOSUPPORT: + iError = WSAEPFNOSUPPORT; + break; + + case EAFNOSUPPORT: + iError = WSAEAFNOSUPPORT; + break; + + case EADDRINUSE: + iError = WSAEADDRINUSE; + break; + + case EADDRNOTAVAIL: + iError = WSAEADDRNOTAVAIL; + break; + + case ENETDOWN: + iError = WSAENETDOWN; + break; + + case ENETUNREACH: + iError = WSAENETUNREACH; + break; + + case ENETRESET: + iError = WSAENETRESET; + break; + + case ECONNABORTED: + iError = WSAECONNABORTED; + break; + + case ECONNRESET: + iError = WSAECONNRESET; + break; + + case ENOBUFS: + iError = WSAENOBUFS; + break; + + case EISCONN: + iError = WSAEISCONN; + break; + + case ENOTCONN: + iError = WSAENOTCONN; + break; + + case ESHUTDOWN: + iError = WSAESHUTDOWN; + break; + + case ETOOMANYREFS: + iError = WSAETOOMANYREFS; + break; + + case ETIMEDOUT: + iError = WSAETIMEDOUT; + break; + + case ECONNREFUSED: + iError = WSAECONNREFUSED; + break; + + case ELOOP: + iError = WSAELOOP; + break; + + case ENAMETOOLONG: + iError = WSAENAMETOOLONG; + break; + + case EHOSTDOWN: + iError = WSAEHOSTDOWN; + break; + + case EHOSTUNREACH: + iError = WSAEHOSTUNREACH; + break; + + case ENOTEMPTY: + iError = WSAENOTEMPTY; + break; +#ifdef EPROCLIM + + case EPROCLIM: + iError = WSAEPROCLIM; + break; +#endif + + case EUSERS: + iError = WSAEUSERS; + break; + + case EDQUOT: + iError = WSAEDQUOT; + break; + + case ESTALE: + iError = WSAESTALE; + break; + + case EREMOTE: + iError = WSAEREMOTE; + break; + /* Special cases */ +#if (EAGAIN != EWOULDBLOCK) + + case EAGAIN: + iError = WSAEWOULDBLOCK; + break; +#endif +#if defined(EPROTO) + + case EPROTO: + iError = WSAECONNRESET; + break; +#endif + default: + break; + } + + /** + * Windows Sockets Extended Error Codes: + * + * WSASYSNOTREADY + * WSAVERNOTSUPPORTED + * WSANOTINITIALISED + * WSAEDISCON + * WSAENOMORE + * WSAECANCELLED + * WSAEINVALIDPROCTABLE + * WSAEINVALIDPROVIDER + * WSAEPROVIDERFAILEDINIT + * WSASYSCALLFAILURE + * WSASERVICE_NOT_FOUND + * WSATYPE_NOT_FOUND + * WSA_E_NO_MORE + * WSA_E_CANCELLED + * WSAEREFUSED + */ + return iError; +} + +HANDLE WSACreateEvent(void) +{ + return CreateEvent(NULL, TRUE, FALSE, NULL); +} + +BOOL WSASetEvent(HANDLE hEvent) +{ + return SetEvent(hEvent); +} + +BOOL WSAResetEvent(HANDLE hEvent) +{ + /* POSIX systems auto reset the socket, + * if no more data is available. */ + return TRUE; +} + +BOOL WSACloseEvent(HANDLE hEvent) +{ + BOOL status = CloseHandle(hEvent); + + if (!status) + SetLastError(6); + + return status; +} + +int WSAEventSelect(SOCKET s, WSAEVENT hEventObject, LONG lNetworkEvents) +{ + u_long arg = 1; + ULONG mode = 0; + + if (_ioctlsocket(s, FIONBIO, &arg) != 0) + return SOCKET_ERROR; + + if (arg == 0) + return 0; + + if (lNetworkEvents & FD_READ) + mode |= WINPR_FD_READ; + + if (lNetworkEvents & FD_WRITE) + mode |= WINPR_FD_WRITE; + + if (SetEventFileDescriptor(hEventObject, (int)s, mode) < 0) + return SOCKET_ERROR; + + return 0; +} + +DWORD WSAWaitForMultipleEvents(DWORD cEvents, const HANDLE* lphEvents, BOOL fWaitAll, + DWORD dwTimeout, BOOL fAlertable) +{ + return WaitForMultipleObjectsEx(cEvents, lphEvents, fWaitAll, dwTimeout, fAlertable); +} + +SOCKET WSASocketA(int af, int type, int protocol, LPWSAPROTOCOL_INFOA lpProtocolInfo, GROUP g, + DWORD dwFlags) +{ + SOCKET s = 0; + s = _socket(af, type, protocol); + return s; +} + +SOCKET WSASocketW(int af, int type, int protocol, LPWSAPROTOCOL_INFOW lpProtocolInfo, GROUP g, + DWORD dwFlags) +{ + return WSASocketA(af, type, protocol, (LPWSAPROTOCOL_INFOA)lpProtocolInfo, g, dwFlags); +} + +int WSAIoctl(SOCKET s, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, + LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned, + LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) +{ + int fd = 0; + int index = 0; + ULONG nFlags = 0; + size_t offset = 0; + size_t ifreq_len = 0; + struct ifreq* ifreq = NULL; + struct ifconf ifconf = { 0 }; + char address[128] = { 0 }; + char broadcast[128] = { 0 }; + char netmask[128] = { 0 }; + char buffer[4096] = { 0 }; + size_t numInterfaces = 0; + size_t maxNumInterfaces = 0; + INTERFACE_INFO* pInterface = NULL; + INTERFACE_INFO* pInterfaces = NULL; + struct sockaddr_in* pAddress = NULL; + struct sockaddr_in* pBroadcast = NULL; + struct sockaddr_in* pNetmask = NULL; + + if ((dwIoControlCode != SIO_GET_INTERFACE_LIST) || + (!lpvOutBuffer || !cbOutBuffer || !lpcbBytesReturned)) + { + WSASetLastError(WSAEINVAL); + return SOCKET_ERROR; + } + + fd = (int)s; + pInterfaces = (INTERFACE_INFO*)lpvOutBuffer; + maxNumInterfaces = cbOutBuffer / sizeof(INTERFACE_INFO); +#ifdef WSAIOCTL_IFADDRS + { + struct ifaddrs* ifap = NULL; + + if (getifaddrs(&ifap) != 0) + { + WSASetLastError(WSAENETDOWN); + return SOCKET_ERROR; + } + + index = 0; + numInterfaces = 0; + + for (struct ifaddrs* ifa = ifap; ifa; ifa = ifa->ifa_next) + { + pInterface = &pInterfaces[index]; + pAddress = (struct sockaddr_in*)&pInterface->iiAddress; + pBroadcast = (struct sockaddr_in*)&pInterface->iiBroadcastAddress; + pNetmask = (struct sockaddr_in*)&pInterface->iiNetmask; + nFlags = 0; + + if (ifa->ifa_flags & IFF_UP) + nFlags |= _IFF_UP; + + if (ifa->ifa_flags & IFF_BROADCAST) + nFlags |= _IFF_BROADCAST; + + if (ifa->ifa_flags & IFF_LOOPBACK) + nFlags |= _IFF_LOOPBACK; + + if (ifa->ifa_flags & IFF_POINTOPOINT) + nFlags |= _IFF_POINTTOPOINT; + + if (ifa->ifa_flags & IFF_MULTICAST) + nFlags |= _IFF_MULTICAST; + + pInterface->iiFlags = nFlags; + + if (ifa->ifa_addr) + { + if ((ifa->ifa_addr->sa_family != AF_INET) && (ifa->ifa_addr->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr), address, sizeof(address), 0, 0, + NI_NUMERICHOST); + inet_pton(ifa->ifa_addr->sa_family, address, (void*)&pAddress->sin_addr); + } + else + { + ZeroMemory(pAddress, sizeof(struct sockaddr_in)); + } + + if (ifa->ifa_dstaddr) + { + if ((ifa->ifa_dstaddr->sa_family != AF_INET) && + (ifa->ifa_dstaddr->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_dstaddr, sizeof(struct sockaddr), broadcast, sizeof(broadcast), + 0, 0, NI_NUMERICHOST); + inet_pton(ifa->ifa_dstaddr->sa_family, broadcast, (void*)&pBroadcast->sin_addr); + } + else + { + ZeroMemory(pBroadcast, sizeof(struct sockaddr_in)); + } + + if (ifa->ifa_netmask) + { + if ((ifa->ifa_netmask->sa_family != AF_INET) && + (ifa->ifa_netmask->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_netmask, sizeof(struct sockaddr), netmask, sizeof(netmask), 0, + 0, NI_NUMERICHOST); + inet_pton(ifa->ifa_netmask->sa_family, netmask, (void*)&pNetmask->sin_addr); + } + else + { + ZeroMemory(pNetmask, sizeof(struct sockaddr_in)); + } + + numInterfaces++; + index++; + } + + *lpcbBytesReturned = (DWORD)(numInterfaces * sizeof(INTERFACE_INFO)); + freeifaddrs(ifap); + return 0; + } +#endif + ifconf.ifc_len = sizeof(buffer); + ifconf.ifc_buf = buffer; + + if (ioctl(fd, SIOCGIFCONF, &ifconf) != 0) + { + WSASetLastError(WSAENETDOWN); + return SOCKET_ERROR; + } + + index = 0; + offset = 0; + numInterfaces = 0; + ifreq = ifconf.ifc_req; + + while ((ifconf.ifc_len >= 0) && (offset < (size_t)ifconf.ifc_len) && + (numInterfaces < maxNumInterfaces)) + { + pInterface = &pInterfaces[index]; + pAddress = (struct sockaddr_in*)&pInterface->iiAddress; + pBroadcast = (struct sockaddr_in*)&pInterface->iiBroadcastAddress; + pNetmask = (struct sockaddr_in*)&pInterface->iiNetmask; + + if (ioctl(fd, SIOCGIFFLAGS, ifreq) != 0) + goto next_ifreq; + + nFlags = 0; + + if (ifreq->ifr_flags & IFF_UP) + nFlags |= _IFF_UP; + + if (ifreq->ifr_flags & IFF_BROADCAST) + nFlags |= _IFF_BROADCAST; + + if (ifreq->ifr_flags & IFF_LOOPBACK) + nFlags |= _IFF_LOOPBACK; + + if (ifreq->ifr_flags & IFF_POINTOPOINT) + nFlags |= _IFF_POINTTOPOINT; + + if (ifreq->ifr_flags & IFF_MULTICAST) + nFlags |= _IFF_MULTICAST; + + pInterface->iiFlags = nFlags; + + if (ioctl(fd, SIOCGIFADDR, ifreq) != 0) + goto next_ifreq; + + if ((ifreq->ifr_addr.sa_family != AF_INET) && (ifreq->ifr_addr.sa_family != AF_INET6)) + goto next_ifreq; + + getnameinfo(&ifreq->ifr_addr, sizeof(ifreq->ifr_addr), address, sizeof(address), 0, 0, + NI_NUMERICHOST); + inet_pton(ifreq->ifr_addr.sa_family, address, (void*)&pAddress->sin_addr); + + if (ioctl(fd, SIOCGIFBRDADDR, ifreq) != 0) + goto next_ifreq; + + if ((ifreq->ifr_addr.sa_family != AF_INET) && (ifreq->ifr_addr.sa_family != AF_INET6)) + goto next_ifreq; + + getnameinfo(&ifreq->ifr_addr, sizeof(ifreq->ifr_addr), broadcast, sizeof(broadcast), 0, 0, + NI_NUMERICHOST); + inet_pton(ifreq->ifr_addr.sa_family, broadcast, (void*)&pBroadcast->sin_addr); + + if (ioctl(fd, SIOCGIFNETMASK, ifreq) != 0) + goto next_ifreq; + + if ((ifreq->ifr_addr.sa_family != AF_INET) && (ifreq->ifr_addr.sa_family != AF_INET6)) + goto next_ifreq; + + getnameinfo(&ifreq->ifr_addr, sizeof(ifreq->ifr_addr), netmask, sizeof(netmask), 0, 0, + NI_NUMERICHOST); + inet_pton(ifreq->ifr_addr.sa_family, netmask, (void*)&pNetmask->sin_addr); + numInterfaces++; + next_ifreq: +#if !defined(__linux__) && !defined(__sun__) && !defined(__CYGWIN__) && !defined(EMSCRIPTEN) + ifreq_len = IFNAMSIZ + ifreq->ifr_addr.sa_len; +#else + ifreq_len = sizeof(*ifreq); +#endif + ifreq = (struct ifreq*)&((BYTE*)ifreq)[ifreq_len]; + offset += ifreq_len; + index++; + } + + *lpcbBytesReturned = (DWORD)(numInterfaces * sizeof(INTERFACE_INFO)); + return 0; +} + +SOCKET _accept(SOCKET s, struct sockaddr* addr, int* addrlen) +{ + int fd = WINPR_ASSERTING_INT_CAST(int, s); + socklen_t s_addrlen = (socklen_t)*addrlen; + const int status = accept(fd, addr, &s_addrlen); + *addrlen = (int)s_addrlen; + return (SOCKET)status; +} + +int _bind(SOCKET s, const struct sockaddr* addr, int namelen) +{ + int status = 0; + int fd = (int)s; + status = bind(fd, addr, (socklen_t)namelen); + + if (status < 0) + return SOCKET_ERROR; + + return status; +} + +int closesocket(SOCKET s) +{ + int status = 0; + int fd = (int)s; + status = close(fd); + return status; +} + +int _connect(SOCKET s, const struct sockaddr* name, int namelen) +{ + int status = 0; + int fd = (int)s; + status = connect(fd, name, (socklen_t)namelen); + + if (status < 0) + return SOCKET_ERROR; + + return status; +} + +// NOLINTNEXTLINE(readability-non-const-parameter) +int _ioctlsocket(SOCKET s, long cmd, u_long* argp) +{ + int fd = (int)s; + + if (cmd == FIONBIO) + { + int flags = 0; + + if (!argp) + return SOCKET_ERROR; + + flags = fcntl(fd, F_GETFL); + + if (flags == -1) + return SOCKET_ERROR; + + if (*argp) + (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK); + else + (void)fcntl(fd, F_SETFL, flags & ~(O_NONBLOCK)); + } + + return 0; +} + +int _getpeername(SOCKET s, struct sockaddr* name, int* namelen) +{ + int status = 0; + int fd = (int)s; + socklen_t s_namelen = (socklen_t)*namelen; + status = getpeername(fd, name, &s_namelen); + *namelen = (int)s_namelen; + return status; +} + +int _getsockname(SOCKET s, struct sockaddr* name, int* namelen) +{ + int status = 0; + int fd = (int)s; + socklen_t s_namelen = (socklen_t)*namelen; + status = getsockname(fd, name, &s_namelen); + *namelen = (int)s_namelen; + return status; +} + +int _getsockopt(SOCKET s, int level, int optname, char* optval, int* optlen) +{ + int status = 0; + int fd = (int)s; + socklen_t s_optlen = (socklen_t)*optlen; + status = getsockopt(fd, level, optname, (void*)optval, &s_optlen); + *optlen = (int)s_optlen; + return status; +} + +u_long _htonl(u_long hostlong) +{ + WINPR_ASSERT(hostlong <= UINT32_MAX); + return htonl((UINT32)hostlong); +} + +u_short _htons(u_short hostshort) +{ + return htons(hostshort); +} + +unsigned long _inet_addr(const char* cp) +{ + return WINPR_ASSERTING_INT_CAST(unsigned long, inet_addr(cp)); +} + +char* _inet_ntoa(struct in_addr in) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + return inet_ntoa(in); +} + +int _listen(SOCKET s, int backlog) +{ + int status = 0; + int fd = (int)s; + status = listen(fd, backlog); + return status; +} + +u_long _ntohl(u_long netlong) +{ + WINPR_ASSERT((netlong & 0xFFFFFFFF00000000ULL) == 0); + return ntohl((UINT32)netlong); +} + +u_short _ntohs(u_short netshort) +{ + return ntohs(netshort); +} + +int _recv(SOCKET s, char* buf, int len, int flags) +{ + int status = 0; + int fd = (int)s; + status = (int)recv(fd, (void*)buf, (size_t)len, flags); + return status; +} + +int _recvfrom(SOCKET s, char* buf, int len, int flags, struct sockaddr* from, int* fromlen) +{ + int status = 0; + int fd = (int)s; + socklen_t s_fromlen = (socklen_t)*fromlen; + status = (int)recvfrom(fd, (void*)buf, (size_t)len, flags, from, &s_fromlen); + *fromlen = (int)s_fromlen; + return status; +} + +int _select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, + const struct timeval* timeout) +{ + int status = 0; + union + { + const struct timeval* cpv; + struct timeval* pv; + } cnv; + cnv.cpv = timeout; + do + { + status = select(nfds, readfds, writefds, exceptfds, cnv.pv); + } while ((status < 0) && (errno == EINTR)); + + return status; +} + +int _send(SOCKET s, const char* buf, int len, int flags) +{ + int status = 0; + int fd = (int)s; + flags |= MSG_NOSIGNAL; + status = (int)send(fd, (const void*)buf, (size_t)len, flags); + return status; +} + +int _sendto(SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to, int tolen) +{ + int status = 0; + int fd = (int)s; + status = (int)sendto(fd, (const void*)buf, (size_t)len, flags, to, (socklen_t)tolen); + return status; +} + +int _setsockopt(SOCKET s, int level, int optname, const char* optval, int optlen) +{ + int status = 0; + int fd = (int)s; + status = setsockopt(fd, level, optname, (const void*)optval, (socklen_t)optlen); + return status; +} + +int _shutdown(SOCKET s, int how) +{ + int status = 0; + int fd = (int)s; + int s_how = -1; + + switch (how) + { + case SD_RECEIVE: + s_how = SHUT_RD; + break; + + case SD_SEND: + s_how = SHUT_WR; + break; + + case SD_BOTH: + s_how = SHUT_RDWR; + break; + default: + break; + } + + if (s_how < 0) + return SOCKET_ERROR; + + status = shutdown(fd, s_how); + return status; +} + +SOCKET _socket(int af, int type, int protocol) +{ + int fd = 0; + SOCKET s = 0; + fd = socket(af, type, protocol); + + if (fd < 0) + return INVALID_SOCKET; + + s = (SOCKET)fd; + return s; +} + +struct hostent* _gethostbyaddr(const char* addr, int len, int type) +{ + struct hostent* host = NULL; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + host = gethostbyaddr((const void*)addr, (socklen_t)len, type); + return host; +} + +struct hostent* _gethostbyname(const char* name) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + struct hostent* host = gethostbyname(name); + return host; +} + +int _gethostname(char* name, int namelen) +{ + int status = 0; + status = gethostname(name, (size_t)namelen); + return status; +} + +struct servent* /* codespell:ignore servent */ _getservbyport(int port, const char* proto) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + return getservbyport(port, proto); +} + +struct servent* /* codespell:ignore servent */ +_getservbyname(const char* name, const char* proto) // codespell:ignore servent + +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + return getservbyname(name, proto); +} + +struct protoent* _getprotobynumber(int number) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + return getprotobynumber(number); +} + +struct protoent* _getprotobyname(const char* name) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + return getprotobyname(name); +} + +#endif /* _WIN32 */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3669221b1a2dc5862247f435c95d6ecb54b6e9a2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/CMakeLists.txt @@ -0,0 +1,30 @@ +# WinPR: Windows Portable Runtime +# libwinpr-wtsapi cmake build script +# +# Copyright 2013 Marc-Andre Moreau +# +# 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(wtsapi.c) + +if(WIN32) + winpr_module_add(wtsapi_win32.c wtsapi_win32.h) + + if(MINGW) + winpr_library_add_private(ntdll.lib) # Only required with MINGW + endif() +endif() + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/ModuleOptions.cmake b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..7f1dcad6473a95168f6250392fa021799d8ce24d --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/ModuleOptions.cmake @@ -0,0 +1,9 @@ +set(MINWIN_LAYER "0") +set(MINWIN_GROUP "none") +set(MINWIN_MAJOR_VERSION "0") +set(MINWIN_MINOR_VERSION "0") +set(MINWIN_SHORT_NAME "wtsapi") +set(MINWIN_LONG_NAME "Windows Terminal Services API") +set(MODULE_LIBRARY_NAME + "api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}" +) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc50f3c15c6b7b64e2d10bec17b835db6cc676b3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/CMakeLists.txt @@ -0,0 +1,60 @@ +set(MODULE_NAME "TestWtsApi") +set(MODULE_PREFIX "TEST_WTSAPI") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(UNIX_ONLY TestWtsApiShutdownSystem.c TestWtsApiWaitSystemEvent.c) + +set(${MODULE_PREFIX}_TESTS TestWtsApiEnumerateProcesses.c TestWtsApiEnumerateSessions.c + TestWtsApiQuerySessionInformation.c TestWtsApiSessionNotification.c +) + +if(NOT WIN32) + set(${MODULE_PREFIX}_TESTS ${${MODULE_PREFIX}_TESTS} ${UNIX_ONLY}) +endif() + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") + +if(TESTS_WTSAPI_EXTRA) + + set(MODULE_NAME "TestWtsApiExtra") + set(MODULE_PREFIX "TEST_WTSAPI_EXTRA") + + set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + + set(${MODULE_PREFIX}_TESTS + TestWtsApiExtraDisconnectSession.c TestWtsApiExtraDynamicVirtualChannel.c TestWtsApiExtraLogoffSession.c + TestWtsApiExtraSendMessage.c TestWtsApiExtraVirtualChannel.c TestWtsApiExtraStartRemoteSessionEx.c + ) + + create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + + add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + + target_link_libraries(${MODULE_NAME} winpr) + + set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + + foreach(test ${${MODULE_PREFIX}_TESTS}) + get_filename_component(TestName ${test} NAME_WE) + add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName}) + set_tests_properties(${TestName} PROPERTIES LABELS "WTSAPI_EXTRA") + endforeach() + + set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test") +endif() diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateProcesses.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateProcesses.c new file mode 100644 index 0000000000000000000000000000000000000000..4e0702f978c596db70e45b90c82e8d3f17d0ca32 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateProcesses.c @@ -0,0 +1,49 @@ + +#include +#include +#include +#include + +int TestWtsApiEnumerateProcesses(int argc, char* argv[]) +{ + DWORD count = 0; + BOOL bSuccess = 0; + HANDLE hServer = NULL; + PWTS_PROCESS_INFOA pProcessInfo = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#endif + + hServer = WTS_CURRENT_SERVER_HANDLE; + + count = 0; + pProcessInfo = NULL; + + bSuccess = WTSEnumerateProcessesA(hServer, 0, 1, &pProcessInfo, &count); + + if (!bSuccess) + { + printf("WTSEnumerateProcesses failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + +#if 0 + { + printf("WTSEnumerateProcesses enumerated %"PRIu32" process:\n", count); + for (DWORD i = 0; i < count; i++) + printf("\t[%"PRIu32"]: %s (%"PRIu32")\n", i, pProcessInfo[i].pProcessName, pProcessInfo[i].ProcessId); + } +#endif + + WTSFreeMemory(pProcessInfo); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateSessions.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateSessions.c new file mode 100644 index 0000000000000000000000000000000000000000..afe48a9df16fc52fee11ad1a247751fdcd9ae4b4 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiEnumerateSessions.c @@ -0,0 +1,50 @@ + +#include +#include +#include +#include + +int TestWtsApiEnumerateSessions(int argc, char* argv[]) +{ + DWORD count = 0; + BOOL bSuccess = 0; + HANDLE hServer = NULL; + PWTS_SESSION_INFOA pSessionInfo = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#endif + + hServer = WTS_CURRENT_SERVER_HANDLE; + + count = 0; + pSessionInfo = NULL; + + bSuccess = WTSEnumerateSessionsA(hServer, 0, 1, &pSessionInfo, &count); + + if (!bSuccess) + { + printf("WTSEnumerateSessions failed: %" PRIu32 "\n", GetLastError()); + return 0; + } + + printf("WTSEnumerateSessions count: %" PRIu32 "\n", count); + + for (DWORD index = 0; index < count; index++) + { + printf("[%" PRIu32 "] SessionId: %" PRIu32 " WinstationName: '%s' State: %s (%u)\n", index, + pSessionInfo[index].SessionId, pSessionInfo[index].pWinStationName, + WTSSessionStateToString(pSessionInfo[index].State), pSessionInfo[index].State); + } + + WTSFreeMemory(pSessionInfo); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDisconnectSession.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDisconnectSession.c new file mode 100644 index 0000000000000000000000000000000000000000..5aa1e3c49c89aee734e3137080f6a099840a5d32 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDisconnectSession.c @@ -0,0 +1,21 @@ + +#include +#include +#include + +int TestWtsApiExtraDisconnectSession(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + HANDLE hServer = WTS_CURRENT_SERVER_HANDLE; + BOOL bSuccess = WTSDisconnectSession(hServer, WTS_CURRENT_SESSION, FALSE); + + if (!bSuccess) + { + printf("WTSDisconnectSession failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDynamicVirtualChannel.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDynamicVirtualChannel.c new file mode 100644 index 0000000000000000000000000000000000000000..1c431392f96e7b5a9b97a9f4ca8ad97f86deeb3a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraDynamicVirtualChannel.c @@ -0,0 +1,49 @@ + +#include +#include +#include + +int TestWtsApiExtraDynamicVirtualChannel(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + HANDLE hVirtualChannel = + WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, "ECHO", WTS_CHANNEL_OPTION_DYNAMIC); + + if (hVirtualChannel == INVALID_HANDLE_VALUE) + { + printf("WTSVirtualChannelOpen failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelOpen opend"); + ULONG bytesWritten = 0; + char buffer[1024] = { 0 }; + size_t length = sizeof(buffer); + BOOL bSuccess = WTSVirtualChannelWrite(hVirtualChannel, buffer, length, &bytesWritten); + + if (!bSuccess) + { + printf("WTSVirtualChannelWrite failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelWrite written"); + + ULONG bytesRead = 0; + bSuccess = WTSVirtualChannelRead(hVirtualChannel, 5000, (PCHAR)buffer, length, &bytesRead); + + if (!bSuccess) + { + printf("WTSVirtualChannelRead failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelRead read"); + + if (!WTSVirtualChannelClose(hVirtualChannel)) + { + printf("WTSVirtualChannelClose failed\n"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraLogoffSession.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraLogoffSession.c new file mode 100644 index 0000000000000000000000000000000000000000..41dcf3615ef56d5113ebeeedbd7f852d5b884d3b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraLogoffSession.c @@ -0,0 +1,22 @@ + +#include +#include +#include + +int TestWtsApiExtraLogoffSession(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + HANDLE hServer = WTS_CURRENT_SERVER_HANDLE; + BOOL bSuccess = WTSLogoffSession(hServer, WTS_CURRENT_SESSION, FALSE); + + if (!bSuccess) + { + printf("WTSLogoffSession failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraSendMessage.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraSendMessage.c new file mode 100644 index 0000000000000000000000000000000000000000..5c43bd9a88cc3c4395e5af72199a629d790d5897 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraSendMessage.c @@ -0,0 +1,29 @@ + +#include +#include +#include +#include + +#define TITLE "thats the title" +#define MESSAGE "thats the message" + +int TestWtsApiExtraSendMessage(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + HANDLE hServer = WTS_CURRENT_SERVER_HANDLE; + DWORD result = 0; + BOOL bSuccess = WTSSendMessageA(hServer, WTS_CURRENT_SESSION, TITLE, strlen(TITLE) + 1, MESSAGE, + strlen(MESSAGE) + 1, MB_CANCELTRYCONTINUE, 3, &result, TRUE); + + if (!bSuccess) + { + printf("WTSSendMessage failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + printf("WTSSendMessage got result: %" PRIu32 "\n", result); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraStartRemoteSessionEx.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraStartRemoteSessionEx.c new file mode 100644 index 0000000000000000000000000000000000000000..0f379ca12c3db9b98fef2c979075b4db5209bb99 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraStartRemoteSessionEx.c @@ -0,0 +1,33 @@ + +#include +#include +#include +#include +#include + +int TestWtsApiExtraStartRemoteSessionEx(int argc, char* argv[]) +{ + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + ULONG logonId = 0; + char logonIdStr[10] = { 0 }; + + DWORD bSuccess = GetEnvironmentVariableA("TEST_SESSION_LOGON_ID", logonIdStr, 10); + if (bSuccess > 0) + { + sscanf(logonIdStr, "%u\n", &logonId); + } + + bSuccess = WTSStartRemoteControlSessionEx( + NULL, logonId, VK_F10, REMOTECONTROL_KBDSHIFT_HOTKEY | REMOTECONTROL_KBDCTRL_HOTKEY, + REMOTECONTROL_FLAG_DISABLE_INPUT); + + if (!bSuccess) + { + printf("WTSStartRemoteControlSessionEx failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraVirtualChannel.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraVirtualChannel.c new file mode 100644 index 0000000000000000000000000000000000000000..f1adcfa2917fc72bc87e0435ebe49e09cae13b4b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiExtraVirtualChannel.c @@ -0,0 +1,51 @@ + +#include +#include +#include + +int TestWtsApiExtraVirtualChannel(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + char buffer[1024] = { 0 }; + const size_t length = sizeof(buffer); + + HANDLE hVirtualChannel = + WTSVirtualChannelOpen(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, "sample"); + + if (hVirtualChannel == INVALID_HANDLE_VALUE) + { + printf("WTSVirtualChannelOpen failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelOpen opend"); + ULONG bytesWritten = 0; + BOOL bSuccess = WTSVirtualChannelWrite(hVirtualChannel, buffer, length, &bytesWritten); + + if (!bSuccess) + { + printf("WTSVirtualChannelWrite failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelWrite written"); + + ULONG bytesRead = 0; + bSuccess = WTSVirtualChannelRead(hVirtualChannel, 5000, buffer, length, &bytesRead); + + if (!bSuccess) + { + printf("WTSVirtualChannelRead failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + printf("WTSVirtualChannelRead read"); + + if (!WTSVirtualChannelClose(hVirtualChannel)) + { + printf("WTSVirtualChannelClose failed\n"); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiQuerySessionInformation.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiQuerySessionInformation.c new file mode 100644 index 0000000000000000000000000000000000000000..bc232f0e82c0ac895634814a94291441f487523b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiQuerySessionInformation.c @@ -0,0 +1,225 @@ + +#include +#include +#include +#include + +int TestWtsApiQuerySessionInformation(int argc, char* argv[]) +{ + DWORD count = 0; + BOOL bSuccess = 0; + HANDLE hServer = NULL; + LPSTR pBuffer = NULL; + DWORD sessionId = 0; + DWORD bytesReturned = 0; + PWTS_SESSION_INFOA pSessionInfo = NULL; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#endif + + hServer = WTS_CURRENT_SERVER_HANDLE; + + count = 0; + pSessionInfo = NULL; + + bSuccess = WTSEnumerateSessionsA(hServer, 0, 1, &pSessionInfo, &count); + + if (!bSuccess) + { + printf("WTSEnumerateSessions failed: %" PRIu32 "\n", GetLastError()); + return 0; + } + + printf("WTSEnumerateSessions count: %" PRIu32 "\n", count); + + for (DWORD index = 0; index < count; index++) + { + char* Username = NULL; + char* Domain = NULL; + char* ClientName = NULL; + ULONG ClientBuildNumber = 0; + USHORT ClientProductId = 0; + ULONG ClientHardwareId = 0; + USHORT ClientProtocolType = 0; + PWTS_CLIENT_DISPLAY ClientDisplay = NULL; + PWTS_CLIENT_ADDRESS ClientAddress = NULL; + WTS_CONNECTSTATE_CLASS ConnectState = WTSInit; + + pBuffer = NULL; + bytesReturned = 0; + + sessionId = pSessionInfo[index].SessionId; + + printf("[%" PRIu32 "] SessionId: %" PRIu32 " State: %s (%u) WinstationName: '%s'\n", index, + pSessionInfo[index].SessionId, WTSSessionStateToString(pSessionInfo[index].State), + pSessionInfo[index].State, pSessionInfo[index].pWinStationName); + + /* WTSUserName */ + + bSuccess = + WTSQuerySessionInformationA(hServer, sessionId, WTSUserName, &pBuffer, &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSUserName failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + Username = (char*)pBuffer; + printf("\tWTSUserName: '%s'\n", Username); + + /* WTSDomainName */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSDomainName, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSDomainName failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + Domain = (char*)pBuffer; + printf("\tWTSDomainName: '%s'\n", Domain); + + /* WTSConnectState */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSConnectState, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSConnectState failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ConnectState = *((WTS_CONNECTSTATE_CLASS*)pBuffer); + printf("\tWTSConnectState: %u (%s)\n", ConnectState, WTSSessionStateToString(ConnectState)); + + /* WTSClientBuildNumber */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientBuildNumber, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientBuildNumber failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientBuildNumber = *((ULONG*)pBuffer); + printf("\tWTSClientBuildNumber: %" PRIu32 "\n", ClientBuildNumber); + + /* WTSClientName */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientName, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientName failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientName = (char*)pBuffer; + printf("\tWTSClientName: '%s'\n", ClientName); + + /* WTSClientProductId */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientProductId, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientProductId failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientProductId = *((USHORT*)pBuffer); + printf("\tWTSClientProductId: %" PRIu16 "\n", ClientProductId); + + /* WTSClientHardwareId */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientHardwareId, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientHardwareId failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientHardwareId = *((ULONG*)pBuffer); + printf("\tWTSClientHardwareId: %" PRIu32 "\n", ClientHardwareId); + + /* WTSClientAddress */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientAddress, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientAddress failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientAddress = (PWTS_CLIENT_ADDRESS)pBuffer; + printf("\tWTSClientAddress: AddressFamily: %" PRIu32 " Address: ", + ClientAddress->AddressFamily); + for (DWORD i = 0; i < sizeof(ClientAddress->Address); i++) + printf("%02" PRIX8 "", ClientAddress->Address[i]); + printf("\n"); + + /* WTSClientDisplay */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientDisplay, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientDisplay failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientDisplay = (PWTS_CLIENT_DISPLAY)pBuffer; + printf("\tWTSClientDisplay: HorizontalResolution: %" PRIu32 " VerticalResolution: %" PRIu32 + " ColorDepth: %" PRIu32 "\n", + ClientDisplay->HorizontalResolution, ClientDisplay->VerticalResolution, + ClientDisplay->ColorDepth); + + /* WTSClientProtocolType */ + + bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientProtocolType, &pBuffer, + &bytesReturned); + + if (!bSuccess) + { + printf("WTSQuerySessionInformation WTSClientProtocolType failed: %" PRIu32 "\n", + GetLastError()); + return -1; + } + + ClientProtocolType = *((USHORT*)pBuffer); + printf("\tWTSClientProtocolType: %" PRIu16 "\n", ClientProtocolType); + } + + WTSFreeMemory(pSessionInfo); + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiSessionNotification.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiSessionNotification.c new file mode 100644 index 0000000000000000000000000000000000000000..e83c27be348f40ad447409f3dbeff9ee2738d242 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiSessionNotification.c @@ -0,0 +1,62 @@ + +#include +#include +#include +#include + +int TestWtsApiSessionNotification(int argc, char* argv[]) +{ + HWND hWnd = NULL; + BOOL bSuccess = 0; + DWORD dwFlags = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#else + /* We create a message-only window and use the predefined class name "STATIC" for simplicity */ + hWnd = CreateWindowA("STATIC", "TestWtsApiSessionNotification", 0, 0, 0, 0, 0, HWND_MESSAGE, + NULL, NULL, NULL); + if (!hWnd) + { + printf("%s: error creating message-only window: %" PRIu32 "\n", __func__, GetLastError()); + return -1; + } +#endif + + dwFlags = NOTIFY_FOR_ALL_SESSIONS; + + bSuccess = WTSRegisterSessionNotification(hWnd, dwFlags); + + if (!bSuccess) + { + printf("%s: WTSRegisterSessionNotification failed: %" PRIu32 "\n", __func__, + GetLastError()); + return -1; + } + + bSuccess = WTSUnRegisterSessionNotification(hWnd); + +#ifdef _WIN32 + if (hWnd) + { + DestroyWindow(hWnd); + hWnd = NULL; + } +#endif + + if (!bSuccess) + { + printf("%s: WTSUnRegisterSessionNotification failed: %" PRIu32 "\n", __func__, + GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiShutdownSystem.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiShutdownSystem.c new file mode 100644 index 0000000000000000000000000000000000000000..431424b71e780d05eae375ba38bef2d3ba89570a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiShutdownSystem.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include + +int TestWtsApiShutdownSystem(int argc, char* argv[]) +{ + BOOL bSuccess = 0; + HANDLE hServer = NULL; + DWORD ShutdownFlag = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#endif + + hServer = WTS_CURRENT_SERVER_HANDLE; + ShutdownFlag = WTS_WSD_SHUTDOWN; + + bSuccess = WTSShutdownSystem(hServer, ShutdownFlag); + + if (!bSuccess) + { + printf("WTSShutdownSystem failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiWaitSystemEvent.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiWaitSystemEvent.c new file mode 100644 index 0000000000000000000000000000000000000000..389c0beb516814c134a4a1b7bfd600072599f4a3 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/test/TestWtsApiWaitSystemEvent.c @@ -0,0 +1,39 @@ + +#include +#include +#include +#include + +int TestWtsApiWaitSystemEvent(int argc, char* argv[]) +{ + BOOL bSuccess = 0; + HANDLE hServer = NULL; + DWORD eventMask = 0; + DWORD eventFlags = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + +#ifndef _WIN32 + if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0)) + { + printf("%s: No RDS environment detected, skipping test\n", __func__); + return 0; + } +#endif + + hServer = WTS_CURRENT_SERVER_HANDLE; + + eventMask = WTS_EVENT_ALL; + eventFlags = 0; + + bSuccess = WTSWaitSystemEvent(hServer, eventMask, &eventFlags); + + if (!bSuccess) + { + printf("WTSWaitSystemEvent failed: %" PRIu32 "\n", GetLastError()); + return -1; + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi.c new file mode 100644 index 0000000000000000000000000000000000000000..ec1459745eb3860eb32c11975673dc0ff2744066 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi.c @@ -0,0 +1,801 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Terminal Services API + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2015 Copyright 2015 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 + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +#include "wtsapi_win32.h" +#endif + +#include "../log.h" +#define TAG WINPR_TAG("wtsapi") + +/** + * Remote Desktop Services API Functions: + * http://msdn.microsoft.com/en-us/library/windows/desktop/aa383464/ + */ + +static HMODULE g_WtsApiModule = NULL; + +static const WtsApiFunctionTable* g_WtsApi = NULL; + +#if defined(_WIN32) +static HMODULE g_WtsApi32Module = NULL; +static WtsApiFunctionTable WtsApi32_WtsApiFunctionTable = { 0 }; + +#ifdef __MINGW32__ +#define WTSAPI32_LOAD_PROC(NAME, TYPE) \ + WtsApi32_WtsApiFunctionTable.p##NAME = GetProcAddressAs(g_WtsApi32Module, "WTS" #NAME, TYPE); +#else +#define WTSAPI32_LOAD_PROC(NAME, TYPE) \ + WtsApi32_WtsApiFunctionTable.p##NAME = GetProcAddressAs(g_WtsApi32Module, "WTS" #NAME, ##TYPE); +#endif + +static BOOL WtsApi32_InitializeWtsApi(void) +{ + g_WtsApi32Module = LoadLibraryA("wtsapi32.dll"); + + if (!g_WtsApi32Module) + return FALSE; + + WTSAPI32_LOAD_PROC(StopRemoteControlSession, WTS_STOP_REMOTE_CONTROL_SESSION_FN); + WTSAPI32_LOAD_PROC(StartRemoteControlSessionW, WTS_START_REMOTE_CONTROL_SESSION_FN_W); + WTSAPI32_LOAD_PROC(StartRemoteControlSessionA, WTS_START_REMOTE_CONTROL_SESSION_FN_A); + WTSAPI32_LOAD_PROC(ConnectSessionW, WTS_CONNECT_SESSION_FN_W); + WTSAPI32_LOAD_PROC(ConnectSessionA, WTS_CONNECT_SESSION_FN_A); + WTSAPI32_LOAD_PROC(EnumerateServersW, WTS_ENUMERATE_SERVERS_FN_W); + WTSAPI32_LOAD_PROC(EnumerateServersA, WTS_ENUMERATE_SERVERS_FN_A); + WTSAPI32_LOAD_PROC(OpenServerW, WTS_OPEN_SERVER_FN_W); + WTSAPI32_LOAD_PROC(OpenServerA, WTS_OPEN_SERVER_FN_A); + WTSAPI32_LOAD_PROC(OpenServerExW, WTS_OPEN_SERVER_EX_FN_W); + WTSAPI32_LOAD_PROC(OpenServerExA, WTS_OPEN_SERVER_EX_FN_A); + WTSAPI32_LOAD_PROC(CloseServer, WTS_CLOSE_SERVER_FN); + WTSAPI32_LOAD_PROC(EnumerateSessionsW, WTS_ENUMERATE_SESSIONS_FN_W); + WTSAPI32_LOAD_PROC(EnumerateSessionsA, WTS_ENUMERATE_SESSIONS_FN_A); + WTSAPI32_LOAD_PROC(EnumerateSessionsExW, WTS_ENUMERATE_SESSIONS_EX_FN_W); + WTSAPI32_LOAD_PROC(EnumerateSessionsExA, WTS_ENUMERATE_SESSIONS_EX_FN_A); + WTSAPI32_LOAD_PROC(EnumerateProcessesW, WTS_ENUMERATE_PROCESSES_FN_W); + WTSAPI32_LOAD_PROC(EnumerateProcessesA, WTS_ENUMERATE_PROCESSES_FN_A); + WTSAPI32_LOAD_PROC(TerminateProcess, WTS_TERMINATE_PROCESS_FN); + WTSAPI32_LOAD_PROC(QuerySessionInformationW, WTS_QUERY_SESSION_INFORMATION_FN_W); + WTSAPI32_LOAD_PROC(QuerySessionInformationA, WTS_QUERY_SESSION_INFORMATION_FN_A); + WTSAPI32_LOAD_PROC(QueryUserConfigW, WTS_QUERY_USER_CONFIG_FN_W); + WTSAPI32_LOAD_PROC(QueryUserConfigA, WTS_QUERY_USER_CONFIG_FN_A); + WTSAPI32_LOAD_PROC(SetUserConfigW, WTS_SET_USER_CONFIG_FN_W); + WTSAPI32_LOAD_PROC(SetUserConfigA, WTS_SET_USER_CONFIG_FN_A); + WTSAPI32_LOAD_PROC(SendMessageW, WTS_SEND_MESSAGE_FN_W); + WTSAPI32_LOAD_PROC(SendMessageA, WTS_SEND_MESSAGE_FN_A); + WTSAPI32_LOAD_PROC(DisconnectSession, WTS_DISCONNECT_SESSION_FN); + WTSAPI32_LOAD_PROC(LogoffSession, WTS_LOGOFF_SESSION_FN); + WTSAPI32_LOAD_PROC(ShutdownSystem, WTS_SHUTDOWN_SYSTEM_FN); + WTSAPI32_LOAD_PROC(WaitSystemEvent, WTS_WAIT_SYSTEM_EVENT_FN); + WTSAPI32_LOAD_PROC(VirtualChannelOpen, WTS_VIRTUAL_CHANNEL_OPEN_FN); + WTSAPI32_LOAD_PROC(VirtualChannelOpenEx, WTS_VIRTUAL_CHANNEL_OPEN_EX_FN); + WTSAPI32_LOAD_PROC(VirtualChannelClose, WTS_VIRTUAL_CHANNEL_CLOSE_FN); + WTSAPI32_LOAD_PROC(VirtualChannelRead, WTS_VIRTUAL_CHANNEL_READ_FN); + WTSAPI32_LOAD_PROC(VirtualChannelWrite, WTS_VIRTUAL_CHANNEL_WRITE_FN); + WTSAPI32_LOAD_PROC(VirtualChannelPurgeInput, WTS_VIRTUAL_CHANNEL_PURGE_INPUT_FN); + WTSAPI32_LOAD_PROC(VirtualChannelPurgeOutput, WTS_VIRTUAL_CHANNEL_PURGE_OUTPUT_FN); + WTSAPI32_LOAD_PROC(VirtualChannelQuery, WTS_VIRTUAL_CHANNEL_QUERY_FN); + WTSAPI32_LOAD_PROC(FreeMemory, WTS_FREE_MEMORY_FN); + WTSAPI32_LOAD_PROC(RegisterSessionNotification, WTS_REGISTER_SESSION_NOTIFICATION_FN); + WTSAPI32_LOAD_PROC(UnRegisterSessionNotification, WTS_UNREGISTER_SESSION_NOTIFICATION_FN); + WTSAPI32_LOAD_PROC(RegisterSessionNotificationEx, WTS_REGISTER_SESSION_NOTIFICATION_EX_FN); + WTSAPI32_LOAD_PROC(UnRegisterSessionNotificationEx, WTS_UNREGISTER_SESSION_NOTIFICATION_EX_FN); + WTSAPI32_LOAD_PROC(QueryUserToken, WTS_QUERY_USER_TOKEN_FN); + WTSAPI32_LOAD_PROC(FreeMemoryExW, WTS_FREE_MEMORY_EX_FN_W); + WTSAPI32_LOAD_PROC(FreeMemoryExA, WTS_FREE_MEMORY_EX_FN_A); + WTSAPI32_LOAD_PROC(EnumerateProcessesExW, WTS_ENUMERATE_PROCESSES_EX_FN_W); + WTSAPI32_LOAD_PROC(EnumerateProcessesExA, WTS_ENUMERATE_PROCESSES_EX_FN_A); + WTSAPI32_LOAD_PROC(EnumerateListenersW, WTS_ENUMERATE_LISTENERS_FN_W); + WTSAPI32_LOAD_PROC(EnumerateListenersA, WTS_ENUMERATE_LISTENERS_FN_A); + WTSAPI32_LOAD_PROC(QueryListenerConfigW, WTS_QUERY_LISTENER_CONFIG_FN_W); + WTSAPI32_LOAD_PROC(QueryListenerConfigA, WTS_QUERY_LISTENER_CONFIG_FN_A); + WTSAPI32_LOAD_PROC(CreateListenerW, WTS_CREATE_LISTENER_FN_W); + WTSAPI32_LOAD_PROC(CreateListenerA, WTS_CREATE_LISTENER_FN_A); + WTSAPI32_LOAD_PROC(SetListenerSecurityW, WTS_SET_LISTENER_SECURITY_FN_W); + WTSAPI32_LOAD_PROC(SetListenerSecurityA, WTS_SET_LISTENER_SECURITY_FN_A); + WTSAPI32_LOAD_PROC(GetListenerSecurityW, WTS_GET_LISTENER_SECURITY_FN_W); + WTSAPI32_LOAD_PROC(GetListenerSecurityA, WTS_GET_LISTENER_SECURITY_FN_A); + WTSAPI32_LOAD_PROC(EnableChildSessions, WTS_ENABLE_CHILD_SESSIONS_FN); + WTSAPI32_LOAD_PROC(IsChildSessionsEnabled, WTS_IS_CHILD_SESSIONS_ENABLED_FN); + WTSAPI32_LOAD_PROC(GetChildSessionId, WTS_GET_CHILD_SESSION_ID_FN); + WTSAPI32_LOAD_PROC(GetActiveConsoleSessionId, WTS_GET_ACTIVE_CONSOLE_SESSION_ID_FN); + + Win32_InitializeWinSta(&WtsApi32_WtsApiFunctionTable); + + g_WtsApi = &WtsApi32_WtsApiFunctionTable; + + return TRUE; +} +#endif + +/* WtsApi Functions */ + +static BOOL CALLBACK InitializeWtsApiStubs(PINIT_ONCE once, PVOID param, PVOID* context); +static INIT_ONCE wtsapiInitOnce = INIT_ONCE_STATIC_INIT; + +#define WTSAPI_STUB_CALL_VOID(_name, ...) \ + InitOnceExecuteOnce(&wtsapiInitOnce, InitializeWtsApiStubs, NULL, NULL); \ + if (!g_WtsApi || !g_WtsApi->p##_name) \ + return; \ + g_WtsApi->p##_name(__VA_ARGS__) + +#define WTSAPI_STUB_CALL_BOOL(_name, ...) \ + InitOnceExecuteOnce(&wtsapiInitOnce, InitializeWtsApiStubs, NULL, NULL); \ + if (!g_WtsApi || !g_WtsApi->p##_name) \ + return FALSE; \ + return g_WtsApi->p##_name(__VA_ARGS__) + +#define WTSAPI_STUB_CALL_HANDLE(_name, ...) \ + InitOnceExecuteOnce(&wtsapiInitOnce, InitializeWtsApiStubs, NULL, NULL); \ + if (!g_WtsApi || !g_WtsApi->p##_name) \ + return NULL; \ + return g_WtsApi->p##_name(__VA_ARGS__) + +BOOL WINAPI WTSStartRemoteControlSessionW(LPWSTR pTargetServerName, ULONG TargetLogonId, + BYTE HotkeyVk, USHORT HotkeyModifiers) +{ + WTSAPI_STUB_CALL_BOOL(StartRemoteControlSessionW, pTargetServerName, TargetLogonId, HotkeyVk, + HotkeyModifiers); +} + +BOOL WINAPI WTSStartRemoteControlSessionA(LPSTR pTargetServerName, ULONG TargetLogonId, + BYTE HotkeyVk, USHORT HotkeyModifiers) +{ + WTSAPI_STUB_CALL_BOOL(StartRemoteControlSessionA, pTargetServerName, TargetLogonId, HotkeyVk, + HotkeyModifiers); +} + +BOOL WINAPI WTSStartRemoteControlSessionExW(LPWSTR pTargetServerName, ULONG TargetLogonId, + BYTE HotkeyVk, USHORT HotkeyModifiers, DWORD flags) +{ + WTSAPI_STUB_CALL_BOOL(StartRemoteControlSessionExW, pTargetServerName, TargetLogonId, HotkeyVk, + HotkeyModifiers, flags); +} + +BOOL WINAPI WTSStartRemoteControlSessionExA(LPSTR pTargetServerName, ULONG TargetLogonId, + BYTE HotkeyVk, USHORT HotkeyModifiers, DWORD flags) +{ + WTSAPI_STUB_CALL_BOOL(StartRemoteControlSessionExA, pTargetServerName, TargetLogonId, HotkeyVk, + HotkeyModifiers, flags); +} + +BOOL WINAPI WTSStopRemoteControlSession(ULONG LogonId) +{ + WTSAPI_STUB_CALL_BOOL(StopRemoteControlSession, LogonId); +} + +BOOL WINAPI WTSConnectSessionW(ULONG LogonId, ULONG TargetLogonId, PWSTR pPassword, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(ConnectSessionW, LogonId, TargetLogonId, pPassword, bWait); +} + +BOOL WINAPI WTSConnectSessionA(ULONG LogonId, ULONG TargetLogonId, PSTR pPassword, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(ConnectSessionA, LogonId, TargetLogonId, pPassword, bWait); +} + +BOOL WINAPI WTSEnumerateServersW(LPWSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOW* ppServerInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateServersW, pDomainName, Reserved, Version, ppServerInfo, pCount); +} + +BOOL WINAPI WTSEnumerateServersA(LPSTR pDomainName, DWORD Reserved, DWORD Version, + PWTS_SERVER_INFOA* ppServerInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateServersA, pDomainName, Reserved, Version, ppServerInfo, pCount); +} + +HANDLE WINAPI WTSOpenServerW(LPWSTR pServerName) +{ + WTSAPI_STUB_CALL_HANDLE(OpenServerW, pServerName); +} + +HANDLE WINAPI WTSOpenServerA(LPSTR pServerName) +{ + WTSAPI_STUB_CALL_HANDLE(OpenServerA, pServerName); +} + +HANDLE WINAPI WTSOpenServerExW(LPWSTR pServerName) +{ + WTSAPI_STUB_CALL_HANDLE(OpenServerExW, pServerName); +} + +HANDLE WINAPI WTSOpenServerExA(LPSTR pServerName) +{ + WTSAPI_STUB_CALL_HANDLE(OpenServerExA, pServerName); +} + +VOID WINAPI WTSCloseServer(HANDLE hServer) +{ + WTSAPI_STUB_CALL_VOID(CloseServer, hServer); +} + +BOOL WINAPI WTSEnumerateSessionsW(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOW* ppSessionInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateSessionsW, hServer, Reserved, Version, ppSessionInfo, pCount); +} + +BOOL WINAPI WTSEnumerateSessionsA(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_SESSION_INFOA* ppSessionInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateSessionsA, hServer, Reserved, Version, ppSessionInfo, pCount); +} + +BOOL WINAPI WTSEnumerateSessionsExW(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1W* ppSessionInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateSessionsExW, hServer, pLevel, Filter, ppSessionInfo, pCount); +} + +BOOL WINAPI WTSEnumerateSessionsExA(HANDLE hServer, DWORD* pLevel, DWORD Filter, + PWTS_SESSION_INFO_1A* ppSessionInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateSessionsExA, hServer, pLevel, Filter, ppSessionInfo, pCount); +} + +BOOL WINAPI WTSEnumerateProcessesW(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOW* ppProcessInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateProcessesW, hServer, Reserved, Version, ppProcessInfo, pCount); +} + +BOOL WINAPI WTSEnumerateProcessesA(HANDLE hServer, DWORD Reserved, DWORD Version, + PWTS_PROCESS_INFOA* ppProcessInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateProcessesA, hServer, Reserved, Version, ppProcessInfo, pCount); +} + +BOOL WINAPI WTSTerminateProcess(HANDLE hServer, DWORD ProcessId, DWORD ExitCode) +{ + WTSAPI_STUB_CALL_BOOL(TerminateProcess, hServer, ProcessId, ExitCode); +} + +BOOL WINAPI WTSQuerySessionInformationW(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, LPWSTR* ppBuffer, + DWORD* pBytesReturned) +{ + WTSAPI_STUB_CALL_BOOL(QuerySessionInformationW, hServer, SessionId, WTSInfoClass, ppBuffer, + pBytesReturned); +} + +BOOL WINAPI WTSQuerySessionInformationA(HANDLE hServer, DWORD SessionId, + WTS_INFO_CLASS WTSInfoClass, LPSTR* ppBuffer, + DWORD* pBytesReturned) +{ + WTSAPI_STUB_CALL_BOOL(QuerySessionInformationA, hServer, SessionId, WTSInfoClass, ppBuffer, + pBytesReturned); +} + +BOOL WINAPI WTSQueryUserConfigW(LPWSTR pServerName, LPWSTR pUserName, + WTS_CONFIG_CLASS WTSConfigClass, LPWSTR* ppBuffer, + DWORD* pBytesReturned) +{ + WTSAPI_STUB_CALL_BOOL(QueryUserConfigW, pServerName, pUserName, WTSConfigClass, ppBuffer, + pBytesReturned); +} + +BOOL WINAPI WTSQueryUserConfigA(LPSTR pServerName, LPSTR pUserName, WTS_CONFIG_CLASS WTSConfigClass, + LPSTR* ppBuffer, DWORD* pBytesReturned) +{ + WTSAPI_STUB_CALL_BOOL(QueryUserConfigA, pServerName, pUserName, WTSConfigClass, ppBuffer, + pBytesReturned); +} + +BOOL WINAPI WTSSetUserConfigW(LPWSTR pServerName, LPWSTR pUserName, WTS_CONFIG_CLASS WTSConfigClass, + LPWSTR pBuffer, DWORD DataLength) +{ + WTSAPI_STUB_CALL_BOOL(SetUserConfigW, pServerName, pUserName, WTSConfigClass, pBuffer, + DataLength); +} + +BOOL WINAPI WTSSetUserConfigA(LPSTR pServerName, LPSTR pUserName, WTS_CONFIG_CLASS WTSConfigClass, + LPSTR pBuffer, DWORD DataLength) +{ + WTSAPI_STUB_CALL_BOOL(SetUserConfigA, pServerName, pUserName, WTSConfigClass, pBuffer, + DataLength); +} + +BOOL WINAPI WTSSendMessageW(HANDLE hServer, DWORD SessionId, LPWSTR pTitle, DWORD TitleLength, + LPWSTR pMessage, DWORD MessageLength, DWORD Style, DWORD Timeout, + DWORD* pResponse, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(SendMessageW, hServer, SessionId, pTitle, TitleLength, pMessage, + MessageLength, Style, Timeout, pResponse, bWait); +} + +BOOL WINAPI WTSSendMessageA(HANDLE hServer, DWORD SessionId, LPSTR pTitle, DWORD TitleLength, + LPSTR pMessage, DWORD MessageLength, DWORD Style, DWORD Timeout, + DWORD* pResponse, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(SendMessageA, hServer, SessionId, pTitle, TitleLength, pMessage, + MessageLength, Style, Timeout, pResponse, bWait); +} + +BOOL WINAPI WTSDisconnectSession(HANDLE hServer, DWORD SessionId, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(DisconnectSession, hServer, SessionId, bWait); +} + +BOOL WINAPI WTSLogoffSession(HANDLE hServer, DWORD SessionId, BOOL bWait) +{ + WTSAPI_STUB_CALL_BOOL(LogoffSession, hServer, SessionId, bWait); +} + +BOOL WINAPI WTSShutdownSystem(HANDLE hServer, DWORD ShutdownFlag) +{ + WTSAPI_STUB_CALL_BOOL(ShutdownSystem, hServer, ShutdownFlag); +} + +BOOL WINAPI WTSWaitSystemEvent(HANDLE hServer, DWORD EventMask, DWORD* pEventFlags) +{ + WTSAPI_STUB_CALL_BOOL(WaitSystemEvent, hServer, EventMask, pEventFlags); +} + +HANDLE WINAPI WTSVirtualChannelOpen(HANDLE hServer, DWORD SessionId, LPSTR pVirtualName) +{ + WTSAPI_STUB_CALL_HANDLE(VirtualChannelOpen, hServer, SessionId, pVirtualName); +} + +HANDLE WINAPI WTSVirtualChannelOpenEx(DWORD SessionId, LPSTR pVirtualName, DWORD flags) +{ + WTSAPI_STUB_CALL_HANDLE(VirtualChannelOpenEx, SessionId, pVirtualName, flags); +} + +BOOL WINAPI WTSVirtualChannelClose(HANDLE hChannelHandle) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelClose, hChannelHandle); +} + +BOOL WINAPI WTSVirtualChannelRead(HANDLE hChannelHandle, ULONG TimeOut, PCHAR Buffer, + ULONG BufferSize, PULONG pBytesRead) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelRead, hChannelHandle, TimeOut, Buffer, BufferSize, + pBytesRead); +} + +BOOL WINAPI WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, ULONG Length, + PULONG pBytesWritten) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelWrite, hChannelHandle, Buffer, Length, pBytesWritten); +} + +BOOL WINAPI WTSVirtualChannelPurgeInput(HANDLE hChannelHandle) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelPurgeInput, hChannelHandle); +} + +BOOL WINAPI WTSVirtualChannelPurgeOutput(HANDLE hChannelHandle) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelPurgeOutput, hChannelHandle); +} + +BOOL WINAPI WTSVirtualChannelQuery(HANDLE hChannelHandle, WTS_VIRTUAL_CLASS WtsVirtualClass, + PVOID* ppBuffer, DWORD* pBytesReturned) +{ + WTSAPI_STUB_CALL_BOOL(VirtualChannelQuery, hChannelHandle, WtsVirtualClass, ppBuffer, + pBytesReturned); +} + +VOID WINAPI WTSFreeMemory(PVOID pMemory) +{ + WTSAPI_STUB_CALL_VOID(FreeMemory, pMemory); +} + +BOOL WINAPI WTSFreeMemoryExW(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, ULONG NumberOfEntries) +{ + WTSAPI_STUB_CALL_BOOL(FreeMemoryExW, WTSTypeClass, pMemory, NumberOfEntries); +} + +BOOL WINAPI WTSFreeMemoryExA(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, ULONG NumberOfEntries) +{ + WTSAPI_STUB_CALL_BOOL(FreeMemoryExA, WTSTypeClass, pMemory, NumberOfEntries); +} + +BOOL WINAPI WTSRegisterSessionNotification(HWND hWnd, DWORD dwFlags) +{ + WTSAPI_STUB_CALL_BOOL(RegisterSessionNotification, hWnd, dwFlags); +} + +BOOL WINAPI WTSUnRegisterSessionNotification(HWND hWnd) +{ + WTSAPI_STUB_CALL_BOOL(UnRegisterSessionNotification, hWnd); +} + +BOOL WINAPI WTSRegisterSessionNotificationEx(HANDLE hServer, HWND hWnd, DWORD dwFlags) +{ + WTSAPI_STUB_CALL_BOOL(RegisterSessionNotificationEx, hServer, hWnd, dwFlags); +} + +BOOL WINAPI WTSUnRegisterSessionNotificationEx(HANDLE hServer, HWND hWnd) +{ + WTSAPI_STUB_CALL_BOOL(UnRegisterSessionNotificationEx, hServer, hWnd); +} + +BOOL WINAPI WTSQueryUserToken(ULONG SessionId, PHANDLE phToken) +{ + WTSAPI_STUB_CALL_BOOL(QueryUserToken, SessionId, phToken); +} + +BOOL WINAPI WTSEnumerateProcessesExW(HANDLE hServer, DWORD* pLevel, DWORD SessionId, + LPWSTR* ppProcessInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateProcessesExW, hServer, pLevel, SessionId, ppProcessInfo, pCount); +} + +BOOL WINAPI WTSEnumerateProcessesExA(HANDLE hServer, DWORD* pLevel, DWORD SessionId, + LPSTR* ppProcessInfo, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateProcessesExA, hServer, pLevel, SessionId, ppProcessInfo, pCount); +} + +BOOL WINAPI WTSEnumerateListenersW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEW pListeners, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateListenersW, hServer, pReserved, Reserved, pListeners, pCount); +} + +BOOL WINAPI WTSEnumerateListenersA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + PWTSLISTENERNAMEA pListeners, DWORD* pCount) +{ + WTSAPI_STUB_CALL_BOOL(EnumerateListenersA, hServer, pReserved, Reserved, pListeners, pCount); +} + +BOOL WINAPI WTSQueryListenerConfigW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, PWTSLISTENERCONFIGW pBuffer) +{ + WTSAPI_STUB_CALL_BOOL(QueryListenerConfigW, hServer, pReserved, Reserved, pListenerName, + pBuffer); +} + +BOOL WINAPI WTSQueryListenerConfigA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, PWTSLISTENERCONFIGA pBuffer) +{ + WTSAPI_STUB_CALL_BOOL(QueryListenerConfigA, hServer, pReserved, Reserved, pListenerName, + pBuffer); +} + +BOOL WINAPI WTSCreateListenerW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, PWTSLISTENERCONFIGW pBuffer, DWORD flag) +{ + WTSAPI_STUB_CALL_BOOL(CreateListenerW, hServer, pReserved, Reserved, pListenerName, pBuffer, + flag); +} + +BOOL WINAPI WTSCreateListenerA(HANDLE hServer, PVOID pReserved, DWORD Reserved, LPSTR pListenerName, + PWTSLISTENERCONFIGA pBuffer, DWORD flag) +{ + WTSAPI_STUB_CALL_BOOL(CreateListenerA, hServer, pReserved, Reserved, pListenerName, pBuffer, + flag); +} + +BOOL WINAPI WTSSetListenerSecurityW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor) +{ + WTSAPI_STUB_CALL_BOOL(SetListenerSecurityW, hServer, pReserved, Reserved, pListenerName, + SecurityInformation, pSecurityDescriptor); +} + +BOOL WINAPI WTSSetListenerSecurityA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor) +{ + WTSAPI_STUB_CALL_BOOL(SetListenerSecurityA, hServer, pReserved, Reserved, pListenerName, + SecurityInformation, pSecurityDescriptor); +} + +BOOL WINAPI WTSGetListenerSecurityW(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPWSTR pListenerName, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, + LPDWORD lpnLengthNeeded) +{ + WTSAPI_STUB_CALL_BOOL(GetListenerSecurityW, hServer, pReserved, Reserved, pListenerName, + SecurityInformation, pSecurityDescriptor, nLength, lpnLengthNeeded); +} + +BOOL WINAPI WTSGetListenerSecurityA(HANDLE hServer, PVOID pReserved, DWORD Reserved, + LPSTR pListenerName, SECURITY_INFORMATION SecurityInformation, + PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, + LPDWORD lpnLengthNeeded) +{ + WTSAPI_STUB_CALL_BOOL(GetListenerSecurityA, hServer, pReserved, Reserved, pListenerName, + SecurityInformation, pSecurityDescriptor, nLength, lpnLengthNeeded); +} + +BOOL CDECL WTSEnableChildSessions(BOOL bEnable) +{ + WTSAPI_STUB_CALL_BOOL(EnableChildSessions, bEnable); +} + +BOOL CDECL WTSIsChildSessionsEnabled(PBOOL pbEnabled) +{ + WTSAPI_STUB_CALL_BOOL(IsChildSessionsEnabled, pbEnabled); +} + +BOOL CDECL WTSGetChildSessionId(PULONG pSessionId) +{ + WTSAPI_STUB_CALL_BOOL(GetChildSessionId, pSessionId); +} + +BOOL CDECL WTSLogonUser(HANDLE hServer, LPCSTR username, LPCSTR password, LPCSTR domain) +{ + WTSAPI_STUB_CALL_BOOL(LogonUser, hServer, username, password, domain); +} + +BOOL CDECL WTSLogoffUser(HANDLE hServer) +{ + WTSAPI_STUB_CALL_BOOL(LogoffUser, hServer); +} + +#ifndef _WIN32 + +/** + * WTSGetActiveConsoleSessionId is declared in WinBase.h and exported by kernel32.dll + */ + +DWORD WINAPI WTSGetActiveConsoleSessionId(void) +{ + InitOnceExecuteOnce(&wtsapiInitOnce, InitializeWtsApiStubs, NULL, NULL); + + if (!g_WtsApi || !g_WtsApi->pGetActiveConsoleSessionId) + return 0xFFFFFFFF; + + return g_WtsApi->pGetActiveConsoleSessionId(); +} + +#endif + +const CHAR* WTSErrorToString(UINT error) +{ + switch (error) + { + case CHANNEL_RC_OK: + return "CHANNEL_RC_OK"; + + case CHANNEL_RC_ALREADY_INITIALIZED: + return "CHANNEL_RC_ALREADY_INITIALIZED"; + + case CHANNEL_RC_NOT_INITIALIZED: + return "CHANNEL_RC_NOT_INITIALIZED"; + + case CHANNEL_RC_ALREADY_CONNECTED: + return "CHANNEL_RC_ALREADY_CONNECTED"; + + case CHANNEL_RC_NOT_CONNECTED: + return "CHANNEL_RC_NOT_CONNECTED"; + + case CHANNEL_RC_TOO_MANY_CHANNELS: + return "CHANNEL_RC_TOO_MANY_CHANNELS"; + + case CHANNEL_RC_BAD_CHANNEL: + return "CHANNEL_RC_BAD_CHANNEL"; + + case CHANNEL_RC_BAD_CHANNEL_HANDLE: + return "CHANNEL_RC_BAD_CHANNEL_HANDLE"; + + case CHANNEL_RC_NO_BUFFER: + return "CHANNEL_RC_NO_BUFFER"; + + case CHANNEL_RC_BAD_INIT_HANDLE: + return "CHANNEL_RC_BAD_INIT_HANDLE"; + + case CHANNEL_RC_NOT_OPEN: + return "CHANNEL_RC_NOT_OPEN"; + + case CHANNEL_RC_BAD_PROC: + return "CHANNEL_RC_BAD_PROC"; + + case CHANNEL_RC_NO_MEMORY: + return "CHANNEL_RC_NO_MEMORY"; + + case CHANNEL_RC_UNKNOWN_CHANNEL_NAME: + return "CHANNEL_RC_UNKNOWN_CHANNEL_NAME"; + + case CHANNEL_RC_ALREADY_OPEN: + return "CHANNEL_RC_ALREADY_OPEN"; + + case CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY: + return "CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY"; + + case CHANNEL_RC_NULL_DATA: + return "CHANNEL_RC_NULL_DATA"; + + case CHANNEL_RC_ZERO_LENGTH: + return "CHANNEL_RC_ZERO_LENGTH"; + + case CHANNEL_RC_INVALID_INSTANCE: + return "CHANNEL_RC_INVALID_INSTANCE"; + + case CHANNEL_RC_UNSUPPORTED_VERSION: + return "CHANNEL_RC_UNSUPPORTED_VERSION"; + + case CHANNEL_RC_INITIALIZATION_ERROR: + return "CHANNEL_RC_INITIALIZATION_ERROR"; + + default: + return "UNKNOWN"; + } +} + +const CHAR* WTSSessionStateToString(WTS_CONNECTSTATE_CLASS state) +{ + switch (state) + { + case WTSActive: + return "WTSActive"; + case WTSConnected: + return "WTSConnected"; + case WTSConnectQuery: + return "WTSConnectQuery"; + case WTSShadow: + return "WTSShadow"; + case WTSDisconnected: + return "WTSDisconnected"; + case WTSIdle: + return "WTSIdle"; + case WTSListen: + return "WTSListen"; + case WTSReset: + return "WTSReset"; + case WTSDown: + return "WTSDown"; + case WTSInit: + return "WTSInit"; + default: + break; + } + return "INVALID_STATE"; +} + +BOOL WTSRegisterWtsApiFunctionTable(const WtsApiFunctionTable* table) +{ + /* Use InitOnceExecuteOnce here as well - otherwise a table set with this + function is overridden on the first use of a WTS* API call (due to + wtsapiInitOnce not being set). */ + union + { + const void* cpv; + void* pv; + } cnv; + cnv.cpv = table; + InitOnceExecuteOnce(&wtsapiInitOnce, InitializeWtsApiStubs, cnv.pv, NULL); + if (!g_WtsApi) + return FALSE; + return TRUE; +} + +static BOOL LoadAndInitialize(char* library) +{ + g_WtsApiModule = LoadLibraryX(library); + + if (!g_WtsApiModule) + return FALSE; + + INIT_WTSAPI_FN pInitWtsApi = GetProcAddressAs(g_WtsApiModule, "InitWtsApi", INIT_WTSAPI_FN); + + if (!pInitWtsApi) + return FALSE; + + g_WtsApi = pInitWtsApi(); + return TRUE; +} + +static void InitializeWtsApiStubs_Env(void) +{ + DWORD nSize = 0; + char* env = NULL; + LPCSTR wts = "WTSAPI_LIBRARY"; + + if (g_WtsApi) + return; + + nSize = GetEnvironmentVariableA(wts, NULL, 0); + + if (!nSize) + return; + + env = (LPSTR)malloc(nSize); + if (env) + { + if (GetEnvironmentVariableA(wts, env, nSize) == nSize - 1) + LoadAndInitialize(env); + free(env); + } +} + +#define FREERDS_LIBRARY_NAME "libfreerds-fdsapi.so" + +static void InitializeWtsApiStubs_FreeRDS(void) +{ + wIniFile* ini = NULL; + const char* prefix = NULL; + const char* libdir = NULL; + + if (g_WtsApi) + return; + + ini = IniFile_New(); + + if (IniFile_ReadFile(ini, "/var/run/freerds.instance") < 0) + { + IniFile_Free(ini); + WLog_ERR(TAG, "failed to parse freerds.instance"); + LoadAndInitialize(FREERDS_LIBRARY_NAME); + return; + } + + prefix = IniFile_GetKeyValueString(ini, "FreeRDS", "prefix"); + libdir = IniFile_GetKeyValueString(ini, "FreeRDS", "libdir"); + WLog_INFO(TAG, "FreeRDS (prefix / libdir): %s / %s", prefix, libdir); + + if (prefix && libdir) + { + char* prefix_libdir = NULL; + char* wtsapi_library = NULL; + prefix_libdir = GetCombinedPath(prefix, libdir); + wtsapi_library = GetCombinedPath(prefix_libdir, FREERDS_LIBRARY_NAME); + + if (wtsapi_library) + { + LoadAndInitialize(wtsapi_library); + } + + free(prefix_libdir); + free(wtsapi_library); + } + + IniFile_Free(ini); +} + +static BOOL CALLBACK InitializeWtsApiStubs(PINIT_ONCE once, PVOID param, PVOID* context) +{ + WINPR_UNUSED(once); + WINPR_UNUSED(context); + if (param) + { + g_WtsApi = (const WtsApiFunctionTable*)param; + return TRUE; + } + + InitializeWtsApiStubs_Env(); + +#ifdef _WIN32 + WtsApi32_InitializeWtsApi(); +#endif + + if (!g_WtsApi) + InitializeWtsApiStubs_FreeRDS(); + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.c new file mode 100644 index 0000000000000000000000000000000000000000..3dff0ea93895144f1a1f367d49f2e6c25215b7dc --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.c @@ -0,0 +1,812 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Terminal Services API + * + * Copyright 2013-2014 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include + +#include + +#include "wtsapi_win32.h" + +#include "../log.h" + +#include + +#pragma comment(lib, "ntdll.lib") + +#define WTSAPI_CHANNEL_MAGIC 0x44484356 +#define TAG WINPR_TAG("wtsapi") + +typedef struct +{ + UINT32 magic; + HANDLE hServer; + DWORD SessionId; + HANDLE hFile; + HANDLE hEvent; + char* VirtualName; + + DWORD flags; + BYTE* chunk; + BOOL dynamic; + BOOL readSync; + BOOL readAsync; + BOOL readDone; + UINT32 readSize; + UINT32 readOffset; + BYTE* readBuffer; + BOOL showProtocol; + BOOL waitObjectMode; + OVERLAPPED overlapped; + CHANNEL_PDU_HEADER* header; +} WTSAPI_CHANNEL; + +static BOOL g_Initialized = FALSE; +static HMODULE g_WinStaModule = NULL; + +typedef HANDLE(WINAPI* fnWinStationVirtualOpen)(HANDLE hServer, DWORD SessionId, + LPSTR pVirtualName); +typedef HANDLE(WINAPI* fnWinStationVirtualOpenEx)(HANDLE hServer, DWORD SessionId, + LPSTR pVirtualName, DWORD flags); + +static fnWinStationVirtualOpen pfnWinStationVirtualOpen = NULL; +static fnWinStationVirtualOpenEx pfnWinStationVirtualOpenEx = NULL; + +BOOL WINAPI Win32_WTSVirtualChannelClose(HANDLE hChannel); + +/** + * NOTE !! + * An application using the WinPR wtsapi frees memory via WTSFreeMemory, which + * might be mapped to Win32_WTSFreeMemory. Latter does not know if the passed + * pointer was allocated by a function in wtsapi32.dll or in some internal + * code below. The WTSFreeMemory implementation in all Windows wtsapi32.dll + * versions up to Windows 10 uses LocalFree since all its allocating functions + * use LocalAlloc() internally. + * For that reason we also have to use LocalAlloc() for any memory returned by + * our WinPR wtsapi functions. + * + * To be safe we only use the _wts_malloc, _wts_calloc, _wts_free wrappers + * for memory management the code below. + */ + +static void* _wts_malloc(size_t size) +{ +#ifdef _UWP + return malloc(size); +#else + return (PVOID)LocalAlloc(LMEM_FIXED, size); +#endif +} + +static void* _wts_calloc(size_t nmemb, size_t size) +{ +#ifdef _UWP + return calloc(nmemb, size); +#else + return (PVOID)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, nmemb * size); +#endif +} + +static void _wts_free(void* ptr) +{ +#ifdef _UWP + free(ptr); +#else + LocalFree((HLOCAL)ptr); +#endif +} + +BOOL Win32_WTSVirtualChannelReadAsync(WTSAPI_CHANNEL* pChannel) +{ + BOOL status = TRUE; + DWORD numBytes = 0; + + if (pChannel->readAsync) + return TRUE; + + ZeroMemory(&(pChannel->overlapped), sizeof(OVERLAPPED)); + pChannel->overlapped.hEvent = pChannel->hEvent; + (void)ResetEvent(pChannel->hEvent); + + if (pChannel->showProtocol) + { + ZeroMemory(pChannel->header, sizeof(CHANNEL_PDU_HEADER)); + + status = ReadFile(pChannel->hFile, pChannel->header, sizeof(CHANNEL_PDU_HEADER), &numBytes, + &(pChannel->overlapped)); + } + else + { + status = ReadFile(pChannel->hFile, pChannel->chunk, CHANNEL_CHUNK_LENGTH, &numBytes, + &(pChannel->overlapped)); + + if (status) + { + pChannel->readOffset = 0; + pChannel->header->length = numBytes; + + pChannel->readDone = TRUE; + (void)SetEvent(pChannel->hEvent); + + return TRUE; + } + } + + if (status) + { + WLog_ERR(TAG, "Unexpected ReadFile status: %" PRId32 " numBytes: %" PRIu32 "", status, + numBytes); + return FALSE; /* ReadFile should return FALSE and set ERROR_IO_PENDING */ + } + + if (GetLastError() != ERROR_IO_PENDING) + { + WLog_ERR(TAG, "ReadFile: GetLastError() = %" PRIu32 "", GetLastError()); + return FALSE; + } + + pChannel->readAsync = TRUE; + + return TRUE; +} + +HANDLE WINAPI Win32_WTSVirtualChannelOpen_Internal(HANDLE hServer, DWORD SessionId, + LPSTR pVirtualName, DWORD flags) +{ + HANDLE hFile; + HANDLE hChannel; + WTSAPI_CHANNEL* pChannel; + size_t virtualNameLen; + + virtualNameLen = pVirtualName ? strlen(pVirtualName) : 0; + + if (!virtualNameLen) + { + SetLastError(ERROR_INVALID_PARAMETER); + return NULL; + } + + if (!pfnWinStationVirtualOpenEx) + { + SetLastError(ERROR_INVALID_FUNCTION); + return NULL; + } + + hFile = pfnWinStationVirtualOpenEx(hServer, SessionId, pVirtualName, flags); + + if (!hFile) + return NULL; + + pChannel = (WTSAPI_CHANNEL*)_wts_calloc(1, sizeof(WTSAPI_CHANNEL)); + + if (!pChannel) + { + (void)CloseHandle(hFile); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return NULL; + } + + hChannel = (HANDLE)pChannel; + pChannel->magic = WTSAPI_CHANNEL_MAGIC; + pChannel->hServer = hServer; + pChannel->SessionId = SessionId; + pChannel->hFile = hFile; + pChannel->VirtualName = _wts_calloc(1, virtualNameLen + 1); + if (!pChannel->VirtualName) + { + (void)CloseHandle(hFile); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + _wts_free(pChannel); + return NULL; + } + memcpy(pChannel->VirtualName, pVirtualName, virtualNameLen); + + pChannel->flags = flags; + pChannel->dynamic = (flags & WTS_CHANNEL_OPTION_DYNAMIC) ? TRUE : FALSE; + + pChannel->showProtocol = pChannel->dynamic; + + pChannel->readSize = CHANNEL_PDU_LENGTH; + pChannel->readBuffer = (BYTE*)_wts_malloc(pChannel->readSize); + + pChannel->header = (CHANNEL_PDU_HEADER*)pChannel->readBuffer; + pChannel->chunk = &(pChannel->readBuffer[sizeof(CHANNEL_PDU_HEADER)]); + + pChannel->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + pChannel->overlapped.hEvent = pChannel->hEvent; + + if (!pChannel->hEvent || !pChannel->VirtualName || !pChannel->readBuffer) + { + Win32_WTSVirtualChannelClose(hChannel); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return NULL; + } + + return hChannel; +} + +HANDLE WINAPI Win32_WTSVirtualChannelOpen(HANDLE hServer, DWORD SessionId, LPSTR pVirtualName) +{ + return Win32_WTSVirtualChannelOpen_Internal(hServer, SessionId, pVirtualName, 0); +} + +HANDLE WINAPI Win32_WTSVirtualChannelOpenEx(DWORD SessionId, LPSTR pVirtualName, DWORD flags) +{ + return Win32_WTSVirtualChannelOpen_Internal(0, SessionId, pVirtualName, flags); +} + +BOOL WINAPI Win32_WTSVirtualChannelClose(HANDLE hChannel) +{ + BOOL status = TRUE; + WTSAPI_CHANNEL* pChannel = (WTSAPI_CHANNEL*)hChannel; + + if (!pChannel || (pChannel->magic != WTSAPI_CHANNEL_MAGIC)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (pChannel->hFile) + { + if (pChannel->readAsync) + { + CancelIo(pChannel->hFile); + pChannel->readAsync = FALSE; + } + + status = CloseHandle(pChannel->hFile); + pChannel->hFile = NULL; + } + + if (pChannel->hEvent) + { + (void)CloseHandle(pChannel->hEvent); + pChannel->hEvent = NULL; + } + + if (pChannel->VirtualName) + { + _wts_free(pChannel->VirtualName); + pChannel->VirtualName = NULL; + } + + if (pChannel->readBuffer) + { + _wts_free(pChannel->readBuffer); + pChannel->readBuffer = NULL; + } + + pChannel->magic = 0; + _wts_free(pChannel); + + return status; +} + +BOOL WINAPI Win32_WTSVirtualChannelRead_Static(WTSAPI_CHANNEL* pChannel, DWORD dwMilliseconds, + LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesTransferred) +{ + if (pChannel->readDone) + { + DWORD numBytesRead = 0; + DWORD numBytesToRead = 0; + + *lpNumberOfBytesTransferred = 0; + + numBytesToRead = nNumberOfBytesToRead; + + if (numBytesToRead > (pChannel->header->length - pChannel->readOffset)) + numBytesToRead = (pChannel->header->length - pChannel->readOffset); + + CopyMemory(lpBuffer, &(pChannel->chunk[pChannel->readOffset]), numBytesToRead); + *lpNumberOfBytesTransferred += numBytesToRead; + pChannel->readOffset += numBytesToRead; + + if (pChannel->readOffset != pChannel->header->length) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + else + { + pChannel->readDone = FALSE; + Win32_WTSVirtualChannelReadAsync(pChannel); + } + + return TRUE; + } + else if (pChannel->readSync) + { + BOOL bSuccess; + OVERLAPPED overlapped = { 0 }; + DWORD numBytesRead = 0; + DWORD numBytesToRead = 0; + + *lpNumberOfBytesTransferred = 0; + + numBytesToRead = nNumberOfBytesToRead; + + if (numBytesToRead > (pChannel->header->length - pChannel->readOffset)) + numBytesToRead = (pChannel->header->length - pChannel->readOffset); + + if (ReadFile(pChannel->hFile, lpBuffer, numBytesToRead, &numBytesRead, &overlapped)) + { + *lpNumberOfBytesTransferred += numBytesRead; + pChannel->readOffset += numBytesRead; + + if (pChannel->readOffset != pChannel->header->length) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + pChannel->readSync = FALSE; + Win32_WTSVirtualChannelReadAsync(pChannel); + + return TRUE; + } + + if (GetLastError() != ERROR_IO_PENDING) + return FALSE; + + bSuccess = GetOverlappedResult(pChannel->hFile, &overlapped, &numBytesRead, TRUE); + + if (!bSuccess) + return FALSE; + + *lpNumberOfBytesTransferred += numBytesRead; + pChannel->readOffset += numBytesRead; + + if (pChannel->readOffset != pChannel->header->length) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + pChannel->readSync = FALSE; + Win32_WTSVirtualChannelReadAsync(pChannel); + + return TRUE; + } + else if (pChannel->readAsync) + { + BOOL bSuccess; + DWORD numBytesRead = 0; + DWORD numBytesToRead = 0; + + *lpNumberOfBytesTransferred = 0; + + if (WaitForSingleObject(pChannel->hEvent, dwMilliseconds) != WAIT_TIMEOUT) + { + bSuccess = + GetOverlappedResult(pChannel->hFile, &(pChannel->overlapped), &numBytesRead, TRUE); + + pChannel->readOffset = 0; + pChannel->header->length = numBytesRead; + + if (!bSuccess && (GetLastError() != ERROR_MORE_DATA)) + return FALSE; + + numBytesToRead = nNumberOfBytesToRead; + + if (numBytesRead < numBytesToRead) + { + numBytesToRead = numBytesRead; + nNumberOfBytesToRead = numBytesRead; + } + + CopyMemory(lpBuffer, pChannel->chunk, numBytesToRead); + *lpNumberOfBytesTransferred += numBytesToRead; + lpBuffer = (BYTE*)lpBuffer + numBytesToRead; + nNumberOfBytesToRead -= numBytesToRead; + pChannel->readOffset += numBytesToRead; + + pChannel->readAsync = FALSE; + + if (!nNumberOfBytesToRead) + { + Win32_WTSVirtualChannelReadAsync(pChannel); + return TRUE; + } + + pChannel->readSync = TRUE; + + numBytesRead = 0; + + bSuccess = Win32_WTSVirtualChannelRead_Static(pChannel, dwMilliseconds, lpBuffer, + nNumberOfBytesToRead, &numBytesRead); + + *lpNumberOfBytesTransferred += numBytesRead; + return bSuccess; + } + else + { + SetLastError(ERROR_IO_INCOMPLETE); + return FALSE; + } + } + + return FALSE; +} + +BOOL WINAPI Win32_WTSVirtualChannelRead_Dynamic(WTSAPI_CHANNEL* pChannel, DWORD dwMilliseconds, + LPVOID lpBuffer, DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesTransferred) +{ + if (pChannel->readSync) + { + BOOL bSuccess; + OVERLAPPED overlapped = { 0 }; + DWORD numBytesRead = 0; + DWORD numBytesToRead = 0; + + *lpNumberOfBytesTransferred = 0; + + numBytesToRead = nNumberOfBytesToRead; + + if (numBytesToRead > (pChannel->header->length - pChannel->readOffset)) + numBytesToRead = (pChannel->header->length - pChannel->readOffset); + + if (ReadFile(pChannel->hFile, lpBuffer, numBytesToRead, &numBytesRead, &overlapped)) + { + *lpNumberOfBytesTransferred += numBytesRead; + pChannel->readOffset += numBytesRead; + + if (pChannel->readOffset != pChannel->header->length) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + pChannel->readSync = FALSE; + Win32_WTSVirtualChannelReadAsync(pChannel); + + return TRUE; + } + + if (GetLastError() != ERROR_IO_PENDING) + return FALSE; + + bSuccess = GetOverlappedResult(pChannel->hFile, &overlapped, &numBytesRead, TRUE); + + if (!bSuccess) + return FALSE; + + *lpNumberOfBytesTransferred += numBytesRead; + pChannel->readOffset += numBytesRead; + + if (pChannel->readOffset != pChannel->header->length) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + pChannel->readSync = FALSE; + Win32_WTSVirtualChannelReadAsync(pChannel); + + return TRUE; + } + else if (pChannel->readAsync) + { + BOOL bSuccess; + DWORD numBytesRead = 0; + + *lpNumberOfBytesTransferred = 0; + + if (WaitForSingleObject(pChannel->hEvent, dwMilliseconds) != WAIT_TIMEOUT) + { + bSuccess = + GetOverlappedResult(pChannel->hFile, &(pChannel->overlapped), &numBytesRead, TRUE); + + if (pChannel->showProtocol) + { + if (numBytesRead != sizeof(CHANNEL_PDU_HEADER)) + return FALSE; + + if (!bSuccess && (GetLastError() != ERROR_MORE_DATA)) + return FALSE; + + CopyMemory(lpBuffer, pChannel->header, numBytesRead); + *lpNumberOfBytesTransferred += numBytesRead; + lpBuffer = (BYTE*)lpBuffer + numBytesRead; + nNumberOfBytesToRead -= numBytesRead; + } + + pChannel->readAsync = FALSE; + + if (!pChannel->header->length) + { + Win32_WTSVirtualChannelReadAsync(pChannel); + return TRUE; + } + + pChannel->readSync = TRUE; + pChannel->readOffset = 0; + + if (!nNumberOfBytesToRead) + { + SetLastError(ERROR_MORE_DATA); + return FALSE; + } + + numBytesRead = 0; + + bSuccess = Win32_WTSVirtualChannelRead_Dynamic(pChannel, dwMilliseconds, lpBuffer, + nNumberOfBytesToRead, &numBytesRead); + + *lpNumberOfBytesTransferred += numBytesRead; + return bSuccess; + } + else + { + SetLastError(ERROR_IO_INCOMPLETE); + return FALSE; + } + } + + return FALSE; +} + +BOOL WINAPI Win32_WTSVirtualChannelRead(HANDLE hChannel, DWORD dwMilliseconds, LPVOID lpBuffer, + DWORD nNumberOfBytesToRead, + LPDWORD lpNumberOfBytesTransferred) +{ + WTSAPI_CHANNEL* pChannel = (WTSAPI_CHANNEL*)hChannel; + + if (!pChannel || (pChannel->magic != WTSAPI_CHANNEL_MAGIC)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (!pChannel->waitObjectMode) + { + OVERLAPPED overlapped = { 0 }; + + if (ReadFile(pChannel->hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesTransferred, + &overlapped)) + return TRUE; + + if (GetLastError() != ERROR_IO_PENDING) + return FALSE; + + if (!dwMilliseconds) + { + CancelIo(pChannel->hFile); + *lpNumberOfBytesTransferred = 0; + return TRUE; + } + + if (WaitForSingleObject(pChannel->hFile, dwMilliseconds) != WAIT_TIMEOUT) + return GetOverlappedResult(pChannel->hFile, &overlapped, lpNumberOfBytesTransferred, + FALSE); + + CancelIo(pChannel->hFile); + SetLastError(ERROR_IO_INCOMPLETE); + + return FALSE; + } + else + { + if (pChannel->dynamic) + { + return Win32_WTSVirtualChannelRead_Dynamic(pChannel, dwMilliseconds, lpBuffer, + nNumberOfBytesToRead, + lpNumberOfBytesTransferred); + } + else + { + return Win32_WTSVirtualChannelRead_Static(pChannel, dwMilliseconds, lpBuffer, + nNumberOfBytesToRead, + lpNumberOfBytesTransferred); + } + } + + return FALSE; +} + +BOOL WINAPI Win32_WTSVirtualChannelWrite(HANDLE hChannel, LPCVOID lpBuffer, + DWORD nNumberOfBytesToWrite, + LPDWORD lpNumberOfBytesTransferred) +{ + OVERLAPPED overlapped = { 0 }; + WTSAPI_CHANNEL* pChannel = (WTSAPI_CHANNEL*)hChannel; + + if (!pChannel || (pChannel->magic != WTSAPI_CHANNEL_MAGIC)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (WriteFile(pChannel->hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesTransferred, + &overlapped)) + return TRUE; + + if (GetLastError() == ERROR_IO_PENDING) + return GetOverlappedResult(pChannel->hFile, &overlapped, lpNumberOfBytesTransferred, TRUE); + + return FALSE; +} + +#ifndef FILE_DEVICE_TERMSRV +#define FILE_DEVICE_TERMSRV 0x00000038 +#endif + +BOOL Win32_WTSVirtualChannelPurge_Internal(HANDLE hChannelHandle, ULONG IoControlCode) +{ + IO_STATUS_BLOCK ioStatusBlock = { 0 }; + WTSAPI_CHANNEL* pChannel = (WTSAPI_CHANNEL*)hChannelHandle; + + if (!pChannel || (pChannel->magic != WTSAPI_CHANNEL_MAGIC)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + NTSTATUS ntstatus = + NtDeviceIoControlFile(pChannel->hFile, 0, 0, 0, &ioStatusBlock, IoControlCode, 0, 0, 0, 0); + + if (ntstatus == STATUS_PENDING) + { + ntstatus = NtWaitForSingleObject(pChannel->hFile, 0, 0); + + if (ntstatus >= 0) + { +#if defined(NONAMELESSUNION) && !defined(__MINGW32__) + ntstatus = ioStatusBlock.DUMMYUNIONNAME.Status; +#else + ntstatus = ioStatusBlock.Status; +#endif + } + } + + if (ntstatus == STATUS_BUFFER_OVERFLOW) + { + ntstatus = STATUS_BUFFER_TOO_SMALL; + const DWORD error = RtlNtStatusToDosError(ntstatus); + SetLastError(error); + return FALSE; + } + + if (ntstatus < 0) + { + const DWORD error = RtlNtStatusToDosError(ntstatus); + SetLastError(error); + return FALSE; + } + + return TRUE; +} + +BOOL WINAPI Win32_WTSVirtualChannelPurgeInput(HANDLE hChannelHandle) +{ + return Win32_WTSVirtualChannelPurge_Internal(hChannelHandle, + (FILE_DEVICE_TERMSRV << 16) | 0x0107); +} + +BOOL WINAPI Win32_WTSVirtualChannelPurgeOutput(HANDLE hChannelHandle) +{ + return Win32_WTSVirtualChannelPurge_Internal(hChannelHandle, + (FILE_DEVICE_TERMSRV << 16) | 0x010B); +} + +BOOL WINAPI Win32_WTSVirtualChannelQuery(HANDLE hChannelHandle, WTS_VIRTUAL_CLASS WtsVirtualClass, + PVOID* ppBuffer, DWORD* pBytesReturned) +{ + WTSAPI_CHANNEL* pChannel = (WTSAPI_CHANNEL*)hChannelHandle; + + if (!pChannel || (pChannel->magic != WTSAPI_CHANNEL_MAGIC)) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (WtsVirtualClass == WTSVirtualClientData) + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + else if (WtsVirtualClass == WTSVirtualFileHandle) + { + *pBytesReturned = sizeof(HANDLE); + *ppBuffer = _wts_calloc(1, *pBytesReturned); + + if (*ppBuffer == NULL) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + CopyMemory(*ppBuffer, &(pChannel->hFile), *pBytesReturned); + } + else if (WtsVirtualClass == WTSVirtualEventHandle) + { + *pBytesReturned = sizeof(HANDLE); + *ppBuffer = _wts_calloc(1, *pBytesReturned); + + if (*ppBuffer == NULL) + { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + + CopyMemory(*ppBuffer, &(pChannel->hEvent), *pBytesReturned); + + Win32_WTSVirtualChannelReadAsync(pChannel); + pChannel->waitObjectMode = TRUE; + } + else + { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + + return TRUE; +} + +VOID WINAPI Win32_WTSFreeMemory(PVOID pMemory) +{ + _wts_free(pMemory); +} + +BOOL WINAPI Win32_WTSFreeMemoryExW(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries) +{ + return FALSE; +} + +BOOL WINAPI Win32_WTSFreeMemoryExA(WTS_TYPE_CLASS WTSTypeClass, PVOID pMemory, + ULONG NumberOfEntries) +{ + return WTSFreeMemoryExW(WTSTypeClass, pMemory, NumberOfEntries); +} + +BOOL Win32_InitializeWinSta(PWtsApiFunctionTable pWtsApi) +{ + g_WinStaModule = LoadLibraryA("winsta.dll"); + + if (!g_WinStaModule) + return FALSE; + + pfnWinStationVirtualOpen = + GetProcAddressAs(g_WinStaModule, "WinStationVirtualOpen", fnWinStationVirtualOpen); + pfnWinStationVirtualOpenEx = + GetProcAddressAs(g_WinStaModule, "WinStationVirtualOpenEx", fnWinStationVirtualOpenEx); + + if (!pfnWinStationVirtualOpen | !pfnWinStationVirtualOpenEx) + return FALSE; + + pWtsApi->pVirtualChannelOpen = Win32_WTSVirtualChannelOpen; + pWtsApi->pVirtualChannelOpenEx = Win32_WTSVirtualChannelOpenEx; + pWtsApi->pVirtualChannelClose = Win32_WTSVirtualChannelClose; + pWtsApi->pVirtualChannelRead = Win32_WTSVirtualChannelRead; + pWtsApi->pVirtualChannelWrite = Win32_WTSVirtualChannelWrite; + pWtsApi->pVirtualChannelPurgeInput = Win32_WTSVirtualChannelPurgeInput; + pWtsApi->pVirtualChannelPurgeOutput = Win32_WTSVirtualChannelPurgeOutput; + pWtsApi->pVirtualChannelQuery = Win32_WTSVirtualChannelQuery; + pWtsApi->pFreeMemory = Win32_WTSFreeMemory; + // pWtsApi->pFreeMemoryExW = Win32_WTSFreeMemoryExW; + // pWtsApi->pFreeMemoryExA = Win32_WTSFreeMemoryExA; + + return TRUE; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.h b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.h new file mode 100644 index 0000000000000000000000000000000000000000..7d4316553a8b757de8dda367b2bc7417b7b1b5b1 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/libwinpr/wtsapi/wtsapi_win32.h @@ -0,0 +1,27 @@ +/** + * WinPR: Windows Portable Runtime + * Windows Terminal Services API + * + * Copyright 2013-2014 Marc-Andre Moreau + * + * 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_WTSAPI_WIN32_PRIVATE_H +#define WINPR_WTSAPI_WIN32_PRIVATE_H + +#include + +BOOL Win32_InitializeWinSta(PWtsApiFunctionTable pWtsApi); + +#endif /* WINPR_WTSAPI_WIN32_PRIVATE_H */ diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/test/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..bef2fb7cc62c0f6dcdf2d47213a8bfb78475cf4a --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/CMakeLists.txt @@ -0,0 +1,23 @@ +set(MODULE_NAME "TestWinPR") +set(MODULE_PREFIX "TEST_WINPR") + +disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR}) + +set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) + +set(${MODULE_PREFIX}_TESTS TestIntrinsics.c TestTypes.c) + +create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) + +add_executable(${MODULE_NAME} ${${MODULE_PREFIX}_SRCS}) + +target_link_libraries(${MODULE_NAME} winpr) + +set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}") + +foreach(test ${${MODULE_PREFIX}_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") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestIntrinsics.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestIntrinsics.c new file mode 100644 index 0000000000000000000000000000000000000000..e9a657bb12a2a6ae0aae40222dde97ebc5b3de13 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestIntrinsics.c @@ -0,0 +1,121 @@ +#include +#include +#include + +#include + +static BOOL g_LZCNT = FALSE; + +static INLINE UINT32 lzcnt_s(UINT32 x) +{ + if (!x) + return 32; + + if (!g_LZCNT) + { + UINT32 y = 0; + 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; + } + + return __lzcnt(x); +} + +static int test_lzcnt(void) +{ + if (lzcnt_s(0x1) != 31) + { + (void)fprintf(stderr, "__lzcnt(0x1) != 31: %" PRIu32 "\n", __lzcnt(0x1)); + return -1; + } + + if (lzcnt_s(0xFF) != 24) + { + (void)fprintf(stderr, "__lzcnt(0xFF) != 24\n"); + return -1; + } + + if (lzcnt_s(0xFFFF) != 16) + { + (void)fprintf(stderr, "__lzcnt(0xFFFF) != 16\n"); + return -1; + } + + if (lzcnt_s(0xFFFFFF) != 8) + { + (void)fprintf(stderr, "__lzcnt(0xFFFFFF) != 8\n"); + return -1; + } + + if (lzcnt_s(0xFFFFFFFF) != 0) + { + (void)fprintf(stderr, "__lzcnt(0xFFFFFFFF) != 0\n"); + return -1; + } + + return 0; +} + +static int test_lzcnt16(void) +{ + if (__lzcnt16(0x1) != 15) + { + (void)fprintf(stderr, "__lzcnt16(0x1) != 15\n"); + return -1; + } + + if (__lzcnt16(0xFF) != 8) + { + (void)fprintf(stderr, "__lzcnt16(0xFF) != 8\n"); + return -1; + } + + if (__lzcnt16(0xFFFF) != 0) + { + (void)fprintf(stderr, "__lzcnt16(0xFFFF) != 0\n"); + return -1; + } + + return 0; +} + +int TestIntrinsics(int argc, char* argv[]) +{ + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + g_LZCNT = IsProcessorFeaturePresentEx(PF_EX_LZCNT); + + printf("LZCNT available: %" PRId32 "\n", g_LZCNT); + + // test_lzcnt16(); + return test_lzcnt(); +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestTypes.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestTypes.c new file mode 100644 index 0000000000000000000000000000000000000000..482c87c3992abd4ec7df6d9a0e91566a62a429c6 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/test/TestTypes.c @@ -0,0 +1,214 @@ +/** + * CTest for winpr types and macros + * + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 Norbert Federa + * + * 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 +#include + +static BOOL test_co_errors(void) +{ + const LONG should[] = { + (LONG)0x80004006l, (LONG)0x80004007l, (LONG)0x80004008l, (LONG)0x80004009l, + (LONG)0x8000400Al, (LONG)0x8000400Bl, (LONG)0x8000400Cl, (LONG)0x8000400Dl, + (LONG)0x8000400El, (LONG)0x8000400Fl, (LONG)0x80004010l, (LONG)0x80004011l, + (LONG)0x80004012l, (LONG)0x80004013l, (LONG)0x80004014l, (LONG)0x80004015l, + (LONG)0x80004016l, (LONG)0x80004017l, (LONG)0x80004018l, (LONG)0x80004019l, + (LONG)0x8000401Al, (LONG)0x8000401Bl, (LONG)0x8000401Cl, (LONG)0x8000401Dl, + (LONG)0x8000401El, (LONG)0x8000401Fl, (LONG)0x80004020l, (LONG)0x80004021l, + (LONG)0x80004022l, (LONG)0x80004023l, (LONG)0x80004024l, (LONG)0x80004025l, + (LONG)0x80004026l, (LONG)0x80004027l, (LONG)0x80004028l, (LONG)0x80004029l, + (LONG)0x8000402Al, (LONG)0x8000402Bl, (LONG)0x80004030l, (LONG)0x80004031l, + (LONG)0x80004032l, (LONG)0x80004033l, (LONG)0x8000FFFFL, (LONG)0x80070005L, + (LONG)0x80070006L, (LONG)0x8007000EL, (LONG)0x80070057L, (LONG)0x80004001L, + (LONG)0x80004002L, (LONG)0x80004003L, (LONG)0x80004004L, (LONG)0x80004005L + }; + const LONG are[] = { CO_E_INIT_TLS, + CO_E_INIT_SHARED_ALLOCATOR, + CO_E_INIT_MEMORY_ALLOCATOR, + CO_E_INIT_CLASS_CACHE, + CO_E_INIT_RPC_CHANNEL, + CO_E_INIT_TLS_SET_CHANNEL_CONTROL, + CO_E_INIT_TLS_CHANNEL_CONTROL, + CO_E_INIT_UNACCEPTED_USER_ALLOCATOR, + CO_E_INIT_SCM_MUTEX_EXISTS, + CO_E_INIT_SCM_FILE_MAPPING_EXISTS, + CO_E_INIT_SCM_MAP_VIEW_OF_FILE, + CO_E_INIT_SCM_EXEC_FAILURE, + CO_E_INIT_ONLY_SINGLE_THREADED, + CO_E_CANT_REMOTE, + CO_E_BAD_SERVER_NAME, + CO_E_WRONG_SERVER_IDENTITY, + CO_E_OLE1DDE_DISABLED, + CO_E_RUNAS_SYNTAX, + CO_E_CREATEPROCESS_FAILURE, + CO_E_RUNAS_CREATEPROCESS_FAILURE, + CO_E_RUNAS_LOGON_FAILURE, + CO_E_LAUNCH_PERMSSION_DENIED, + CO_E_START_SERVICE_FAILURE, + CO_E_REMOTE_COMMUNICATION_FAILURE, + CO_E_SERVER_START_TIMEOUT, + CO_E_CLSREG_INCONSISTENT, + CO_E_IIDREG_INCONSISTENT, + CO_E_NOT_SUPPORTED, + CO_E_RELOAD_DLL, + CO_E_MSI_ERROR, + CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT, + CO_E_SERVER_PAUSED, + CO_E_SERVER_NOT_PAUSED, + CO_E_CLASS_DISABLED, + CO_E_CLRNOTAVAILABLE, + CO_E_ASYNC_WORK_REJECTED, + CO_E_SERVER_INIT_TIMEOUT, + CO_E_NO_SECCTX_IN_ACTIVATE, + CO_E_TRACKER_CONFIG, + CO_E_THREADPOOL_CONFIG, + CO_E_SXS_CONFIG, + CO_E_MALFORMED_SPN, + E_UNEXPECTED, + E_ACCESSDENIED, + E_HANDLE, + E_OUTOFMEMORY, + E_INVALIDARG, + E_NOTIMPL, + E_NOINTERFACE, + E_POINTER, + E_ABORT, + E_FAIL }; + + if (ARRAYSIZE(should) != ARRAYSIZE(are)) + { + const size_t a = ARRAYSIZE(should); + const size_t b = ARRAYSIZE(are); + printf("mismatch: %" PRIuz " vs %" PRIuz "\n", a, b); + return FALSE; + } + for (size_t x = 0; x < ARRAYSIZE(are); x++) + { + const LONG a = are[x]; + const LONG b = should[x]; + if (a != b) + { + printf("mismatch[%" PRIuz "]: %08" PRIx32 " vs %08" PRIx32 "\n", x, a, b); + return FALSE; + } + } + return TRUE; +} + +static BOOL TestSucceededFailedMacros(HRESULT hr, char* sym, BOOL isSuccess) +{ + BOOL rv = TRUE; + + if (SUCCEEDED(hr) && !isSuccess) + { + printf("Error: SUCCEEDED with \"%s\" must be false\n", sym); + rv = FALSE; + } + if (!SUCCEEDED(hr) && isSuccess) + { + printf("Error: SUCCEEDED with \"%s\" must be true\n", sym); + rv = FALSE; + } + if (!FAILED(hr) && !isSuccess) + { + printf("Error: FAILED with \"%s\" must be true\n", sym); + rv = FALSE; + } + if (FAILED(hr) && isSuccess) + { + printf("Error: FAILED with \"%s\" must be false\n", sym); + rv = FALSE; + } + + return rv; +} + +int TestTypes(int argc, char* argv[]) +{ + BOOL ok = TRUE; + HRESULT hr = 0; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + if (!test_co_errors()) + goto err; + + if (S_OK != 0L) + { + printf("Error: S_OK should be 0\n"); + goto err; + } + if (S_FALSE != 1L) + { + printf("Error: S_FALSE should be 1\n"); + goto err; + } + + /* Test HRESULT success codes */ + ok &= TestSucceededFailedMacros(S_OK, "S_OK", TRUE); + ok &= TestSucceededFailedMacros(S_FALSE, "S_FALSE", TRUE); + + /* Test some HRESULT error codes */ + ok &= TestSucceededFailedMacros(E_NOTIMPL, "E_NOTIMPL", FALSE); + ok &= TestSucceededFailedMacros(E_OUTOFMEMORY, "E_OUTOFMEMORY", FALSE); + ok &= TestSucceededFailedMacros(E_INVALIDARG, "E_INVALIDARG", FALSE); + ok &= TestSucceededFailedMacros(E_FAIL, "E_FAIL", FALSE); + ok &= TestSucceededFailedMacros(E_ABORT, "E_ABORT", FALSE); + + /* Test some WIN32 error codes converted to HRESULT*/ + hr = HRESULT_FROM_WIN32(ERROR_SUCCESS); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_SUCCESS)", TRUE); + + hr = HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_INVALID_FUNCTION)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_NOACCESS); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_NOACCESS)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_TIMEOUT)", FALSE); + + hr = HRESULT_FROM_WIN32(RPC_S_ZERO_DIVIDE); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(RPC_S_ZERO_DIVIDE)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_STATIC_INIT); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_STATIC_INIT)", FALSE); + + hr = HRESULT_FROM_WIN32(ERROR_ENCRYPTION_FAILED); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(ERROR_ENCRYPTION_FAILED)", FALSE); + + hr = HRESULT_FROM_WIN32(WSAECANCELLED); + ok &= TestSucceededFailedMacros(hr, "HRESULT_FROM_WIN32(WSAECANCELLED)", FALSE); + + if (ok) + { + printf("Test completed successfully\n"); + return 0; + } + +err: + printf("Error: Test failed\n"); + return -1; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..559a683ad57a8739d4f7c54dbfda788cb06014be --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/CMakeLists.txt @@ -0,0 +1,130 @@ +# WinPR: Windows Portable Runtime +# winpr cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2016 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. + +# Soname versioning - use winpr version +set(WINPR_TOOLS_VERSION_MAJOR "${WINPR_VERSION_MAJOR}") +set(WINPR_TOOLS_VERSION_MINOR "${WINPR_VERSION_MINOR}") +set(WINPR_TOOLS_VERSION_REVISION "${WINPR_VERSION_REVISION}") + +set(WINPR_TOOLS_API_VERSION "${WINPR_TOOLS_VERSION_MAJOR}") +set(WINPR_TOOLS_VERSION "${WINPR_TOOLS_VERSION_MAJOR}.${WINPR_TOOLS_VERSION_MINOR}.${WINPR_TOOLS_VERSION_REVISION}") +set(WINPR_TOOLS_VERSION_FULL "${WINPR_TOOLS_VERSION}") +set(WINPR_TOOLS_API_VERSION "${WINPR_TOOLS_VERSION_MAJOR}") + +set(WINPR_TOOLS_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +set(WINPR_TOOLS_SRCS "") +set(WINPR_TOOLS_LIBS "") +set(WINPR_TOOLS_INCLUDES "") +set(WINPR_TOOLS_DEFINITIONS "") + +macro(winpr_tools_module_add) + file(RELATIVE_PATH _relPath "${WINPR_TOOLS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}") + foreach(_src ${ARGN}) + if(_relPath) + list(APPEND WINPR_TOOLS_SRCS "${_relPath}/${_src}") + else() + list(APPEND WINPR_TOOLS_SRCS "${_src}") + endif() + endforeach() + if(_relPath) + set(WINPR_TOOLS_SRCS ${WINPR_TOOLS_SRCS} PARENT_SCOPE) + endif() +endmacro() + +macro(winpr_tools_include_directory_add) + file(RELATIVE_PATH _relPath "${WINPR_TOOLS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}") + foreach(_inc ${ARGN}) + if(IS_ABSOLUTE ${_inc}) + list(APPEND WINPR_TOOLS_INCLUDES "${_inc}") + else() + if(_relPath) + list(APPEND WINPR_TOOLS_INCLUDES "${_relPath}/${_inc}") + else() + list(APPEND WINPR_TOOLS_INCLUDES "${_inc}") + endif() + endif() + endforeach() + if(_relPath) + set(WINPR_TOOLS_INCLUDES ${WINPR_TOOLS_INCLUDES} PARENT_SCOPE) + endif() +endmacro() + +macro(winpr_tools_library_add) + foreach(_lib ${ARGN}) + list(APPEND WINPR_TOOLS_LIBS "${_lib}") + endforeach() + set(WINPR_TOOLS_LIBS ${WINPR_TOOLS_LIBS} PARENT_SCOPE) +endmacro() + +macro(winpr_tools_definition_add) + foreach(_define ${ARGN}) + list(APPEND WINPR_TOOLS_DEFINITONS "${_define}") + endforeach() + set(WINPR_TOOLS_DEFINITONS ${WINPR_TOOLS_DEFINITONS} PARENT_SCOPE) +endmacro() + +add_subdirectory(makecert) + +set(MODULE_NAME winpr-tools) +list(REMOVE_DUPLICATES WINPR_TOOLS_DEFINITIONS) +list(REMOVE_DUPLICATES WINPR_TOOLS_INCLUDES) +include_directories(${WINPR_TOOLS_INCLUDES}) + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${WINPR_VERSION}" WINPR_TOOLS_SRCS) + +add_compile_definitions(${WINPR_DEFINITIONS}) +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${WINPR_TOOLS_LIBS}) + +install(TARGETS ${MODULE_NAME} COMPONENT libraries EXPORT WinPR-toolsTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Tools") + +# Add all command line utilities +add_subdirectory(makecert-cli) +add_subdirectory(hash-cli) + +include(pkg-config-install-prefix) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/winpr-tools.pc.in ${CMAKE_CURRENT_BINARY_DIR}/winpr-tools${WINPR_TOOLS_VERSION_MAJOR}.pc + @ONLY +) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/winpr-tools${WINPR_TOOLS_VERSION_MAJOR}.pc + DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR} +) + +export(PACKAGE ${MODULE_NAME}) + +setfreerdpcmakeinstalldir(WINPR_CMAKE_INSTALL_DIR "WinPR-tools${WINPR_VERSION_MAJOR}") + +configure_package_config_file( + WinPR-toolsConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/WinPR-toolsConfig.cmake + INSTALL_DESTINATION ${WINPR_CMAKE_INSTALL_DIR} PATH_VARS WINPR_INCLUDE_DIR +) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/WinPR-toolsConfigVersion.cmake VERSION ${WINPR_VERSION} COMPATIBILITY SameMajorVersion +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/WinPR-toolsConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/WinPR-toolsConfigVersion.cmake DESTINATION ${WINPR_CMAKE_INSTALL_DIR} +) + +install(EXPORT WinPR-toolsTargets DESTINATION ${WINPR_CMAKE_INSTALL_DIR}) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/WinPR-toolsConfig.cmake.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/WinPR-toolsConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..65f9f4824b5403ba8feaf42eec697987fc0c49ad --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/WinPR-toolsConfig.cmake.in @@ -0,0 +1,12 @@ +include(CMakeFindDependencyMacro) +find_dependency(WinPR @FREERDP_VERSION@) + +@PACKAGE_INIT@ + +set(WinPR-tools_VERSION_MAJOR "@WINPR_VERSION_MAJOR@") +set(WinPR-tools_VERSION_MINOR "@WINPR_VERSION_MINOR@") +set(WinPR-tools_VERSION_REVISION "@WINPR_VERSION_REVISION@") + +set_and_check(WinPR-tools_INCLUDE_DIR "@PACKAGE_WINPR_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/WinPR-toolsTargets.cmake") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..025963127deda0d5c1633d2960ecd2793cb6892f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/CMakeLists.txt @@ -0,0 +1,32 @@ +# WinPR: Windows Portable Runtime +# winpr-hash cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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-hash") +set(MODULE_PREFIX "WINPR_TOOLS_HASH") + +set(${MODULE_PREFIX}_SRCS hash.c) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${WINPR_VERSION}" ${MODULE_PREFIX}_SRCS) + +set(${MODULE_PREFIX}_LIBS winpr) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS}) + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT tools EXPORT WinPRTargets) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Tools") +generate_and_install_freerdp_man_from_template(${MODULE_NAME} "1" "${WINPR_API_VERSION}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/hash.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/hash.c new file mode 100644 index 0000000000000000000000000000000000000000..610a12aae487d723cd3a6df4483f34b188a9273f --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/hash.c @@ -0,0 +1,216 @@ +/** + * WinPR: Windows Portable Runtime + * NTLM Hashing Tool + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include +#include + +#include +#include +#include + +/** + * Define NTOWFv1(Password, User, Domain) as + * MD4(UNICODE(Password)) + * EndDefine + * + * Define LMOWFv1(Password, User, Domain) as + * ConcatenationOf(DES(UpperCase(Password)[0..6], "KGS!@#$%"), + * DES(UpperCase(Password)[7..13], "KGS!@#$%")) + * EndDefine + * + * Define NTOWFv2(Password, User, Domain) as + * HMAC_MD5(MD4(UNICODE(Password)), + * UNICODE(ConcatenationOf(UpperCase(User), Domain))) + * EndDefine + * + * Define LMOWFv2(Password, User, Domain) as + * NTOWFv2(Password, User, Domain) + * EndDefine + * + */ + +static int usage_and_exit(void) +{ + printf("winpr-hash: NTLM hashing tool\n"); + printf("Usage: winpr-hash -u -p [-d ] [-f <_default_,sam>] [-v " + "<_1_,2>]\n"); + return 1; +} + +int main(int argc, char* argv[]) +{ + int index = 1; + int format = 0; + unsigned long version = 1; + BYTE NtHash[16]; + char* User = NULL; + size_t UserLength = 0; + char* Domain = NULL; + size_t DomainLength = 0; + char* Password = NULL; + size_t PasswordLength = 0; + errno = 0; + + while (index < argc) + { + if (strcmp("-d", argv[index]) == 0) + { + index++; + + if (index == argc) + { + printf("missing domain\n\n"); + return usage_and_exit(); + } + + Domain = argv[index]; + } + else if (strcmp("-u", argv[index]) == 0) + { + index++; + + if (index == argc) + { + printf("missing username\n\n"); + return usage_and_exit(); + } + + User = argv[index]; + } + else if (strcmp("-p", argv[index]) == 0) + { + index++; + + if (index == argc) + { + printf("missing password\n\n"); + return usage_and_exit(); + } + + Password = argv[index]; + } + else if (strcmp("-v", argv[index]) == 0) + { + index++; + + if (index == argc) + { + printf("missing version parameter\n\n"); + return usage_and_exit(); + } + + version = strtoul(argv[index], NULL, 0); + + if (((version != 1) && (version != 2)) || (errno != 0)) + { + printf("unknown version %lu \n\n", version); + return usage_and_exit(); + } + } + else if (strcmp("-f", argv[index]) == 0) + { + index++; + + if (index == argc) + { + printf("missing format\n\n"); + return usage_and_exit(); + } + + if (strcmp("default", argv[index]) == 0) + format = 0; + else if (strcmp("sam", argv[index]) == 0) + format = 1; + } + else if (strcmp("-h", argv[index]) == 0) + { + return usage_and_exit(); + } + + index++; + } + + if ((!User) || (!Password)) + { + printf("missing username or password\n\n"); + return usage_and_exit(); + } + winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); + + UserLength = strlen(User); + PasswordLength = strlen(Password); + DomainLength = (Domain) ? strlen(Domain) : 0; + + WINPR_ASSERT(UserLength <= UINT32_MAX); + WINPR_ASSERT(PasswordLength <= UINT32_MAX); + WINPR_ASSERT(DomainLength <= UINT32_MAX); + + if (version == 2) + { + if (!Domain) + { + printf("missing domain (version 2 requires a domain to specified)\n\n"); + return usage_and_exit(); + } + + if (!NTOWFv2A(Password, (UINT32)PasswordLength, User, (UINT32)UserLength, Domain, + (UINT32)DomainLength, NtHash)) + { + (void)fprintf(stderr, "Hash creation failed\n"); + return 1; + } + } + else + { + if (!NTOWFv1A(Password, (UINT32)PasswordLength, NtHash)) + { + (void)fprintf(stderr, "Hash creation failed\n"); + return 1; + } + } + + if (format == 0) + { + for (int idx = 0; idx < 16; idx++) + printf("%02" PRIx8 "", NtHash[idx]); + + printf("\n"); + } + else if (format == 1) + { + printf("%s:", User); + + if (DomainLength > 0) + printf("%s:", Domain); + else + printf(":"); + + printf(":"); + + for (int idx = 0; idx < 16; idx++) + printf("%02" PRIx8 "", NtHash[idx]); + + printf(":::"); + printf("\n"); + } + + return 0; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/winpr-hash.1.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/winpr-hash.1.in new file mode 100644 index 0000000000000000000000000000000000000000..388b7fa6bdc0e13df3c2089ed4273022fd17d53e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/hash-cli/winpr-hash.1.in @@ -0,0 +1,42 @@ +.TH @MANPAGE_NAME@ 1 2017-01-11 "@WINPR_VERSION_FULL@" "FreeRDP" +.SH NAME +@MANPAGE_NAME@ \- NTLM hashing tool +.SH SYNOPSIS +.B @MANPAGE_NAME@ +\fB-u\fP username +\fB-p\fP password +[\fB-d\fP domain] +[\fB-f\fP { \fIdefault\fP | sam }] +[\fB-v\fP { \fI1\fP | 2 }] +.SH DESCRIPTION +.B @MANPAGE_NAME@ +is a small utility that can be used to create a NTLM hash from a username and password pair. The created hash can be outputted as plain hash or in SAM format. +.SH OPTIONS +.IP "-u username" +The username to use. +.IP "-p password" +Password to use. +.IP "-d domain" +A optional parameter to specify the domain of the user. +.IP "-f format" +Specify the output format. The \fIdefault\fP outputs only the plain NTLM +hash. The second output format available is \fIsam\fP which outputs the +created hash in a format that it can be used in SAM file: + +user:domain::hash::: +.IP "-v version" +Version allows it to specify the NTLM version to use. The default is to use version 1. In case +version 2 is used a domain needs to be specified. +.SH EXAMPLES +@MANPAGE_NAME@ -u \fIuser\fP -p \fIpassword\fP -d \fIdomain\fP -f \fIsam\fP -v \fI2\fP + +Create a version \fI2\fP NTLM hash for \fIuser\fP with \fIdomain\fP and \fIpassword\fP and output it in \fIsam\fP format. +.SH EXIT STATUS +.TP +.B 0 +Successful program execution. +.TP +.B 1 +Missing or invalid arguments. +.SH AUTHOR +FreeRDP diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ad9e3807b4cf7ab80ded344da2d3c13b8ae3df0b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/CMakeLists.txt @@ -0,0 +1,34 @@ +# WinPR: Windows Portable Runtime +# winpr-makecert cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2016 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. + +set(MODULE_NAME "winpr-makecert") +set(MODULE_PREFIX "WINPR_MAKECERT") + +set(${MODULE_PREFIX}_SRCS main.c) + +addtargetwithresourcefile(${MODULE_NAME} TRUE "${WINPR_VERSION}" ${MODULE_PREFIX}_SRCS) + +set(${MODULE_PREFIX}_LIBS winpr-tools) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS} winpr) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Tools") + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT tools EXPORT WinPRTargets) + +generate_and_install_freerdp_man_from_template(${MODULE_NAME} "1" "${WINPR_API_VERSION}") diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/main.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/main.c new file mode 100644 index 0000000000000000000000000000000000000000..fa01f7efd9605e79f80ea75eaa5b7604f275f78e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/main.c @@ -0,0 +1,45 @@ +/** + * WinPR: Windows Portable Runtime + * makecert replacement + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 +#include +#include + +#include +#include +#include + +#include + +int main(int argc, char* argv[]) +{ + MAKECERT_CONTEXT* context = NULL; + int ret = 0; + + context = makecert_context_new(); + if (!context) + return 1; + + if (makecert_context_process(context, argc, argv) < 0) + ret = 1; + + makecert_context_free(context); + + return ret; +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/winpr-makecert.1.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/winpr-makecert.1.in new file mode 100644 index 0000000000000000000000000000000000000000..a1eb841b76f3d813bee5ebfcd381695444c7dd1b --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert-cli/winpr-makecert.1.in @@ -0,0 +1,116 @@ +.de URL +\\$2 \(laURL: \\$1 \(ra\\$3 +.. +.if \n[.g] .mso www.tmac +.TH @MANPAGE_NAME@ 1 2017-01-11 "@WINPR_VERSION_FULL@" "FreeRDP" +.SH NAME +@MANPAGE_NAME@ \- A tool to create X.509 certificates. +.SH SYNOPSIS +.B @MANPAGE_NAME@ +[\fB-rdp\fP] +[\fB-silent\fP] +[\fB-live\fP] +[\fB-format\fP { \fIcrt\fP | \fIpem\fP | \fIpfx\fP }] +[\fB-p\fP password] +[\fB-n\fP common_name] +[\fB-y\fP years] +[\fB-m\fP months] +[\fB-len\fP length] +[\fB-#\fP serial] +[\fB-a\fP { \fImd5\fP | \fIsha1\fP | \fIsha256\fP | \fIs384\fP | \fIsha512\fP }] +[\fB-path\fP outputpath] +[outputname] +.SH DESCRIPTION +.B @MANPAGE_NAME@ +is a tool for generating X.509 certificates modeled after the Windows command +MakeCert. @MANPAGE_NAME@ aims to be command line compatible with MakeCert +however not all options are supported or implemented yet. + +Unimplemented features are not described here. They are marked as "Unsupported" +in @MANPAGE_NAME@s help. + +In contrast to it's Windows counterpart @MANPAGE_NAME@ does, unless the +\fB\-live\fP option is given, always creates and save a certificate. +If \fIoutputname\fP isn't set it is tried to determine the host name of the +computer the command is run on. +.br +\fBWarning:\fP if the file already exists it will be overwritten without asking. + +Without further options the generated certificates have the following properties: + +* 2048 bit long +.br +* sha256 as hash algorithm +.br +* the detected host name is used as common name +.br +* a time stamp is used as serial number +.br +* validity period of one year +.br +* saved in the current working directory in crt format +.SH OPTIONS +.IP "-rdp" +Dummy parameter. Can be used to quickly generate a certificate with default +properties without specifying any further parameters. +.IP "-silent" +Don't print the generated certificate to stdout. +.IP "-f format" +Three formats are supported: crt, pem and pfx. +.br +\fIcrt\fP outputs the key and the certificate in a separate file each with the file +endings .key and .crt. +.br +\fIpem\fP outputs the key and certificate into a single file with the file ending pem. +.br +And \fIpfx\fP outputs key and certificate into a pkcs12 file with the ending .pfx. +.IP "-p password" +Password to use if the pfx format is used as format. +.IP "-live" +Don't write the key/certificate to disk. When used from the command line this +can be thought as "dummy" mode. +.IP "-n common_name" +The common name to use in the certificate. +.IP "-m months" +Validity period in months (multiple of 31 days, not clanendar months). +.IP "-y years" +Validity period in years (365 days, leap years not accounted). If months and years are specified the specified +the values are accumulated. +.IP "-len length" +Key length in bits to use. +.IP "-a { \fImd5\fP | \fIsha1\fP | \fIsha256\fP | \fIs384\fP | \fIsha512\fP }" +The hashing algorithm to use. +.IP "-# serial" +The serial number to use for the certificate. +.IP "-path" +A directory where the certificate should be created in. +.IP "outputname" +The base name of the created file(s). A suffix, the format specific suffix is +appended to this name. +.SH EXAMPLES +@MANPAGE_NAME@ -rdp + +Creates a certificate with the default properties, saved to a file in the +current working directory in crt format named like the host. If the host is +named freerdp the created files are called freerdp.key and freerdp.crt. + + +@MANPAGE_NAME@ -len 4096 -a sha384 -path /tmp -# 22 -m 144 -y 1 -format crt mycert + +The command above creates the file /tmp/mycert.pem containing a key and a +certificate with a length of 4096. It will use sha384 as hash algorithm. +The certificate has the serial number 22 and is valid for 12 years (144 months). +.SH EXIT STATUS +.TP +.B 0 +Successful program execution. +.TP +.B 1 +Otherwise. + +.SH SEE ALSO + +.URL "https://msdn.microsoft.com/library/windows/desktop/aa386968.aspx" "MakeCert help page" + +.SH AUTHOR +FreeRDP diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/CMakeLists.txt b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..37b83112581c8fddd5c3c6bd60059572df6df390 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/CMakeLists.txt @@ -0,0 +1,41 @@ +# WinPR: Windows Portable Runtime +# winpr-makecert cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# 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-makecert-tool") +set(MODULE_PREFIX "WINPR_MAKECERT_TOOL") + +set(${MODULE_PREFIX}_SRCS makecert.c) + +if(OPENSSL_FOUND) + winpr_tools_include_directory_add(${OPENSSL_INCLUDE_DIR}) +endif() + +if(MBEDTLS_FOUND) + winpr_tools_include_directory_add(${MBEDTLS_INCLUDE_DIR}) +endif() + +winpr_tools_module_add(${${MODULE_PREFIX}_SRCS}) + +if(OPENSSL_FOUND) + list(APPEND ${MODULE_PREFIX}_LIBS ${OPENSSL_LIBRARIES}) +endif() + +if(MBEDTLS_FOUND) + list(APPEND ${MODULE_PREFIX}_LIBS ${MBEDTLS_LIBRARIES}) +endif() + +winpr_tools_library_add(${${MODULE_PREFIX}_LIBS} winpr) diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/makecert.c b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/makecert.c new file mode 100644 index 0000000000000000000000000000000000000000..ac3555d769d038afcbe85de885c7c95ba0bd50e2 --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/makecert/makecert.c @@ -0,0 +1,1157 @@ +/** + * WinPR: Windows Portable Runtime + * makecert replacement + * + * Copyright 2012 Marc-Andre Moreau + * + * 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 + +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_OPENSSL +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include + +struct S_MAKECERT_CONTEXT +{ + int argc; + char** argv; + +#ifdef WITH_OPENSSL + X509* x509; + EVP_PKEY* pkey; + PKCS12* pkcs12; +#endif + + BOOL live; + BOOL silent; + + BOOL crtFormat; + BOOL pemFormat; + BOOL pfxFormat; + + char* password; + + char* output_file; + char* output_path; + char* default_name; + char* common_name; + + int duration_years; + int duration_months; +}; + +static char* makecert_read_str(BIO* bio, size_t* pOffset) +{ + int status = -1; + size_t offset = 0; + size_t length = 0; + char* x509_str = NULL; + + while (offset >= length) + { + size_t new_len = 0; + size_t readBytes = 0; + char* new_str = NULL; + new_len = length * 2; + if (new_len == 0) + new_len = 2048; + + if (new_len > INT_MAX) + { + status = -1; + break; + } + + new_str = (char*)realloc(x509_str, new_len); + + if (!new_str) + { + status = -1; + break; + } + + length = new_len; + x509_str = new_str; + ERR_clear_error(); +#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER) + status = BIO_read_ex(bio, &x509_str[offset], length - offset, &readBytes); +#else + status = BIO_read(bio, &x509_str[offset], length - offset); + readBytes = status; +#endif + if (status <= 0) + break; + + offset += readBytes; + } + + if (status < 0) + { + free(x509_str); + if (pOffset) + *pOffset = 0; + return NULL; + } + + x509_str[offset] = '\0'; + if (pOffset) + *pOffset = offset + 1; + return x509_str; +} + +static int makecert_print_command_line_help(COMMAND_LINE_ARGUMENT_A* args, int argc, char** argv) +{ + char* str = NULL; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + + if (!argv || (argc < 1)) + return -1; + + printf("Usage: %s [options] [output file]\n", argv[0]); + printf("\n"); + arg = args; + + do + { + if (arg->Flags & COMMAND_LINE_VALUE_FLAG) + { + printf(" %s", "-"); + printf("%-20s", arg->Name); + printf("\t%s\n", arg->Text); + } + else if ((arg->Flags & COMMAND_LINE_VALUE_REQUIRED) || + (arg->Flags & COMMAND_LINE_VALUE_OPTIONAL)) + { + printf(" %s", "-"); + + if (arg->Format) + { + size_t length = strlen(arg->Name) + strlen(arg->Format) + 2; + str = malloc(length + 1); + + if (!str) + return -1; + + (void)sprintf_s(str, length + 1, "%s %s", arg->Name, arg->Format); + (void)printf("%-20s", str); + free(str); + } + else + { + printf("%-20s", arg->Name); + } + + printf("\t%s\n", arg->Text); + } + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + return 1; +} + +#ifdef WITH_OPENSSL +static int x509_add_ext(X509* cert, int nid, char* value) +{ + X509V3_CTX ctx; + X509_EXTENSION* ext = NULL; + + if (!cert || !value) + return 0; + + X509V3_set_ctx_nodb(&ctx) X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0); + ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value); + + if (!ext) + return 0; + + X509_add_ext(cert, ext, -1); + X509_EXTENSION_free(ext); + return 1; +} +#endif + +static char* x509_name_parse(char* name, char* txt, size_t* length) +{ + char* p = NULL; + char* entry = NULL; + + if (!name || !txt || !length) + return NULL; + + p = strstr(name, txt); + + if (!p) + return NULL; + + entry = p + strlen(txt) + 1; + p = strchr(entry, '='); + + if (!p) + *length = strlen(entry); + else + *length = (size_t)(p - entry); + + return entry; +} + +static char* get_name(COMPUTER_NAME_FORMAT type) +{ + DWORD nSize = 0; + + if (GetComputerNameExA(type, NULL, &nSize)) + return NULL; + + if (GetLastError() != ERROR_MORE_DATA) + return NULL; + + char* computerName = calloc(1, nSize); + + if (!computerName) + return NULL; + + if (!GetComputerNameExA(type, computerName, &nSize)) + { + free(computerName); + return NULL; + } + + return computerName; +} + +static char* x509_get_default_name(void) +{ + char* computerName = get_name(ComputerNamePhysicalDnsFullyQualified); + if (!computerName) + computerName = get_name(ComputerNamePhysicalNetBIOS); + return computerName; +} + +static int command_line_pre_filter(void* pvctx, int index, int argc, LPSTR* argv) +{ + MAKECERT_CONTEXT* context = pvctx; + if (!context || !argv || (index < 0) || (argc < 0)) + return -1; + + if (index == (argc - 1)) + { + if (argv[index][0] != '-') + { + context->output_file = _strdup(argv[index]); + + if (!context->output_file) + return -1; + + return 1; + } + } + + return 0; +} + +static int makecert_context_parse_arguments(MAKECERT_CONTEXT* context, + COMMAND_LINE_ARGUMENT_A* args, int argc, char** argv) +{ + int status = 0; + DWORD flags = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + + if (!context || !argv || (argc < 0)) + return -1; + + /** + * makecert -r -pe -n "CN=%COMPUTERNAME%" -eku 1.3.6.1.5.5.7.3.1 -ss my -sr LocalMachine + * -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 + */ + CommandLineClearArgumentsA(args); + flags = COMMAND_LINE_SEPARATOR_SPACE | COMMAND_LINE_SIGIL_DASH; + status = + CommandLineParseArgumentsA(argc, argv, args, flags, context, command_line_pre_filter, NULL); + + if (status & COMMAND_LINE_STATUS_PRINT_HELP) + { + makecert_print_command_line_help(args, argc, argv); + return 0; + } + + arg = args; + errno = 0; + + do + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + CommandLineSwitchStart(arg) + /* Basic Options */ + CommandLineSwitchCase(arg, "silent") + { + context->silent = TRUE; + } + CommandLineSwitchCase(arg, "live") + { + context->live = TRUE; + } + CommandLineSwitchCase(arg, "format") + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + if (strcmp(arg->Value, "crt") == 0) + { + context->crtFormat = TRUE; + context->pemFormat = FALSE; + context->pfxFormat = FALSE; + } + else if (strcmp(arg->Value, "pem") == 0) + { + context->crtFormat = FALSE; + context->pemFormat = TRUE; + context->pfxFormat = FALSE; + } + else if (strcmp(arg->Value, "pfx") == 0) + { + context->crtFormat = FALSE; + context->pemFormat = FALSE; + context->pfxFormat = TRUE; + } + else + return -1; + } + CommandLineSwitchCase(arg, "path") + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + context->output_path = _strdup(arg->Value); + + if (!context->output_path) + return -1; + } + CommandLineSwitchCase(arg, "p") + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + context->password = _strdup(arg->Value); + + if (!context->password) + return -1; + } + CommandLineSwitchCase(arg, "n") + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + context->common_name = _strdup(arg->Value); + + if (!context->common_name) + return -1; + } + CommandLineSwitchCase(arg, "y") + { + long val = 0; + + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + val = strtol(arg->Value, NULL, 0); + + if ((errno != 0) || (val < 0) || (val > INT32_MAX)) + return -1; + + context->duration_years = (int)val; + } + CommandLineSwitchCase(arg, "m") + { + long val = 0; + + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + val = strtol(arg->Value, NULL, 0); + + if ((errno != 0) || (val < 0)) + return -1; + + context->duration_months = (int)val; + } + CommandLineSwitchDefault(arg) + { + } + CommandLineSwitchEnd(arg) + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + return 1; +} + +int makecert_context_set_output_file_name(MAKECERT_CONTEXT* context, const char* name) +{ + if (!context) + return -1; + + free(context->output_file); + context->output_file = NULL; + + if (name) + context->output_file = _strdup(name); + + if (!context->output_file) + return -1; + + return 1; +} + +int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, const char* path) +{ +#ifdef WITH_OPENSSL + FILE* fp = NULL; + int status = 0; + size_t length = 0; + size_t offset = 0; + char* filename = NULL; + char* fullpath = NULL; + char* ext = NULL; + int ret = -1; + BIO* bio = NULL; + char* x509_str = NULL; + + if (!context) + return -1; + + if (!context->output_file) + { + context->output_file = _strdup(context->default_name); + + if (!context->output_file) + return -1; + } + + /* + * Output Certificate File + */ + length = strlen(context->output_file); + filename = malloc(length + 8); + + if (!filename) + return -1; + + if (context->crtFormat) + ext = "crt"; + else if (context->pemFormat) + ext = "pem"; + else if (context->pfxFormat) + ext = "pfx"; + else + goto out_fail; + + (void)sprintf_s(filename, length + 8, "%s.%s", context->output_file, ext); + + if (path) + fullpath = GetCombinedPath(path, filename); + else + fullpath = _strdup(filename); + + if (!fullpath) + goto out_fail; + + fp = winpr_fopen(fullpath, "w+"); + + if (fp) + { + if (context->pfxFormat) + { + if (!context->password) + { + context->password = _strdup("password"); + + if (!context->password) + goto out_fail; + + printf("Using default export password \"password\"\n"); + } + +#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) + OpenSSL_add_all_algorithms(); + OpenSSL_add_all_ciphers(); + OpenSSL_add_all_digests(); +#else + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS | + OPENSSL_INIT_LOAD_CONFIG, + NULL); +#endif + context->pkcs12 = PKCS12_create(context->password, context->default_name, context->pkey, + context->x509, NULL, 0, 0, 0, 0, 0); + + if (!context->pkcs12) + goto out_fail; + + bio = BIO_new(BIO_s_mem()); + + if (!bio) + goto out_fail; + + status = i2d_PKCS12_bio(bio, context->pkcs12); + + if (status != 1) + goto out_fail; + + x509_str = makecert_read_str(bio, &offset); + + if (!x509_str) + goto out_fail; + + length = offset; + + if (fwrite((void*)x509_str, length, 1, fp) != 1) + goto out_fail; + } + else + { + bio = BIO_new(BIO_s_mem()); + + if (!bio) + goto out_fail; + + if (!PEM_write_bio_X509(bio, context->x509)) + goto out_fail; + + x509_str = makecert_read_str(bio, &offset); + + if (!x509_str) + goto out_fail; + + length = offset; + + if (fwrite(x509_str, length, 1, fp) != 1) + goto out_fail; + + free(x509_str); + x509_str = NULL; + BIO_free_all(bio); + bio = NULL; + + if (context->pemFormat) + { + bio = BIO_new(BIO_s_mem()); + + if (!bio) + goto out_fail; + + status = PEM_write_bio_PrivateKey(bio, context->pkey, NULL, NULL, 0, NULL, NULL); + + if (status < 0) + goto out_fail; + + x509_str = makecert_read_str(bio, &offset); + if (!x509_str) + goto out_fail; + + length = offset; + + if (fwrite(x509_str, length, 1, fp) != 1) + goto out_fail; + } + } + } + + ret = 1; +out_fail: + BIO_free_all(bio); + + if (fp) + (void)fclose(fp); + + free(x509_str); + free(filename); + free(fullpath); + return ret; +#else + WLog_ERR(TAG, "%s only supported with OpenSSL", __func__); + return -1; +#endif +} + +int makecert_context_output_private_key_file(MAKECERT_CONTEXT* context, const char* path) +{ +#ifdef WITH_OPENSSL + FILE* fp = NULL; + size_t length = 0; + size_t offset = 0; + char* filename = NULL; + char* fullpath = NULL; + int ret = -1; + BIO* bio = NULL; + char* x509_str = NULL; + + if (!context->crtFormat) + return 1; + + if (!context->output_file) + { + context->output_file = _strdup(context->default_name); + + if (!context->output_file) + return -1; + } + + /** + * Output Private Key File + */ + length = strlen(context->output_file); + filename = malloc(length + 8); + + if (!filename) + return -1; + + (void)sprintf_s(filename, length + 8, "%s.key", context->output_file); + + if (path) + fullpath = GetCombinedPath(path, filename); + else + fullpath = _strdup(filename); + + if (!fullpath) + goto out_fail; + + fp = winpr_fopen(fullpath, "w+"); + + if (!fp) + goto out_fail; + + bio = BIO_new(BIO_s_mem()); + + if (!bio) + goto out_fail; + + if (!PEM_write_bio_PrivateKey(bio, context->pkey, NULL, NULL, 0, NULL, NULL)) + goto out_fail; + + x509_str = makecert_read_str(bio, &offset); + + if (!x509_str) + goto out_fail; + + length = offset; + + if (fwrite((void*)x509_str, length, 1, fp) != 1) + goto out_fail; + + ret = 1; +out_fail: + + if (fp) + (void)fclose(fp); + + BIO_free_all(bio); + free(x509_str); + free(filename); + free(fullpath); + return ret; +#else + WLog_ERR(TAG, "%s only supported with OpenSSL", __func__); + return -1; +#endif +} + +#ifdef WITH_OPENSSL +static BOOL makecert_create_rsa(EVP_PKEY** ppkey, size_t key_length) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(ppkey); + +#if !defined(OPENSSL_VERSION_MAJOR) || (OPENSSL_VERSION_MAJOR < 3) + RSA* rsa = NULL; +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + rsa = RSA_generate_key(key_length, RSA_F4, NULL, NULL); +#else + { + BIGNUM* bn = BN_secure_new(); + + if (!bn) + return FALSE; + + rsa = RSA_new(); + + if (!rsa) + { + BN_clear_free(bn); + return FALSE; + } + + BN_set_word(bn, RSA_F4); + const int res = RSA_generate_key_ex(rsa, key_length, bn, NULL); + BN_clear_free(bn); + + if (res != 1) + return FALSE; + } +#endif + + if (!EVP_PKEY_assign_RSA(*ppkey, rsa)) + { + RSA_free(rsa); + return FALSE; + } + rc = TRUE; +#else + EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL); + if (!pctx) + return FALSE; + + if (EVP_PKEY_keygen_init(pctx) != 1) + goto fail; + + WINPR_ASSERT(key_length <= UINT_MAX); + unsigned int keylen = (unsigned int)key_length; + const OSSL_PARAM params[] = { OSSL_PARAM_construct_uint("bits", &keylen), + OSSL_PARAM_construct_end() }; + if (EVP_PKEY_CTX_set_params(pctx, params) != 1) + goto fail; + + if (EVP_PKEY_generate(pctx, ppkey) != 1) + goto fail; + + rc = TRUE; +fail: + EVP_PKEY_CTX_free(pctx); +#endif + return rc; +} +#endif + +int makecert_context_process(MAKECERT_CONTEXT* context, int argc, char** argv) +{ + COMMAND_LINE_ARGUMENT_A args[] = { + /* Custom Options */ + + { "rdp", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Unsupported - Generate certificate with required options for RDP usage." }, + { "silent", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Silently generate certificate without verbose output." }, + { "live", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Generate certificate live in memory when used as a library." }, + { "format", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specify certificate file format" }, + { "path", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specify certificate file output path" }, + { "p", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specify certificate export password" }, + + /* Basic Options */ + + { "n", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies the subject's certificate name. This name must conform to the X.500 standard. " + "The simplest method is to specify the name in double quotes, preceded by CN=; for " + "example, " + "-n \"CN=myName\"." }, + { "pe", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Unsupported - Marks the generated private key as exportable. This allows the private " + "key to " + "be included in the certificate." }, + { "sk", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's key container location, which contains the " + "private " + "key. " + "If a key container does not exist, it will be created." }, + { "sr", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's certificate store location. location can be " + "either " + "currentuser (the default) or localmachine." }, + { "ss", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's certificate store name that stores the output " + "certificate." }, + { "#", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies a serial number from 1 to 2,147,483,647. The default is a unique value " + "generated " + "by Makecert.exe." }, + { "$", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the signing authority of the certificate, which must be set to " + "either commercial " + "(for certificates used by commercial software publishers) or individual (for " + "certificates " + "used by individual software publishers)." }, + + /* Extended Options */ + + { "a", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies the signature algorithm. algorithm must be md5, sha1, sha256 (the default), " + "sha384, or sha512." }, + { "b", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the start of the validity period. Defaults to the current " + "date." }, + { "crl", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Unsupported - Generates a certificate relocation list (CRL) instead of a certificate." }, + { "cy", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the certificate type. Valid values are end for end-entity and " + "authority for certification authority." }, + { "e", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the end of the validity period. Defaults to 12/31/2039 11:59:59 " + "GMT." }, + { "eku", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Inserts a list of comma-separated, enhanced key usage object identifiers " + "(OIDs) into the certificate." }, + { "h", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the maximum height of the tree below this certificate." }, + { "ic", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's certificate file." }, + { "ik", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's key container name." }, + { "iky", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's key type, which must be one of the following: " + "signature (which indicates that the key is used for a digital signature), " + "exchange (which indicates that the key is used for key encryption and key exchange), " + "or an integer that represents a provider type. " + "By default, you can pass 1 for an exchange key or 2 for a signature key." }, + { "in", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's certificate common name." }, + { "ip", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's CryptoAPI provider name. For information about the " + "CryptoAPI provider name, see the –sp option." }, + { "ir", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the location of the issuer's certificate store. location can be " + "either currentuser (the default) or localmachine." }, + { "is", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's certificate store name." }, + { "iv", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's .pvk private key file." }, + { "iy", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the issuer's CryptoAPI provider type. For information about the " + "CryptoAPI provider type, see the –sy option." }, + { "l", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Links to policy information (for example, to a URL)." }, + { "len", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies the generated key length, in bits." }, + { "m", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies the duration, in months, of the certificate validity period." }, + { "y", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Specifies the duration, in years, of the certificate validity period." }, + { "nscp", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Unsupported - Includes the Netscape client-authorization extension." }, + { "r", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, NULL, + "Unsupported - Creates a self-signed certificate." }, + { "sc", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's certificate file." }, + { "sky", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's key type, which must be one of the following: " + "signature (which indicates that the key is used for a digital signature), " + "exchange (which indicates that the key is used for key encryption and key exchange), " + "or an integer that represents a provider type. " + "By default, you can pass 1 for an exchange key or 2 for a signature key." }, + { "sp", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's CryptoAPI provider name, which must be defined in " + "the " + "registry subkeys of " + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\Defaults\\Provider. If both –sp " + "and " + "–sy are present, " + "the type of the CryptoAPI provider must correspond to the Type value of the provider's " + "subkey." }, + { "sv", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's .pvk private key file. The file is created if " + "none " + "exists." }, + { "sy", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the subject's CryptoAPI provider type, which must be defined in " + "the " + "registry subkeys of " + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\\Defaults\\Provider Types. If " + "both " + "–sy and –sp are present, " + "the name of the CryptoAPI provider must correspond to the Name value of the provider " + "type " + "subkey." }, + { "tbs", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, + "Unsupported - Specifies the certificate or CRL file to be signed." }, + + /* Help */ + + { "?", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_HELP, NULL, NULL, NULL, -1, "help", + "print help" }, + { "!", COMMAND_LINE_VALUE_FLAG | COMMAND_LINE_PRINT_HELP, NULL, NULL, NULL, -1, "help-ext", + "print extended help" }, + { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } + }; +#ifdef WITH_OPENSSL + size_t length = 0; + char* entry = NULL; + int key_length = 0; + long serial = 0; + X509_NAME* name = NULL; + const EVP_MD* md = NULL; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + int ret = 0; + ret = makecert_context_parse_arguments(context, args, argc, argv); + + if (ret < 1) + { + return ret; + } + + if (!context->default_name && !context->common_name) + { + context->default_name = x509_get_default_name(); + + if (!context->default_name) + return -1; + } + else + { + context->default_name = _strdup(context->common_name); + + if (!context->default_name) + return -1; + } + + if (!context->common_name) + { + context->common_name = _strdup(context->default_name); + + if (!context->common_name) + return -1; + } + + if (!context->pkey) + context->pkey = EVP_PKEY_new(); + + if (!context->pkey) + return -1; + + if (!context->x509) + context->x509 = X509_new(); + + if (!context->x509) + return -1; + + key_length = 2048; + arg = CommandLineFindArgumentA(args, "len"); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + unsigned long val = strtoul(arg->Value, NULL, 0); + + if ((errno != 0) || (val > INT_MAX)) + return -1; + key_length = (int)val; + } + + if (!makecert_create_rsa(&context->pkey, WINPR_ASSERTING_INT_CAST(size_t, key_length))) + return -1; + + X509_set_version(context->x509, 2); + arg = CommandLineFindArgumentA(args, "#"); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + serial = strtol(arg->Value, NULL, 0); + + if (errno != 0) + return -1; + } + else + serial = (long)GetTickCount64(); + + ASN1_INTEGER_set(X509_get_serialNumber(context->x509), serial); + { + ASN1_TIME* before = NULL; + ASN1_TIME* after = NULL; +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + before = X509_get_notBefore(context->x509); + after = X509_get_notAfter(context->x509); +#else + before = X509_getm_notBefore(context->x509); + after = X509_getm_notAfter(context->x509); +#endif + X509_gmtime_adj(before, 0); + + long duration = context->duration_months * 31l + context->duration_years * 365l; + duration *= 60l * 60l * 24l; + X509_gmtime_adj(after, duration); + } + X509_set_pubkey(context->x509, context->pkey); + name = X509_get_subject_name(context->x509); + arg = CommandLineFindArgumentA(args, "n"); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + entry = x509_name_parse(arg->Value, "C", &length); + + if (entry) + X509_NAME_add_entry_by_txt(name, "C", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + + entry = x509_name_parse(arg->Value, "ST", &length); + + if (entry) + X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + + entry = x509_name_parse(arg->Value, "L", &length); + + if (entry) + X509_NAME_add_entry_by_txt(name, "L", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + + entry = x509_name_parse(arg->Value, "O", &length); + + if (entry) + X509_NAME_add_entry_by_txt(name, "O", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + + entry = x509_name_parse(arg->Value, "OU", &length); + + if (entry) + X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + + entry = context->common_name; + length = strlen(entry); + X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + } + else + { + entry = context->common_name; + length = strlen(entry); + X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_UTF8, (const unsigned char*)entry, + (int)length, -1, 0); + } + + X509_set_issuer_name(context->x509, name); + x509_add_ext(context->x509, NID_ext_key_usage, "serverAuth"); + arg = CommandLineFindArgumentA(args, "a"); + md = EVP_sha256(); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + md = EVP_get_digestbyname(arg->Value); + if (!md) + return -1; + } + + if (!X509_sign(context->x509, context->pkey, md)) + return -1; + + /** + * Print certificate + */ + + if (!context->silent) + { + BIO* bio = NULL; + int status = 0; + char* x509_str = NULL; + bio = BIO_new(BIO_s_mem()); + + if (!bio) + return -1; + + status = X509_print(bio, context->x509); + + if (status < 0) + { + BIO_free_all(bio); + return -1; + } + + x509_str = makecert_read_str(bio, NULL); + if (!x509_str) + { + BIO_free_all(bio); + return -1; + } + + printf("%s", x509_str); + free(x509_str); + BIO_free_all(bio); + } + + /** + * Output certificate and private key to files + */ + + if (!context->live) + { + if (!winpr_PathFileExists(context->output_path)) + { + if (!CreateDirectoryA(context->output_path, NULL)) + return -1; + } + + if (makecert_context_output_certificate_file(context, context->output_path) != 1) + return -1; + + if (context->crtFormat) + { + if (makecert_context_output_private_key_file(context, context->output_path) < 0) + return -1; + } + } + + return 0; +#else + WLog_ERR(TAG, "%s only supported with OpenSSL", __func__); + return -1; +#endif +} + +MAKECERT_CONTEXT* makecert_context_new(void) +{ + MAKECERT_CONTEXT* context = (MAKECERT_CONTEXT*)calloc(1, sizeof(MAKECERT_CONTEXT)); + + if (context) + { + context->crtFormat = TRUE; + context->duration_years = 1; + } + + return context; +} + +void makecert_context_free(MAKECERT_CONTEXT* context) +{ + if (context) + { + free(context->password); + free(context->default_name); + free(context->common_name); + free(context->output_file); + free(context->output_path); +#ifdef WITH_OPENSSL + X509_free(context->x509); + EVP_PKEY_free(context->pkey); +#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) + CRYPTO_cleanup_all_ex_data(); +#endif +#endif + free(context); + } +} diff --git a/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/winpr-tools.pc.in b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/winpr-tools.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..6898253884edbde93a1dfa50e363be1e9c27490e --- /dev/null +++ b/local-test-freerdp-delta-01/afc-freerdp/winpr/tools/winpr-tools.pc.in @@ -0,0 +1,15 @@ +prefix=@PKG_CONFIG_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${prefix}/@WINPR_INCLUDE_DIR@ +libs=-lwinpr-tools@WINPR_TOOLS_API_VERSION@ + +Name: WinPR +Description: WinPR: Windows Portable Runtime +URL: http://www.freerdp.com/ +Version: @WINPR_TOOLS_VERSION@ +Requires: +Requires.private: winpr@WINPR_VERSION_MAJOR@ libssl +Libs: -L${libdir} ${libs} +Libs.private: -lcrypto +Cflags: -I${includedir}